text stringlengths 1 1.02k | class_index int64 0 1.38k | source stringclasses 431
values |
|---|---|---|
Load weights from the specified dduf file. | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.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 DiffusionPipeline
>>> # Download pipeline from huggingface.co and cache.
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
>>> scheduler = LMSDiscreteScheduler.from_config(pipeline.scheduler.config)
>>> pipeline.scheduler = scheduler
```
"""
# Copy the kwargs to re-use during loading connected pipeline.
kwargs_copied = kwargs.copy() | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
cache_dir = kwargs.pop("cache_dir", None)
force_download = kwargs.pop("force_download", False)
proxies = kwargs.pop("proxies", None)
local_files_only = kwargs.pop("local_files_only", None)
token = kwargs.pop("token", None)
revision = kwargs.pop("revision", None)
from_flax... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
dduf_file = kwargs.pop("dduf_file", None)
use_safetensors = kwargs.pop("use_safetensors", None)
use_onnx = kwargs.pop("use_onnx", None)
load_connected_pipeline = kwargs.pop("load_connected_pipeline", False) | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if low_cpu_mem_usage and not is_accelerate_available():
low_cpu_mem_usage = False
logger.warning(
"Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"
" environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly r... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if device_map is not None and not is_torch_version(">=", "1.9.0"):
raise NotImplementedError(
"Loading and dispatching requires torch >= 1.9.0. Please either update your PyTorch version or set"
" `device_map=None`."
)
if device_map is not None and not is_... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if device_map is not None and device_map in SUPPORTED_DEVICE_MAP:
if is_accelerate_version("<", "0.28.0"):
raise NotImplementedError("Device placement requires `accelerate` version `0.28.0` or later.")
if low_cpu_mem_usage is False and device_map is not None:
raise Value... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# 1. Download the checkpoints and configs
# use snapshot download here to get it working from from_pretrained
if not os.path.isdir(pretrained_model_name_or_path):
if pretrained_model_name_or_path.count("/") > 1:
raise ValueError(
f'The provided pretrained_... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
custom_revision=custom_revision,
variant=variant,
dduf_file=dduf_file,
load_connected_pipeline=load_connected_pipeline,
**kwargs,
)
else:
cached_folder = pretrained_model_name_or_path | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# The variant filenames can have the legacy sharding checkpoint format that we check and throw
# a warning if detected.
if variant is not None and _check_legacy_sharding_variant_format(folder=cached_folder, variant=variant):
warn_msg = (
f"Warning: The repository contains sha... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
logger.warning(warn_msg) | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
dduf_entries = None
if dduf_file:
dduf_file_path = os.path.join(cached_folder, dduf_file)
dduf_entries = read_dduf_file(dduf_file_path)
# The reader contains already all the files needed, no need to check it again
cached_folder = ""
config_dict = cls.load... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# 2. Define which model components should load variants
# We retrieve the information by matching whether variant model checkpoints exist in the subfolders.
# Example: `diffusion_pytorch_model.safetensors` -> `diffusion_pytorch_model.fp16.safetensors`
# with variant being `"fp16"`.
model... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# 3. Load the pipeline class, if using custom module then load it from the hub
# if we load from explicit class, let's use it
custom_pipeline, custom_class_name = _resolve_custom_pipeline_and_cls(
folder=cached_folder, config=config_dict, custom_pipeline=custom_pipeline
)
pip... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# DEPRECATED: To be removed in 1.0.0
# we are deprecating the `StableDiffusionInpaintPipelineLegacy` pipeline which gets loaded
# when a user requests for a `StableDiffusionInpaintPipeline` with `diffusers` version being <= 0.5.1.
_maybe_raise_warning_for_inpainting(
pipeline_class=p... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# some modules can be passed directly to the init
# in this case they are already instantiated in `kwargs`
# extract them here
expected_modules, optional_kwargs = cls._get_signature_keys(pipeline_class)
expected_types = pipeline_class._get_signature_types()
passed_class_obj = {k:... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# remove `null` components
def load_module(name, value):
if value[0] is None:
return False
if name in passed_class_obj and passed_class_obj[name] is None:
return False
return True
init_dict = {k: v for k, v in init_dict.items() if load... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
_is_valid_type = class_obj.__class__.__name__ in _expected_class_types
if not _is_valid_type:
logger.warning(
f"Expected types for {key}: {_expected_class_types}, got {class_obj.__class__.__name__}."
)
# Special case: safety_checker must be loaded... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# 5. Throw nice warnings / errors for fast accelerate loading
if len(unused_kwargs) > 0:
logger.warning(
f"Keyword arguments {unused_kwargs} are not expected by {pipeline_class.__name__} and will be ignored."
)
# import it here to avoid circular import
fr... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# 6. device map delegation
final_device_map = None
if device_map is not None:
final_device_map = _get_final_device_map(
device_map=device_map,
pipeline_class=pipeline_class,
passed_class_obj=passed_class_obj,
init_dict=init_dict... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# 7. Load each module in the pipeline
current_device_map = None
for name, (library_name, class_name) in logging.tqdm(init_dict.items(), desc="Loading pipeline components..."):
# 7.1 device_map shenanigans
if final_device_map is not None and len(final_device_map) > 0:
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# 7.4 Use passed sub model or load class_name from library_name
if name in passed_class_obj:
# if the model is in a pipeline module, then we load it from the pipeline
# check that passed_class_obj has correct parent class
maybe_raise_or_warn(
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
loaded_sub_model = passed_class_obj[name]
else:
# load sub model
loaded_sub_model = load_sub_model(
library_name=library_name,
class_name=class_name,
importable_classes=importable_classes,
pipelin... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
cached_folder=cached_folder,
use_safetensors=use_safetensors,
dduf_entries=dduf_entries,
)
logger.info(
f"Loaded {name} as {class_name} from `{name}` subfolder of {pretrained_model_name_or_path}."
) | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
init_kwargs[name] = loaded_sub_model # UNet(...), # DiffusionSchedule(...)
# 8. Handle connected pipelines.
if pipeline_class._load_connected_pipes and os.path.isfile(os.path.join(cached_folder, "README.md")):
init_kwargs = _update_init_kwargs_with_connected_pipeline(
init_... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# 9. Potentially add passed objects if expected
missing_modules = set(expected_modules) - set(init_kwargs.keys())
passed_modules = list(passed_class_obj.keys())
optional_modules = pipeline_class._optional_components
if len(missing_modules) > 0 and missing_modules <= set(passed_modules + ... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# 11. Save where the model was instantiated from
model.register_to_config(_name_or_path=pretrained_model_name_or_path)
if device_map is not None:
setattr(model, "hf_device_map", final_device_map)
return model
@property
def name_or_path(self) -> str:
return getattr(se... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if not hasattr(model, "_hf_hook"):
return self.device
for module in model.modules():
if (
hasattr(module, "_hf_hook")
and hasattr(module._hf_hook, "execution_device")
and module._hf_hook.execution_device is not None
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
def enable_model_cpu_offload(self, gpu_id: Optional[int] = None, device: Union[torch.device, str] = "cuda"):
r"""
Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
to `enable_sequential_cpu_offload`, this method moves one whole model at... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
Arguments:
gpu_id (`int`, *optional*):
The ID of the accelerator that shall be used in inference. If not specified, it will default to 0.
device (`torch.Device` or `str`, *optional*, defaults to "cuda"):
The PyTorch device type of the accelerator that shall be use... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if self.model_cpu_offload_seq is None:
raise ValueError(
"Model CPU offload cannot be enabled because no `model_cpu_offload_seq` class attribute is set."
)
if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
from accelerate import cpu... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# _offload_gpu_id should be set to passed gpu_id (or id in passed `device`) or default to previously set id or default to 0
self._offload_gpu_id = gpu_id or torch_device.index or getattr(self, "_offload_gpu_id", 0)
device_type = torch_device.type
device = torch.device(f"{device_type}:{self._off... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if not isinstance(model, torch.nn.Module):
continue
# This is because the model would already be placed on a CUDA device.
_, _, is_loaded_in_8bit_bnb = _check_bnb_status(model)
if is_loaded_in_8bit_bnb:
logger.info(
f"Skipping the ... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if name in self._exclude_from_cpu_offload:
model.to(device)
else:
_, hook = cpu_offload_with_hook(model, device)
self._all_hooks.append(hook)
def maybe_free_model_hooks(self):
r"""
Function that offloads all components, removes all model h... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
def enable_sequential_cpu_offload(self, gpu_id: Optional[int] = None, device: Union[torch.device, str] = "cuda"):
r"""
Offloads all models to CPU using 🤗 Accelerate, significantly reducing memory usage. When called, the state
dicts of all `torch.nn.Module` components (except those in `self._exc... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
Arguments:
gpu_id (`int`, *optional*):
The ID of the accelerator that shall be used in inference. If not specified, it will default to 0.
device (`torch.Device` or `str`, *optional*, defaults to "cuda"):
The PyTorch device type of the accelerator that shall be use... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
is_pipeline_device_mapped = self.hf_device_map is not None and len(self.hf_device_map) > 1
if is_pipeline_device_mapped:
raise ValueError(
"It seems like you have activated a device mapping strategy on the pipeline so calling `enable_sequential_cpu_offload() isn't allowed. You can ca... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# _offload_gpu_id should be set to passed gpu_id (or id in passed `device`) or default to previously set id or default to 0
self._offload_gpu_id = gpu_id or torch_device.index or getattr(self, "_offload_gpu_id", 0)
device_type = torch_device.type
device = torch.device(f"{device_type}:{self._off... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if name in self._exclude_from_cpu_offload:
model.to(device)
else:
# make sure to offload buffers if not all high level weights
# are of type nn.Module
offload_buffers = len(model._parameters) > 0
cpu_offload(model, device, offlo... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
Parameters:
pretrained_model_name (`str` or `os.PathLike`, *optional*):
A string, the *repository id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline
hosted on the Hub.
custom_pipeline (`str`, *optional*):
Can be either:
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
- A string, the *file name* of a community pipeline hosted on GitHub under
[Community](https://github.com/huggingface/diffusers/tree/main/examples/community). Valid file
names must match the file name and not the pipeline script (`clip_guided_stable_diffusion`
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
For more information on how to load and create custom pipelines, take a look at [How to contribute a
community pipeline](https://huggingface.co/docs/diffusers/main/en/using-diffusers/contribute_pipeline).
force_download (`bool`, *optional*, defaults to `False`):
Whether or n... | 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*, defaults to `"main"`):
The specific model version to use. It can be a branch name, a tag name, or a commit id similar to
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
loading `from_flax`.
dduf_file(`str`, *optional*):
Load weights from the specified DDUF file.
use_safetensors (`bool`, *optional*, defaults to `None`):
If set to `None`, the safetensors weights are downloaded if they're available **and** if the
saf... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
trust_remote_code (`bool`, *optional*, defaults to `False`):
Whether or not to allow for custom pipelines and components defined on the Hub in their own files. This
option should only be set to `True` for repositories you trust and in which you have read the code, as
it w... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
Returns:
`os.PathLike`:
A path to the downloaded pipeline.
<Tip>
To use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models), log-in with
`huggingface-cli login`.
</Tip> | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
"""
cache_dir = kwargs.pop("cache_dir", None)
force_download = kwargs.pop("force_download", False)
proxies = kwargs.pop("proxies", None)
local_files_only = kwargs.pop("local_files_only", None)
token = kwargs.pop("token", None)
revision = kwargs.pop("revision", None)
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if dduf_file:
if custom_pipeline:
raise NotImplementedError("Custom pipelines are not supported with DDUF at the moment.")
if load_connected_pipeline:
raise NotImplementedError("Connected pipelines are not supported with DDUF at the moment.")
return _d... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
model_info_call_error: Optional[Exception] = None
if not local_files_only:
try:
info = model_info(pretrained_model_name, token=token, revision=revision)
except (HTTPError, OfflineModeIsEnabled, requests.ConnectionError) as e:
logger.warning(f"Couldn't conn... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if not local_files_only:
filenames = {sibling.rfilename for sibling in info.siblings}
if variant is not None and _check_legacy_sharding_variant_format(filenames=filenames, variant=variant):
warn_msg = (
f"Warning: The repository contains sharded checkpoints fo... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
)
logger.warning(warn_msg) | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
model_filenames, variant_filenames = variant_compatible_siblings(filenames, variant=variant)
config_file = hf_hub_download(
pretrained_model_name,
cls.config_name,
cache_dir=cache_dir,
revision=revision,
proxies=proxies,
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if revision in DEPRECATED_REVISION_ARGS and version.parse(
version.parse(__version__).base_version
) >= version.parse("0.22.0"):
warn_deprecated_model_variant(pretrained_model_name, token, variant, revision, model_filenames)
custom_components, folder_names = _get... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# allow all patterns from non-model folders
# this enables downloading schedulers, tokenizers, ...
allow_patterns += [f"{k}/*" for k in folder_names if k not in model_folder_names]
# add custom component files
allow_patterns += [f"{k}/{f}.py" for k, f in custom_components... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if load_pipe_from_hub and not trust_remote_code:
raise ValueError(
f"The repository for {pretrained_model_name} contains custom code in {custom_pipeline}.py which must be executed to correctly "
f"load the model. You can inspect the repository content at https://h... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if load_components_from_hub and not trust_remote_code:
raise ValueError(
f"The repository for {pretrained_model_name} contains custom code in {'.py, '.join([os.path.join(k, v) for k,v in custom_components.items()])} which must be executed to correctly "
f"load the... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# retrieve passed components that should not be downloaded
pipeline_class = _get_pipeline_class(
cls,
config_dict,
load_connected_pipeline=load_connected_pipeline,
custom_pipeline=custom_pipeline,
repo_id=pretrained_model_name i... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# retrieve all patterns that should not be downloaded and error out when needed
ignore_patterns = _get_ignore_patterns(
passed_components,
model_folder_names,
model_filenames,
variant_filenames,
use_safetensors,
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# Don't download index files of forbidden patterns either
ignore_patterns = ignore_patterns + [f"{i}.index.*json" for i in ignore_patterns]
re_ignore_pattern = [re.compile(fnmatch.translate(p)) for p in ignore_patterns]
re_allow_pattern = [re.compile(fnmatch.translate(p)) for p in al... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
user_agent = {"pipeline_class": cls.__name__}
if custom_pipeline is not None and not custom_pipeline.endswith(".py"):
user_agent["custom_pipeline"] = custom_pipeline
# download all allow_patterns - ignore_patterns
try:
cached_folder = snapshot_download(
p... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
diffusers_module = importlib.import_module(__name__.split(".")[0])
pipeline_class = getattr(diffusers_module, cls_name, None) if isinstance(cls_name, str) else None | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if pipeline_class is not None and pipeline_class._load_connected_pipes:
modelcard = ModelCard.load(os.path.join(cached_folder, "README.md"))
connected_pipes = sum([getattr(modelcard.data, k, []) for k in CONNECTED_PIPES_KEYS], [])
for connected_pipe_repo_id in connected_p... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
except FileNotFoundError:
# Means we tried to load pipeline with `local_files_only=True` but the files have not been found in local cache.
# This can happen in two cases:
# 1. If the user passed `local_files_only=True` => we raise the error directly
# 2... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
@classmethod
def _get_signature_keys(cls, obj):
parameters = inspect.signature(obj.__init__).parameters
required_parameters = {k: v for k, v in parameters.items() if v.default == inspect._empty}
optional_parameters = set({k for k, v in parameters.items() if v.default != inspect._empty})
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
@classmethod
def _get_signature_types(cls):
signature_types = {}
for k, v in inspect.signature(cls.__init__).parameters.items():
if inspect.isclass(v.annotation):
signature_types[k] = (v.annotation,)
elif get_origin(v.annotation) == Union:
sign... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
```py
>>> from diffusers import (
... StableDiffusionPipeline,
... StableDiffusionImg2ImgPipeline,
... StableDiffusionInpaintPipeline,
... )
>>> text2img = StableDiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
>>> img2... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if set(components.keys()) != expected_modules:
raise ValueError(
f"{self} has been incorrectly initialized or {self.__class__} is incorrectly implemented. Expected"
f" {expected_modules} to be defined, but {components.keys()} are defined."
)
return compon... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if iterable is not None:
return tqdm(iterable, **self._progress_bar_config)
elif total is not None:
return tqdm(total=total, **self._progress_bar_config)
else:
raise ValueError("Either `total` or `iterable` has to be defined.")
def set_progress_bar_config(self, *... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
Parameters:
attention_op (`Callable`, *optional*):
Override the default `None` operator for use as `op` argument to the
[`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention)
fu... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape usi... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
def set_use_memory_efficient_attention_xformers(
self, valid: bool, attention_op: Optional[Callable] = None
) -> None:
# Recursively walk through all the children.
# Any children which exposes the set_use_memory_efficient_attention_xformers method
# gets the message
def fn_re... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
r"""
Enable sliced attention computation. When this option is enabled, the attention module splits the input tensor
in slices to compute attention in several steps. For more than one attention head, the computati... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
Args:
slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
`"max"`, maximum amount of memory will be saved by running only one slice at a time. If a number is
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]
```
"""
self.set_attention_slice(slice_size)
def disable_attention_slicing(self):
r"""
Disable sliced attention computation. I... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
@classmethod
def from_pipe(cls, pipeline, **kwargs):
r"""
Create a new pipeline from a given pipeline. This method is useful to create a new pipeline from the existing
pipeline components without reallocating additional memory.
Arguments:
pipeline (`DiffusionPipeline`):
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# derive the pipeline class to instantiate
custom_pipeline = kwargs.pop("custom_pipeline", None)
custom_revision = kwargs.pop("custom_revision", None)
if custom_pipeline is not None:
pipeline_class = _get_custom_pipeline_class(custom_pipeline, revision=custom_revision)
else:... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# get the class of each component based on its type hint
# e.g. {"unet": UNet2DConditionModel, "text_encoder": CLIPTextMode}
component_types = pipeline_class._get_signature_types()
pretrained_model_name_or_path = original_config.pop("_name_or_path", None)
# allow users pass modules in `... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
original_class_obj = {}
for name, component in pipeline.components.items():
if name in expected_modules and name not in passed_class_obj:
# for model components, we will not switch over if the class does not matches the type hint in the new pipeline's signature
if (
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
f" please pass the component of the correct type to the new pipeline. `from_pipe(..., {name}={name})`"
) | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# allow users pass optional kwargs to override the original pipelines config attribute
passed_pipe_kwargs = {k: kwargs.pop(k) for k in optional_kwargs if k in kwargs}
original_pipe_kwargs = {
k: original_config[k]
for k in original_config.keys()
if k in optional_kwarg... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
pipeline_kwargs = {
**passed_class_obj,
**original_class_obj,
**passed_pipe_kwargs,
**original_pipe_kwargs,
**kwargs,
}
# store unused config as private attribute in the new pipeline
unused_original_config = {
f"{'' if k.st... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
new_pipeline = pipeline_class(**pipeline_kwargs)
if pretrained_model_name_or_path is not None:
new_pipeline.register_to_config(_name_or_path=pretrained_model_name_or_path)
new_pipeline.register_to_config(**unused_original_config)
if torch_dtype is not None:
new_pipeline.... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
class StableDiffusionMixin:
r"""
Helper for DiffusionPipeline with vae and unet.(mainly for LDM such as stable diffusion)
"""
def enable_vae_slicing(self):
r"""
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
compute deco... | 40 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
def enable_vae_tiling(self):
r"""
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
processing larger images.
""... | 40 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL. | 40 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
Args:
s1 (`float`):
Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
mitigate "oversmoothing effect" in the enhanced denoising process.
s2 (`float`):
Scaling factor for stage 2 to attenuate the contrib... | 40 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
def fuse_qkv_projections(self, unet: bool = True, vae: bool = True):
"""
Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
are fused. For cross-attention modules, key and value projection matrices are fused.
<Tip warning={true}>... | 40 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
self.fusing_vae = True
self.vae.fuse_qkv_projections()
self.vae.set_attn_processor(FusedAttnProcessor2_0())
def unfuse_qkv_projections(self, unet: bool = True, vae: bool = True):
"""Disable QKV projection fusion if enabled.
<Tip warning={true}>
This API is 🧪 exper... | 40 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if vae:
if not self.fusing_vae:
logger.warning("The VAE was not initially fused for QKV projections. Doing nothing.")
else:
self.vae.unfuse_qkv_projections()
self.fusing_vae = False | 40 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
class SplitInferenceModule(nn.Module):
r"""
A wrapper module class that splits inputs along a specified dimension before performing a forward pass.
This module is useful when you need to perform inference on large tensors in a memory-efficient way by breaking
them into smaller chunks, processing each c... | 41 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_noise_utils.py |
Workflow:
1. The keyword arguments specified in `input_kwargs_to_split` are split into smaller chunks using
`torch.split()` along the dimension `split_dim` and with a chunk size of `split_size`.
2. The `module` is invoked once for each split with both the split inputs and any unchanged arguments... | 41 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_noise_utils.py |
It is also possible to nest `SplitInferenceModule` across different split dimensions for more complex
multi-dimensional splitting.
"""
def __init__(
self,
module: nn.Module,
split_size: int = 1,
split_dim: int = 0,
input_kwargs_to_split: List[str] = ["hidden_states"]... | 41 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_noise_utils.py |
Args:
*args (`Any`):
Positional arguments that are passed directly to the `module` without modification.
**kwargs (`Dict[str, torch.Tensor]`):
Keyword arguments passed to the underlying `module`. Only keyword arguments whose names match the
entries... | 41 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_noise_utils.py |
Returns:
`Union[torch.Tensor, Tuple[torch.Tensor]]`:
The outputs obtained from `SplitInferenceModule` are the same as if the underlying module was inferred
without it.
- If the underlying module returns a single tensor, the result will be a single concatenated... | 41 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_noise_utils.py |
# 1. Split inputs that were specified during initialization and also present in passed kwargs
for key in list(kwargs.keys()):
if key not in self.input_kwargs_to_split or not torch.is_tensor(kwargs[key]):
continue
split_inputs[key] = torch.split(kwargs[key], self.split_siz... | 41 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_noise_utils.py |
# 3. Concatenate split restuls to obtain final outputs
if isinstance(results[0], torch.Tensor):
return torch.cat(results, dim=self.split_dim)
elif isinstance(results[0], tuple):
return tuple([torch.cat(x, dim=self.split_dim) for x in zip(*results)])
else:
rais... | 41 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_noise_utils.py |
class AnimateDiffFreeNoiseMixin:
r"""Mixin class for [FreeNoise](https://arxiv.org/abs/2310.15169)."""
def _enable_free_noise_in_block(self, block: Union[CrossAttnDownBlockMotion, DownBlockMotion, UpBlockMotion]):
r"""Helper function to enable FreeNoise in transformer blocks."""
for motion_mod... | 42 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_noise_utils.py |
for i in range(num_transformer_blocks):
if isinstance(motion_module.transformer_blocks[i], FreeNoiseTransformerBlock):
motion_module.transformer_blocks[i].set_free_noise_properties(
self._free_noise_context_length,
self._free_noise_cont... | 42 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_noise_utils.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.