From b5673641117378a350d2567b2d4e2e522e781fd3 Mon Sep 17 00:00:00 2001 From: Anatoly Belikov Date: Fri, 31 May 2024 09:53:09 +0300 Subject: [PATCH] pydoc-generated documentation --- docs/generated/multigen.html | 30 + docs/generated/multigen.hypernet.html | 2019 +++++++++++++++++ docs/generated/multigen.loader.html | 82 + ...lines.masked_stable_diffusion_img2img.html | 1582 +++++++++++++ ...es.masked_stable_diffusion_xl_img2img.html | 1588 +++++++++++++ docs/generated/multigen.pipes.html | 807 +++++++ docs/generated/multigen.prompting.html | 71 + docs/generated/multigen.sessions.html | 97 + docs/generated/multigen.util.html | 30 + docs/generated/multigen.worker.html | 216 ++ docs/generated/multigen.worker_base.html | 221 ++ 11 files changed, 6743 insertions(+) create mode 100644 docs/generated/multigen.html create mode 100644 docs/generated/multigen.hypernet.html create mode 100644 docs/generated/multigen.loader.html create mode 100644 docs/generated/multigen.pipelines.masked_stable_diffusion_img2img.html create mode 100644 docs/generated/multigen.pipelines.masked_stable_diffusion_xl_img2img.html create mode 100644 docs/generated/multigen.pipes.html create mode 100644 docs/generated/multigen.prompting.html create mode 100644 docs/generated/multigen.sessions.html create mode 100644 docs/generated/multigen.util.html create mode 100644 docs/generated/multigen.worker.html create mode 100644 docs/generated/multigen.worker_base.html diff --git a/docs/generated/multigen.html b/docs/generated/multigen.html new file mode 100644 index 0000000..eb9d0de --- /dev/null +++ b/docs/generated/multigen.html @@ -0,0 +1,30 @@ + +Python: package multigen + + + + + +
 
+ 
multigen
index
/home/imgen/projects/metafusion/multigen/__init__.py
+

+

+ + + + + +
 
+Package Contents
       
hypernet
+loader
+pipelines (package)
+
pipes
+prompting
+sessions
+
util
+worker
+worker_base
+
+ \ No newline at end of file diff --git a/docs/generated/multigen.hypernet.html b/docs/generated/multigen.hypernet.html new file mode 100644 index 0000000..2d2ee17 --- /dev/null +++ b/docs/generated/multigen.hypernet.html @@ -0,0 +1,2019 @@ + +Python: module multigen.hypernet + + + + + +
 
+ 
multigen.hypernet
index
/home/imgen/projects/metafusion/multigen/hypernet.py
+

+

+ + + + + +
 
+Modules
       
torch.nn.functional
+diffusers
+
inspect
+torch.nn
+
os
+torch
+

+ + + + + +
 
+Classes
       
+
builtins.object +
+
+
Hypernetwork +
+
+
torch.nn.modules.module.Module(builtins.object) +
+
+
HyperAttnProcessor +
HypernetworkModule +
+
+
+

+ + + + + + + +
 
+class HyperAttnProcessor(torch.nn.modules.module.Module)
   HyperAttnProcessor(hypernets=[])

+Processor for implementing the hypernet attention mechanism.

+Args:
+    hypernets (`list`, *optional*):
+        List of hypernetworks to use
 
 
Method resolution order:
+
HyperAttnProcessor
+
torch.nn.modules.module.Module
+
builtins.object
+
+
+Methods defined here:
+
__call__(self, attn: diffusers.models.attention_processor.Attention, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None)
Call self as a function.
+ +
__init__(self, hypernets=[])
Initialize internal Module state, shared by both nn.Module and ScriptModule.
+ +
+Data and other attributes defined here:
+
__annotations__ = {}
+ +
+Methods inherited from torch.nn.modules.module.Module:
+
__delattr__(self, name)
Implement delattr(self, name).
+ +
__dir__(self)
Default dir() implementation.
+ +
__getattr__(self, name: str) -> Any
# On the return type:
+# We choose to return `Any` in the `__getattr__` type signature instead of a more strict `Union[Tensor, Module]`.
+# This is done for better interop with various type checkers for the end users.
+# Having a stricter return type doesn't play nicely with `register_buffer()` and forces
+# people to excessively use type-ignores, asserts, casts, etc.
+# See full discussion on the problems with returning `Union` here
+# https://github.com/microsoft/pyright/issues/4213
+ +
__getstate__(self)
+ +
__repr__(self)
Return repr(self).
+ +
__setattr__(self, name: str, value: Union[torch.Tensor, ForwardRef('Module')]) -> None
Implement setattr(self, name, value).
+ +
__setstate__(self, state)
+ +
add_module(self, name: str, module: Optional[ForwardRef('Module')]) -> None
Add a child module to the current module.

+The module can be accessed as an attribute using the given name.

+Args:
+    name (str): name of the child module. The child module can be
+        accessed from this module using the given name
+    module (Module): child module to be added to the module.
+ +
apply(self: ~T, fn: Callable[[ForwardRef('Module')], NoneType]) -> ~T
Apply ``fn`` recursively to every submodule (as returned by ``.children()``) as well as self.

+Typical use includes initializing the parameters of a model
+(see also :ref:`nn-init-doc`).

+Args:
+    fn (:class:`Module` -> None): function to be applied to each submodule

+Returns:
+    Module: self

+Example::

+    >>> @torch.no_grad()
+    >>> def init_weights(m):
+    >>>     print(m)
+    >>>     if type(m) == nn.Linear:
+    >>>         m.weight.fill_(1.0)
+    >>>         print(m.weight)
+    >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
+    >>> net.apply(init_weights)
+    Linear(in_features=2, out_features=2, bias=True)
+    Parameter containing:
+    tensor([[1., 1.],
+            [1., 1.]], requires_grad=True)
+    Linear(in_features=2, out_features=2, bias=True)
+    Parameter containing:
+    tensor([[1., 1.],
+            [1., 1.]], requires_grad=True)
+    Sequential(
+      (0): Linear(in_features=2, out_features=2, bias=True)
+      (1): Linear(in_features=2, out_features=2, bias=True)
+    )
+ +
bfloat16(self: ~T) -> ~T
Casts all floating point parameters and buffers to ``bfloat16`` datatype.

+.. note::
+    This method modifies the module in-place.

+Returns:
+    Module: self
+ +
buffers(self, recurse: bool = True) -> Iterator[torch.Tensor]
Return an iterator over module buffers.

+Args:
+    recurse (bool): if True, then yields buffers of this module
+        and all submodules. Otherwise, yields only buffers that
+        are direct members of this module.

+Yields:
+    torch.Tensor: module buffer

+Example::

+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> for buf in model.buffers():
+    >>>     print(type(buf), buf.size())
+    <class 'torch.Tensor'> (20L,)
+    <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
+ +
children(self) -> Iterator[ForwardRef('Module')]
Return an iterator over immediate children modules.

+Yields:
+    Module: a child module
+ +
compile(self, *args, **kwargs)
Compile this Module's forward using :func:`torch.compile`.

+This Module's `__call__` method is compiled and all arguments are passed as-is
+to :func:`torch.compile`.

+See :func:`torch.compile` for details on the arguments for this function.
+ +
cpu(self: ~T) -> ~T
Move all model parameters and buffers to the CPU.

+.. note::
+    This method modifies the module in-place.

+Returns:
+    Module: self
+ +
cuda(self: ~T, device: Union[int, torch.device, NoneType] = None) -> ~T
Move all model parameters and buffers to the GPU.

+This also makes associated parameters and buffers different objects. So
+it should be called before constructing optimizer if the module will
+live on GPU while being optimized.

+.. note::
+    This method modifies the module in-place.

+Args:
+    device (int, optional): if specified, all parameters will be
+        copied to that device

+Returns:
+    Module: self
+ +
double(self: ~T) -> ~T
Casts all floating point parameters and buffers to ``double`` datatype.

+.. note::
+    This method modifies the module in-place.

+Returns:
+    Module: self
+ +
eval(self: ~T) -> ~T
Set the module in evaluation mode.

+This has any effect only on certain modules. See documentations of
+particular modules for details of their behaviors in training/evaluation
+mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
+etc.

+This is equivalent with :meth:`self.train(False) <torch.nn.Module.train>`.

+See :ref:`locally-disable-grad-doc` for a comparison between
+`.eval()` and several similar mechanisms that may be confused with it.

+Returns:
+    Module: self
+ +
extra_repr(self) -> str
Set the extra representation of the module.

+To print customized extra information, you should re-implement
+this method in your own modules. Both single-line and multi-line
+strings are acceptable.
+ +
float(self: ~T) -> ~T
Casts all floating point parameters and buffers to ``float`` datatype.

+.. note::
+    This method modifies the module in-place.

+Returns:
+    Module: self
+ +
forward = _forward_unimplemented(self, *input: Any) -> None
Define the computation performed at every call.

+Should be overridden by all subclasses.

+.. note::
+    Although the recipe for forward pass needs to be defined within
+    this function, one should call the :class:`Module` instance afterwards
+    instead of this since the former takes care of running the
+    registered hooks while the latter silently ignores them.
+ +
get_buffer(self, target: str) -> 'Tensor'
Return the buffer given by ``target`` if it exists, otherwise throw an error.

+See the docstring for ``get_submodule`` for a more detailed
+explanation of this method's functionality as well as how to
+correctly specify ``target``.

+Args:
+    target: The fully-qualified string name of the buffer
+        to look for. (See ``get_submodule`` for how to specify a
+        fully-qualified string.)

+Returns:
+    torch.Tensor: The buffer referenced by ``target``

+Raises:
+    AttributeError: If the target string references an invalid
+        path or resolves to something that is not a
+        buffer
+ +
get_extra_state(self) -> Any
Return any extra state to include in the module's state_dict.

+Implement this and a corresponding :func:`set_extra_state` for your module
+if you need to store extra state. This function is called when building the
+module's `state_dict()`.

+Note that extra state should be picklable to ensure working serialization
+of the state_dict. We only provide provide backwards compatibility guarantees
+for serializing Tensors; other objects may break backwards compatibility if
+their serialized pickled form changes.

+Returns:
+    object: Any extra state to store in the module's state_dict
+ +
get_parameter(self, target: str) -> 'Parameter'
Return the parameter given by ``target`` if it exists, otherwise throw an error.

+See the docstring for ``get_submodule`` for a more detailed
+explanation of this method's functionality as well as how to
+correctly specify ``target``.

+Args:
+    target: The fully-qualified string name of the Parameter
+        to look for. (See ``get_submodule`` for how to specify a
+        fully-qualified string.)

+Returns:
+    torch.nn.Parameter: The Parameter referenced by ``target``

+Raises:
+    AttributeError: If the target string references an invalid
+        path or resolves to something that is not an
+        ``nn.Parameter``
+ +
get_submodule(self, target: str) -> 'Module'
Return the submodule given by ``target`` if it exists, otherwise throw an error.

+For example, let's say you have an ``nn.Module`` ``A`` that
+looks like this:

+.. code-block:: text

+    A(
+        (net_b): Module(
+            (net_c): Module(
+                (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2))
+            )
+            (linear): Linear(in_features=100, out_features=200, bias=True)
+        )
+    )

+(The diagram shows an ``nn.Module`` ``A``. ``A`` has a nested
+submodule ``net_b``, which itself has two submodules ``net_c``
+and ``linear``. ``net_c`` then has a submodule ``conv``.)

+To check whether or not we have the ``linear`` submodule, we
+would call ``get_submodule("net_b.linear")``. To check whether
+we have the ``conv`` submodule, we would call
+``get_submodule("net_b.net_c.conv")``.

+The runtime of ``get_submodule`` is bounded by the degree
+of module nesting in ``target``. A query against
+``named_modules`` achieves the same result, but it is O(N) in
+the number of transitive modules. So, for a simple check to see
+if some submodule exists, ``get_submodule`` should always be
+used.

+Args:
+    target: The fully-qualified string name of the submodule
+        to look for. (See above example for how to specify a
+        fully-qualified string.)

+Returns:
+    torch.nn.Module: The submodule referenced by ``target``

+Raises:
+    AttributeError: If the target string references an invalid
+        path or resolves to something that is not an
+        ``nn.Module``
+ +
half(self: ~T) -> ~T
Casts all floating point parameters and buffers to ``half`` datatype.

+.. note::
+    This method modifies the module in-place.

+Returns:
+    Module: self
+ +
ipu(self: ~T, device: Union[int, torch.device, NoneType] = None) -> ~T
Move all model parameters and buffers to the IPU.

+This also makes associated parameters and buffers different objects. So
+it should be called before constructing optimizer if the module will
+live on IPU while being optimized.

+.. note::
+    This method modifies the module in-place.

+Arguments:
+    device (int, optional): if specified, all parameters will be
+        copied to that device

+Returns:
+    Module: self
+ +
load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from :attr:`state_dict` into this module and its descendants.

+If :attr:`strict` is ``True``, then
+the keys of :attr:`state_dict` must exactly match the keys returned
+by this module's :meth:`~torch.nn.Module.state_dict` function.

+.. warning::
+    If :attr:`assign` is ``True`` the optimizer must be created after
+    the call to :attr:`load_state_dict` unless
+    :func:`~torch.__future__.get_swap_module_params_on_conversion` is ``True``.

+Args:
+    state_dict (dict): a dict containing parameters and
+        persistent buffers.
+    strict (bool, optional): whether to strictly enforce that the keys
+        in :attr:`state_dict` match the keys returned by this module's
+        :meth:`~torch.nn.Module.state_dict` function. Default: ``True``
+    assign (bool, optional): When ``False``, the properties of the tensors
+        in the current module are preserved while when ``True``, the
+        properties of the Tensors in the state dict are preserved. The only
+        exception is the ``requires_grad`` field of :class:`~torch.nn.Parameter`s
+        for which the value from the module is preserved.
+        Default: ``False``

+Returns:
+    ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
+        * **missing_keys** is a list of str containing the missing keys
+        * **unexpected_keys** is a list of str containing the unexpected keys

+Note:
+    If a parameter or buffer is registered as ``None`` and its corresponding key
+    exists in :attr:`state_dict`, :meth:`load_state_dict` will raise a
+    ``RuntimeError``.
+ +
modules(self) -> Iterator[ForwardRef('Module')]
Return an iterator over all modules in the network.

+Yields:
+    Module: a module in the network

+Note:
+    Duplicate modules are returned only once. In the following
+    example, ``l`` will be returned only once.

+Example::

+    >>> l = nn.Linear(2, 2)
+    >>> net = nn.Sequential(l, l)
+    >>> for idx, m in enumerate(net.modules()):
+    ...     print(idx, '->', m)

+    0 -> Sequential(
+      (0): Linear(in_features=2, out_features=2, bias=True)
+      (1): Linear(in_features=2, out_features=2, bias=True)
+    )
+    1 -> Linear(in_features=2, out_features=2, bias=True)
+ +
named_buffers(self, prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) -> Iterator[Tuple[str, torch.Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

+Args:
+    prefix (str): prefix to prepend to all buffer names.
+    recurse (bool, optional): if True, then yields buffers of this module
+        and all submodules. Otherwise, yields only buffers that
+        are direct members of this module. Defaults to True.
+    remove_duplicate (bool, optional): whether to remove the duplicated buffers in the result. Defaults to True.

+Yields:
+    (str, torch.Tensor): Tuple containing the name and buffer

+Example::

+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> for name, buf in self.named_buffers():
+    >>>     if name in ['running_var']:
+    >>>         print(buf.size())
+ +
named_children(self) -> Iterator[Tuple[str, ForwardRef('Module')]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

+Yields:
+    (str, Module): Tuple containing a name and child module

+Example::

+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> for name, module in model.named_children():
+    >>>     if name in ['conv4', 'conv5']:
+    >>>         print(module)
+ +
named_modules(self, memo: Optional[Set[ForwardRef('Module')]] = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

+Args:
+    memo: a memo to store the set of modules already added to the result
+    prefix: a prefix that will be added to the name of the module
+    remove_duplicate: whether to remove the duplicated module instances in the result
+        or not

+Yields:
+    (str, Module): Tuple of name and module

+Note:
+    Duplicate modules are returned only once. In the following
+    example, ``l`` will be returned only once.

+Example::

+    >>> l = nn.Linear(2, 2)
+    >>> net = nn.Sequential(l, l)
+    >>> for idx, m in enumerate(net.named_modules()):
+    ...     print(idx, '->', m)

+    0 -> ('', Sequential(
+      (0): Linear(in_features=2, out_features=2, bias=True)
+      (1): Linear(in_features=2, out_features=2, bias=True)
+    ))
+    1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
+ +
named_parameters(self, prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) -> Iterator[Tuple[str, torch.nn.parameter.Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

+Args:
+    prefix (str): prefix to prepend to all parameter names.
+    recurse (bool): if True, then yields parameters of this module
+        and all submodules. Otherwise, yields only parameters that
+        are direct members of this module.
+    remove_duplicate (bool, optional): whether to remove the duplicated
+        parameters in the result. Defaults to True.

+Yields:
+    (str, Parameter): Tuple containing the name and parameter

+Example::

+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> for name, param in self.named_parameters():
+    >>>     if name in ['bias']:
+    >>>         print(param.size())
+ +
parameters(self, recurse: bool = True) -> Iterator[torch.nn.parameter.Parameter]
Return an iterator over module parameters.

+This is typically passed to an optimizer.

+Args:
+    recurse (bool): if True, then yields parameters of this module
+        and all submodules. Otherwise, yields only parameters that
+        are direct members of this module.

+Yields:
+    Parameter: module parameter

+Example::

+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> for param in model.parameters():
+    >>>     print(type(param), param.size())
+    <class 'torch.Tensor'> (20L,)
+    <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
+ +
register_backward_hook(self, hook: Callable[[ForwardRef('Module'), Union[Tuple[torch.Tensor, ...], torch.Tensor], Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[NoneType, Tuple[torch.Tensor, ...], torch.Tensor]]) -> torch.utils.hooks.RemovableHandle
Register a backward hook on the module.

+This function is deprecated in favor of :meth:`~torch.nn.Module.register_full_backward_hook` and
+the behavior of this function will change in future versions.

+Returns:
+    :class:`torch.utils.hooks.RemovableHandle`:
+        a handle that can be used to remove the added hook by calling
+        ``handle.remove()``
+ +
register_buffer(self, name: str, tensor: Optional[torch.Tensor], persistent: bool = True) -> None
Add a buffer to the module.

+This is typically used to register a buffer that should not to be
+considered a model parameter. For example, BatchNorm's ``running_mean``
+is not a parameter, but is part of the module's state. Buffers, by
+default, are persistent and will be saved alongside parameters. This
+behavior can be changed by setting :attr:`persistent` to ``False``. The
+only difference between a persistent buffer and a non-persistent buffer
+is that the latter will not be a part of this module's
+:attr:`state_dict`.

+Buffers can be accessed as attributes using given names.

+Args:
+    name (str): name of the buffer. The buffer can be accessed
+        from this module using the given name
+    tensor (Tensor or None): buffer to be registered. If ``None``, then operations
+        that run on buffers, such as :attr:`cuda`, are ignored. If ``None``,
+        the buffer is **not** included in the module's :attr:`state_dict`.
+    persistent (bool): whether the buffer is part of this module's
+        :attr:`state_dict`.

+Example::

+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> self.register_buffer('running_mean', torch.zeros(num_features))
+ +
register_forward_hook(self, hook: Union[Callable[[~T, Tuple[Any, ...], Any], Optional[Any]], Callable[[~T, Tuple[Any, ...], Dict[str, Any], Any], Optional[Any]]], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) -> torch.utils.hooks.RemovableHandle
Register a forward hook on the module.

+The hook will be called every time after :func:`forward` has computed an output.

+If ``with_kwargs`` is ``False`` or not specified, the input contains only
+the positional arguments given to the module. Keyword arguments won't be
+passed to the hooks and only to the ``forward``. The hook can modify the
+output. It can modify the input inplace but it will not have effect on
+forward since this is called after :func:`forward` is called. The hook
+should have the following signature::

+    hook(module, args, output) -> None or modified output

+If ``with_kwargs`` is ``True``, the forward hook will be passed the
+``kwargs`` given to the forward function and be expected to return the
+output possibly modified. The hook should have the following signature::

+    hook(module, args, kwargs, output) -> None or modified output

+Args:
+    hook (Callable): The user defined hook to be registered.
+    prepend (bool): If ``True``, the provided ``hook`` will be fired
+        before all existing ``forward`` hooks on this
+        :class:`torch.nn.modules.Module`. Otherwise, the provided
+        ``hook`` will be fired after all existing ``forward`` hooks on
+        this :class:`torch.nn.modules.Module`. Note that global
+        ``forward`` hooks registered with
+        :func:`register_module_forward_hook` will fire before all hooks
+        registered by this method.
+        Default: ``False``
+    with_kwargs (bool): If ``True``, the ``hook`` will be passed the
+        kwargs given to the forward function.
+        Default: ``False``
+    always_call (bool): If ``True`` the ``hook`` will be run regardless of
+        whether an exception is raised while calling the Module.
+        Default: ``False``

+Returns:
+    :class:`torch.utils.hooks.RemovableHandle`:
+        a handle that can be used to remove the added hook by calling
+        ``handle.remove()``
+ +
register_forward_pre_hook(self, hook: Union[Callable[[~T, Tuple[Any, ...]], Optional[Any]], Callable[[~T, Tuple[Any, ...], Dict[str, Any]], Optional[Tuple[Any, Dict[str, Any]]]]], *, prepend: bool = False, with_kwargs: bool = False) -> torch.utils.hooks.RemovableHandle
Register a forward pre-hook on the module.

+The hook will be called every time before :func:`forward` is invoked.


+If ``with_kwargs`` is false or not specified, the input contains only
+the positional arguments given to the module. Keyword arguments won't be
+passed to the hooks and only to the ``forward``. The hook can modify the
+input. User can either return a tuple or a single modified value in the
+hook. We will wrap the value into a tuple if a single value is returned
+(unless that value is already a tuple). The hook should have the
+following signature::

+    hook(module, args) -> None or modified input

+If ``with_kwargs`` is true, the forward pre-hook will be passed the
+kwargs given to the forward function. And if the hook modifies the
+input, both the args and kwargs should be returned. The hook should have
+the following signature::

+    hook(module, args, kwargs) -> None or a tuple of modified input and kwargs

+Args:
+    hook (Callable): The user defined hook to be registered.
+    prepend (bool): If true, the provided ``hook`` will be fired before
+        all existing ``forward_pre`` hooks on this
+        :class:`torch.nn.modules.Module`. Otherwise, the provided
+        ``hook`` will be fired after all existing ``forward_pre`` hooks
+        on this :class:`torch.nn.modules.Module`. Note that global
+        ``forward_pre`` hooks registered with
+        :func:`register_module_forward_pre_hook` will fire before all
+        hooks registered by this method.
+        Default: ``False``
+    with_kwargs (bool): If true, the ``hook`` will be passed the kwargs
+        given to the forward function.
+        Default: ``False``

+Returns:
+    :class:`torch.utils.hooks.RemovableHandle`:
+        a handle that can be used to remove the added hook by calling
+        ``handle.remove()``
+ +
register_full_backward_hook(self, hook: Callable[[ForwardRef('Module'), Union[Tuple[torch.Tensor, ...], torch.Tensor], Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[NoneType, Tuple[torch.Tensor, ...], torch.Tensor]], prepend: bool = False) -> torch.utils.hooks.RemovableHandle
Register a backward hook on the module.

+The hook will be called every time the gradients with respect to a module
+are computed, i.e. the hook will execute if and only if the gradients with
+respect to module outputs are computed. The hook should have the following
+signature::

+    hook(module, grad_input, grad_output) -> tuple(Tensor) or None

+The :attr:`grad_input` and :attr:`grad_output` are tuples that contain the gradients
+with respect to the inputs and outputs respectively. The hook should
+not modify its arguments, but it can optionally return a new gradient with
+respect to the input that will be used in place of :attr:`grad_input` in
+subsequent computations. :attr:`grad_input` will only correspond to the inputs given
+as positional arguments and all kwarg arguments are ignored. Entries
+in :attr:`grad_input` and :attr:`grad_output` will be ``None`` for all non-Tensor
+arguments.

+For technical reasons, when this hook is applied to a Module, its forward function will
+receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
+of each Tensor returned by the Module's forward function.

+.. warning ::
+    Modifying inputs or outputs inplace is not allowed when using backward hooks and
+    will raise an error.

+Args:
+    hook (Callable): The user-defined hook to be registered.
+    prepend (bool): If true, the provided ``hook`` will be fired before
+        all existing ``backward`` hooks on this
+        :class:`torch.nn.modules.Module`. Otherwise, the provided
+        ``hook`` will be fired after all existing ``backward`` hooks on
+        this :class:`torch.nn.modules.Module`. Note that global
+        ``backward`` hooks registered with
+        :func:`register_module_full_backward_hook` will fire before
+        all hooks registered by this method.

+Returns:
+    :class:`torch.utils.hooks.RemovableHandle`:
+        a handle that can be used to remove the added hook by calling
+        ``handle.remove()``
+ +
register_full_backward_pre_hook(self, hook: Callable[[ForwardRef('Module'), Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[NoneType, Tuple[torch.Tensor, ...], torch.Tensor]], prepend: bool = False) -> torch.utils.hooks.RemovableHandle
Register a backward pre-hook on the module.

+The hook will be called every time the gradients for the module are computed.
+The hook should have the following signature::

+    hook(module, grad_output) -> tuple[Tensor] or None

+The :attr:`grad_output` is a tuple. The hook should
+not modify its arguments, but it can optionally return a new gradient with
+respect to the output that will be used in place of :attr:`grad_output` in
+subsequent computations. Entries in :attr:`grad_output` will be ``None`` for
+all non-Tensor arguments.

+For technical reasons, when this hook is applied to a Module, its forward function will
+receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
+of each Tensor returned by the Module's forward function.

+.. warning ::
+    Modifying inputs inplace is not allowed when using backward hooks and
+    will raise an error.

+Args:
+    hook (Callable): The user-defined hook to be registered.
+    prepend (bool): If true, the provided ``hook`` will be fired before
+        all existing ``backward_pre`` hooks on this
+        :class:`torch.nn.modules.Module`. Otherwise, the provided
+        ``hook`` will be fired after all existing ``backward_pre`` hooks
+        on this :class:`torch.nn.modules.Module`. Note that global
+        ``backward_pre`` hooks registered with
+        :func:`register_module_full_backward_pre_hook` will fire before
+        all hooks registered by this method.

+Returns:
+    :class:`torch.utils.hooks.RemovableHandle`:
+        a handle that can be used to remove the added hook by calling
+        ``handle.remove()``
+ +
register_load_state_dict_post_hook(self, hook)
Register a post hook to be run after module's ``load_state_dict`` is called.

+It should have the following signature::
+    hook(module, incompatible_keys) -> None

+The ``module`` argument is the current module that this hook is registered
+on, and the ``incompatible_keys`` argument is a ``NamedTuple`` consisting
+of attributes ``missing_keys`` and ``unexpected_keys``. ``missing_keys``
+is a ``list`` of ``str`` containing the missing keys and
+``unexpected_keys`` is a ``list`` of ``str`` containing the unexpected keys.

+The given incompatible_keys can be modified inplace if needed.

+Note that the checks performed when calling :func:`load_state_dict` with
+``strict=True`` are affected by modifications the hook makes to
+``missing_keys`` or ``unexpected_keys``, as expected. Additions to either
+set of keys will result in an error being thrown when ``strict=True``, and
+clearing out both missing and unexpected keys will avoid an error.

+Returns:
+    :class:`torch.utils.hooks.RemovableHandle`:
+        a handle that can be used to remove the added hook by calling
+        ``handle.remove()``
+ +
register_module(self, name: str, module: Optional[ForwardRef('Module')]) -> None
Alias for :func:`add_module`.
+ +
register_parameter(self, name: str, param: Optional[torch.nn.parameter.Parameter]) -> None
Add a parameter to the module.

+The parameter can be accessed as an attribute using given name.

+Args:
+    name (str): name of the parameter. The parameter can be accessed
+        from this module using the given name
+    param (Parameter or None): parameter to be added to the module. If
+        ``None``, then operations that run on parameters, such as :attr:`cuda`,
+        are ignored. If ``None``, the parameter is **not** included in the
+        module's :attr:`state_dict`.
+ +
register_state_dict_pre_hook(self, hook)
Register a pre-hook for the :meth:`~torch.nn.Module.state_dict` method.

+These hooks will be called with arguments: ``self``, ``prefix``,
+and ``keep_vars`` before calling ``state_dict`` on ``self``. The registered
+hooks can be used to perform pre-processing before the ``state_dict``
+call is made.
+ +
requires_grad_(self: ~T, requires_grad: bool = True) -> ~T
Change if autograd should record operations on parameters in this module.

+This method sets the parameters' :attr:`requires_grad` attributes
+in-place.

+This method is helpful for freezing part of the module for finetuning
+or training parts of a model individually (e.g., GAN training).

+See :ref:`locally-disable-grad-doc` for a comparison between
+`.requires_grad_()` and several similar mechanisms that may be confused with it.

+Args:
+    requires_grad (bool): whether autograd should record operations on
+                          parameters in this module. Default: ``True``.

+Returns:
+    Module: self
+ +
set_extra_state(self, state: Any) -> None
Set extra state contained in the loaded `state_dict`.

+This function is called from :func:`load_state_dict` to handle any extra state
+found within the `state_dict`. Implement this function and a corresponding
+:func:`get_extra_state` for your module if you need to store extra state within its
+`state_dict`.

+Args:
+    state (dict): Extra state from the `state_dict`
+ +
share_memory(self: ~T) -> ~T
See :meth:`torch.Tensor.share_memory_`.
+ +
state_dict(self, *args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.

+Both parameters and persistent buffers (e.g. running averages) are
+included. Keys are corresponding parameter and buffer names.
+Parameters and buffers set to ``None`` are not included.

+.. note::
+    The returned object is a shallow copy. It contains references
+    to the module's parameters and buffers.

+.. warning::
+    Currently ``state_dict()`` also accepts positional arguments for
+    ``destination``, ``prefix`` and ``keep_vars`` in order. However,
+    this is being deprecated and keyword arguments will be enforced in
+    future releases.

+.. warning::
+    Please avoid the use of argument ``destination`` as it is not
+    designed for end-users.

+Args:
+    destination (dict, optional): If provided, the state of module will
+        be updated into the dict and the same object is returned.
+        Otherwise, an ``OrderedDict`` will be created and returned.
+        Default: ``None``.
+    prefix (str, optional): a prefix added to parameter and buffer
+        names to compose the keys in state_dict. Default: ``''``.
+    keep_vars (bool, optional): by default the :class:`~torch.Tensor` s
+        returned in the state dict are detached from autograd. If it's
+        set to ``True``, detaching will not be performed.
+        Default: ``False``.

+Returns:
+    dict:
+        a dictionary containing a whole state of the module

+Example::

+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> module.state_dict().keys()
+    ['bias', 'weight']
+ +
to(self, *args, **kwargs)
Move and/or cast the parameters and buffers.

+This can be called as

+.. function:: to(device=None, dtype=None, non_blocking=False)
+   :noindex:

+.. function:: to(dtype, non_blocking=False)
+   :noindex:

+.. function:: to(tensor, non_blocking=False)
+   :noindex:

+.. function:: to(memory_format=torch.channels_last)
+   :noindex:

+Its signature is similar to :meth:`torch.Tensor.to`, but only accepts
+floating point or complex :attr:`dtype`\ s. In addition, this method will
+only cast the floating point or complex parameters and buffers to :attr:`dtype`
+(if given). The integral parameters and buffers will be moved
+:attr:`device`, if that is given, but with dtypes unchanged. When
+:attr:`non_blocking` is set, it tries to convert/move asynchronously
+with respect to the host if possible, e.g., moving CPU Tensors with
+pinned memory to CUDA devices.

+See below for examples.

+.. note::
+    This method modifies the module in-place.

+Args:
+    device (:class:`torch.device`): the desired device of the parameters
+        and buffers in this module
+    dtype (:class:`torch.dtype`): the desired floating point or complex dtype of
+        the parameters and buffers in this module
+    tensor (torch.Tensor): Tensor whose dtype and device are the desired
+        dtype and device for all parameters and buffers in this module
+    memory_format (:class:`torch.memory_format`): the desired memory
+        format for 4D parameters and buffers in this module (keyword
+        only argument)

+Returns:
+    Module: self

+Examples::

+    >>> # xdoctest: +IGNORE_WANT("non-deterministic")
+    >>> linear = nn.Linear(2, 2)
+    >>> linear.weight
+    Parameter containing:
+    tensor([[ 0.1913, -0.3420],
+            [-0.5113, -0.2325]])
+    >>> linear.to(torch.double)
+    Linear(in_features=2, out_features=2, bias=True)
+    >>> linear.weight
+    Parameter containing:
+    tensor([[ 0.1913, -0.3420],
+            [-0.5113, -0.2325]], dtype=torch.float64)
+    >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1)
+    >>> gpu1 = torch.device("cuda:1")
+    >>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
+    Linear(in_features=2, out_features=2, bias=True)
+    >>> linear.weight
+    Parameter containing:
+    tensor([[ 0.1914, -0.3420],
+            [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
+    >>> cpu = torch.device("cpu")
+    >>> linear.to(cpu)
+    Linear(in_features=2, out_features=2, bias=True)
+    >>> linear.weight
+    Parameter containing:
+    tensor([[ 0.1914, -0.3420],
+            [-0.5112, -0.2324]], dtype=torch.float16)

+    >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
+    >>> linear.weight
+    Parameter containing:
+    tensor([[ 0.3741+0.j,  0.2382+0.j],
+            [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
+    >>> linear(torch.ones(3, 2, dtype=torch.cdouble))
+    tensor([[0.6122+0.j, 0.1150+0.j],
+            [0.6122+0.j, 0.1150+0.j],
+            [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
+ +
to_empty(self: ~T, *, device: Union[int, str, torch.device, NoneType], recurse: bool = True) -> ~T
Move the parameters and buffers to the specified device without copying storage.

+Args:
+    device (:class:`torch.device`): The desired device of the parameters
+        and buffers in this module.
+    recurse (bool): Whether parameters and buffers of submodules should
+        be recursively moved to the specified device.

+Returns:
+    Module: self
+ +
train(self: ~T, mode: bool = True) -> ~T
Set the module in training mode.

+This has any effect only on certain modules. See documentations of
+particular modules for details of their behaviors in training/evaluation
+mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
+etc.

+Args:
+    mode (bool): whether to set training mode (``True``) or evaluation
+                 mode (``False``). Default: ``True``.

+Returns:
+    Module: self
+ +
type(self: ~T, dst_type: Union[torch.dtype, str]) -> ~T
Casts all parameters and buffers to :attr:`dst_type`.

+.. note::
+    This method modifies the module in-place.

+Args:
+    dst_type (type or string): the desired type

+Returns:
+    Module: self
+ +
xpu(self: ~T, device: Union[int, torch.device, NoneType] = None) -> ~T
Move all model parameters and buffers to the XPU.

+This also makes associated parameters and buffers different objects. So
+it should be called before constructing optimizer if the module will
+live on XPU while being optimized.

+.. note::
+    This method modifies the module in-place.

+Arguments:
+    device (int, optional): if specified, all parameters will be
+        copied to that device

+Returns:
+    Module: self
+ +
zero_grad(self, set_to_none: bool = True) -> None
Reset gradients of all model parameters.

+See similar function under :class:`torch.optim.Optimizer` for more context.

+Args:
+    set_to_none (bool): instead of setting to zero, set the grads to None.
+        See :meth:`torch.optim.Optimizer.zero_grad` for details.
+ +
+Data descriptors inherited from torch.nn.modules.module.Module:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+
+Data and other attributes inherited from torch.nn.modules.module.Module:
+
T_destination = ~T_destination
+ +
call_super_init = False
+ +
dump_patches = False
+ +

+ + + + + + + +
 
+class Hypernetwork(builtins.object)
   Hypernetwork(name=None, enable_sizes=None, layer_structure=None, activation_func=None, weight_init=None, add_layer_norm=False, use_dropout=False, activate_output=False, **kwargs)

+
 
 Methods defined here:
+
__init__(self, name=None, enable_sizes=None, layer_structure=None, activation_func=None, weight_init=None, add_layer_norm=False, use_dropout=False, activate_output=False, **kwargs)
Initialize self.  See help(type(self)) for accurate signature.
+ +
eval(self)
+ +
load(self, filename)
+ +
set_multiplier(self, multiplier)
+ +
shorthash(self)
+ +
to(self, device)
+ +
train(self, mode=True)
+ +
weights(self)
+ +
+Data descriptors defined here:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+
+Data and other attributes defined here:
+
filename = None
+ +
name = None
+ +

+ + + + + + + +
 
+class HypernetworkModule(torch.nn.modules.module.Module)
   HypernetworkModule(dim, state_dict=None, layer_structure=None, activation_func=None, weight_init='Normal', add_layer_norm=False, activate_output=False, dropout_structure=None)

+
 
 
Method resolution order:
+
HypernetworkModule
+
torch.nn.modules.module.Module
+
builtins.object
+
+
+Methods defined here:
+
__init__(self, dim, state_dict=None, layer_structure=None, activation_func=None, weight_init='Normal', add_layer_norm=False, activate_output=False, dropout_structure=None)
Initialize internal Module state, shared by both nn.Module and ScriptModule.
+ +
fix_old_state_dict(self, state_dict)
+ +
forward(self, x)
Define the computation performed at every call.

+Should be overridden by all subclasses.

+.. note::
+    Although the recipe for forward pass needs to be defined within
+    this function, one should call the :class:`Module` instance afterwards
+    instead of this since the former takes care of running the
+    registered hooks while the latter silently ignores them.
+ +
trainables(self)
+ +
+Data and other attributes defined here:
+
__annotations__ = {}
+ +
activation_dict = {'celu': <class 'torch.nn.modules.activation.CELU'>, 'elu': <class 'torch.nn.modules.activation.ELU'>, 'gelu': <class 'torch.nn.modules.activation.GELU'>, 'glu': <class 'torch.nn.modules.activation.GLU'>, 'hardshrink': <class 'torch.nn.modules.activation.Hardshrink'>, 'hardsigmoid': <class 'torch.nn.modules.activation.Hardsigmoid'>, 'hardswish': <class 'torch.nn.modules.activation.Hardswish'>, 'hardtanh': <class 'torch.nn.modules.activation.Hardtanh'>, 'leakyrelu': <class 'torch.nn.modules.activation.LeakyReLU'>, 'linear': <class 'torch.nn.modules.linear.Identity'>, ...}
+ +
+Methods inherited from torch.nn.modules.module.Module:
+
__call__ = _wrapped_call_impl(self, *args, **kwargs)
+ +
__delattr__(self, name)
Implement delattr(self, name).
+ +
__dir__(self)
Default dir() implementation.
+ +
__getattr__(self, name: str) -> Any
# On the return type:
+# We choose to return `Any` in the `__getattr__` type signature instead of a more strict `Union[Tensor, Module]`.
+# This is done for better interop with various type checkers for the end users.
+# Having a stricter return type doesn't play nicely with `register_buffer()` and forces
+# people to excessively use type-ignores, asserts, casts, etc.
+# See full discussion on the problems with returning `Union` here
+# https://github.com/microsoft/pyright/issues/4213
+ +
__getstate__(self)
+ +
__repr__(self)
Return repr(self).
+ +
__setattr__(self, name: str, value: Union[torch.Tensor, ForwardRef('Module')]) -> None
Implement setattr(self, name, value).
+ +
__setstate__(self, state)
+ +
add_module(self, name: str, module: Optional[ForwardRef('Module')]) -> None
Add a child module to the current module.

+The module can be accessed as an attribute using the given name.

+Args:
+    name (str): name of the child module. The child module can be
+        accessed from this module using the given name
+    module (Module): child module to be added to the module.
+ +
apply(self: ~T, fn: Callable[[ForwardRef('Module')], NoneType]) -> ~T
Apply ``fn`` recursively to every submodule (as returned by ``.children()``) as well as self.

+Typical use includes initializing the parameters of a model
+(see also :ref:`nn-init-doc`).

+Args:
+    fn (:class:`Module` -> None): function to be applied to each submodule

+Returns:
+    Module: self

+Example::

+    >>> @torch.no_grad()
+    >>> def init_weights(m):
+    >>>     print(m)
+    >>>     if type(m) == nn.Linear:
+    >>>         m.weight.fill_(1.0)
+    >>>         print(m.weight)
+    >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
+    >>> net.apply(init_weights)
+    Linear(in_features=2, out_features=2, bias=True)
+    Parameter containing:
+    tensor([[1., 1.],
+            [1., 1.]], requires_grad=True)
+    Linear(in_features=2, out_features=2, bias=True)
+    Parameter containing:
+    tensor([[1., 1.],
+            [1., 1.]], requires_grad=True)
+    Sequential(
+      (0): Linear(in_features=2, out_features=2, bias=True)
+      (1): Linear(in_features=2, out_features=2, bias=True)
+    )
+ +
bfloat16(self: ~T) -> ~T
Casts all floating point parameters and buffers to ``bfloat16`` datatype.

+.. note::
+    This method modifies the module in-place.

+Returns:
+    Module: self
+ +
buffers(self, recurse: bool = True) -> Iterator[torch.Tensor]
Return an iterator over module buffers.

+Args:
+    recurse (bool): if True, then yields buffers of this module
+        and all submodules. Otherwise, yields only buffers that
+        are direct members of this module.

+Yields:
+    torch.Tensor: module buffer

+Example::

+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> for buf in model.buffers():
+    >>>     print(type(buf), buf.size())
+    <class 'torch.Tensor'> (20L,)
+    <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
+ +
children(self) -> Iterator[ForwardRef('Module')]
Return an iterator over immediate children modules.

+Yields:
+    Module: a child module
+ +
compile(self, *args, **kwargs)
Compile this Module's forward using :func:`torch.compile`.

+This Module's `__call__` method is compiled and all arguments are passed as-is
+to :func:`torch.compile`.

+See :func:`torch.compile` for details on the arguments for this function.
+ +
cpu(self: ~T) -> ~T
Move all model parameters and buffers to the CPU.

+.. note::
+    This method modifies the module in-place.

+Returns:
+    Module: self
+ +
cuda(self: ~T, device: Union[int, torch.device, NoneType] = None) -> ~T
Move all model parameters and buffers to the GPU.

+This also makes associated parameters and buffers different objects. So
+it should be called before constructing optimizer if the module will
+live on GPU while being optimized.

+.. note::
+    This method modifies the module in-place.

+Args:
+    device (int, optional): if specified, all parameters will be
+        copied to that device

+Returns:
+    Module: self
+ +
double(self: ~T) -> ~T
Casts all floating point parameters and buffers to ``double`` datatype.

+.. note::
+    This method modifies the module in-place.

+Returns:
+    Module: self
+ +
eval(self: ~T) -> ~T
Set the module in evaluation mode.

+This has any effect only on certain modules. See documentations of
+particular modules for details of their behaviors in training/evaluation
+mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
+etc.

+This is equivalent with :meth:`self.train(False) <torch.nn.Module.train>`.

+See :ref:`locally-disable-grad-doc` for a comparison between
+`.eval()` and several similar mechanisms that may be confused with it.

+Returns:
+    Module: self
+ +
extra_repr(self) -> str
Set the extra representation of the module.

+To print customized extra information, you should re-implement
+this method in your own modules. Both single-line and multi-line
+strings are acceptable.
+ +
float(self: ~T) -> ~T
Casts all floating point parameters and buffers to ``float`` datatype.

+.. note::
+    This method modifies the module in-place.

+Returns:
+    Module: self
+ +
get_buffer(self, target: str) -> 'Tensor'
Return the buffer given by ``target`` if it exists, otherwise throw an error.

+See the docstring for ``get_submodule`` for a more detailed
+explanation of this method's functionality as well as how to
+correctly specify ``target``.

+Args:
+    target: The fully-qualified string name of the buffer
+        to look for. (See ``get_submodule`` for how to specify a
+        fully-qualified string.)

+Returns:
+    torch.Tensor: The buffer referenced by ``target``

+Raises:
+    AttributeError: If the target string references an invalid
+        path or resolves to something that is not a
+        buffer
+ +
get_extra_state(self) -> Any
Return any extra state to include in the module's state_dict.

+Implement this and a corresponding :func:`set_extra_state` for your module
+if you need to store extra state. This function is called when building the
+module's `state_dict()`.

+Note that extra state should be picklable to ensure working serialization
+of the state_dict. We only provide provide backwards compatibility guarantees
+for serializing Tensors; other objects may break backwards compatibility if
+their serialized pickled form changes.

+Returns:
+    object: Any extra state to store in the module's state_dict
+ +
get_parameter(self, target: str) -> 'Parameter'
Return the parameter given by ``target`` if it exists, otherwise throw an error.

+See the docstring for ``get_submodule`` for a more detailed
+explanation of this method's functionality as well as how to
+correctly specify ``target``.

+Args:
+    target: The fully-qualified string name of the Parameter
+        to look for. (See ``get_submodule`` for how to specify a
+        fully-qualified string.)

+Returns:
+    torch.nn.Parameter: The Parameter referenced by ``target``

+Raises:
+    AttributeError: If the target string references an invalid
+        path or resolves to something that is not an
+        ``nn.Parameter``
+ +
get_submodule(self, target: str) -> 'Module'
Return the submodule given by ``target`` if it exists, otherwise throw an error.

+For example, let's say you have an ``nn.Module`` ``A`` that
+looks like this:

+.. code-block:: text

+    A(
+        (net_b): Module(
+            (net_c): Module(
+                (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2))
+            )
+            (linear): Linear(in_features=100, out_features=200, bias=True)
+        )
+    )

+(The diagram shows an ``nn.Module`` ``A``. ``A`` has a nested
+submodule ``net_b``, which itself has two submodules ``net_c``
+and ``linear``. ``net_c`` then has a submodule ``conv``.)

+To check whether or not we have the ``linear`` submodule, we
+would call ``get_submodule("net_b.linear")``. To check whether
+we have the ``conv`` submodule, we would call
+``get_submodule("net_b.net_c.conv")``.

+The runtime of ``get_submodule`` is bounded by the degree
+of module nesting in ``target``. A query against
+``named_modules`` achieves the same result, but it is O(N) in
+the number of transitive modules. So, for a simple check to see
+if some submodule exists, ``get_submodule`` should always be
+used.

+Args:
+    target: The fully-qualified string name of the submodule
+        to look for. (See above example for how to specify a
+        fully-qualified string.)

+Returns:
+    torch.nn.Module: The submodule referenced by ``target``

+Raises:
+    AttributeError: If the target string references an invalid
+        path or resolves to something that is not an
+        ``nn.Module``
+ +
half(self: ~T) -> ~T
Casts all floating point parameters and buffers to ``half`` datatype.

+.. note::
+    This method modifies the module in-place.

+Returns:
+    Module: self
+ +
ipu(self: ~T, device: Union[int, torch.device, NoneType] = None) -> ~T
Move all model parameters and buffers to the IPU.

+This also makes associated parameters and buffers different objects. So
+it should be called before constructing optimizer if the module will
+live on IPU while being optimized.

+.. note::
+    This method modifies the module in-place.

+Arguments:
+    device (int, optional): if specified, all parameters will be
+        copied to that device

+Returns:
+    Module: self
+ +
load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from :attr:`state_dict` into this module and its descendants.

+If :attr:`strict` is ``True``, then
+the keys of :attr:`state_dict` must exactly match the keys returned
+by this module's :meth:`~torch.nn.Module.state_dict` function.

+.. warning::
+    If :attr:`assign` is ``True`` the optimizer must be created after
+    the call to :attr:`load_state_dict` unless
+    :func:`~torch.__future__.get_swap_module_params_on_conversion` is ``True``.

+Args:
+    state_dict (dict): a dict containing parameters and
+        persistent buffers.
+    strict (bool, optional): whether to strictly enforce that the keys
+        in :attr:`state_dict` match the keys returned by this module's
+        :meth:`~torch.nn.Module.state_dict` function. Default: ``True``
+    assign (bool, optional): When ``False``, the properties of the tensors
+        in the current module are preserved while when ``True``, the
+        properties of the Tensors in the state dict are preserved. The only
+        exception is the ``requires_grad`` field of :class:`~torch.nn.Parameter`s
+        for which the value from the module is preserved.
+        Default: ``False``

+Returns:
+    ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
+        * **missing_keys** is a list of str containing the missing keys
+        * **unexpected_keys** is a list of str containing the unexpected keys

+Note:
+    If a parameter or buffer is registered as ``None`` and its corresponding key
+    exists in :attr:`state_dict`, :meth:`load_state_dict` will raise a
+    ``RuntimeError``.
+ +
modules(self) -> Iterator[ForwardRef('Module')]
Return an iterator over all modules in the network.

+Yields:
+    Module: a module in the network

+Note:
+    Duplicate modules are returned only once. In the following
+    example, ``l`` will be returned only once.

+Example::

+    >>> l = nn.Linear(2, 2)
+    >>> net = nn.Sequential(l, l)
+    >>> for idx, m in enumerate(net.modules()):
+    ...     print(idx, '->', m)

+    0 -> Sequential(
+      (0): Linear(in_features=2, out_features=2, bias=True)
+      (1): Linear(in_features=2, out_features=2, bias=True)
+    )
+    1 -> Linear(in_features=2, out_features=2, bias=True)
+ +
named_buffers(self, prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) -> Iterator[Tuple[str, torch.Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

+Args:
+    prefix (str): prefix to prepend to all buffer names.
+    recurse (bool, optional): if True, then yields buffers of this module
+        and all submodules. Otherwise, yields only buffers that
+        are direct members of this module. Defaults to True.
+    remove_duplicate (bool, optional): whether to remove the duplicated buffers in the result. Defaults to True.

+Yields:
+    (str, torch.Tensor): Tuple containing the name and buffer

+Example::

+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> for name, buf in self.named_buffers():
+    >>>     if name in ['running_var']:
+    >>>         print(buf.size())
+ +
named_children(self) -> Iterator[Tuple[str, ForwardRef('Module')]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

+Yields:
+    (str, Module): Tuple containing a name and child module

+Example::

+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> for name, module in model.named_children():
+    >>>     if name in ['conv4', 'conv5']:
+    >>>         print(module)
+ +
named_modules(self, memo: Optional[Set[ForwardRef('Module')]] = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

+Args:
+    memo: a memo to store the set of modules already added to the result
+    prefix: a prefix that will be added to the name of the module
+    remove_duplicate: whether to remove the duplicated module instances in the result
+        or not

+Yields:
+    (str, Module): Tuple of name and module

+Note:
+    Duplicate modules are returned only once. In the following
+    example, ``l`` will be returned only once.

+Example::

+    >>> l = nn.Linear(2, 2)
+    >>> net = nn.Sequential(l, l)
+    >>> for idx, m in enumerate(net.named_modules()):
+    ...     print(idx, '->', m)

+    0 -> ('', Sequential(
+      (0): Linear(in_features=2, out_features=2, bias=True)
+      (1): Linear(in_features=2, out_features=2, bias=True)
+    ))
+    1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
+ +
named_parameters(self, prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) -> Iterator[Tuple[str, torch.nn.parameter.Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

+Args:
+    prefix (str): prefix to prepend to all parameter names.
+    recurse (bool): if True, then yields parameters of this module
+        and all submodules. Otherwise, yields only parameters that
+        are direct members of this module.
+    remove_duplicate (bool, optional): whether to remove the duplicated
+        parameters in the result. Defaults to True.

+Yields:
+    (str, Parameter): Tuple containing the name and parameter

+Example::

+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> for name, param in self.named_parameters():
+    >>>     if name in ['bias']:
+    >>>         print(param.size())
+ +
parameters(self, recurse: bool = True) -> Iterator[torch.nn.parameter.Parameter]
Return an iterator over module parameters.

+This is typically passed to an optimizer.

+Args:
+    recurse (bool): if True, then yields parameters of this module
+        and all submodules. Otherwise, yields only parameters that
+        are direct members of this module.

+Yields:
+    Parameter: module parameter

+Example::

+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> for param in model.parameters():
+    >>>     print(type(param), param.size())
+    <class 'torch.Tensor'> (20L,)
+    <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
+ +
register_backward_hook(self, hook: Callable[[ForwardRef('Module'), Union[Tuple[torch.Tensor, ...], torch.Tensor], Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[NoneType, Tuple[torch.Tensor, ...], torch.Tensor]]) -> torch.utils.hooks.RemovableHandle
Register a backward hook on the module.

+This function is deprecated in favor of :meth:`~torch.nn.Module.register_full_backward_hook` and
+the behavior of this function will change in future versions.

+Returns:
+    :class:`torch.utils.hooks.RemovableHandle`:
+        a handle that can be used to remove the added hook by calling
+        ``handle.remove()``
+ +
register_buffer(self, name: str, tensor: Optional[torch.Tensor], persistent: bool = True) -> None
Add a buffer to the module.

+This is typically used to register a buffer that should not to be
+considered a model parameter. For example, BatchNorm's ``running_mean``
+is not a parameter, but is part of the module's state. Buffers, by
+default, are persistent and will be saved alongside parameters. This
+behavior can be changed by setting :attr:`persistent` to ``False``. The
+only difference between a persistent buffer and a non-persistent buffer
+is that the latter will not be a part of this module's
+:attr:`state_dict`.

+Buffers can be accessed as attributes using given names.

+Args:
+    name (str): name of the buffer. The buffer can be accessed
+        from this module using the given name
+    tensor (Tensor or None): buffer to be registered. If ``None``, then operations
+        that run on buffers, such as :attr:`cuda`, are ignored. If ``None``,
+        the buffer is **not** included in the module's :attr:`state_dict`.
+    persistent (bool): whether the buffer is part of this module's
+        :attr:`state_dict`.

+Example::

+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> self.register_buffer('running_mean', torch.zeros(num_features))
+ +
register_forward_hook(self, hook: Union[Callable[[~T, Tuple[Any, ...], Any], Optional[Any]], Callable[[~T, Tuple[Any, ...], Dict[str, Any], Any], Optional[Any]]], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) -> torch.utils.hooks.RemovableHandle
Register a forward hook on the module.

+The hook will be called every time after :func:`forward` has computed an output.

+If ``with_kwargs`` is ``False`` or not specified, the input contains only
+the positional arguments given to the module. Keyword arguments won't be
+passed to the hooks and only to the ``forward``. The hook can modify the
+output. It can modify the input inplace but it will not have effect on
+forward since this is called after :func:`forward` is called. The hook
+should have the following signature::

+    hook(module, args, output) -> None or modified output

+If ``with_kwargs`` is ``True``, the forward hook will be passed the
+``kwargs`` given to the forward function and be expected to return the
+output possibly modified. The hook should have the following signature::

+    hook(module, args, kwargs, output) -> None or modified output

+Args:
+    hook (Callable): The user defined hook to be registered.
+    prepend (bool): If ``True``, the provided ``hook`` will be fired
+        before all existing ``forward`` hooks on this
+        :class:`torch.nn.modules.Module`. Otherwise, the provided
+        ``hook`` will be fired after all existing ``forward`` hooks on
+        this :class:`torch.nn.modules.Module`. Note that global
+        ``forward`` hooks registered with
+        :func:`register_module_forward_hook` will fire before all hooks
+        registered by this method.
+        Default: ``False``
+    with_kwargs (bool): If ``True``, the ``hook`` will be passed the
+        kwargs given to the forward function.
+        Default: ``False``
+    always_call (bool): If ``True`` the ``hook`` will be run regardless of
+        whether an exception is raised while calling the Module.
+        Default: ``False``

+Returns:
+    :class:`torch.utils.hooks.RemovableHandle`:
+        a handle that can be used to remove the added hook by calling
+        ``handle.remove()``
+ +
register_forward_pre_hook(self, hook: Union[Callable[[~T, Tuple[Any, ...]], Optional[Any]], Callable[[~T, Tuple[Any, ...], Dict[str, Any]], Optional[Tuple[Any, Dict[str, Any]]]]], *, prepend: bool = False, with_kwargs: bool = False) -> torch.utils.hooks.RemovableHandle
Register a forward pre-hook on the module.

+The hook will be called every time before :func:`forward` is invoked.


+If ``with_kwargs`` is false or not specified, the input contains only
+the positional arguments given to the module. Keyword arguments won't be
+passed to the hooks and only to the ``forward``. The hook can modify the
+input. User can either return a tuple or a single modified value in the
+hook. We will wrap the value into a tuple if a single value is returned
+(unless that value is already a tuple). The hook should have the
+following signature::

+    hook(module, args) -> None or modified input

+If ``with_kwargs`` is true, the forward pre-hook will be passed the
+kwargs given to the forward function. And if the hook modifies the
+input, both the args and kwargs should be returned. The hook should have
+the following signature::

+    hook(module, args, kwargs) -> None or a tuple of modified input and kwargs

+Args:
+    hook (Callable): The user defined hook to be registered.
+    prepend (bool): If true, the provided ``hook`` will be fired before
+        all existing ``forward_pre`` hooks on this
+        :class:`torch.nn.modules.Module`. Otherwise, the provided
+        ``hook`` will be fired after all existing ``forward_pre`` hooks
+        on this :class:`torch.nn.modules.Module`. Note that global
+        ``forward_pre`` hooks registered with
+        :func:`register_module_forward_pre_hook` will fire before all
+        hooks registered by this method.
+        Default: ``False``
+    with_kwargs (bool): If true, the ``hook`` will be passed the kwargs
+        given to the forward function.
+        Default: ``False``

+Returns:
+    :class:`torch.utils.hooks.RemovableHandle`:
+        a handle that can be used to remove the added hook by calling
+        ``handle.remove()``
+ +
register_full_backward_hook(self, hook: Callable[[ForwardRef('Module'), Union[Tuple[torch.Tensor, ...], torch.Tensor], Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[NoneType, Tuple[torch.Tensor, ...], torch.Tensor]], prepend: bool = False) -> torch.utils.hooks.RemovableHandle
Register a backward hook on the module.

+The hook will be called every time the gradients with respect to a module
+are computed, i.e. the hook will execute if and only if the gradients with
+respect to module outputs are computed. The hook should have the following
+signature::

+    hook(module, grad_input, grad_output) -> tuple(Tensor) or None

+The :attr:`grad_input` and :attr:`grad_output` are tuples that contain the gradients
+with respect to the inputs and outputs respectively. The hook should
+not modify its arguments, but it can optionally return a new gradient with
+respect to the input that will be used in place of :attr:`grad_input` in
+subsequent computations. :attr:`grad_input` will only correspond to the inputs given
+as positional arguments and all kwarg arguments are ignored. Entries
+in :attr:`grad_input` and :attr:`grad_output` will be ``None`` for all non-Tensor
+arguments.

+For technical reasons, when this hook is applied to a Module, its forward function will
+receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
+of each Tensor returned by the Module's forward function.

+.. warning ::
+    Modifying inputs or outputs inplace is not allowed when using backward hooks and
+    will raise an error.

+Args:
+    hook (Callable): The user-defined hook to be registered.
+    prepend (bool): If true, the provided ``hook`` will be fired before
+        all existing ``backward`` hooks on this
+        :class:`torch.nn.modules.Module`. Otherwise, the provided
+        ``hook`` will be fired after all existing ``backward`` hooks on
+        this :class:`torch.nn.modules.Module`. Note that global
+        ``backward`` hooks registered with
+        :func:`register_module_full_backward_hook` will fire before
+        all hooks registered by this method.

+Returns:
+    :class:`torch.utils.hooks.RemovableHandle`:
+        a handle that can be used to remove the added hook by calling
+        ``handle.remove()``
+ +
register_full_backward_pre_hook(self, hook: Callable[[ForwardRef('Module'), Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[NoneType, Tuple[torch.Tensor, ...], torch.Tensor]], prepend: bool = False) -> torch.utils.hooks.RemovableHandle
Register a backward pre-hook on the module.

+The hook will be called every time the gradients for the module are computed.
+The hook should have the following signature::

+    hook(module, grad_output) -> tuple[Tensor] or None

+The :attr:`grad_output` is a tuple. The hook should
+not modify its arguments, but it can optionally return a new gradient with
+respect to the output that will be used in place of :attr:`grad_output` in
+subsequent computations. Entries in :attr:`grad_output` will be ``None`` for
+all non-Tensor arguments.

+For technical reasons, when this hook is applied to a Module, its forward function will
+receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
+of each Tensor returned by the Module's forward function.

+.. warning ::
+    Modifying inputs inplace is not allowed when using backward hooks and
+    will raise an error.

+Args:
+    hook (Callable): The user-defined hook to be registered.
+    prepend (bool): If true, the provided ``hook`` will be fired before
+        all existing ``backward_pre`` hooks on this
+        :class:`torch.nn.modules.Module`. Otherwise, the provided
+        ``hook`` will be fired after all existing ``backward_pre`` hooks
+        on this :class:`torch.nn.modules.Module`. Note that global
+        ``backward_pre`` hooks registered with
+        :func:`register_module_full_backward_pre_hook` will fire before
+        all hooks registered by this method.

+Returns:
+    :class:`torch.utils.hooks.RemovableHandle`:
+        a handle that can be used to remove the added hook by calling
+        ``handle.remove()``
+ +
register_load_state_dict_post_hook(self, hook)
Register a post hook to be run after module's ``load_state_dict`` is called.

+It should have the following signature::
+    hook(module, incompatible_keys) -> None

+The ``module`` argument is the current module that this hook is registered
+on, and the ``incompatible_keys`` argument is a ``NamedTuple`` consisting
+of attributes ``missing_keys`` and ``unexpected_keys``. ``missing_keys``
+is a ``list`` of ``str`` containing the missing keys and
+``unexpected_keys`` is a ``list`` of ``str`` containing the unexpected keys.

+The given incompatible_keys can be modified inplace if needed.

+Note that the checks performed when calling :func:`load_state_dict` with
+``strict=True`` are affected by modifications the hook makes to
+``missing_keys`` or ``unexpected_keys``, as expected. Additions to either
+set of keys will result in an error being thrown when ``strict=True``, and
+clearing out both missing and unexpected keys will avoid an error.

+Returns:
+    :class:`torch.utils.hooks.RemovableHandle`:
+        a handle that can be used to remove the added hook by calling
+        ``handle.remove()``
+ +
register_module(self, name: str, module: Optional[ForwardRef('Module')]) -> None
Alias for :func:`add_module`.
+ +
register_parameter(self, name: str, param: Optional[torch.nn.parameter.Parameter]) -> None
Add a parameter to the module.

+The parameter can be accessed as an attribute using given name.

+Args:
+    name (str): name of the parameter. The parameter can be accessed
+        from this module using the given name
+    param (Parameter or None): parameter to be added to the module. If
+        ``None``, then operations that run on parameters, such as :attr:`cuda`,
+        are ignored. If ``None``, the parameter is **not** included in the
+        module's :attr:`state_dict`.
+ +
register_state_dict_pre_hook(self, hook)
Register a pre-hook for the :meth:`~torch.nn.Module.state_dict` method.

+These hooks will be called with arguments: ``self``, ``prefix``,
+and ``keep_vars`` before calling ``state_dict`` on ``self``. The registered
+hooks can be used to perform pre-processing before the ``state_dict``
+call is made.
+ +
requires_grad_(self: ~T, requires_grad: bool = True) -> ~T
Change if autograd should record operations on parameters in this module.

+This method sets the parameters' :attr:`requires_grad` attributes
+in-place.

+This method is helpful for freezing part of the module for finetuning
+or training parts of a model individually (e.g., GAN training).

+See :ref:`locally-disable-grad-doc` for a comparison between
+`.requires_grad_()` and several similar mechanisms that may be confused with it.

+Args:
+    requires_grad (bool): whether autograd should record operations on
+                          parameters in this module. Default: ``True``.

+Returns:
+    Module: self
+ +
set_extra_state(self, state: Any) -> None
Set extra state contained in the loaded `state_dict`.

+This function is called from :func:`load_state_dict` to handle any extra state
+found within the `state_dict`. Implement this function and a corresponding
+:func:`get_extra_state` for your module if you need to store extra state within its
+`state_dict`.

+Args:
+    state (dict): Extra state from the `state_dict`
+ +
share_memory(self: ~T) -> ~T
See :meth:`torch.Tensor.share_memory_`.
+ +
state_dict(self, *args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.

+Both parameters and persistent buffers (e.g. running averages) are
+included. Keys are corresponding parameter and buffer names.
+Parameters and buffers set to ``None`` are not included.

+.. note::
+    The returned object is a shallow copy. It contains references
+    to the module's parameters and buffers.

+.. warning::
+    Currently ``state_dict()`` also accepts positional arguments for
+    ``destination``, ``prefix`` and ``keep_vars`` in order. However,
+    this is being deprecated and keyword arguments will be enforced in
+    future releases.

+.. warning::
+    Please avoid the use of argument ``destination`` as it is not
+    designed for end-users.

+Args:
+    destination (dict, optional): If provided, the state of module will
+        be updated into the dict and the same object is returned.
+        Otherwise, an ``OrderedDict`` will be created and returned.
+        Default: ``None``.
+    prefix (str, optional): a prefix added to parameter and buffer
+        names to compose the keys in state_dict. Default: ``''``.
+    keep_vars (bool, optional): by default the :class:`~torch.Tensor` s
+        returned in the state dict are detached from autograd. If it's
+        set to ``True``, detaching will not be performed.
+        Default: ``False``.

+Returns:
+    dict:
+        a dictionary containing a whole state of the module

+Example::

+    >>> # xdoctest: +SKIP("undefined vars")
+    >>> module.state_dict().keys()
+    ['bias', 'weight']
+ +
to(self, *args, **kwargs)
Move and/or cast the parameters and buffers.

+This can be called as

+.. function:: to(device=None, dtype=None, non_blocking=False)
+   :noindex:

+.. function:: to(dtype, non_blocking=False)
+   :noindex:

+.. function:: to(tensor, non_blocking=False)
+   :noindex:

+.. function:: to(memory_format=torch.channels_last)
+   :noindex:

+Its signature is similar to :meth:`torch.Tensor.to`, but only accepts
+floating point or complex :attr:`dtype`\ s. In addition, this method will
+only cast the floating point or complex parameters and buffers to :attr:`dtype`
+(if given). The integral parameters and buffers will be moved
+:attr:`device`, if that is given, but with dtypes unchanged. When
+:attr:`non_blocking` is set, it tries to convert/move asynchronously
+with respect to the host if possible, e.g., moving CPU Tensors with
+pinned memory to CUDA devices.

+See below for examples.

+.. note::
+    This method modifies the module in-place.

+Args:
+    device (:class:`torch.device`): the desired device of the parameters
+        and buffers in this module
+    dtype (:class:`torch.dtype`): the desired floating point or complex dtype of
+        the parameters and buffers in this module
+    tensor (torch.Tensor): Tensor whose dtype and device are the desired
+        dtype and device for all parameters and buffers in this module
+    memory_format (:class:`torch.memory_format`): the desired memory
+        format for 4D parameters and buffers in this module (keyword
+        only argument)

+Returns:
+    Module: self

+Examples::

+    >>> # xdoctest: +IGNORE_WANT("non-deterministic")
+    >>> linear = nn.Linear(2, 2)
+    >>> linear.weight
+    Parameter containing:
+    tensor([[ 0.1913, -0.3420],
+            [-0.5113, -0.2325]])
+    >>> linear.to(torch.double)
+    Linear(in_features=2, out_features=2, bias=True)
+    >>> linear.weight
+    Parameter containing:
+    tensor([[ 0.1913, -0.3420],
+            [-0.5113, -0.2325]], dtype=torch.float64)
+    >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1)
+    >>> gpu1 = torch.device("cuda:1")
+    >>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
+    Linear(in_features=2, out_features=2, bias=True)
+    >>> linear.weight
+    Parameter containing:
+    tensor([[ 0.1914, -0.3420],
+            [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
+    >>> cpu = torch.device("cpu")
+    >>> linear.to(cpu)
+    Linear(in_features=2, out_features=2, bias=True)
+    >>> linear.weight
+    Parameter containing:
+    tensor([[ 0.1914, -0.3420],
+            [-0.5112, -0.2324]], dtype=torch.float16)

+    >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
+    >>> linear.weight
+    Parameter containing:
+    tensor([[ 0.3741+0.j,  0.2382+0.j],
+            [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
+    >>> linear(torch.ones(3, 2, dtype=torch.cdouble))
+    tensor([[0.6122+0.j, 0.1150+0.j],
+            [0.6122+0.j, 0.1150+0.j],
+            [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
+ +
to_empty(self: ~T, *, device: Union[int, str, torch.device, NoneType], recurse: bool = True) -> ~T
Move the parameters and buffers to the specified device without copying storage.

+Args:
+    device (:class:`torch.device`): The desired device of the parameters
+        and buffers in this module.
+    recurse (bool): Whether parameters and buffers of submodules should
+        be recursively moved to the specified device.

+Returns:
+    Module: self
+ +
train(self: ~T, mode: bool = True) -> ~T
Set the module in training mode.

+This has any effect only on certain modules. See documentations of
+particular modules for details of their behaviors in training/evaluation
+mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
+etc.

+Args:
+    mode (bool): whether to set training mode (``True``) or evaluation
+                 mode (``False``). Default: ``True``.

+Returns:
+    Module: self
+ +
type(self: ~T, dst_type: Union[torch.dtype, str]) -> ~T
Casts all parameters and buffers to :attr:`dst_type`.

+.. note::
+    This method modifies the module in-place.

+Args:
+    dst_type (type or string): the desired type

+Returns:
+    Module: self
+ +
xpu(self: ~T, device: Union[int, torch.device, NoneType] = None) -> ~T
Move all model parameters and buffers to the XPU.

+This also makes associated parameters and buffers different objects. So
+it should be called before constructing optimizer if the module will
+live on XPU while being optimized.

+.. note::
+    This method modifies the module in-place.

+Arguments:
+    device (int, optional): if specified, all parameters will be
+        copied to that device

+Returns:
+    Module: self
+ +
zero_grad(self, set_to_none: bool = True) -> None
Reset gradients of all model parameters.

+See similar function under :class:`torch.optim.Optimizer` for more context.

+Args:
+    set_to_none (bool): instead of setting to zero, set the grads to None.
+        See :meth:`torch.optim.Optimizer.zero_grad` for details.
+ +
+Data descriptors inherited from torch.nn.modules.module.Module:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+
+Data and other attributes inherited from torch.nn.modules.module.Module:
+
T_destination = ~T_destination
+ +
call_super_init = False
+ +
dump_patches = False
+ +

+ + + + + +
 
+Functions
       
add_hypernet(unet: <module 'diffusers.models.unets.unet_2d_condition' from '/home/imgen/miniconda3/envs/py31/lib/python3.10/site-packages/diffusers/models/unets/unet_2d_condition.py'>, hypernet: multigen.hypernet.Hypernetwork) -> None
Add a hypernetwork to an unet.
+
apply_hypernetworks(hypernetworks, context, layer=None)
+
apply_single_hypernetwork(hypernetwork, context_k, context_v, layer=None)
+
clear_hypernets(unet: <module 'diffusers.models.unets.unet_2d_condition' from '/home/imgen/miniconda3/envs/py31/lib/python3.10/site-packages/diffusers/models/unets/unet_2d_condition.py'>) -> None
Remove all hypernetworks from an unet.
+
parse_dropout_structure(layer_structure, use_dropout, last_layer_dropout)
+
+ \ No newline at end of file diff --git a/docs/generated/multigen.loader.html b/docs/generated/multigen.loader.html new file mode 100644 index 0000000..f80c73e --- /dev/null +++ b/docs/generated/multigen.loader.html @@ -0,0 +1,82 @@ + +Python: module multigen.loader + + + + + +
 
+ 
multigen.loader
index
/home/imgen/projects/metafusion/multigen/loader.py
+

+

+ + + + + +
 
+Modules
       
logging
+
torch
+

+ + + + + +
 
+Classes
       
+
builtins.object +
+
+
Loader +
+
+
+

+ + + + + + + +
 
+class Loader(builtins.object)
   class for loading diffusion pipelines from files.
 
 Methods defined here:
+
__init__(self)
Initialize self.  See help(type(self)) for accurate signature.
+ +
get_pipeline(self, model_id)
+ +
load_pipeline(self, cls: Type[diffusers.pipelines.pipeline_utils.DiffusionPipeline], path, torch_dtype=torch.float16, device=device(type='cuda'), **additional_args)
+ +
register_pipeline(self, pipe: diffusers.pipelines.pipeline_utils.DiffusionPipeline, model_id)
+ +
remove_pipeline(self, model_id)
+ +
+Data descriptors defined here:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+

+ + + + + +
 
+Functions
       
copy_pipe(pipe)
+

+ + + + + +
 
+Data
       Type = typing.Type
+logger = <Logger /home/imgen/projects/metafusion/multigen/loader.py (WARNING)>
+ \ No newline at end of file diff --git a/docs/generated/multigen.pipelines.masked_stable_diffusion_img2img.html b/docs/generated/multigen.pipelines.masked_stable_diffusion_img2img.html new file mode 100644 index 0000000..48be425 --- /dev/null +++ b/docs/generated/multigen.pipelines.masked_stable_diffusion_img2img.html @@ -0,0 +1,1582 @@ + +Python: module multigen.pipelines.masked_stable_diffusion_img2img + + + + + +
 
+ 
multigen.pipelines.masked_stable_diffusion_img2img
index
/home/imgen/projects/metafusion/multigen/pipelines/masked_stable_diffusion_img2img.py
+

+

+ + + + + +
 
+Modules
       
PIL
+
numpy
+
torch
+

+ + + + + +
 
+Classes
       
+
diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline(diffusers.pipelines.pipeline_utils.DiffusionPipeline, diffusers.pipelines.pipeline_utils.StableDiffusionMixin, diffusers.loaders.textual_inversion.TextualInversionLoaderMixin, diffusers.loaders.ip_adapter.IPAdapterMixin, diffusers.loaders.lora.LoraLoaderMixin, diffusers.loaders.single_file.FromSingleFileMixin) +
+
+
MaskedStableDiffusionImg2ImgPipeline +
+
+
+

+ + + + + + + +
 
+class MaskedStableDiffusionImg2ImgPipeline(diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline)
   MaskedStableDiffusionImg2ImgPipeline(vae: diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL, text_encoder: transformers.models.clip.modeling_clip.CLIPTextModel, tokenizer: transformers.models.clip.tokenization_clip.CLIPTokenizer, unet: diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, scheduler: diffusers.schedulers.scheduling_utils.KarrasDiffusionSchedulers, safety_checker: diffusers.pipelines.stable_diffusion.safety_checker.StableDiffusionSafetyChecker, feature_extractor: transformers.models.clip.image_processing_clip.CLIPImageProcessor, image_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True)

+
 
 
Method resolution order:
+
MaskedStableDiffusionImg2ImgPipeline
+
diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline
+
diffusers.pipelines.pipeline_utils.DiffusionPipeline
+
diffusers.configuration_utils.ConfigMixin
+
diffusers.utils.hub_utils.PushToHubMixin
+
diffusers.pipelines.pipeline_utils.StableDiffusionMixin
+
diffusers.loaders.textual_inversion.TextualInversionLoaderMixin
+
diffusers.loaders.ip_adapter.IPAdapterMixin
+
diffusers.loaders.lora.LoraLoaderMixin
+
diffusers.loaders.single_file.FromSingleFileMixin
+
builtins.object
+
+
+Methods defined here:
+
__call__(self, prompt: Union[str, List[str]] = None, image: Union[PIL.Image.Image, numpy.ndarray, torch.FloatTensor, List[PIL.Image.Image], List[numpy.ndarray], List[torch.FloatTensor]] = None, original_image: Union[PIL.Image.Image, numpy.ndarray, torch.FloatTensor, List[PIL.Image.Image], List[numpy.ndarray], List[torch.FloatTensor]] = None, strength: float = 0.8, num_inference_steps: Optional[int] = 50, timesteps: List[int] = None, guidance_scale: Optional[float] = 7.5, negative_prompt: Union[str, List[str], NoneType] = None, num_images_per_prompt: Optional[int] = 1, eta: Optional[float] = 0.0, generator: Union[torch._C.Generator, List[torch._C.Generator], NoneType] = None, prompt_embeds: Optional[torch.FloatTensor] = None, negative_prompt_embeds: Optional[torch.FloatTensor] = None, ip_adapter_image: Union[PIL.Image.Image, numpy.ndarray, torch.FloatTensor, List[PIL.Image.Image], List[numpy.ndarray], List[torch.FloatTensor], NoneType] = None, ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None, output_type: Optional[str] = 'pil', return_dict: bool = True, cross_attention_kwargs: Optional[Dict[str, Any]] = None, clip_skip: int = None, callback_on_step_end: Optional[Callable[[int, int, Dict], NoneType]] = None, callback_on_step_end_tensor_inputs: List[str] = ['latents'], mask: Union[torch.FloatTensor, PIL.Image.Image, numpy.ndarray, List[torch.FloatTensor], List[PIL.Image.Image], List[numpy.ndarray]] = None, sample_mode='sample', **kwargs)
The call function to the pipeline for generation.

+Args:
+    prompt (`str` or `List[str]`, *optional*):
+        The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
+    image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
+        `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
+        numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
+        or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
+        list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
+        latents as `image`, but if passing latents directly it is not encoded again.
+    original_image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
+        Original image without mask. If provided it will be used to compute latents for non-inpaint area.
+    strength (`float`, *optional*, defaults to 0.8):
+        Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
+        starting point and more noise is added the higher the `strength`. The number of denoising steps depends
+        on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
+        process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
+        essentially ignores `image`.
+    num_inference_steps (`int`, *optional*, defaults to 50):
+        The number of denoising steps. More denoising steps usually lead to a higher quality image at the
+        expense of slower inference. This parameter is modulated by `strength`.
+    timesteps (`List[int]`, *optional*):
+        Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
+        in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
+        passed will be used. Must be in descending order.
+    guidance_scale (`float`, *optional*, defaults to 7.5):
+        A higher guidance scale value encourages the model to generate images closely linked to the text
+        `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
+    negative_prompt (`str` or `List[str]`, *optional*):
+        The prompt or prompts to guide what to not include in image generation. If not defined, you need to
+        pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
+    num_images_per_prompt (`int`, *optional*, defaults to 1):
+        The number of images to generate per prompt.
+    eta (`float`, *optional*, defaults to 0.0):
+        Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
+        to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
+    generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
+        A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
+        generation deterministic.
+    prompt_embeds (`torch.FloatTensor`, *optional*):
+        Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
+        provided, text embeddings are generated from the `prompt` input argument.
+    negative_prompt_embeds (`torch.FloatTensor`, *optional*):
+        Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
+        not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
+    ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
+    ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
+        Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
+        IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
+        contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
+        provided, embeddings are computed from the `ip_adapter_image` input argument.
+    output_type (`str`, *optional*, defaults to `"pil"`):
+        The output format of the generated image. Choose between `PIL.Image` or `np.array`.
+    return_dict (`bool`, *optional*, defaults to `True`):
+        Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
+        plain tuple.
+    cross_attention_kwargs (`dict`, *optional*):
+        A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
+        [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
+    clip_skip (`int`, *optional*):
+        Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
+        the output of the pre-final layer will be used for computing the prompt embeddings.
+    callback_on_step_end (`Callable`, *optional*):
+        A function that calls at the end of each denoising steps during the inference. The function is called
+        with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
+        callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
+        `callback_on_step_end_tensor_inputs`.
+    callback_on_step_end_tensor_inputs (`List`, *optional*):
+        The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
+        will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
+        `._callback_tensor_inputs` attribute of your pipeline class.
+    mask (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`, *optional*):
+        A mask with non-zero elements for the area to be inpainted. If not specified, no mask is applied.
+    sample_mode (`str`, *optional*)
+        Controls how latent code for masked area is initialised. It can be one of sample, argmax, random
+Examples:

+Returns:
+    [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
+        If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
+        otherwise a `tuple` is returned where the first element is a list with the generated images and the
+        second element is a list of `bool`s indicating whether the corresponding generated image contains
+        "not-safe-for-work" (nsfw) content.
+ +
denormalize(self, latents)
+ +
latents_to_img(self, latents)
+ +
prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True, sample_mode: str = 'sample')
+ +
upcast_vae(self)
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
+ +
+Data and other attributes defined here:
+
debug_save = 0
+ +
+Methods inherited from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline:
+
__init__(self, vae: diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL, text_encoder: transformers.models.clip.modeling_clip.CLIPTextModel, tokenizer: transformers.models.clip.tokenization_clip.CLIPTokenizer, unet: diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, scheduler: diffusers.schedulers.scheduling_utils.KarrasDiffusionSchedulers, safety_checker: diffusers.pipelines.stable_diffusion.safety_checker.StableDiffusionSafetyChecker, feature_extractor: transformers.models.clip.image_processing_clip.CLIPImageProcessor, image_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True)
Initialize self.  See help(type(self)) for accurate signature.
+ +
check_inputs(self, prompt, strength, callback_steps, negative_prompt=None, prompt_embeds=None, negative_prompt_embeds=None, ip_adapter_image=None, ip_adapter_image_embeds=None, callback_on_step_end_tensor_inputs=None)
+ +
decode_latents(self, latents)
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
+ +
encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None)
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
+ +
encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt=None, prompt_embeds: Optional[torch.FloatTensor] = None, negative_prompt_embeds: Optional[torch.FloatTensor] = None, lora_scale: Optional[float] = None, clip_skip: Optional[int] = None)
Encodes the prompt into text encoder hidden states.

+Args:
+    prompt (`str` or `List[str]`, *optional*):
+        prompt to be encoded
+    device: (`torch.device`):
+        torch device
+    num_images_per_prompt (`int`):
+        number of images that should be generated per prompt
+    do_classifier_free_guidance (`bool`):
+        whether to use classifier free guidance or not
+    negative_prompt (`str` or `List[str]`, *optional*):
+        The prompt or prompts not to guide the image generation. If not defined, one has to pass
+        `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
+        less than `1`).
+    prompt_embeds (`torch.FloatTensor`, *optional*):
+        Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
+        provided, text embeddings will be generated from `prompt` input argument.
+    negative_prompt_embeds (`torch.FloatTensor`, *optional*):
+        Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
+        weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
+        argument.
+    lora_scale (`float`, *optional*):
+        A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
+    clip_skip (`int`, *optional*):
+        Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
+        the output of the pre-final layer will be used for computing the prompt embeddings.
+ +
get_guidance_scale_embedding(self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32) -> torch.FloatTensor
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

+Args:
+    w (`torch.Tensor`):
+        Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
+    embedding_dim (`int`, *optional*, defaults to 512):
+        Dimension of the embeddings to generate.
+    dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
+        Data type of the generated embeddings.

+Returns:
+    `torch.FloatTensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
+ +
get_timesteps(self, num_inference_steps, strength, device)
+ +
prepare_extra_step_kwargs(self, generator, eta)
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
+ +
prepare_ip_adapter_image_embeds(self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance)
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
+ +
run_safety_checker(self, image, device, dtype)
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
+ +
+Readonly properties inherited from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline:
+
clip_skip
+
+
cross_attention_kwargs
+
+
do_classifier_free_guidance
+
+
guidance_scale
+
+
interrupt
+
+
num_timesteps
+
+
+Data and other attributes inherited from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline:
+
model_cpu_offload_seq = 'text_encoder->image_encoder->unet->vae'
+ +
+Methods inherited from diffusers.pipelines.pipeline_utils.DiffusionPipeline:
+
__setattr__(self, name: str, value: Any)
Implement setattr(self, name, value).
+ +
disable_attention_slicing(self)
Disable sliced attention computation. If `enable_attention_slicing` was previously called, attention is
+computed in one step.
+ +
disable_xformers_memory_efficient_attention(self)
Disable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).
+ +
enable_attention_slicing(self, slice_size: Union[str, int, NoneType] = 'auto')
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 computation is performed
+sequentially over each head. This is useful to save some memory in exchange for a small speed decrease.

+<Tip warning={true}>

+⚠️ Don't enable attention slicing if you're already using `scaled_dot_product_attention` (SDPA) from PyTorch
+2.0 or xFormers. These attention computations are already very memory efficient so you won't need to enable
+this function. If you enable attention slicing with SDPA or xFormers, it can lead to serious slow downs!

+</Tip>

+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
+        provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
+        must be a multiple of `slice_size`.

+Examples:

+```py
+>>> import torch
+>>> from diffusers import StableDiffusionPipeline

+>>> pipe = StableDiffusionPipeline.from_pretrained(
+...     "runwayml/stable-diffusion-v1-5",
+...     torch_dtype=torch.float16,
+...     use_safetensors=True,
+... )

+>>> prompt = "a photo of an astronaut riding a horse on mars"
+>>> pipe.enable_attention_slicing()
+>>> image = pipe(prompt).images[0]
+```
+ +
enable_model_cpu_offload(self, gpu_id: Optional[int] = None, device: Union[torch.device, str] = 'cuda')
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 a time to the GPU when its `forward`
+method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
+`enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.

+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 used in inference. If not specified, it will
+        default to "cuda".
+ +
enable_sequential_cpu_offload(self, gpu_id: Optional[int] = None, device: Union[torch.device, str] = 'cuda')
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._exclude_from_cpu_offload`) are saved to CPU
+and then moved to `torch.device('meta')` and loaded to GPU only when their specific submodule has its `forward`
+method called. Offloading happens on a submodule basis. Memory savings are higher than with
+`enable_model_cpu_offload`, but performance is lower.

+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 used in inference. If not specified, it will
+        default to "cuda".
+ +
enable_xformers_memory_efficient_attention(self, attention_op: Optional[Callable] = None)
Enable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/). When this
+option is enabled, you should observe lower GPU memory usage and a potential speed up during inference. Speed
+up during training is not guaranteed.

+<Tip warning={true}>

+⚠️ When memory efficient attention and sliced attention are both enabled, memory efficient attention takes
+precedent.

+</Tip>

+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)
+        function of xFormers.

+Examples:

+```py
+>>> import torch
+>>> from diffusers import DiffusionPipeline
+>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

+>>> 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 using VAE for Flash Attention
+>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
+```
+ +
maybe_free_model_hooks(self)
Function that offloads all components, removes all model hooks that were added when using
+`enable_model_cpu_offload` and then applies them again. In case the model has not been offloaded this function
+is a no-op. Make sure to add this function to the end of the `__call__` function of your pipeline so that it
+functions correctly when applying enable_model_cpu_offload.
+ +
progress_bar(self, iterable=None, total=None)
+ +
register_modules(self, **kwargs)
+ +
remove_all_hooks(self)
Removes all hooks that were added when using `enable_sequential_cpu_offload` or `enable_model_cpu_offload`.
+ +
reset_device_map(self)
Resets the device maps (if any) to None.
+ +
save_pretrained(self, save_directory: Union[str, os.PathLike], safe_serialization: bool = True, variant: Optional[str] = None, push_to_hub: bool = False, **kwargs)
Save all saveable variables of the pipeline to a directory. A pipeline variable can be saved and loaded if its
+class implements both a save and loading method. The pipeline is easily reloaded using the
+[`~DiffusionPipeline.from_pretrained`] class method.

+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 `pickle`.
+    variant (`str`, *optional*):
+        If specified, weights are saved in the format `pytorch_model.<variant>.bin`.
+    push_to_hub (`bool`, *optional*, defaults to `False`):
+        Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
+        repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
+        namespace).
+    kwargs (`Dict[str, Any]`, *optional*):
+        Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
+ +
set_attention_slice(self, slice_size: Optional[int])
+ +
set_progress_bar_config(self, **kwargs)
+ +
set_use_memory_efficient_attention_xformers(self, valid: bool, attention_op: Optional[Callable] = None) -> None
+ +
to(self, *args, **kwargs)
Performs Pipeline dtype and/or device conversion. A torch.dtype and torch.device are inferred from the
+arguments of `self.to(*args, **kwargs).`

+<Tip>

+    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) → DiffusionPipeline` to return a pipeline with the specified
+  [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype)
+- `to(device, silence_dtype_warnings=False) → DiffusionPipeline` to return a pipeline with the specified
+  [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device)
+- `to(device=None, dtype=None, silence_dtype_warnings=False) → DiffusionPipeline` to return a pipeline with the
+  specified [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device) and
+  [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype)

+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
+        [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device)
+    silence_dtype_warnings (`str`, *optional*, defaults to `False`):
+        Whether to omit warnings if the target `dtype` is not compatible with the target `device`.

+Returns:
+    [`DiffusionPipeline`]: The pipeline converted to specified `dtype` and/or `dtype`.
+ +
+Class methods inherited from diffusers.pipelines.pipeline_utils.DiffusionPipeline:
+
download(pretrained_model_name, **kwargs) -> Union[str, os.PathLike] from builtins.type
Download and cache a PyTorch diffusion pipeline from pretrained pipeline weights.

+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:

+            - A string, the *repository id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained
+              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 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`
+              instead of `clip_guided_stable_diffusion.py`). Community pipelines are always loaded from the
+              current `main` branch of GitHub.

+            - A path to a *directory* (`./my_pipeline_directory/`) containing a custom pipeline. The directory
+              must contain a file called `pipeline.py` that defines the custom pipeline.

+        <Tip warning={true}>

+        🧪 This is an experimental feature and may change in the future.

+        </Tip>

+        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 not to force the (re-)download of the model weights and configuration files, overriding the
+        cached versions if they exist.
+    resume_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
+        incompletely downloaded files are deleted.
+    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`):
+        Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
+    local_files_only (`bool`, *optional*, defaults to `False`):
+        Whether to only load local model weights and configuration files or not. If set to `True`, the model
+        won't be downloaded from the Hub.
+    token (`str` or *bool*, *optional*):
+        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
+        `diffusers-cli login` (stored in `~/.huggingface`) is used.
+    revision (`str`, *optional*, defaults to `"main"`):
+        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
+        `revision` when loading a custom pipeline from the Hub. It can be a 🤗 Diffusers version when loading a
+        custom pipeline from GitHub, otherwise it defaults to `"main"` when loading from the Hub.
+    mirror (`str`, *optional*):
+        Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
+        guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
+        information.
+    variant (`str`, *optional*):
+        Load weights from a specified variant filename such as `"fp16"` or `"ema"`. This is ignored when
+        loading `from_flax`.
+    use_safetensors (`bool`, *optional*, defaults to `None`):
+        If set to `None`, the safetensors weights are downloaded if they're available **and** if the
+        safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
+        weights. If set to `False`, safetensors weights are not loaded.
+    use_onnx (`bool`, *optional*, defaults to `False`):
+        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 files ending
+        with `.onnx` and `.pb`.
+    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 will execute code present on the Hub on your local machine.

+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>
+ +
from_pipe(pipeline, **kwargs) from builtins.type
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`):
+        The pipeline from which to create a new pipeline.

+Returns:
+    `DiffusionPipeline`:
+        A new pipeline with the same weights and configurations as `pipeline`.

+Examples:

+```py
+>>> from diffusers import StableDiffusionPipeline, StableDiffusionSAGPipeline

+>>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
+>>> new_pipe = StableDiffusionSAGPipeline.from_pipe(pipe)
+```
+ +
from_pretrained(pretrained_model_name_or_path: Union[str, os.PathLike, NoneType], **kwargs) from builtins.type
Instantiate a PyTorch diffusion pipeline from pretrained pipeline weights.

+The pipeline is set in evaluation mode (`model.eval()`) by default.

+If you get the error message below, you need to finetune the weights for your downstream task:

+```
+Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/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 the model instantiated
+You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
+```

+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 *directory* (for example `./my_pipeline_directory/`) containing pipeline weights
+              saved using
+            [`~DiffusionPipeline.save_pretrained`].
+    torch_dtype (`str` or `torch.dtype`, *optional*):
+        Override the default `torch.dtype` and load the model with another dtype. If "auto" is passed, the
+        dtype is automatically derived from the model's weights.
+    custom_pipeline (`str`, *optional*):

+        <Tip warning={true}>

+        🧪 This is an experimental feature and may change in the future.

+        </Tip>

+        Can be either:

+            - 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 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`
+              instead of `clip_guided_stable_diffusion.py`). Community pipelines are always loaded from the
+              current main branch of GitHub.
+            - A path to a directory (`./my_pipeline_directory/`) containing a custom pipeline. The directory
+              must contain a file called `pipeline.py` that defines the custom pipeline.

+        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`):
+        Whether or not to force the (re-)download of the model weights and configuration files, overriding the
+        cached versions if they exist.
+    cache_dir (`Union[str, os.PathLike]`, *optional*):
+        Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
+        is not used.
+    resume_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
+        incompletely downloaded files are deleted.
+    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`):
+        Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
+    local_files_only (`bool`, *optional*, defaults to `False`):
+        Whether to only load local model weights and configuration files or not. If set to `True`, the model
+        won't be downloaded from the Hub.
+    token (`str` or *bool*, *optional*):
+        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
+        `diffusers-cli login` (stored in `~/.huggingface`) is used.
+    revision (`str`, *optional*, defaults to `"main"`):
+        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
+        `revision` when loading a custom pipeline from the Hub. Defaults to the latest stable 🤗 Diffusers
+        version.
+    mirror (`str`, *optional*):
+        Mirror source to resolve accessibility issues if you’re downloading a model in China. We do not
+        guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
+        information.
+    device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
+        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.

+        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`, *optional*):
+        A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
+        each GPU and the available CPU RAM if unset.
+    offload_folder (`str` or `os.PathLike`, *optional*):
+        The path to offload weights if device_map contains the value `"disk"`.
+    offload_state_dict (`bool`, *optional*):
+        If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if
+        the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`
+        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 in CPU memory (including peak memory) while loading the model.
+        Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
+        argument to `True` will raise an error.
+    use_safetensors (`bool`, *optional*, defaults to `None`):
+        If set to `None`, the safetensors weights are downloaded if they're available **and** if the
+        safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
+        weights. If set to `False`, safetensors weights are not loaded.
+    use_onnx (`bool`, *optional*, defaults to `None`):
+        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 files ending
+        with `.onnx` and `.pb`.
+    kwargs (remaining dictionary of keyword arguments, *optional*):
+        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*):
+        Load weights from a specified variant filename such as `"fp16"` or `"ema"`. This is ignored when
+        loading `from_flax`.

+<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.
+>>> pipeline = DiffusionPipeline.from_pretrained("CompVis/ldm-text2im-large-256")

+>>> # Download pipeline that requires an authorization token
+>>> # For more information on access tokens, please refer to this section
+>>> # of the documentation](https://huggingface.co/docs/hub/security-tokens)
+>>> pipeline = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")

+>>> # Use a different scheduler
+>>> from diffusers import LMSDiscreteScheduler

+>>> scheduler = LMSDiscreteScheduler.from_config(pipeline.scheduler.config)
+>>> pipeline.scheduler = scheduler
+```
+ +
+Static methods inherited from diffusers.pipelines.pipeline_utils.DiffusionPipeline:
+
numpy_to_pil(images)
Convert a NumPy image or a batch of images to a PIL image.
+ +
+Readonly properties inherited from diffusers.pipelines.pipeline_utils.DiffusionPipeline:
+
components
+
The `self.components` property can be useful to run different pipelines with the same weights and
+configurations without reallocating additional memory.

+Returns (`dict`):
+    A dictionary containing all the modules needed to initialize the pipeline.

+Examples:

+```py
+>>> from diffusers import (
+...     StableDiffusionPipeline,
+...     StableDiffusionImg2ImgPipeline,
+...     StableDiffusionInpaintPipeline,
+... )

+>>> text2img = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
+>>> img2img = StableDiffusionImg2ImgPipeline(**text2img.components)
+>>> inpaint = StableDiffusionInpaintPipeline(**text2img.components)
+```
+
+
device
+
Returns:
+    `torch.device`: The torch device on which the pipeline is located.
+
+
dtype
+
Returns:
+    `torch.dtype`: The torch dtype on which the pipeline is located.
+
+
name_or_path
+
+
+Data and other attributes inherited from diffusers.pipelines.pipeline_utils.DiffusionPipeline:
+
config_name = 'model_index.json'
+ +
hf_device_map = None
+ +
+Methods inherited from diffusers.configuration_utils.ConfigMixin:
+
__getattr__(self, name: str) -> Any
The only reason we overwrite `getattr` here is to gracefully deprecate accessing
+config attributes directly. See https://github.com/huggingface/diffusers/pull/3129

+This function is mostly copied from PyTorch's __getattr__ overwrite:
+https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
+ +
__repr__(self)
Return repr(self).
+ +
register_to_config(self, **kwargs)
+ +
save_config(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs)
Save a configuration object to the directory specified in `save_directory` so that it can be reloaded using the
+[`~ConfigMixin.from_config`] class method.

+Args:
+    save_directory (`str` or `os.PathLike`):
+        Directory where the configuration JSON file is saved (will be created if it does not exist).
+    push_to_hub (`bool`, *optional*, defaults to `False`):
+        Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
+        repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
+        namespace).
+    kwargs (`Dict[str, Any]`, *optional*):
+        Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
+ +
to_json_file(self, json_file_path: Union[str, os.PathLike])
Save the configuration instance's parameters to a JSON file.

+Args:
+    json_file_path (`str` or `os.PathLike`):
+        Path to the JSON file to save a configuration instance's parameters.
+ +
to_json_string(self) -> str
Serializes the configuration instance to a JSON string.

+Returns:
+    `str`:
+        String containing all the attributes that make up the configuration instance in JSON format.
+ +
+Class methods inherited from diffusers.configuration_utils.ConfigMixin:
+
extract_init_dict(config_dict, **kwargs) from builtins.type
+ +
from_config(config: Union[diffusers.configuration_utils.FrozenDict, Dict[str, Any]] = None, return_unused_kwargs=False, **kwargs) from builtins.type
Instantiate a Python class from a config dictionary.

+Parameters:
+    config (`Dict[str, Any]`):
+        A config dictionary from which the Python class is instantiated. Make sure to only load configuration
+        files of compatible classes.
+    return_unused_kwargs (`bool`, *optional*, defaults to `False`):
+        Whether kwargs that are not consumed by the Python class should be returned or not.
+    kwargs (remaining dictionary of keyword arguments, *optional*):
+        Can be used to update the configuration object (after it is loaded) and initiate the Python class.
+        `**kwargs` are passed directly to the underlying scheduler/model's `__init__` method and eventually
+        overwrite the same named arguments in `config`.

+Returns:
+    [`ModelMixin`] or [`SchedulerMixin`]:
+        A model or scheduler object instantiated from a config dictionary.

+Examples:

+```python
+>>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler

+>>> # Download scheduler from huggingface.co and cache.
+>>> scheduler = DDPMScheduler.from_pretrained("google/ddpm-cifar10-32")

+>>> # Instantiate DDIM scheduler class with same config as DDPM
+>>> scheduler = DDIMScheduler.from_config(scheduler.config)

+>>> # Instantiate PNDM scheduler class with same config as DDPM
+>>> scheduler = PNDMScheduler.from_config(scheduler.config)
+```
+ +
get_config_dict(*args, **kwargs) from builtins.type
+ +
load_config(pretrained_model_name_or_path: Union[str, os.PathLike], return_unused_kwargs=False, return_commit_hash=False, **kwargs) -> Tuple[Dict[str, Any], Dict[str, Any]] from builtins.type
Load a model or scheduler configuration.

+Parameters:
+    pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
+        Can be either:

+            - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
+              the Hub.
+            - A path to a *directory* (for example `./my_model_directory`) containing model weights saved with
+              [`~ConfigMixin.save_config`].

+    cache_dir (`Union[str, os.PathLike]`, *optional*):
+        Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
+        is not used.
+    force_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to force the (re-)download of the model weights and configuration files, overriding the
+        cached versions if they exist.
+    resume_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
+        incompletely downloaded files are deleted.
+    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`):
+        Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
+    local_files_only (`bool`, *optional*, defaults to `False`):
+        Whether to only load local model weights and configuration files or not. If set to `True`, the model
+        won't be downloaded from the Hub.
+    token (`str` or *bool*, *optional*):
+        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
+        `diffusers-cli login` (stored in `~/.huggingface`) is used.
+    revision (`str`, *optional*, defaults to `"main"`):
+        The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
+        allowed by Git.
+    subfolder (`str`, *optional*, defaults to `""`):
+        The subfolder location of a model file within a larger model repository on the Hub or locally.
+    return_unused_kwargs (`bool`, *optional*, defaults to `False):
+        Whether unused keyword arguments of the config are returned.
+    return_commit_hash (`bool`, *optional*, defaults to `False):
+        Whether the `commit_hash` of the loaded configuration are returned.

+Returns:
+    `dict`:
+        A dictionary of all the parameters stored in a JSON configuration file.
+ +
+Readonly properties inherited from diffusers.configuration_utils.ConfigMixin:
+
config
+
Returns the config of the class as a frozen dictionary

+Returns:
+    `Dict[str, Any]`: Config of the class.
+
+
+Data descriptors inherited from diffusers.configuration_utils.ConfigMixin:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+
+Data and other attributes inherited from diffusers.configuration_utils.ConfigMixin:
+
has_compatibles = False
+ +
ignore_for_config = []
+ +
+Methods inherited from diffusers.utils.hub_utils.PushToHubMixin:
+
push_to_hub(self, repo_id: str, commit_message: Optional[str] = None, private: Optional[bool] = None, token: Optional[str] = None, create_pr: bool = False, safe_serialization: bool = True, variant: Optional[str] = None) -> str
Upload model, scheduler, or pipeline files to the 🤗 Hugging Face Hub.

+Parameters:
+    repo_id (`str`):
+        The name of the repository you want to push your model, scheduler, or pipeline files to. It should
+        contain your organization name when pushing to an organization. `repo_id` can also be a path to a local
+        directory.
+    commit_message (`str`, *optional*):
+        Message to commit while pushing. Default to `"Upload {object}"`.
+    private (`bool`, *optional*):
+        Whether or not the repository created should be private.
+    token (`str`, *optional*):
+        The token to use as HTTP bearer authorization for remote files. The token generated when running
+        `huggingface-cli login` (stored in `~/.huggingface`).
+    create_pr (`bool`, *optional*, defaults to `False`):
+        Whether or not to create a PR with the uploaded files or directly commit.
+    safe_serialization (`bool`, *optional*, defaults to `True`):
+        Whether or not to convert the model weights to the `safetensors` format.
+    variant (`str`, *optional*):
+        If specified, weights are saved in the format `pytorch_model.<variant>.bin`.

+Examples:

+```python
+from diffusers import UNet2DConditionModel

+unet = UNet2DConditionModel.from_pretrained("stabilityai/stable-diffusion-2", subfolder="unet")

+# Push the `unet` to your namespace with the name "my-finetuned-unet".
+unet.push_to_hub("my-finetuned-unet")

+# Push the `unet` to an organization with the name "my-finetuned-unet".
+unet.push_to_hub("your-org/my-finetuned-unet")
+```
+ +
+Methods inherited from diffusers.pipelines.pipeline_utils.StableDiffusionMixin:
+
disable_freeu(self)
Disables the FreeU mechanism if enabled.
+ +
disable_vae_slicing(self)
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
+computing decoding in one step.
+ +
disable_vae_tiling(self)
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
+computing decoding in one step.
+ +
enable_freeu(self, s1: float, s2: float, b1: float, b2: float)
Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.

+The suffixes after the scaling factors represent the stages where they are being applied.

+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.

+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 contributions of the skip features. This is done to
+        mitigate "oversmoothing effect" in the enhanced denoising process.
+    b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
+    b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
+ +
enable_vae_slicing(self)
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
+compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
+ +
enable_vae_tiling(self)
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.
+ +
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}>

+This API is 🧪 experimental.

+</Tip>

+Args:
+    unet (`bool`, defaults to `True`): To apply fusion on the UNet.
+    vae (`bool`, defaults to `True`): To apply fusion on the VAE.
+ +
unfuse_qkv_projections(self, unet: bool = True, vae: bool = True)
Disable QKV projection fusion if enabled.

+<Tip warning={true}>

+This API is 🧪 experimental.

+</Tip>

+Args:
+    unet (`bool`, defaults to `True`): To apply fusion on the UNet.
+    vae (`bool`, defaults to `True`): To apply fusion on the VAE.
+ +
+Methods inherited from diffusers.loaders.textual_inversion.TextualInversionLoaderMixin:
+
load_textual_inversion(self, pretrained_model_name_or_path: Union[str, List[str], Dict[str, torch.Tensor], List[Dict[str, torch.Tensor]]], token: Union[str, List[str], NoneType] = None, tokenizer: Optional[ForwardRef('PreTrainedTokenizer')] = None, text_encoder: Optional[ForwardRef('PreTrainedModel')] = None, **kwargs)
Load Textual Inversion embeddings into the text encoder of [`StableDiffusionPipeline`] (both 🤗 Diffusers and
+Automatic1111 formats are supported).

+Parameters:
+    pretrained_model_name_or_path (`str` or `os.PathLike` or `List[str or os.PathLike]` or `Dict` or `List[Dict]`):
+        Can be either one of the following or a list of them:

+            - A string, the *model id* (for example `sd-concepts-library/low-poly-hd-logos-icons`) of a
+              pretrained model hosted on the Hub.
+            - A path to a *directory* (for example `./my_text_inversion_directory/`) containing the textual
+              inversion weights.
+            - A path to a *file* (for example `./my_text_inversions.pt`) containing textual inversion weights.
+            - A [torch state
+              dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).

+    token (`str` or `List[str]`, *optional*):
+        Override the token to use for the textual inversion weights. If `pretrained_model_name_or_path` is a
+        list, then `token` must also be a list of equal length.
+    text_encoder ([`~transformers.CLIPTextModel`], *optional*):
+        Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
+        If not specified, function will take self.tokenizer.
+    tokenizer ([`~transformers.CLIPTokenizer`], *optional*):
+        A `CLIPTokenizer` to tokenize text. If not specified, function will take self.tokenizer.
+    weight_name (`str`, *optional*):
+        Name of a custom weight file. This should be used when:

+            - The saved textual inversion file is in 🤗 Diffusers format, but was saved under a specific weight
+              name such as `text_inv.bin`.
+            - The saved textual inversion file is in the Automatic1111 format.
+    cache_dir (`Union[str, os.PathLike]`, *optional*):
+        Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
+        is not used.
+    force_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to force the (re-)download of the model weights and configuration files, overriding the
+        cached versions if they exist.
+    resume_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
+        incompletely downloaded files are deleted.
+    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.
+    local_files_only (`bool`, *optional*, defaults to `False`):
+        Whether to only load local model weights and configuration files or not. If set to `True`, the model
+        won't be downloaded from the Hub.
+    token (`str` or *bool*, *optional*):
+        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
+        `diffusers-cli login` (stored in `~/.huggingface`) is used.
+    revision (`str`, *optional*, defaults to `"main"`):
+        The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
+        allowed by Git.
+    subfolder (`str`, *optional*, defaults to `""`):
+        The subfolder location of a model file within a larger model repository on the Hub or locally.
+    mirror (`str`, *optional*):
+        Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
+        guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
+        information.

+Example:

+To load a Textual Inversion embedding vector in 🤗 Diffusers format:

+```py
+from diffusers import StableDiffusionPipeline
+import torch

+model_id = "runwayml/stable-diffusion-v1-5"
+pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

+pipe.load_textual_inversion("sd-concepts-library/cat-toy")

+prompt = "A <cat-toy> backpack"

+image = pipe(prompt, num_inference_steps=50).images[0]
+image.save("cat-backpack.png")
+```

+To load a Textual Inversion embedding vector in Automatic1111 format, make sure to download the vector first
+(for example from [civitAI](https://civitai.com/models/3036?modelVersionId=9857)) and then load the vector
+locally:

+```py
+from diffusers import StableDiffusionPipeline
+import torch

+model_id = "runwayml/stable-diffusion-v1-5"
+pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

+pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")

+prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."

+image = pipe(prompt, num_inference_steps=50).images[0]
+image.save("character.png")
+```
+ +
maybe_convert_prompt(self, prompt: Union[str, List[str]], tokenizer: 'PreTrainedTokenizer')
Processes prompts that include a special token corresponding to a multi-vector textual inversion embedding to
+be replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
+inversion token or if the textual inversion token is a single vector, the input prompt is returned.

+Parameters:
+    prompt (`str` or list of `str`):
+        The prompt or prompts to guide the image generation.
+    tokenizer (`PreTrainedTokenizer`):
+        The tokenizer responsible for encoding the prompt into input tokens.

+Returns:
+    `str` or list of `str`: The converted prompt
+ +
unload_textual_inversion(self, tokens: Union[str, List[str], NoneType] = None, tokenizer: Optional[ForwardRef('PreTrainedTokenizer')] = None, text_encoder: Optional[ForwardRef('PreTrainedModel')] = None)
Unload Textual Inversion embeddings from the text encoder of [`StableDiffusionPipeline`]

+Example:
+```py
+from diffusers import AutoPipelineForText2Image
+import torch

+pipeline = AutoPipelineForText2Image.from_pretrained("runwayml/stable-diffusion-v1-5")

+# Example 1
+pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")
+pipeline.load_textual_inversion("sd-concepts-library/moeb-style")

+# Remove all token embeddings
+pipeline.unload_textual_inversion()

+# Example 2
+pipeline.load_textual_inversion("sd-concepts-library/moeb-style")
+pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")

+# Remove just one token
+pipeline.unload_textual_inversion("<moe-bius>")

+# Example 3: unload from SDXL
+pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0")
+embedding_path = hf_hub_download(
+    repo_id="linoyts/web_y2k", filename="web_y2k_emb.safetensors", repo_type="model"
+)

+# load embeddings to the text encoders
+state_dict = load_file(embedding_path)

+# load embeddings of text_encoder 1 (CLIP ViT-L/14)
+pipeline.load_textual_inversion(
+    state_dict["clip_l"],
+    token=["<s0>", "<s1>"],
+    text_encoder=pipeline.text_encoder,
+    tokenizer=pipeline.tokenizer,
+)
+# load embeddings of text_encoder 2 (CLIP ViT-G/14)
+pipeline.load_textual_inversion(
+    state_dict["clip_g"],
+    token=["<s0>", "<s1>"],
+    text_encoder=pipeline.text_encoder_2,
+    tokenizer=pipeline.tokenizer_2,
+)

+# Unload explicitly from both text encoders abd tokenizers
+pipeline.unload_textual_inversion(
+    tokens=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder, tokenizer=pipeline.tokenizer
+)
+pipeline.unload_textual_inversion(
+    tokens=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder_2, tokenizer=pipeline.tokenizer_2
+)
+```
+ +
+Methods inherited from diffusers.loaders.ip_adapter.IPAdapterMixin:
+
load_ip_adapter(self, pretrained_model_name_or_path_or_dict: Union[str, List[str], Dict[str, torch.Tensor]], subfolder: Union[str, List[str]], weight_name: Union[str, List[str]], image_encoder_folder: Optional[str] = 'image_encoder', **kwargs)
Parameters:
+    pretrained_model_name_or_path_or_dict (`str` or `List[str]` or `os.PathLike` or `List[os.PathLike]` or `dict` or `List[dict]`):
+        Can be either:

+            - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
+              the Hub.
+            - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
+              with [`ModelMixin.save_pretrained`].
+            - A [torch state
+              dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
+    subfolder (`str` or `List[str]`):
+        The subfolder location of a model file within a larger model repository on the Hub or locally. If a
+        list is passed, it should have the same length as `weight_name`.
+    weight_name (`str` or `List[str]`):
+        The name of the weight file to load. If a list is passed, it should have the same length as
+        `weight_name`.
+    image_encoder_folder (`str`, *optional*, defaults to `image_encoder`):
+        The subfolder location of the image encoder within a larger model repository on the Hub or locally.
+        Pass `None` to not load the image encoder. If the image encoder is located in a folder inside
+        `subfolder`, you only need to pass the name of the folder that contains image encoder weights, e.g.
+        `image_encoder_folder="image_encoder"`. If the image encoder is located in a folder other than
+        `subfolder`, you should pass the path to the folder that contains image encoder weights, for example,
+        `image_encoder_folder="different_subfolder/image_encoder"`.
+    cache_dir (`Union[str, os.PathLike]`, *optional*):
+        Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
+        is not used.
+    force_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to force the (re-)download of the model weights and configuration files, overriding the
+        cached versions if they exist.
+    resume_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
+        incompletely downloaded files are deleted.
+    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.
+    local_files_only (`bool`, *optional*, defaults to `False`):
+        Whether to only load local model weights and configuration files or not. If set to `True`, the model
+        won't be downloaded from the Hub.
+    token (`str` or *bool*, *optional*):
+        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
+        `diffusers-cli login` (stored in `~/.huggingface`) is used.
+    revision (`str`, *optional*, defaults to `"main"`):
+        The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
+        allowed by Git.
+    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 in CPU memory (including peak memory) while loading the model.
+        Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
+        argument to `True` will raise an error.
+ +
set_ip_adapter_scale(self, scale)
Sets the conditioning scale between text and image.

+Example:

+```py
+pipeline.set_ip_adapter_scale(0.5)
+```
+ +
unload_ip_adapter(self)
Unloads the IP Adapter weights

+Examples:

+```python
+>>> # Assuming `pipeline` is already loaded with the IP Adapter weights.
+>>> pipeline.unload_ip_adapter()
+>>> ...
+```
+ +
+Methods inherited from diffusers.loaders.lora.LoraLoaderMixin:
+
delete_adapters(self, adapter_names: Union[List[str], str])
Args:
+Deletes the LoRA layers of `adapter_name` for the unet and text-encoder(s).
+    adapter_names (`Union[List[str], str]`):
+        The names of the adapter to delete. Can be a single string or a list of strings
+ +
disable_lora(self)
+ +
disable_lora_for_text_encoder(self, text_encoder: Optional[ForwardRef('PreTrainedModel')] = None)
Disables the LoRA layers for the text encoder.

+Args:
+    text_encoder (`torch.nn.Module`, *optional*):
+        The text encoder module to disable the LoRA layers for. If `None`, it will try to get the
+        `text_encoder` attribute.
+ +
enable_lora(self)
+ +
enable_lora_for_text_encoder(self, text_encoder: Optional[ForwardRef('PreTrainedModel')] = None)
Enables the LoRA layers for the text encoder.

+Args:
+    text_encoder (`torch.nn.Module`, *optional*):
+        The text encoder module to enable the LoRA layers for. If `None`, it will try to get the `text_encoder`
+        attribute.
+ +
fuse_lora(self, fuse_unet: bool = True, fuse_text_encoder: bool = True, lora_scale: float = 1.0, safe_fusing: bool = False, adapter_names: Optional[List[str]] = None)
Fuses the LoRA parameters into the original parameters of the corresponding blocks.

+<Tip warning={true}>

+This is an experimental API.

+</Tip>

+Args:
+    fuse_unet (`bool`, defaults to `True`): Whether to fuse the UNet LoRA parameters.
+    fuse_text_encoder (`bool`, defaults to `True`):
+        Whether to fuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
+        LoRA parameters then it won't have any effect.
+    lora_scale (`float`, defaults to 1.0):
+        Controls how much to influence the outputs with the LoRA parameters.
+    safe_fusing (`bool`, defaults to `False`):
+        Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
+    adapter_names (`List[str]`, *optional*):
+        Adapter names to be used for fusing. If nothing is passed, all active adapters will be fused.

+Example:

+```py
+from diffusers import DiffusionPipeline
+import torch

+pipeline = DiffusionPipeline.from_pretrained(
+    "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
+).to("cuda")
+pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
+pipeline.fuse_lora(lora_scale=0.7)
+```
+ +
get_active_adapters(self) -> List[str]
Gets the list of the current active adapters.

+Example:

+```python
+from diffusers import DiffusionPipeline

+pipeline = DiffusionPipeline.from_pretrained(
+    "stabilityai/stable-diffusion-xl-base-1.0",
+).to("cuda")
+pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy")
+pipeline.get_active_adapters()
+```
+ +
get_list_adapters(self) -> Dict[str, List[str]]
Gets the current list of all available adapters in the pipeline.
+ +
load_lora_weights(self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], adapter_name=None, **kwargs)
Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
+`self.text_encoder`.

+All kwargs are forwarded to `self.lora_state_dict`.

+See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.

+See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
+`self.unet`.

+See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
+into `self.text_encoder`.

+Parameters:
+    pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
+        See [`~loaders.LoraLoaderMixin.lora_state_dict`].
+    kwargs (`dict`, *optional*):
+        See [`~loaders.LoraLoaderMixin.lora_state_dict`].
+    adapter_name (`str`, *optional*):
+        Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
+        `default_{i}` where i is the total number of adapters being loaded.
+ +
set_adapters(self, adapter_names: Union[List[str], str], adapter_weights: Union[float, Dict, List[float], List[Dict], NoneType] = None)
+ +
set_adapters_for_text_encoder(self, adapter_names: Union[List[str], str], text_encoder: Optional[ForwardRef('PreTrainedModel')] = None, text_encoder_weights: Union[float, List[float], List[NoneType], NoneType] = None)
Sets the adapter layers for the text encoder.

+Args:
+    adapter_names (`List[str]` or `str`):
+        The names of the adapters to use.
+    text_encoder (`torch.nn.Module`, *optional*):
+        The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
+        attribute.
+    text_encoder_weights (`List[float]`, *optional*):
+        The weights to use for the text encoder. If `None`, the weights are set to `1.0` for all the adapters.
+ +
set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None
Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case
+you want to load multiple adapters and free some GPU memory.

+Args:
+    adapter_names (`List[str]`):
+        List of adapters to send device to.
+    device (`Union[torch.device, str, int]`):
+        Device to send the adapters to. Can be either a torch device, a str or an integer.
+ +
unfuse_lora(self, unfuse_unet: bool = True, unfuse_text_encoder: bool = True)
Reverses the effect of
+[`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.fuse_lora).

+<Tip warning={true}>

+This is an experimental API.

+</Tip>

+Args:
+    unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
+    unfuse_text_encoder (`bool`, defaults to `True`):
+        Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
+        LoRA parameters then it won't have any effect.
+ +
unload_lora_weights(self)
Unloads the LoRA parameters.

+Examples:

+```python
+>>> # Assuming `pipeline` is already loaded with the LoRA parameters.
+>>> pipeline.unload_lora_weights()
+>>> ...
+```
+ +
+Class methods inherited from diffusers.loaders.lora.LoraLoaderMixin:
+
load_lora_into_text_encoder(state_dict, network_alphas, text_encoder, prefix=None, lora_scale=1.0, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None) from builtins.type
This will load the LoRA layers specified in `state_dict` into `text_encoder`

+Parameters:
+    state_dict (`dict`):
+        A standard state dict containing the lora layer parameters. The key should be prefixed with an
+        additional `text_encoder` to distinguish between unet lora layers.
+    network_alphas (`Dict[str, float]`):
+        See `LoRALinearLayer` for more details.
+    text_encoder (`CLIPTextModel`):
+        The text encoder model to load the LoRA layers into.
+    prefix (`str`):
+        Expected prefix of the `text_encoder` in the `state_dict`.
+    lora_scale (`float`):
+        How much to scale the output of the lora linear layer before it is added with the output of the regular
+        lora layer.
+    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 in CPU memory (including peak memory) while loading the model.
+        Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
+        argument to `True` will raise an error.
+    adapter_name (`str`, *optional*):
+        Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
+        `default_{i}` where i is the total number of adapters being loaded.
+ +
load_lora_into_transformer(state_dict, network_alphas, transformer, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None) from builtins.type
This will load the LoRA layers specified in `state_dict` into `transformer`.

+Parameters:
+    state_dict (`dict`):
+        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
+        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
+        encoder lora layers.
+    network_alphas (`Dict[str, float]`):
+        See `LoRALinearLayer` for more details.
+    unet (`UNet2DConditionModel`):
+        The UNet model to load the LoRA layers into.
+    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 in CPU memory (including peak memory) while loading the model.
+        Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
+        argument to `True` will raise an error.
+    adapter_name (`str`, *optional*):
+        Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
+        `default_{i}` where i is the total number of adapters being loaded.
+ +
load_lora_into_unet(state_dict, network_alphas, unet, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None) from builtins.type
This will load the LoRA layers specified in `state_dict` into `unet`.

+Parameters:
+    state_dict (`dict`):
+        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
+        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
+        encoder lora layers.
+    network_alphas (`Dict[str, float]`):
+        See `LoRALinearLayer` for more details.
+    unet (`UNet2DConditionModel`):
+        The UNet model to load the LoRA layers into.
+    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 in CPU memory (including peak memory) while loading the model.
+        Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
+        argument to `True` will raise an error.
+    adapter_name (`str`, *optional*):
+        Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
+        `default_{i}` where i is the total number of adapters being loaded.
+ +
lora_state_dict(pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], **kwargs) from builtins.type
Return state dict for lora weights and the network alphas.

+<Tip warning={true}>

+We support loading A1111 formatted LoRA checkpoints in a limited capacity.

+This function is experimental and might change in the future.

+</Tip>

+Parameters:
+    pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
+        Can be either:

+            - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
+              the Hub.
+            - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
+              with [`ModelMixin.save_pretrained`].
+            - A [torch state
+              dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).

+    cache_dir (`Union[str, os.PathLike]`, *optional*):
+        Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
+        is not used.
+    force_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to force the (re-)download of the model weights and configuration files, overriding the
+        cached versions if they exist.
+    resume_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
+        incompletely downloaded files are deleted.
+    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.
+    local_files_only (`bool`, *optional*, defaults to `False`):
+        Whether to only load local model weights and configuration files or not. If set to `True`, the model
+        won't be downloaded from the Hub.
+    token (`str` or *bool*, *optional*):
+        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
+        `diffusers-cli login` (stored in `~/.huggingface`) is used.
+    revision (`str`, *optional*, defaults to `"main"`):
+        The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
+        allowed by Git.
+    subfolder (`str`, *optional*, defaults to `""`):
+        The subfolder location of a model file within a larger model repository on the Hub or locally.
+    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 in CPU memory (including peak memory) while loading the model.
+        Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
+        argument to `True` will raise an error.
+    mirror (`str`, *optional*):
+        Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
+        guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
+        information.
+ +
save_lora_weights(save_directory: Union[str, os.PathLike], unet_lora_layers: Dict[str, Union[torch.nn.modules.module.Module, torch.Tensor]] = None, text_encoder_lora_layers: Dict[str, torch.nn.modules.module.Module] = None, transformer_lora_layers: Dict[str, torch.nn.modules.module.Module] = None, is_main_process: bool = True, weight_name: str = None, save_function: Callable = None, safe_serialization: bool = True) from builtins.type
Save the LoRA parameters corresponding to the UNet and text encoder.

+Arguments:
+    save_directory (`str` or `os.PathLike`):
+        Directory to save LoRA parameters to. Will be created if it doesn't exist.
+    unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
+        State dict of the LoRA layers corresponding to the `unet`.
+    text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
+        State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
+        encoder LoRA state dict because it comes from 🤗 Transformers.
+    is_main_process (`bool`, *optional*, defaults to `True`):
+        Whether the process calling this is the main process or not. Useful during distributed training and you
+        need to call this function on all processes. In this case, set `is_main_process=True` only on the main
+        process to avoid race conditions.
+    save_function (`Callable`):
+        The function to use to save the state dictionary. Useful during distributed training when you need to
+        replace `torch.save` with another method. Can be configured with the environment variable
+        `DIFFUSERS_SAVE_MODE`.
+    safe_serialization (`bool`, *optional*, defaults to `True`):
+        Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
+ +
+Static methods inherited from diffusers.loaders.lora.LoraLoaderMixin:
+
write_lora_layers(state_dict: Dict[str, torch.Tensor], save_directory: str, is_main_process: bool, weight_name: str, save_function: Callable, safe_serialization: bool)
+ +
+Readonly properties inherited from diffusers.loaders.lora.LoraLoaderMixin:
+
lora_scale
+
+
+Data and other attributes inherited from diffusers.loaders.lora.LoraLoaderMixin:
+
num_fused_loras = 0
+ +
text_encoder_name = 'text_encoder'
+ +
transformer_name = 'transformer'
+ +
unet_name = 'unet'
+ +
+Class methods inherited from diffusers.loaders.single_file.FromSingleFileMixin:
+
from_single_file(pretrained_model_link_or_path, **kwargs) from builtins.type
Instantiate a [`DiffusionPipeline`] from pretrained pipeline weights saved in the `.ckpt` or `.safetensors`
+format. The pipeline is set in evaluation mode (`model.eval()`) by default.

+Parameters:
+    pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
+        Can be either:
+            - A link to the `.ckpt` file (for example
+              `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
+            - A path to a *file* containing all pipeline weights.
+    torch_dtype (`str` or `torch.dtype`, *optional*):
+        Override the default `torch.dtype` and load the model with another dtype.
+    force_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to force the (re-)download of the model weights and configuration files, overriding the
+        cached versions if they exist.
+    cache_dir (`Union[str, os.PathLike]`, *optional*):
+        Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
+        is not used.
+    resume_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
+        incompletely downloaded files are deleted.
+    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.
+    local_files_only (`bool`, *optional*, defaults to `False`):
+        Whether to only load local model weights and configuration files or not. If set to `True`, the model
+        won't be downloaded from the Hub.
+    token (`str` or *bool*, *optional*):
+        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
+        `diffusers-cli login` (stored in `~/.huggingface`) is used.
+    revision (`str`, *optional*, defaults to `"main"`):
+        The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
+        allowed by Git.
+    original_config_file (`str`, *optional*):
+        The path to the original config file that was used to train the model. If not provided, the config file
+        will be inferred from the checkpoint file.
+    model_type (`str`, *optional*):
+        The type of model to load. If not provided, the model type will be inferred from the checkpoint file.
+    image_size (`int`, *optional*):
+        The size of the image output. It's used to configure the `sample_size` parameter of the UNet and VAE
+        model.
+    load_safety_checker (`bool`, *optional*, defaults to `False`):
+        Whether to load the safety checker model or not. By default, the safety checker is not loaded unless a
+        `safety_checker` component is passed to the `kwargs`.
+    num_in_channels (`int`, *optional*):
+        Specify the number of input channels for the UNet model. Read more about how to configure UNet model
+        with this parameter
+        [here](https://huggingface.co/docs/diffusers/training/adapt_a_model#configure-unet2dconditionmodel-parameters).
+    scaling_factor (`float`, *optional*):
+        The scaling factor to use for the VAE model. If not provided, it is inferred from the config file
+        first. If the scaling factor is not found in the config file, the default value 0.18215 is used.
+    scheduler_type (`str`, *optional*):
+        The type of scheduler to load. If not provided, the scheduler type will be inferred from the checkpoint
+        file.
+    prediction_type (`str`, *optional*):
+        The type of prediction to load. If not provided, the prediction type will be inferred from the
+        checkpoint file.
+    kwargs (remaining dictionary of keyword arguments, *optional*):
+        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.

+Examples:

+```py
+>>> from diffusers import StableDiffusionPipeline

+>>> # Download pipeline from huggingface.co and cache.
+>>> pipeline = StableDiffusionPipeline.from_single_file(
+...     "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
+... )

+>>> # Download pipeline from local file
+>>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
+>>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly")

+>>> # Enable float16 and move to GPU
+>>> pipeline = StableDiffusionPipeline.from_single_file(
+...     "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
+...     torch_dtype=torch.float16,
+... )
+>>> pipeline.to("cuda")
+```
+ +

+ + + + + +
 
+Data
       Any = typing.Any
+Callable = typing.Callable
+Dict = typing.Dict
+List = typing.List
+Optional = typing.Optional
+PipelineImageInput = typing.Union[PIL.Image.Image, numpy.ndarray, tor...t[numpy.ndarray], typing.List[torch.FloatTensor]]
+Union = typing.Union
+ \ No newline at end of file diff --git a/docs/generated/multigen.pipelines.masked_stable_diffusion_xl_img2img.html b/docs/generated/multigen.pipelines.masked_stable_diffusion_xl_img2img.html new file mode 100644 index 0000000..926d49a --- /dev/null +++ b/docs/generated/multigen.pipelines.masked_stable_diffusion_xl_img2img.html @@ -0,0 +1,1588 @@ + +Python: module multigen.pipelines.masked_stable_diffusion_xl_img2img + + + + + +
 
+ 
multigen.pipelines.masked_stable_diffusion_xl_img2img
index
/home/imgen/projects/metafusion/multigen/pipelines/masked_stable_diffusion_xl_img2img.py
+

+

+ + + + + +
 
+Modules
       
PIL
+inspect
+
diffusers.utils.logging
+numpy
+
torch
+

+ + + + + +
 
+Classes
       
+
diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline(diffusers.pipelines.pipeline_utils.DiffusionPipeline, diffusers.pipelines.pipeline_utils.StableDiffusionMixin, diffusers.loaders.textual_inversion.TextualInversionLoaderMixin, diffusers.loaders.single_file.FromSingleFileMixin, diffusers.loaders.lora.StableDiffusionXLLoraLoaderMixin, diffusers.loaders.ip_adapter.IPAdapterMixin) +
+
+
MaskedStableDiffusionXLImg2ImgPipeline +
+
+
+

+ + + + + + + +
 
+class MaskedStableDiffusionXLImg2ImgPipeline(diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline)
   MaskedStableDiffusionXLImg2ImgPipeline(vae: diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL, text_encoder: transformers.models.clip.modeling_clip.CLIPTextModel, text_encoder_2: transformers.models.clip.modeling_clip.CLIPTextModelWithProjection, tokenizer: transformers.models.clip.tokenization_clip.CLIPTokenizer, tokenizer_2: transformers.models.clip.tokenization_clip.CLIPTokenizer, unet: diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, scheduler: diffusers.schedulers.scheduling_utils.KarrasDiffusionSchedulers, image_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection = None, feature_extractor: transformers.models.clip.image_processing_clip.CLIPImageProcessor = None, requires_aesthetics_score: bool = False, force_zeros_for_empty_prompt: bool = True, add_watermarker: Optional[bool] = None)

+
 
 
Method resolution order:
+
MaskedStableDiffusionXLImg2ImgPipeline
+
diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline
+
diffusers.pipelines.pipeline_utils.DiffusionPipeline
+
diffusers.configuration_utils.ConfigMixin
+
diffusers.utils.hub_utils.PushToHubMixin
+
diffusers.pipelines.pipeline_utils.StableDiffusionMixin
+
diffusers.loaders.textual_inversion.TextualInversionLoaderMixin
+
diffusers.loaders.single_file.FromSingleFileMixin
+
diffusers.loaders.lora.StableDiffusionXLLoraLoaderMixin
+
diffusers.loaders.lora.LoraLoaderMixin
+
diffusers.loaders.ip_adapter.IPAdapterMixin
+
builtins.object
+
+
+Methods defined here:
+
__call__(self, prompt: Union[str, List[str]] = None, prompt_2: Union[str, List[str], NoneType] = None, image: Union[PIL.Image.Image, numpy.ndarray, torch.FloatTensor, List[PIL.Image.Image], List[numpy.ndarray], List[torch.FloatTensor]] = None, original_image: Union[PIL.Image.Image, numpy.ndarray, torch.FloatTensor, List[PIL.Image.Image], List[numpy.ndarray], List[torch.FloatTensor]] = None, strength: float = 0.3, num_inference_steps: Optional[int] = 50, timesteps: List[int] = None, denoising_start: Optional[float] = None, denoising_end: Optional[float] = None, guidance_scale: Optional[float] = 5.0, negative_prompt: Union[str, List[str], NoneType] = None, negative_prompt_2: Union[str, List[str], NoneType] = None, num_images_per_prompt: Optional[int] = 1, eta: Optional[float] = 0.0, generator: Union[torch._C.Generator, List[torch._C.Generator], NoneType] = None, latents: Optional[torch.FloatTensor] = None, prompt_embeds: Optional[torch.FloatTensor] = None, negative_prompt_embeds: Optional[torch.FloatTensor] = None, pooled_prompt_embeds: Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None, ip_adapter_image: Union[PIL.Image.Image, numpy.ndarray, torch.FloatTensor, List[PIL.Image.Image], List[numpy.ndarray], List[torch.FloatTensor], NoneType] = None, ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None, output_type: Optional[str] = 'pil', return_dict: bool = True, cross_attention_kwargs: Optional[Dict[str, Any]] = None, guidance_rescale: float = 0.0, original_size: Tuple[int, int] = None, crops_coords_top_left: Tuple[int, int] = (0, 0), target_size: Tuple[int, int] = None, negative_original_size: Optional[Tuple[int, int]] = None, negative_crops_coords_top_left: Tuple[int, int] = (0, 0), negative_target_size: Optional[Tuple[int, int]] = None, aesthetic_score: float = 6.0, negative_aesthetic_score: float = 2.5, clip_skip: Optional[int] = None, callback_on_step_end: Optional[Callable[[int, int, Dict], NoneType]] = None, callback_on_step_end_tensor_inputs: List[str] = ['latents'], mask: Union[torch.FloatTensor, PIL.Image.Image, numpy.ndarray, List[torch.FloatTensor], List[PIL.Image.Image], List[numpy.ndarray]] = None, sample_mode='sample', **kwargs)
The call function to the pipeline for generation.

+Args:
+    prompt (`str` or `List[str]`, *optional*):
+        The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
+    image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
+        `Image` or tensor representing an image batch to be used as the starting point. Can also accept image
+        latents as `image`, but if passing latents directly it is not encoded again.
+    strength (`float`, *optional*, defaults to 0.8):
+        Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
+        starting point and more noise is added the higher the `strength`. The number of denoising steps depends
+        on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
+        process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
+        essentially ignores `image`.
+    num_inference_steps (`int`, *optional*, defaults to 50):
+        The number of denoising steps. More denoising steps usually lead to a higher quality image at the
+        expense of slower inference. This parameter is modulated by `strength`.
+    guidance_scale (`float`, *optional*, defaults to 7.5):
+        A higher guidance scale value encourages the model to generate images closely linked to the text
+        ,`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
+    negative_prompt (`str` or `List[str]`, *optional*):
+        The prompt or prompts to guide what to not include in image generation. If not defined, you need to
+        pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
+    num_images_per_prompt (`int`, *optional*, defaults to 1):
+        The number of images to generate per prompt.
+    eta (`float`, *optional*, defaults to 0.0):
+        Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
+        to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
+    generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
+        A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
+        generation deterministic.
+    prompt_embeds (`torch.FloatTensor`, *optional*):
+        Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
+        provided, text embeddings are generated from the `prompt` input argument.
+    negative_prompt_embeds (`torch.FloatTensor`, *optional*):
+        Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
+        not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
+    output_type (`str`, *optional*, defaults to `"pil"`):
+        The output format of the generated image. Choose between `PIL.Image` or `np.array`.
+    return_dict (`bool`, *optional*, defaults to `True`):
+        Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
+        plain tuple.
+    callback (`Callable`, *optional*):
+        A function that calls every `callback_steps` steps during inference. The function is called with the
+        following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
+    callback_steps (`int`, *optional*, defaults to 1):
+        The frequency at which the `callback` function is called. If not specified, the callback is called at
+        every step.
+    cross_attention_kwargs (`dict`, *optional*):
+        A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
+        [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
+    mask (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`, *optional*):
+        A mask with non-zero elements for the area to be inpainted. If not specified, no mask is applied.
+                sample_mode (`str`, *optional*):
+                        control latents initialisation for the inpaint area, can be one of sample, argmax, random
+Examples:

+Returns:
+    [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
+        If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
+        otherwise a `tuple` is returned where the first element is a list with the generated images and the
+        second element is a list of `bool`s indicating whether the corresponding generated image contains
+        "not-safe-for-work" (nsfw) content.
+ +
denormalize(self, latents)
+ +
latents_to_img(self, latents)
+ +
prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True, sample_mode: str = 'sample')
+ +
random_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None)
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
+ +
+Data and other attributes defined here:
+
debug_save = 0
+ +
+Methods inherited from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline:
+
__init__(self, vae: diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL, text_encoder: transformers.models.clip.modeling_clip.CLIPTextModel, text_encoder_2: transformers.models.clip.modeling_clip.CLIPTextModelWithProjection, tokenizer: transformers.models.clip.tokenization_clip.CLIPTokenizer, tokenizer_2: transformers.models.clip.tokenization_clip.CLIPTokenizer, unet: diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, scheduler: diffusers.schedulers.scheduling_utils.KarrasDiffusionSchedulers, image_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection = None, feature_extractor: transformers.models.clip.image_processing_clip.CLIPImageProcessor = None, requires_aesthetics_score: bool = False, force_zeros_for_empty_prompt: bool = True, add_watermarker: Optional[bool] = None)
Initialize self.  See help(type(self)) for accurate signature.
+ +
check_inputs(self, prompt, prompt_2, strength, num_inference_steps, callback_steps, negative_prompt=None, negative_prompt_2=None, prompt_embeds=None, negative_prompt_embeds=None, ip_adapter_image=None, ip_adapter_image_embeds=None, callback_on_step_end_tensor_inputs=None)
+ +
encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None)
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
+ +
encode_prompt(self, prompt: str, prompt_2: Optional[str] = None, device: Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: Optional[str] = None, negative_prompt_2: Optional[str] = None, prompt_embeds: Optional[torch.FloatTensor] = None, negative_prompt_embeds: Optional[torch.FloatTensor] = None, pooled_prompt_embeds: Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None, lora_scale: Optional[float] = None, clip_skip: Optional[int] = None)
Encodes the prompt into text encoder hidden states.

+Args:
+    prompt (`str` or `List[str]`, *optional*):
+        prompt to be encoded
+    prompt_2 (`str` or `List[str]`, *optional*):
+        The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
+        used in both text-encoders
+    device: (`torch.device`):
+        torch device
+    num_images_per_prompt (`int`):
+        number of images that should be generated per prompt
+    do_classifier_free_guidance (`bool`):
+        whether to use classifier free guidance or not
+    negative_prompt (`str` or `List[str]`, *optional*):
+        The prompt or prompts not to guide the image generation. If not defined, one has to pass
+        `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
+        less than `1`).
+    negative_prompt_2 (`str` or `List[str]`, *optional*):
+        The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
+        `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
+    prompt_embeds (`torch.FloatTensor`, *optional*):
+        Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
+        provided, text embeddings will be generated from `prompt` input argument.
+    negative_prompt_embeds (`torch.FloatTensor`, *optional*):
+        Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
+        weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
+        argument.
+    pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
+        Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
+        If not provided, pooled text embeddings will be generated from `prompt` input argument.
+    negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
+        Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
+        weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
+        input argument.
+    lora_scale (`float`, *optional*):
+        A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
+    clip_skip (`int`, *optional*):
+        Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
+        the output of the pre-final layer will be used for computing the prompt embeddings.
+ +
get_guidance_scale_embedding(self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32) -> torch.FloatTensor
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

+Args:
+    w (`torch.Tensor`):
+        Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
+    embedding_dim (`int`, *optional*, defaults to 512):
+        Dimension of the embeddings to generate.
+    dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
+        Data type of the generated embeddings.

+Returns:
+    `torch.FloatTensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
+ +
get_timesteps(self, num_inference_steps, strength, device, denoising_start=None)
+ +
prepare_extra_step_kwargs(self, generator, eta)
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
+ +
prepare_ip_adapter_image_embeds(self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance)
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
+ +
upcast_vae(self)
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
+ +
+Readonly properties inherited from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline:
+
clip_skip
+
+
cross_attention_kwargs
+
+
denoising_end
+
+
denoising_start
+
+
do_classifier_free_guidance
+
+
guidance_rescale
+
+
guidance_scale
+
+
interrupt
+
+
num_timesteps
+
+
+Data and other attributes inherited from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline:
+
model_cpu_offload_seq = 'text_encoder->text_encoder_2->image_encoder->unet->vae'
+ +
+Methods inherited from diffusers.pipelines.pipeline_utils.DiffusionPipeline:
+
__setattr__(self, name: str, value: Any)
Implement setattr(self, name, value).
+ +
disable_attention_slicing(self)
Disable sliced attention computation. If `enable_attention_slicing` was previously called, attention is
+computed in one step.
+ +
disable_xformers_memory_efficient_attention(self)
Disable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).
+ +
enable_attention_slicing(self, slice_size: Union[str, int, NoneType] = 'auto')
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 computation is performed
+sequentially over each head. This is useful to save some memory in exchange for a small speed decrease.

+<Tip warning={true}>

+⚠️ Don't enable attention slicing if you're already using `scaled_dot_product_attention` (SDPA) from PyTorch
+2.0 or xFormers. These attention computations are already very memory efficient so you won't need to enable
+this function. If you enable attention slicing with SDPA or xFormers, it can lead to serious slow downs!

+</Tip>

+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
+        provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
+        must be a multiple of `slice_size`.

+Examples:

+```py
+>>> import torch
+>>> from diffusers import StableDiffusionPipeline

+>>> pipe = StableDiffusionPipeline.from_pretrained(
+...     "runwayml/stable-diffusion-v1-5",
+...     torch_dtype=torch.float16,
+...     use_safetensors=True,
+... )

+>>> prompt = "a photo of an astronaut riding a horse on mars"
+>>> pipe.enable_attention_slicing()
+>>> image = pipe(prompt).images[0]
+```
+ +
enable_model_cpu_offload(self, gpu_id: Optional[int] = None, device: Union[torch.device, str] = 'cuda')
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 a time to the GPU when its `forward`
+method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
+`enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.

+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 used in inference. If not specified, it will
+        default to "cuda".
+ +
enable_sequential_cpu_offload(self, gpu_id: Optional[int] = None, device: Union[torch.device, str] = 'cuda')
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._exclude_from_cpu_offload`) are saved to CPU
+and then moved to `torch.device('meta')` and loaded to GPU only when their specific submodule has its `forward`
+method called. Offloading happens on a submodule basis. Memory savings are higher than with
+`enable_model_cpu_offload`, but performance is lower.

+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 used in inference. If not specified, it will
+        default to "cuda".
+ +
enable_xformers_memory_efficient_attention(self, attention_op: Optional[Callable] = None)
Enable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/). When this
+option is enabled, you should observe lower GPU memory usage and a potential speed up during inference. Speed
+up during training is not guaranteed.

+<Tip warning={true}>

+⚠️ When memory efficient attention and sliced attention are both enabled, memory efficient attention takes
+precedent.

+</Tip>

+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)
+        function of xFormers.

+Examples:

+```py
+>>> import torch
+>>> from diffusers import DiffusionPipeline
+>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

+>>> 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 using VAE for Flash Attention
+>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
+```
+ +
maybe_free_model_hooks(self)
Function that offloads all components, removes all model hooks that were added when using
+`enable_model_cpu_offload` and then applies them again. In case the model has not been offloaded this function
+is a no-op. Make sure to add this function to the end of the `__call__` function of your pipeline so that it
+functions correctly when applying enable_model_cpu_offload.
+ +
progress_bar(self, iterable=None, total=None)
+ +
register_modules(self, **kwargs)
+ +
remove_all_hooks(self)
Removes all hooks that were added when using `enable_sequential_cpu_offload` or `enable_model_cpu_offload`.
+ +
reset_device_map(self)
Resets the device maps (if any) to None.
+ +
save_pretrained(self, save_directory: Union[str, os.PathLike], safe_serialization: bool = True, variant: Optional[str] = None, push_to_hub: bool = False, **kwargs)
Save all saveable variables of the pipeline to a directory. A pipeline variable can be saved and loaded if its
+class implements both a save and loading method. The pipeline is easily reloaded using the
+[`~DiffusionPipeline.from_pretrained`] class method.

+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 `pickle`.
+    variant (`str`, *optional*):
+        If specified, weights are saved in the format `pytorch_model.<variant>.bin`.
+    push_to_hub (`bool`, *optional*, defaults to `False`):
+        Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
+        repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
+        namespace).
+    kwargs (`Dict[str, Any]`, *optional*):
+        Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
+ +
set_attention_slice(self, slice_size: Optional[int])
+ +
set_progress_bar_config(self, **kwargs)
+ +
set_use_memory_efficient_attention_xformers(self, valid: bool, attention_op: Optional[Callable] = None) -> None
+ +
to(self, *args, **kwargs)
Performs Pipeline dtype and/or device conversion. A torch.dtype and torch.device are inferred from the
+arguments of `self.to(*args, **kwargs).`

+<Tip>

+    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) → DiffusionPipeline` to return a pipeline with the specified
+  [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype)
+- `to(device, silence_dtype_warnings=False) → DiffusionPipeline` to return a pipeline with the specified
+  [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device)
+- `to(device=None, dtype=None, silence_dtype_warnings=False) → DiffusionPipeline` to return a pipeline with the
+  specified [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device) and
+  [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype)

+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
+        [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device)
+    silence_dtype_warnings (`str`, *optional*, defaults to `False`):
+        Whether to omit warnings if the target `dtype` is not compatible with the target `device`.

+Returns:
+    [`DiffusionPipeline`]: The pipeline converted to specified `dtype` and/or `dtype`.
+ +
+Class methods inherited from diffusers.pipelines.pipeline_utils.DiffusionPipeline:
+
download(pretrained_model_name, **kwargs) -> Union[str, os.PathLike] from builtins.type
Download and cache a PyTorch diffusion pipeline from pretrained pipeline weights.

+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:

+            - A string, the *repository id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained
+              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 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`
+              instead of `clip_guided_stable_diffusion.py`). Community pipelines are always loaded from the
+              current `main` branch of GitHub.

+            - A path to a *directory* (`./my_pipeline_directory/`) containing a custom pipeline. The directory
+              must contain a file called `pipeline.py` that defines the custom pipeline.

+        <Tip warning={true}>

+        🧪 This is an experimental feature and may change in the future.

+        </Tip>

+        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 not to force the (re-)download of the model weights and configuration files, overriding the
+        cached versions if they exist.
+    resume_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
+        incompletely downloaded files are deleted.
+    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`):
+        Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
+    local_files_only (`bool`, *optional*, defaults to `False`):
+        Whether to only load local model weights and configuration files or not. If set to `True`, the model
+        won't be downloaded from the Hub.
+    token (`str` or *bool*, *optional*):
+        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
+        `diffusers-cli login` (stored in `~/.huggingface`) is used.
+    revision (`str`, *optional*, defaults to `"main"`):
+        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
+        `revision` when loading a custom pipeline from the Hub. It can be a 🤗 Diffusers version when loading a
+        custom pipeline from GitHub, otherwise it defaults to `"main"` when loading from the Hub.
+    mirror (`str`, *optional*):
+        Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
+        guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
+        information.
+    variant (`str`, *optional*):
+        Load weights from a specified variant filename such as `"fp16"` or `"ema"`. This is ignored when
+        loading `from_flax`.
+    use_safetensors (`bool`, *optional*, defaults to `None`):
+        If set to `None`, the safetensors weights are downloaded if they're available **and** if the
+        safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
+        weights. If set to `False`, safetensors weights are not loaded.
+    use_onnx (`bool`, *optional*, defaults to `False`):
+        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 files ending
+        with `.onnx` and `.pb`.
+    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 will execute code present on the Hub on your local machine.

+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>
+ +
from_pipe(pipeline, **kwargs) from builtins.type
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`):
+        The pipeline from which to create a new pipeline.

+Returns:
+    `DiffusionPipeline`:
+        A new pipeline with the same weights and configurations as `pipeline`.

+Examples:

+```py
+>>> from diffusers import StableDiffusionPipeline, StableDiffusionSAGPipeline

+>>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
+>>> new_pipe = StableDiffusionSAGPipeline.from_pipe(pipe)
+```
+ +
from_pretrained(pretrained_model_name_or_path: Union[str, os.PathLike, NoneType], **kwargs) from builtins.type
Instantiate a PyTorch diffusion pipeline from pretrained pipeline weights.

+The pipeline is set in evaluation mode (`model.eval()`) by default.

+If you get the error message below, you need to finetune the weights for your downstream task:

+```
+Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/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 the model instantiated
+You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
+```

+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 *directory* (for example `./my_pipeline_directory/`) containing pipeline weights
+              saved using
+            [`~DiffusionPipeline.save_pretrained`].
+    torch_dtype (`str` or `torch.dtype`, *optional*):
+        Override the default `torch.dtype` and load the model with another dtype. If "auto" is passed, the
+        dtype is automatically derived from the model's weights.
+    custom_pipeline (`str`, *optional*):

+        <Tip warning={true}>

+        🧪 This is an experimental feature and may change in the future.

+        </Tip>

+        Can be either:

+            - 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 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`
+              instead of `clip_guided_stable_diffusion.py`). Community pipelines are always loaded from the
+              current main branch of GitHub.
+            - A path to a directory (`./my_pipeline_directory/`) containing a custom pipeline. The directory
+              must contain a file called `pipeline.py` that defines the custom pipeline.

+        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`):
+        Whether or not to force the (re-)download of the model weights and configuration files, overriding the
+        cached versions if they exist.
+    cache_dir (`Union[str, os.PathLike]`, *optional*):
+        Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
+        is not used.
+    resume_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
+        incompletely downloaded files are deleted.
+    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`):
+        Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
+    local_files_only (`bool`, *optional*, defaults to `False`):
+        Whether to only load local model weights and configuration files or not. If set to `True`, the model
+        won't be downloaded from the Hub.
+    token (`str` or *bool*, *optional*):
+        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
+        `diffusers-cli login` (stored in `~/.huggingface`) is used.
+    revision (`str`, *optional*, defaults to `"main"`):
+        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
+        `revision` when loading a custom pipeline from the Hub. Defaults to the latest stable 🤗 Diffusers
+        version.
+    mirror (`str`, *optional*):
+        Mirror source to resolve accessibility issues if you’re downloading a model in China. We do not
+        guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
+        information.
+    device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
+        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.

+        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`, *optional*):
+        A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
+        each GPU and the available CPU RAM if unset.
+    offload_folder (`str` or `os.PathLike`, *optional*):
+        The path to offload weights if device_map contains the value `"disk"`.
+    offload_state_dict (`bool`, *optional*):
+        If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if
+        the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`
+        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 in CPU memory (including peak memory) while loading the model.
+        Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
+        argument to `True` will raise an error.
+    use_safetensors (`bool`, *optional*, defaults to `None`):
+        If set to `None`, the safetensors weights are downloaded if they're available **and** if the
+        safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
+        weights. If set to `False`, safetensors weights are not loaded.
+    use_onnx (`bool`, *optional*, defaults to `None`):
+        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 files ending
+        with `.onnx` and `.pb`.
+    kwargs (remaining dictionary of keyword arguments, *optional*):
+        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*):
+        Load weights from a specified variant filename such as `"fp16"` or `"ema"`. This is ignored when
+        loading `from_flax`.

+<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.
+>>> pipeline = DiffusionPipeline.from_pretrained("CompVis/ldm-text2im-large-256")

+>>> # Download pipeline that requires an authorization token
+>>> # For more information on access tokens, please refer to this section
+>>> # of the documentation](https://huggingface.co/docs/hub/security-tokens)
+>>> pipeline = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")

+>>> # Use a different scheduler
+>>> from diffusers import LMSDiscreteScheduler

+>>> scheduler = LMSDiscreteScheduler.from_config(pipeline.scheduler.config)
+>>> pipeline.scheduler = scheduler
+```
+ +
+Static methods inherited from diffusers.pipelines.pipeline_utils.DiffusionPipeline:
+
numpy_to_pil(images)
Convert a NumPy image or a batch of images to a PIL image.
+ +
+Readonly properties inherited from diffusers.pipelines.pipeline_utils.DiffusionPipeline:
+
components
+
The `self.components` property can be useful to run different pipelines with the same weights and
+configurations without reallocating additional memory.

+Returns (`dict`):
+    A dictionary containing all the modules needed to initialize the pipeline.

+Examples:

+```py
+>>> from diffusers import (
+...     StableDiffusionPipeline,
+...     StableDiffusionImg2ImgPipeline,
+...     StableDiffusionInpaintPipeline,
+... )

+>>> text2img = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
+>>> img2img = StableDiffusionImg2ImgPipeline(**text2img.components)
+>>> inpaint = StableDiffusionInpaintPipeline(**text2img.components)
+```
+
+
device
+
Returns:
+    `torch.device`: The torch device on which the pipeline is located.
+
+
dtype
+
Returns:
+    `torch.dtype`: The torch dtype on which the pipeline is located.
+
+
name_or_path
+
+
+Data and other attributes inherited from diffusers.pipelines.pipeline_utils.DiffusionPipeline:
+
config_name = 'model_index.json'
+ +
hf_device_map = None
+ +
+Methods inherited from diffusers.configuration_utils.ConfigMixin:
+
__getattr__(self, name: str) -> Any
The only reason we overwrite `getattr` here is to gracefully deprecate accessing
+config attributes directly. See https://github.com/huggingface/diffusers/pull/3129

+This function is mostly copied from PyTorch's __getattr__ overwrite:
+https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
+ +
__repr__(self)
Return repr(self).
+ +
register_to_config(self, **kwargs)
+ +
save_config(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs)
Save a configuration object to the directory specified in `save_directory` so that it can be reloaded using the
+[`~ConfigMixin.from_config`] class method.

+Args:
+    save_directory (`str` or `os.PathLike`):
+        Directory where the configuration JSON file is saved (will be created if it does not exist).
+    push_to_hub (`bool`, *optional*, defaults to `False`):
+        Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
+        repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
+        namespace).
+    kwargs (`Dict[str, Any]`, *optional*):
+        Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
+ +
to_json_file(self, json_file_path: Union[str, os.PathLike])
Save the configuration instance's parameters to a JSON file.

+Args:
+    json_file_path (`str` or `os.PathLike`):
+        Path to the JSON file to save a configuration instance's parameters.
+ +
to_json_string(self) -> str
Serializes the configuration instance to a JSON string.

+Returns:
+    `str`:
+        String containing all the attributes that make up the configuration instance in JSON format.
+ +
+Class methods inherited from diffusers.configuration_utils.ConfigMixin:
+
extract_init_dict(config_dict, **kwargs) from builtins.type
+ +
from_config(config: Union[diffusers.configuration_utils.FrozenDict, Dict[str, Any]] = None, return_unused_kwargs=False, **kwargs) from builtins.type
Instantiate a Python class from a config dictionary.

+Parameters:
+    config (`Dict[str, Any]`):
+        A config dictionary from which the Python class is instantiated. Make sure to only load configuration
+        files of compatible classes.
+    return_unused_kwargs (`bool`, *optional*, defaults to `False`):
+        Whether kwargs that are not consumed by the Python class should be returned or not.
+    kwargs (remaining dictionary of keyword arguments, *optional*):
+        Can be used to update the configuration object (after it is loaded) and initiate the Python class.
+        `**kwargs` are passed directly to the underlying scheduler/model's `__init__` method and eventually
+        overwrite the same named arguments in `config`.

+Returns:
+    [`ModelMixin`] or [`SchedulerMixin`]:
+        A model or scheduler object instantiated from a config dictionary.

+Examples:

+```python
+>>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler

+>>> # Download scheduler from huggingface.co and cache.
+>>> scheduler = DDPMScheduler.from_pretrained("google/ddpm-cifar10-32")

+>>> # Instantiate DDIM scheduler class with same config as DDPM
+>>> scheduler = DDIMScheduler.from_config(scheduler.config)

+>>> # Instantiate PNDM scheduler class with same config as DDPM
+>>> scheduler = PNDMScheduler.from_config(scheduler.config)
+```
+ +
get_config_dict(*args, **kwargs) from builtins.type
+ +
load_config(pretrained_model_name_or_path: Union[str, os.PathLike], return_unused_kwargs=False, return_commit_hash=False, **kwargs) -> Tuple[Dict[str, Any], Dict[str, Any]] from builtins.type
Load a model or scheduler configuration.

+Parameters:
+    pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
+        Can be either:

+            - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
+              the Hub.
+            - A path to a *directory* (for example `./my_model_directory`) containing model weights saved with
+              [`~ConfigMixin.save_config`].

+    cache_dir (`Union[str, os.PathLike]`, *optional*):
+        Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
+        is not used.
+    force_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to force the (re-)download of the model weights and configuration files, overriding the
+        cached versions if they exist.
+    resume_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
+        incompletely downloaded files are deleted.
+    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`):
+        Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
+    local_files_only (`bool`, *optional*, defaults to `False`):
+        Whether to only load local model weights and configuration files or not. If set to `True`, the model
+        won't be downloaded from the Hub.
+    token (`str` or *bool*, *optional*):
+        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
+        `diffusers-cli login` (stored in `~/.huggingface`) is used.
+    revision (`str`, *optional*, defaults to `"main"`):
+        The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
+        allowed by Git.
+    subfolder (`str`, *optional*, defaults to `""`):
+        The subfolder location of a model file within a larger model repository on the Hub or locally.
+    return_unused_kwargs (`bool`, *optional*, defaults to `False):
+        Whether unused keyword arguments of the config are returned.
+    return_commit_hash (`bool`, *optional*, defaults to `False):
+        Whether the `commit_hash` of the loaded configuration are returned.

+Returns:
+    `dict`:
+        A dictionary of all the parameters stored in a JSON configuration file.
+ +
+Readonly properties inherited from diffusers.configuration_utils.ConfigMixin:
+
config
+
Returns the config of the class as a frozen dictionary

+Returns:
+    `Dict[str, Any]`: Config of the class.
+
+
+Data descriptors inherited from diffusers.configuration_utils.ConfigMixin:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+
+Data and other attributes inherited from diffusers.configuration_utils.ConfigMixin:
+
has_compatibles = False
+ +
ignore_for_config = []
+ +
+Methods inherited from diffusers.utils.hub_utils.PushToHubMixin:
+
push_to_hub(self, repo_id: str, commit_message: Optional[str] = None, private: Optional[bool] = None, token: Optional[str] = None, create_pr: bool = False, safe_serialization: bool = True, variant: Optional[str] = None) -> str
Upload model, scheduler, or pipeline files to the 🤗 Hugging Face Hub.

+Parameters:
+    repo_id (`str`):
+        The name of the repository you want to push your model, scheduler, or pipeline files to. It should
+        contain your organization name when pushing to an organization. `repo_id` can also be a path to a local
+        directory.
+    commit_message (`str`, *optional*):
+        Message to commit while pushing. Default to `"Upload {object}"`.
+    private (`bool`, *optional*):
+        Whether or not the repository created should be private.
+    token (`str`, *optional*):
+        The token to use as HTTP bearer authorization for remote files. The token generated when running
+        `huggingface-cli login` (stored in `~/.huggingface`).
+    create_pr (`bool`, *optional*, defaults to `False`):
+        Whether or not to create a PR with the uploaded files or directly commit.
+    safe_serialization (`bool`, *optional*, defaults to `True`):
+        Whether or not to convert the model weights to the `safetensors` format.
+    variant (`str`, *optional*):
+        If specified, weights are saved in the format `pytorch_model.<variant>.bin`.

+Examples:

+```python
+from diffusers import UNet2DConditionModel

+unet = UNet2DConditionModel.from_pretrained("stabilityai/stable-diffusion-2", subfolder="unet")

+# Push the `unet` to your namespace with the name "my-finetuned-unet".
+unet.push_to_hub("my-finetuned-unet")

+# Push the `unet` to an organization with the name "my-finetuned-unet".
+unet.push_to_hub("your-org/my-finetuned-unet")
+```
+ +
+Methods inherited from diffusers.pipelines.pipeline_utils.StableDiffusionMixin:
+
disable_freeu(self)
Disables the FreeU mechanism if enabled.
+ +
disable_vae_slicing(self)
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
+computing decoding in one step.
+ +
disable_vae_tiling(self)
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
+computing decoding in one step.
+ +
enable_freeu(self, s1: float, s2: float, b1: float, b2: float)
Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.

+The suffixes after the scaling factors represent the stages where they are being applied.

+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.

+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 contributions of the skip features. This is done to
+        mitigate "oversmoothing effect" in the enhanced denoising process.
+    b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
+    b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
+ +
enable_vae_slicing(self)
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
+compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
+ +
enable_vae_tiling(self)
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.
+ +
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}>

+This API is 🧪 experimental.

+</Tip>

+Args:
+    unet (`bool`, defaults to `True`): To apply fusion on the UNet.
+    vae (`bool`, defaults to `True`): To apply fusion on the VAE.
+ +
unfuse_qkv_projections(self, unet: bool = True, vae: bool = True)
Disable QKV projection fusion if enabled.

+<Tip warning={true}>

+This API is 🧪 experimental.

+</Tip>

+Args:
+    unet (`bool`, defaults to `True`): To apply fusion on the UNet.
+    vae (`bool`, defaults to `True`): To apply fusion on the VAE.
+ +
+Methods inherited from diffusers.loaders.textual_inversion.TextualInversionLoaderMixin:
+
load_textual_inversion(self, pretrained_model_name_or_path: Union[str, List[str], Dict[str, torch.Tensor], List[Dict[str, torch.Tensor]]], token: Union[str, List[str], NoneType] = None, tokenizer: Optional[ForwardRef('PreTrainedTokenizer')] = None, text_encoder: Optional[ForwardRef('PreTrainedModel')] = None, **kwargs)
Load Textual Inversion embeddings into the text encoder of [`StableDiffusionPipeline`] (both 🤗 Diffusers and
+Automatic1111 formats are supported).

+Parameters:
+    pretrained_model_name_or_path (`str` or `os.PathLike` or `List[str or os.PathLike]` or `Dict` or `List[Dict]`):
+        Can be either one of the following or a list of them:

+            - A string, the *model id* (for example `sd-concepts-library/low-poly-hd-logos-icons`) of a
+              pretrained model hosted on the Hub.
+            - A path to a *directory* (for example `./my_text_inversion_directory/`) containing the textual
+              inversion weights.
+            - A path to a *file* (for example `./my_text_inversions.pt`) containing textual inversion weights.
+            - A [torch state
+              dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).

+    token (`str` or `List[str]`, *optional*):
+        Override the token to use for the textual inversion weights. If `pretrained_model_name_or_path` is a
+        list, then `token` must also be a list of equal length.
+    text_encoder ([`~transformers.CLIPTextModel`], *optional*):
+        Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
+        If not specified, function will take self.tokenizer.
+    tokenizer ([`~transformers.CLIPTokenizer`], *optional*):
+        A `CLIPTokenizer` to tokenize text. If not specified, function will take self.tokenizer.
+    weight_name (`str`, *optional*):
+        Name of a custom weight file. This should be used when:

+            - The saved textual inversion file is in 🤗 Diffusers format, but was saved under a specific weight
+              name such as `text_inv.bin`.
+            - The saved textual inversion file is in the Automatic1111 format.
+    cache_dir (`Union[str, os.PathLike]`, *optional*):
+        Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
+        is not used.
+    force_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to force the (re-)download of the model weights and configuration files, overriding the
+        cached versions if they exist.
+    resume_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
+        incompletely downloaded files are deleted.
+    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.
+    local_files_only (`bool`, *optional*, defaults to `False`):
+        Whether to only load local model weights and configuration files or not. If set to `True`, the model
+        won't be downloaded from the Hub.
+    token (`str` or *bool*, *optional*):
+        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
+        `diffusers-cli login` (stored in `~/.huggingface`) is used.
+    revision (`str`, *optional*, defaults to `"main"`):
+        The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
+        allowed by Git.
+    subfolder (`str`, *optional*, defaults to `""`):
+        The subfolder location of a model file within a larger model repository on the Hub or locally.
+    mirror (`str`, *optional*):
+        Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
+        guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
+        information.

+Example:

+To load a Textual Inversion embedding vector in 🤗 Diffusers format:

+```py
+from diffusers import StableDiffusionPipeline
+import torch

+model_id = "runwayml/stable-diffusion-v1-5"
+pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

+pipe.load_textual_inversion("sd-concepts-library/cat-toy")

+prompt = "A <cat-toy> backpack"

+image = pipe(prompt, num_inference_steps=50).images[0]
+image.save("cat-backpack.png")
+```

+To load a Textual Inversion embedding vector in Automatic1111 format, make sure to download the vector first
+(for example from [civitAI](https://civitai.com/models/3036?modelVersionId=9857)) and then load the vector
+locally:

+```py
+from diffusers import StableDiffusionPipeline
+import torch

+model_id = "runwayml/stable-diffusion-v1-5"
+pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

+pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")

+prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."

+image = pipe(prompt, num_inference_steps=50).images[0]
+image.save("character.png")
+```
+ +
maybe_convert_prompt(self, prompt: Union[str, List[str]], tokenizer: 'PreTrainedTokenizer')
Processes prompts that include a special token corresponding to a multi-vector textual inversion embedding to
+be replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
+inversion token or if the textual inversion token is a single vector, the input prompt is returned.

+Parameters:
+    prompt (`str` or list of `str`):
+        The prompt or prompts to guide the image generation.
+    tokenizer (`PreTrainedTokenizer`):
+        The tokenizer responsible for encoding the prompt into input tokens.

+Returns:
+    `str` or list of `str`: The converted prompt
+ +
unload_textual_inversion(self, tokens: Union[str, List[str], NoneType] = None, tokenizer: Optional[ForwardRef('PreTrainedTokenizer')] = None, text_encoder: Optional[ForwardRef('PreTrainedModel')] = None)
Unload Textual Inversion embeddings from the text encoder of [`StableDiffusionPipeline`]

+Example:
+```py
+from diffusers import AutoPipelineForText2Image
+import torch

+pipeline = AutoPipelineForText2Image.from_pretrained("runwayml/stable-diffusion-v1-5")

+# Example 1
+pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")
+pipeline.load_textual_inversion("sd-concepts-library/moeb-style")

+# Remove all token embeddings
+pipeline.unload_textual_inversion()

+# Example 2
+pipeline.load_textual_inversion("sd-concepts-library/moeb-style")
+pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")

+# Remove just one token
+pipeline.unload_textual_inversion("<moe-bius>")

+# Example 3: unload from SDXL
+pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0")
+embedding_path = hf_hub_download(
+    repo_id="linoyts/web_y2k", filename="web_y2k_emb.safetensors", repo_type="model"
+)

+# load embeddings to the text encoders
+state_dict = load_file(embedding_path)

+# load embeddings of text_encoder 1 (CLIP ViT-L/14)
+pipeline.load_textual_inversion(
+    state_dict["clip_l"],
+    token=["<s0>", "<s1>"],
+    text_encoder=pipeline.text_encoder,
+    tokenizer=pipeline.tokenizer,
+)
+# load embeddings of text_encoder 2 (CLIP ViT-G/14)
+pipeline.load_textual_inversion(
+    state_dict["clip_g"],
+    token=["<s0>", "<s1>"],
+    text_encoder=pipeline.text_encoder_2,
+    tokenizer=pipeline.tokenizer_2,
+)

+# Unload explicitly from both text encoders abd tokenizers
+pipeline.unload_textual_inversion(
+    tokens=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder, tokenizer=pipeline.tokenizer
+)
+pipeline.unload_textual_inversion(
+    tokens=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder_2, tokenizer=pipeline.tokenizer_2
+)
+```
+ +
+Class methods inherited from diffusers.loaders.single_file.FromSingleFileMixin:
+
from_single_file(pretrained_model_link_or_path, **kwargs) from builtins.type
Instantiate a [`DiffusionPipeline`] from pretrained pipeline weights saved in the `.ckpt` or `.safetensors`
+format. The pipeline is set in evaluation mode (`model.eval()`) by default.

+Parameters:
+    pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
+        Can be either:
+            - A link to the `.ckpt` file (for example
+              `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
+            - A path to a *file* containing all pipeline weights.
+    torch_dtype (`str` or `torch.dtype`, *optional*):
+        Override the default `torch.dtype` and load the model with another dtype.
+    force_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to force the (re-)download of the model weights and configuration files, overriding the
+        cached versions if they exist.
+    cache_dir (`Union[str, os.PathLike]`, *optional*):
+        Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
+        is not used.
+    resume_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
+        incompletely downloaded files are deleted.
+    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.
+    local_files_only (`bool`, *optional*, defaults to `False`):
+        Whether to only load local model weights and configuration files or not. If set to `True`, the model
+        won't be downloaded from the Hub.
+    token (`str` or *bool*, *optional*):
+        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
+        `diffusers-cli login` (stored in `~/.huggingface`) is used.
+    revision (`str`, *optional*, defaults to `"main"`):
+        The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
+        allowed by Git.
+    original_config_file (`str`, *optional*):
+        The path to the original config file that was used to train the model. If not provided, the config file
+        will be inferred from the checkpoint file.
+    model_type (`str`, *optional*):
+        The type of model to load. If not provided, the model type will be inferred from the checkpoint file.
+    image_size (`int`, *optional*):
+        The size of the image output. It's used to configure the `sample_size` parameter of the UNet and VAE
+        model.
+    load_safety_checker (`bool`, *optional*, defaults to `False`):
+        Whether to load the safety checker model or not. By default, the safety checker is not loaded unless a
+        `safety_checker` component is passed to the `kwargs`.
+    num_in_channels (`int`, *optional*):
+        Specify the number of input channels for the UNet model. Read more about how to configure UNet model
+        with this parameter
+        [here](https://huggingface.co/docs/diffusers/training/adapt_a_model#configure-unet2dconditionmodel-parameters).
+    scaling_factor (`float`, *optional*):
+        The scaling factor to use for the VAE model. If not provided, it is inferred from the config file
+        first. If the scaling factor is not found in the config file, the default value 0.18215 is used.
+    scheduler_type (`str`, *optional*):
+        The type of scheduler to load. If not provided, the scheduler type will be inferred from the checkpoint
+        file.
+    prediction_type (`str`, *optional*):
+        The type of prediction to load. If not provided, the prediction type will be inferred from the
+        checkpoint file.
+    kwargs (remaining dictionary of keyword arguments, *optional*):
+        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.

+Examples:

+```py
+>>> from diffusers import StableDiffusionPipeline

+>>> # Download pipeline from huggingface.co and cache.
+>>> pipeline = StableDiffusionPipeline.from_single_file(
+...     "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
+... )

+>>> # Download pipeline from local file
+>>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
+>>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly")

+>>> # Enable float16 and move to GPU
+>>> pipeline = StableDiffusionPipeline.from_single_file(
+...     "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
+...     torch_dtype=torch.float16,
+... )
+>>> pipeline.to("cuda")
+```
+ +
+Methods inherited from diffusers.loaders.lora.StableDiffusionXLLoraLoaderMixin:
+
load_lora_weights(self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], adapter_name: Optional[str] = None, **kwargs)
Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
+`self.text_encoder`.

+All kwargs are forwarded to `self.lora_state_dict`.

+See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.

+See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
+`self.unet`.

+See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
+into `self.text_encoder`.

+Parameters:
+    pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
+        See [`~loaders.LoraLoaderMixin.lora_state_dict`].
+    adapter_name (`str`, *optional*):
+        Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
+        `default_{i}` where i is the total number of adapters being loaded.
+    kwargs (`dict`, *optional*):
+        See [`~loaders.LoraLoaderMixin.lora_state_dict`].
+ +
+Class methods inherited from diffusers.loaders.lora.StableDiffusionXLLoraLoaderMixin:
+
save_lora_weights(save_directory: Union[str, os.PathLike], unet_lora_layers: Dict[str, Union[torch.nn.modules.module.Module, torch.Tensor]] = None, text_encoder_lora_layers: Dict[str, Union[torch.nn.modules.module.Module, torch.Tensor]] = None, text_encoder_2_lora_layers: Dict[str, Union[torch.nn.modules.module.Module, torch.Tensor]] = None, is_main_process: bool = True, weight_name: str = None, save_function: Callable = None, safe_serialization: bool = True) from builtins.type
Save the LoRA parameters corresponding to the UNet and text encoder.

+Arguments:
+    save_directory (`str` or `os.PathLike`):
+        Directory to save LoRA parameters to. Will be created if it doesn't exist.
+    unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
+        State dict of the LoRA layers corresponding to the `unet`.
+    text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
+        State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
+        encoder LoRA state dict because it comes from 🤗 Transformers.
+    is_main_process (`bool`, *optional*, defaults to `True`):
+        Whether the process calling this is the main process or not. Useful during distributed training and you
+        need to call this function on all processes. In this case, set `is_main_process=True` only on the main
+        process to avoid race conditions.
+    save_function (`Callable`):
+        The function to use to save the state dictionary. Useful during distributed training when you need to
+        replace `torch.save` with another method. Can be configured with the environment variable
+        `DIFFUSERS_SAVE_MODE`.
+    safe_serialization (`bool`, *optional*, defaults to `True`):
+        Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
+ +
+Methods inherited from diffusers.loaders.lora.LoraLoaderMixin:
+
delete_adapters(self, adapter_names: Union[List[str], str])
Args:
+Deletes the LoRA layers of `adapter_name` for the unet and text-encoder(s).
+    adapter_names (`Union[List[str], str]`):
+        The names of the adapter to delete. Can be a single string or a list of strings
+ +
disable_lora(self)
+ +
disable_lora_for_text_encoder(self, text_encoder: Optional[ForwardRef('PreTrainedModel')] = None)
Disables the LoRA layers for the text encoder.

+Args:
+    text_encoder (`torch.nn.Module`, *optional*):
+        The text encoder module to disable the LoRA layers for. If `None`, it will try to get the
+        `text_encoder` attribute.
+ +
enable_lora(self)
+ +
enable_lora_for_text_encoder(self, text_encoder: Optional[ForwardRef('PreTrainedModel')] = None)
Enables the LoRA layers for the text encoder.

+Args:
+    text_encoder (`torch.nn.Module`, *optional*):
+        The text encoder module to enable the LoRA layers for. If `None`, it will try to get the `text_encoder`
+        attribute.
+ +
fuse_lora(self, fuse_unet: bool = True, fuse_text_encoder: bool = True, lora_scale: float = 1.0, safe_fusing: bool = False, adapter_names: Optional[List[str]] = None)
Fuses the LoRA parameters into the original parameters of the corresponding blocks.

+<Tip warning={true}>

+This is an experimental API.

+</Tip>

+Args:
+    fuse_unet (`bool`, defaults to `True`): Whether to fuse the UNet LoRA parameters.
+    fuse_text_encoder (`bool`, defaults to `True`):
+        Whether to fuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
+        LoRA parameters then it won't have any effect.
+    lora_scale (`float`, defaults to 1.0):
+        Controls how much to influence the outputs with the LoRA parameters.
+    safe_fusing (`bool`, defaults to `False`):
+        Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
+    adapter_names (`List[str]`, *optional*):
+        Adapter names to be used for fusing. If nothing is passed, all active adapters will be fused.

+Example:

+```py
+from diffusers import DiffusionPipeline
+import torch

+pipeline = DiffusionPipeline.from_pretrained(
+    "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
+).to("cuda")
+pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
+pipeline.fuse_lora(lora_scale=0.7)
+```
+ +
get_active_adapters(self) -> List[str]
Gets the list of the current active adapters.

+Example:

+```python
+from diffusers import DiffusionPipeline

+pipeline = DiffusionPipeline.from_pretrained(
+    "stabilityai/stable-diffusion-xl-base-1.0",
+).to("cuda")
+pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy")
+pipeline.get_active_adapters()
+```
+ +
get_list_adapters(self) -> Dict[str, List[str]]
Gets the current list of all available adapters in the pipeline.
+ +
set_adapters(self, adapter_names: Union[List[str], str], adapter_weights: Union[float, Dict, List[float], List[Dict], NoneType] = None)
+ +
set_adapters_for_text_encoder(self, adapter_names: Union[List[str], str], text_encoder: Optional[ForwardRef('PreTrainedModel')] = None, text_encoder_weights: Union[float, List[float], List[NoneType], NoneType] = None)
Sets the adapter layers for the text encoder.

+Args:
+    adapter_names (`List[str]` or `str`):
+        The names of the adapters to use.
+    text_encoder (`torch.nn.Module`, *optional*):
+        The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
+        attribute.
+    text_encoder_weights (`List[float]`, *optional*):
+        The weights to use for the text encoder. If `None`, the weights are set to `1.0` for all the adapters.
+ +
set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None
Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case
+you want to load multiple adapters and free some GPU memory.

+Args:
+    adapter_names (`List[str]`):
+        List of adapters to send device to.
+    device (`Union[torch.device, str, int]`):
+        Device to send the adapters to. Can be either a torch device, a str or an integer.
+ +
unfuse_lora(self, unfuse_unet: bool = True, unfuse_text_encoder: bool = True)
Reverses the effect of
+[`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.fuse_lora).

+<Tip warning={true}>

+This is an experimental API.

+</Tip>

+Args:
+    unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
+    unfuse_text_encoder (`bool`, defaults to `True`):
+        Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
+        LoRA parameters then it won't have any effect.
+ +
unload_lora_weights(self)
Unloads the LoRA parameters.

+Examples:

+```python
+>>> # Assuming `pipeline` is already loaded with the LoRA parameters.
+>>> pipeline.unload_lora_weights()
+>>> ...
+```
+ +
+Class methods inherited from diffusers.loaders.lora.LoraLoaderMixin:
+
load_lora_into_text_encoder(state_dict, network_alphas, text_encoder, prefix=None, lora_scale=1.0, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None) from builtins.type
This will load the LoRA layers specified in `state_dict` into `text_encoder`

+Parameters:
+    state_dict (`dict`):
+        A standard state dict containing the lora layer parameters. The key should be prefixed with an
+        additional `text_encoder` to distinguish between unet lora layers.
+    network_alphas (`Dict[str, float]`):
+        See `LoRALinearLayer` for more details.
+    text_encoder (`CLIPTextModel`):
+        The text encoder model to load the LoRA layers into.
+    prefix (`str`):
+        Expected prefix of the `text_encoder` in the `state_dict`.
+    lora_scale (`float`):
+        How much to scale the output of the lora linear layer before it is added with the output of the regular
+        lora layer.
+    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 in CPU memory (including peak memory) while loading the model.
+        Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
+        argument to `True` will raise an error.
+    adapter_name (`str`, *optional*):
+        Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
+        `default_{i}` where i is the total number of adapters being loaded.
+ +
load_lora_into_transformer(state_dict, network_alphas, transformer, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None) from builtins.type
This will load the LoRA layers specified in `state_dict` into `transformer`.

+Parameters:
+    state_dict (`dict`):
+        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
+        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
+        encoder lora layers.
+    network_alphas (`Dict[str, float]`):
+        See `LoRALinearLayer` for more details.
+    unet (`UNet2DConditionModel`):
+        The UNet model to load the LoRA layers into.
+    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 in CPU memory (including peak memory) while loading the model.
+        Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
+        argument to `True` will raise an error.
+    adapter_name (`str`, *optional*):
+        Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
+        `default_{i}` where i is the total number of adapters being loaded.
+ +
load_lora_into_unet(state_dict, network_alphas, unet, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None) from builtins.type
This will load the LoRA layers specified in `state_dict` into `unet`.

+Parameters:
+    state_dict (`dict`):
+        A standard state dict containing the lora layer parameters. The keys can either be indexed directly
+        into the unet or prefixed with an additional `unet` which can be used to distinguish between text
+        encoder lora layers.
+    network_alphas (`Dict[str, float]`):
+        See `LoRALinearLayer` for more details.
+    unet (`UNet2DConditionModel`):
+        The UNet model to load the LoRA layers into.
+    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 in CPU memory (including peak memory) while loading the model.
+        Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
+        argument to `True` will raise an error.
+    adapter_name (`str`, *optional*):
+        Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
+        `default_{i}` where i is the total number of adapters being loaded.
+ +
lora_state_dict(pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], **kwargs) from builtins.type
Return state dict for lora weights and the network alphas.

+<Tip warning={true}>

+We support loading A1111 formatted LoRA checkpoints in a limited capacity.

+This function is experimental and might change in the future.

+</Tip>

+Parameters:
+    pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
+        Can be either:

+            - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
+              the Hub.
+            - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
+              with [`ModelMixin.save_pretrained`].
+            - A [torch state
+              dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).

+    cache_dir (`Union[str, os.PathLike]`, *optional*):
+        Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
+        is not used.
+    force_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to force the (re-)download of the model weights and configuration files, overriding the
+        cached versions if they exist.
+    resume_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
+        incompletely downloaded files are deleted.
+    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.
+    local_files_only (`bool`, *optional*, defaults to `False`):
+        Whether to only load local model weights and configuration files or not. If set to `True`, the model
+        won't be downloaded from the Hub.
+    token (`str` or *bool*, *optional*):
+        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
+        `diffusers-cli login` (stored in `~/.huggingface`) is used.
+    revision (`str`, *optional*, defaults to `"main"`):
+        The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
+        allowed by Git.
+    subfolder (`str`, *optional*, defaults to `""`):
+        The subfolder location of a model file within a larger model repository on the Hub or locally.
+    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 in CPU memory (including peak memory) while loading the model.
+        Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
+        argument to `True` will raise an error.
+    mirror (`str`, *optional*):
+        Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
+        guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
+        information.
+ +
+Static methods inherited from diffusers.loaders.lora.LoraLoaderMixin:
+
write_lora_layers(state_dict: Dict[str, torch.Tensor], save_directory: str, is_main_process: bool, weight_name: str, save_function: Callable, safe_serialization: bool)
+ +
+Readonly properties inherited from diffusers.loaders.lora.LoraLoaderMixin:
+
lora_scale
+
+
+Data and other attributes inherited from diffusers.loaders.lora.LoraLoaderMixin:
+
num_fused_loras = 0
+ +
text_encoder_name = 'text_encoder'
+ +
transformer_name = 'transformer'
+ +
unet_name = 'unet'
+ +
+Methods inherited from diffusers.loaders.ip_adapter.IPAdapterMixin:
+
load_ip_adapter(self, pretrained_model_name_or_path_or_dict: Union[str, List[str], Dict[str, torch.Tensor]], subfolder: Union[str, List[str]], weight_name: Union[str, List[str]], image_encoder_folder: Optional[str] = 'image_encoder', **kwargs)
Parameters:
+    pretrained_model_name_or_path_or_dict (`str` or `List[str]` or `os.PathLike` or `List[os.PathLike]` or `dict` or `List[dict]`):
+        Can be either:

+            - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
+              the Hub.
+            - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
+              with [`ModelMixin.save_pretrained`].
+            - A [torch state
+              dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
+    subfolder (`str` or `List[str]`):
+        The subfolder location of a model file within a larger model repository on the Hub or locally. If a
+        list is passed, it should have the same length as `weight_name`.
+    weight_name (`str` or `List[str]`):
+        The name of the weight file to load. If a list is passed, it should have the same length as
+        `weight_name`.
+    image_encoder_folder (`str`, *optional*, defaults to `image_encoder`):
+        The subfolder location of the image encoder within a larger model repository on the Hub or locally.
+        Pass `None` to not load the image encoder. If the image encoder is located in a folder inside
+        `subfolder`, you only need to pass the name of the folder that contains image encoder weights, e.g.
+        `image_encoder_folder="image_encoder"`. If the image encoder is located in a folder other than
+        `subfolder`, you should pass the path to the folder that contains image encoder weights, for example,
+        `image_encoder_folder="different_subfolder/image_encoder"`.
+    cache_dir (`Union[str, os.PathLike]`, *optional*):
+        Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
+        is not used.
+    force_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to force the (re-)download of the model weights and configuration files, overriding the
+        cached versions if they exist.
+    resume_download (`bool`, *optional*, defaults to `False`):
+        Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
+        incompletely downloaded files are deleted.
+    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.
+    local_files_only (`bool`, *optional*, defaults to `False`):
+        Whether to only load local model weights and configuration files or not. If set to `True`, the model
+        won't be downloaded from the Hub.
+    token (`str` or *bool*, *optional*):
+        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
+        `diffusers-cli login` (stored in `~/.huggingface`) is used.
+    revision (`str`, *optional*, defaults to `"main"`):
+        The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
+        allowed by Git.
+    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 in CPU memory (including peak memory) while loading the model.
+        Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
+        argument to `True` will raise an error.
+ +
set_ip_adapter_scale(self, scale)
Sets the conditioning scale between text and image.

+Example:

+```py
+pipeline.set_ip_adapter_scale(0.5)
+```
+ +
unload_ip_adapter(self)
Unloads the IP Adapter weights

+Examples:

+```python
+>>> # Assuming `pipeline` is already loaded with the IP Adapter weights.
+>>> pipeline.unload_ip_adapter()
+>>> ...
+```
+ +

+ + + + + +
 
+Data
       Any = typing.Any
+Callable = typing.Callable
+Dict = typing.Dict
+List = typing.List
+Optional = typing.Optional
+PipelineImageInput = typing.Union[PIL.Image.Image, numpy.ndarray, tor...t[numpy.ndarray], typing.List[torch.FloatTensor]]
+Tuple = typing.Tuple
+Union = typing.Union
+XLA_AVAILABLE = False
+logger = <Logger multigen.pipelines.masked_stable_diffusion_xl_img2img (WARNING)>
+ \ No newline at end of file diff --git a/docs/generated/multigen.pipes.html b/docs/generated/multigen.pipes.html new file mode 100644 index 0000000..e07d80f --- /dev/null +++ b/docs/generated/multigen.pipes.html @@ -0,0 +1,807 @@ + +Python: module multigen.pipes + + + + + +
 
+ 
multigen.pipes
index
/home/imgen/projects/metafusion/multigen/pipes.py
+

+

+ + + + + +
 
+Modules
       
PIL.Image
+PIL.ImageFilter
+copy
+
cv2
+importlib
+logging
+
numpy
+os
+torch
+

+ + + + + +
 
+Classes
       
+
builtins.object +
+
+
BasePipe +
+
+
Cond2ImPipe +
+
+
CIm2ImPipe +
+
+
Im2ImPipe +
+
+
MaskedIm2ImPipe +
+
+
InpaintingPipe +
Prompt2ImPipe +
+
+
+
+
enum.Enum(builtins.object) +
+
+
ControlnetType +
+
+
+

+ + + + + + + +
 
+class BasePipe(builtins.object)
   BasePipe(model_id: str, sd_pipe_class: Optional[Type[diffusers.pipelines.pipeline_utils.DiffusionPipeline]] = None, pipe: Optional[diffusers.pipelines.pipeline_utils.DiffusionPipeline] = None, **args)

+Base class for all pipelines.

+Provides some basic functionality to load and save models,
+as well as pipeline configuration
 
 Methods defined here:
+
__init__(self, model_id: str, sd_pipe_class: Optional[Type[diffusers.pipelines.pipeline_utils.DiffusionPipeline]] = None, pipe: Optional[diffusers.pipelines.pipeline_utils.DiffusionPipeline] = None, **args)
Constructor

+Args:
+    model_id (str):
+        path or id of the model to load
+    sd_pipe_class (Type, *optional*):
+      a subclass of DiffusionPipeline to load model to.
+    pipe (DiffusionPipeline, *optional*):
+        an instance of the pipeline to use,
+        if provided the model_id won't be used for loading.
+    **args:
+        additional arguments passed to sd_pipe_class constructor
+ +
add_hypernet(self, path, multiplier=None)
+ +
clear_hypernets(self)
+ +
from_pipe(self, pipe, **args)
+ +
get_config(self)
Return parameters for this model.

+:return: dict
+ +
load_lora(self, path, multiplier=1.0)
+ +
setup(self, steps=50, clip_skip=0, loras=[], **args)
Setup pipeline for generation.

+Args:
+    steps (int, *optional*):
+        number of inference steps
+    clip_skip (int, *optional*):
+        number of top layers to skip in clip model
+    **args (dict, *optional*):
+        dict with additional parameters such as scheduler and timestep_spacing,
+        other parameters will be ignored.
+        scheduler is a scheduler class names from diffusers.schedulers module
+        timestep_spacing (`str`, defaults to `"leading"`):
+        The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
+        Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
+    :return: None
+ +
try_set_scheduler(self, inputs)
+ +
+Readonly properties defined here:
+
hypernets
+
+
model_id
+
The model id used by the pipeline
+
+
scheduler
+
The scheduler used by the pipeline
+
+
+Data descriptors defined here:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+

+ + + + + + + +
 
+class CIm2ImPipe(Cond2ImPipe)
   CIm2ImPipe(model_id, pipe: Optional[diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline] = None, ctypes=['soft'], model_type=&lt;ControlnetType.SD: 1&gt;, **args)

+A pipeline for conditional image-to-image generation
+where the conditional image is derived from the input image.
+The processing of the input image depends on the specified conditioning type(s).
 
 
Method resolution order:
+
CIm2ImPipe
+
Cond2ImPipe
+
BasePipe
+
builtins.object
+
+
+Methods defined here:
+
__init__(self, model_id, pipe: Optional[diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline] = None, ctypes=['soft'], model_type=<ControlnetType.SD: 1>, **args)
Initialize the CIm2ImPipe.

+Args:
+    model_id (str):
+        The identifier of the model to load.
+    pipe (StableDiffusion(XL)ControlNetPipeline, *optional*):
+        An instance of the pipeline to use. If provided, the model_id won't be used for loading. Defaults to None.
+    ctypes (list of str, optional):
+        The types of conditioning to apply to the input image. Defaults to ["soft"].
+        can be one of canny, pose, soft, soft-sobel, depth, None
+    model_type (ControlnetType, optional):
+        The type of ControlNet model to use(SD or SDXL). Defaults to ControlnetType.SD.
+    **args:
+        Additional arguments passed to the Cond2ImPipe constructor.
+ +
setup(self, fimage, width=None, height=None, image=None, cscales=None, guess_mode=False, **args)
Set up the pipeline with the given parameters.

+Args:
+    fimage (str):
+        The path to the input image file.
+    width (int, *optional*):
+        The width of the generated image. Defaults to the width of the input image.
+    height (int, *optional*):
+        The height of the generated image. Defaults to the height of the input image.
+    image (PIL.Image.Image, *optional*):
+        The input image. Defaults to None. fimage should be None if this argument is provided.
+    cscales (list, optional):
+        The list of conditioning scales. Defaults to None.
+    guess_mode (bool, optional):
+        Whether to use guess mode. Defaults to False.
+        it enables image generation without text prompt.
+    **args: Additional arguments for the pipeline setup.
+ +
+Methods inherited from Cond2ImPipe:
+
gen(self, inputs)
Generate an image from the given inputs.

+Args:
+    inputs (dict): The dictionary of input parameters.

+Returns:
+    PIL.Image.Image: The generated image.
+ +
get_cmodels(self)
+ +
get_config(self)
Return parameters for this model.

+:return: dict
+ +
get_cpath(self)
+ +
get_default_cond_scales(self)
+ +
get_sd_class(self)
+ +
+Data and other attributes inherited from Cond2ImPipe:
+
cmodels = {'canny': 'sd-controlnet-canny', 'depth': 'control_v11f1p_sd15_depth', 'inpaint': 'control_v11p_sd15_inpaint', 'ip2p': 'control_v11e_sd15_ip2p', 'pose': 'control_v11p_sd15_openpose', 'qr': 'controlnet_qrcode-control_v1p_sd15', 'scribble': 'control_v11p_sd15_scribble', 'soft': 'control_v11p_sd15_softedge', 'soft-sobel': 'control_v11p_sd15_softedge'}
+ +
cmodelsxl = {'qr': 'controlnet-qr-pattern-sdxl'}
+ +
cond_scales_defaults = {'canny': 0.75, 'depth': 0.5, 'inpaint': 1.0, 'ip2p': 0.5, 'pose': 1.0, 'qr': 1.5, 'scribble': 0.95, 'soft': 0.95, 'soft-sobel': 0.3}
+ +
cond_scales_defaults_xl = {'qr': 0.5}
+ +
cpath = './models-cn/'
+ +
cpathxl = './models-cn-xl/'
+ +
+Methods inherited from BasePipe:
+
add_hypernet(self, path, multiplier=None)
+ +
clear_hypernets(self)
+ +
from_pipe(self, pipe, **args)
+ +
load_lora(self, path, multiplier=1.0)
+ +
try_set_scheduler(self, inputs)
+ +
+Readonly properties inherited from BasePipe:
+
hypernets
+
+
model_id
+
The model id used by the pipeline
+
+
scheduler
+
The scheduler used by the pipeline
+
+
+Data descriptors inherited from BasePipe:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+

+ + + + + + + +
 
+class Cond2ImPipe(BasePipe)
   Cond2ImPipe(model_id, pipe: Optional[diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline] = None, ctypes=['soft'], model_type=&lt;ControlnetType.SD: 1&gt;, **args)

+
 
 
Method resolution order:
+
Cond2ImPipe
+
BasePipe
+
builtins.object
+
+
+Methods defined here:
+
__init__(self, model_id, pipe: Optional[diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline] = None, ctypes=['soft'], model_type=<ControlnetType.SD: 1>, **args)
Constructor

+Args:
+    model_id (str):
+        Path or identifier of the model to load.
+    pipe (StableDiffusion(XL)ControlNetPipeline, *optional*):
+        An instance of the pipeline to use. If provided, `model_id` won't be used for loading.
+    model_type (ControlnetType, *optional*):
+        determines whether it's SD or SDXL model, defaults to ControlnetType.SD
+    **args:
+        Additional arguments passed to the `BasePipe` constructor.
+ +
gen(self, inputs)
Generate an image from the given inputs.

+Args:
+    inputs (dict): The dictionary of input parameters.

+Returns:
+    PIL.Image.Image: The generated image.
+ +
get_cmodels(self)
+ +
get_config(self)
Return parameters for this model.

+:return: dict
+ +
get_cpath(self)
+ +
get_default_cond_scales(self)
+ +
get_sd_class(self)
+ +
setup(self, fimage, width=None, height=None, image=None, cscales=None, guess_mode=False, **args)
Set up the pipeline with the given parameters.

+Args:
+    fimage (str):
+        The path to the input image file.
+    width (int, *optional*):
+        The width of the generated image. Defaults to the width of the input image.
+    height (int, *optional*):
+        The height of the generated image. Defaults to the height of the input image.
+    image (PIL.Image.Image, *optional*):
+        The input image. Defaults to None. fimage should be None if this argument is provided.
+    cscales (list, optional):
+        The list of conditioning scales. Defaults to None.
+    guess_mode (bool, optional):
+        Whether to use guess mode. Defaults to False.
+        it enables image generation without text prompt.
+    **args: Additional arguments for the pipeline setup.
+ +
+Data and other attributes defined here:
+
cmodels = {'canny': 'sd-controlnet-canny', 'depth': 'control_v11f1p_sd15_depth', 'inpaint': 'control_v11p_sd15_inpaint', 'ip2p': 'control_v11e_sd15_ip2p', 'pose': 'control_v11p_sd15_openpose', 'qr': 'controlnet_qrcode-control_v1p_sd15', 'scribble': 'control_v11p_sd15_scribble', 'soft': 'control_v11p_sd15_softedge', 'soft-sobel': 'control_v11p_sd15_softedge'}
+ +
cmodelsxl = {'qr': 'controlnet-qr-pattern-sdxl'}
+ +
cond_scales_defaults = {'canny': 0.75, 'depth': 0.5, 'inpaint': 1.0, 'ip2p': 0.5, 'pose': 1.0, 'qr': 1.5, 'scribble': 0.95, 'soft': 0.95, 'soft-sobel': 0.3}
+ +
cond_scales_defaults_xl = {'qr': 0.5}
+ +
cpath = './models-cn/'
+ +
cpathxl = './models-cn-xl/'
+ +
+Methods inherited from BasePipe:
+
add_hypernet(self, path, multiplier=None)
+ +
clear_hypernets(self)
+ +
from_pipe(self, pipe, **args)
+ +
load_lora(self, path, multiplier=1.0)
+ +
try_set_scheduler(self, inputs)
+ +
+Readonly properties inherited from BasePipe:
+
hypernets
+
+
model_id
+
The model id used by the pipeline
+
+
scheduler
+
The scheduler used by the pipeline
+
+
+Data descriptors inherited from BasePipe:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+

+ + + + + + + +
 
+class ControlnetType(enum.Enum)
   ControlnetType(value, names=None, *, module=None, qualname=None, type=None, start=1)

+An enumeration.
 
 
Method resolution order:
+
ControlnetType
+
enum.Enum
+
builtins.object
+
+
+Data and other attributes defined here:
+
SD = <ControlnetType.SD: 1>
+ +
SDXL = <ControlnetType.SDXL: 2>
+ +
+Data descriptors inherited from enum.Enum:
+
name
+
The name of the Enum member.
+
+
value
+
The value of the Enum member.
+
+
+Readonly properties inherited from enum.EnumMeta:
+
__members__
+
Returns a mapping of member name->value.

+This mapping lists all enum members, including aliases. Note that this
+is a read-only view of the internal mapping.
+
+

+ + + + + + + +
 
+class Im2ImPipe(BasePipe)
   Im2ImPipe(model_id, pipe: Optional[diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline] = None, **args)

+
 
 
Method resolution order:
+
Im2ImPipe
+
BasePipe
+
builtins.object
+
+
+Methods defined here:
+
__init__(self, model_id, pipe: Optional[diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline] = None, **args)
Constructor

+Args:
+    model_id (str):
+        path or id of the model to load
+    sd_pipe_class (Type, *optional*):
+      a subclass of DiffusionPipeline to load model to.
+    pipe (DiffusionPipeline, *optional*):
+        an instance of the pipeline to use,
+        if provided the model_id won't be used for loading.
+    **args:
+        additional arguments passed to sd_pipe_class constructor
+ +
gen(self, inputs: dict)
Generate an image from a prompt and input image.

+Args:
+    inputs (dict): Input dictionary containing the prompt and other parameters overriding pipeline configuration.

+Returns:
+    Pil.Image.Image: Generated image.
+ +
get_config(self)
Return parameters for this pipeline.

+Returns:
+    dict: pipeline parameters.
+ +
scale_image(self, image, scale)
Scale the input image.

+Args:
+    image (Image.Image): Input image.
+    scale (list or float, optional): Scale factor for the input image. Defaults to None.

+Returns:
+    Image.Image: Scaled input image.
+ +
setup(self, fimage, image=None, strength=0.75, gscale=7.5, scale=None, **args)
Setup pipeline for generation.

+Args:
+    fimage (str): File path to the input image.
+    image (Image.Image, *optional*): Input image. Defaults to None.
+    strength (float, *optional*):
+        Strength image modification. Defaults to 0.75. A lower strength values keep result close to the input image.
+         value of 1 means input image more or less ignored.
+    gscale (float, *optional*): Guidance scale for the model. Defaults to 7.5.
+    scale (list or float, *optional*): Scale factor for the input image. Defaults to None.
+    **args: Additional arguments passed to BasePipe setup method.
+ +
+Methods inherited from BasePipe:
+
add_hypernet(self, path, multiplier=None)
+ +
clear_hypernets(self)
+ +
from_pipe(self, pipe, **args)
+ +
load_lora(self, path, multiplier=1.0)
+ +
try_set_scheduler(self, inputs)
+ +
+Readonly properties inherited from BasePipe:
+
hypernets
+
+
model_id
+
The model id used by the pipeline
+
+
scheduler
+
The scheduler used by the pipeline
+
+
+Data descriptors inherited from BasePipe:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+

+ + + + + + + +
 
+class InpaintingPipe(BasePipe)
   InpaintingPipe(model_id, pipe: Optional[diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline] = None, **args)

+A pipeline for inpainting images using ControlNet models.
 
 
Method resolution order:
+
InpaintingPipe
+
BasePipe
+
builtins.object
+
+
+Methods defined here:
+
__init__(self, model_id, pipe: Optional[diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline] = None, **args)
Initialize the InpaintingPipe.

+Args:
+    model_id (str):
+        The identifier of the model to load.
+    pipe (StableDiffusion(XL)ControlNetPipeline, *optional*):
+        An instance of the pipeline to use. If provided, the model_id won't be used for loading. Defaults to None.
+    **args:
+        Additional arguments passed to the BasePipe constructor.
+ +
gen(self, inputs)
Generate an inpainted image using the pipeline.

+Args:
+    inputs (dict):
+        A dictionary of additional parameters to pass to the pipeline.

+Returns:
+    PIL.Image:
+        The generated inpainted image.
+ +
setup(self, fimage, mask_image, image=None, **args)
Set up the pipeline for inpainting with the given image and mask.

+Args:
+    fimage:
+        The path to the base image to be inpainted.
+    mask_image:
+        The mask image indicating the areas to be inpainted.
+    image (optional):
+        An additional image input for processing. Defaults to None.
+    **args:
+        Additional arguments passed to the BasePipe setup method.
+ +
+Methods inherited from BasePipe:
+
add_hypernet(self, path, multiplier=None)
+ +
clear_hypernets(self)
+ +
from_pipe(self, pipe, **args)
+ +
get_config(self)
Return parameters for this model.

+:return: dict
+ +
load_lora(self, path, multiplier=1.0)
+ +
try_set_scheduler(self, inputs)
+ +
+Readonly properties inherited from BasePipe:
+
hypernets
+
+
model_id
+
The model id used by the pipeline
+
+
scheduler
+
The scheduler used by the pipeline
+
+
+Data descriptors inherited from BasePipe:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+

+ + + + + + + +
 
+class MaskedIm2ImPipe(Im2ImPipe)
   MaskedIm2ImPipe(*args, pipe: Optional[diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline] = None, **kwargs)

+A pipeline for image-to-image translation with masking.

+MaskedIm2ImPipe is image to image pipeline that uses mask to redraw only certain parts of the input image.
+It can be used as an inpainting pipeline with any non-inpaint models.
+The pipeline computes mask from the difference between
+original image and image with a mask on it. Color of the mask affects the result.
 
 
Method resolution order:
+
MaskedIm2ImPipe
+
Im2ImPipe
+
BasePipe
+
builtins.object
+
+
+Methods defined here:
+
__init__(self, *args, pipe: Optional[diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline] = None, **kwargs)
Initialize a MaskedIm2ImPipe instance.

+Args:
+    *args: arguments passed to Im2ImPipe.
+    pipe (StableDiffusionImg2ImgPipeline, *optional*): The underlying pipeline. Defaults to None.
+    **kwargs: Additional keyword arguments passed to Im2ImPipe constructor.
+ +
blur_mask(self, pil_mask, blur)
+ +
gen(self, inputs)
Generate an image from a prompt and input image.

+Args:
+    inputs (dict): Input dictionary containing the prompt and other parameters overriding pipeline configuration.

+Returns:
+    Pil.Image.Image: Generated image.
+ +
setup(self, original_image=None, image_painted=None, mask=None, blur=4, blur_compose=4, sample_mode='sample', scale=None, **kwargs)
Set up the pipeline.

+Args:
+   original_image (str or Image.Image, *optional*):
+        The original image. Defaults to None.
+   image_painted (str or Image.Image, *optional*):
+        The painted image. Defaults to None.
+   mask (array-like or Image.Image, *optional*):
+       The mask. Defaults to None. If None tt will be computed from the difference
+       between original_image and image_painted
+   blur (int, *optional*):
+        The blur radius for the mask. Defaults to 4.
+   blur_compose (int, *optional*):
+        The blur radius for composing the original and generated images. Defaults to 4.
+   sample_mode (str, *optional*):
+        control latents initialisation for the inpaint area, can be one of sample, argmax, random Defaults to 'sample'.
+   scale (list or float, *optional*):
+        The scale factor for resizing of the input image. Defaults to None.
+   **kwargs: Additional keyword arguments passed to Im2ImPipe constructor.
+ +
+Methods inherited from Im2ImPipe:
+
get_config(self)
Return parameters for this pipeline.

+Returns:
+    dict: pipeline parameters.
+ +
scale_image(self, image, scale)
Scale the input image.

+Args:
+    image (Image.Image): Input image.
+    scale (list or float, optional): Scale factor for the input image. Defaults to None.

+Returns:
+    Image.Image: Scaled input image.
+ +
+Methods inherited from BasePipe:
+
add_hypernet(self, path, multiplier=None)
+ +
clear_hypernets(self)
+ +
from_pipe(self, pipe, **args)
+ +
load_lora(self, path, multiplier=1.0)
+ +
try_set_scheduler(self, inputs)
+ +
+Readonly properties inherited from BasePipe:
+
hypernets
+
+
model_id
+
The model id used by the pipeline
+
+
scheduler
+
The scheduler used by the pipeline
+
+
+Data descriptors inherited from BasePipe:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+

+ + + + + + + +
 
+class Prompt2ImPipe(BasePipe)
   Prompt2ImPipe(model_id: str, pipe: Optional[diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline] = None, lpw=False, **args)

+Base class for all pipelines that take a prompt and return an image.
 
 
Method resolution order:
+
Prompt2ImPipe
+
BasePipe
+
builtins.object
+
+
+Methods defined here:
+
__init__(self, model_id: str, pipe: Optional[diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline] = None, lpw=False, **args)
Constructor

+Args:
+    model_id (str):
+        path or id of the model to load
+    sd_pipe_class (Type, *optional*):
+      a subclass of DiffusionPipeline to load model to.
+    pipe (DiffusionPipeline, *optional*):
+        an instance of the pipeline to use,
+        if provided the model_id won't be used for loading.
+    **args:
+        additional arguments passed to sd_pipe_class constructor
+ +
gen(self, inputs: dict)
Generate an image from a prompt.

+Args:
+    inputs (dict):
+        input dictionary containing the prompt and other parameters

+Returns:
+    image (Pil.Image.Image):
+        generated image
+ +
setup(self, width=768, height=768, guidance_scale=7.5, **args) -> None
Setup pipeline for generation.

+Args:
+    width (int, *optional*):
+        image width (default: 768)
+    height (int, *optional*):
+        image height (default: 768)
+    guidance_scale (float, *optional*):
+        guidance scale for the model (default: 7.5)
+    **args:
+        additional arguments passed to BasePipe setup method
+ +
+Methods inherited from BasePipe:
+
add_hypernet(self, path, multiplier=None)
+ +
clear_hypernets(self)
+ +
from_pipe(self, pipe, **args)
+ +
get_config(self)
Return parameters for this model.

+:return: dict
+ +
load_lora(self, path, multiplier=1.0)
+ +
try_set_scheduler(self, inputs)
+ +
+Readonly properties inherited from BasePipe:
+
hypernets
+
+
model_id
+
The model id used by the pipeline
+
+
scheduler
+
The scheduler used by the pipeline
+
+
+Data descriptors inherited from BasePipe:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+

+ + + + + +
 
+Functions
       
add_scheduler(pipe, scheduler)
+
canny_processor(oriImg)
+
get_diffusion_scheduler_names()
return list of schedulers that can be use in our pipelines
+
sobel_processor(oriImg, ksize=9)
+

+ + + + + +
 
+Data
       Optional = typing.Optional
+Type = typing.Type
+ \ No newline at end of file diff --git a/docs/generated/multigen.prompting.html b/docs/generated/multigen.prompting.html new file mode 100644 index 0000000..494cf6d --- /dev/null +++ b/docs/generated/multigen.prompting.html @@ -0,0 +1,71 @@ + +Python: module multigen.prompting + + + + + +
 
+ 
multigen.prompting
index
/home/imgen/projects/metafusion/multigen/prompting.py
+

+

+ + + + + +
 
+Modules
       
random
+

+ + + + + +
 
+Classes
       
+
builtins.object +
+
+
Cfgen +
+
+
+

+ + + + + + + +
 
+class Cfgen(builtins.object)
   Cfgen(prompt, negative_prompt='', max_count=0, seeds=None, max_seed_rounds=1, **kwargs)

+
 
 Methods defined here:
+
__init__(self, prompt, negative_prompt='', max_count=0, seeds=None, max_seed_rounds=1, **kwargs)
Initialize self.  See help(type(self)) for accurate signature.
+ +
__iter__(self)
+ +
__next__(self)
+ +
+Data descriptors defined here:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+

+ + + + + +
 
+Functions
       
get_prompt(prompt_desc)
+
+ \ No newline at end of file diff --git a/docs/generated/multigen.sessions.html b/docs/generated/multigen.sessions.html new file mode 100644 index 0000000..ee6ac0d --- /dev/null +++ b/docs/generated/multigen.sessions.html @@ -0,0 +1,97 @@ + +Python: module multigen.sessions + + + + + +
 
+ 
multigen.sessions
index
/home/imgen/projects/metafusion/multigen/sessions.py
+

+

+ + + + + +
 
+Modules
       
json
+
os
+
torch
+
multigen.util
+

+ + + + + +
 
+Classes
       
+
builtins.object +
+
+
GenSession +
+
+
+

+ + + + + + + +
 
+class GenSession(builtins.object)
   GenSession(session_dir, pipe, config: multigen.prompting.Cfgen, name_prefix='')

+
 
 Methods defined here:
+
__init__(self, session_dir, pipe, config: multigen.prompting.Cfgen, name_prefix='')
Initialize a GenSession instance.

+Args:
+    session_dir (str):
+        The directory to store the session files.
+    pipe (Pipe):
+        The pipeline object for generating images.
+    config (Cfgen):
+        The configuration object for the generation process.
+    name_prefix (str, *optional*):
+        The prefix for the generated file names. Defaults to "".
+ +
gen_sess(self, add_count=0, save_img=True, drop_cfg=False, force_collect=False, callback=None, save_metadata=False)
Run image generation session

+Args:
+    add_count (int, *optional*):
+        The number of additional iterations to add. Defaults to 0.
+    save_img (bool, *optional*):
+        Whether to save the generated images on local filesystem. Defaults to True.
+    drop_cfg (bool, *optional*):
+        If true don't save configuration file for each image. Defaults to False.
+    force_collect (bool, *optional*):
+        Force returning generated images even if save_img is true. Defaults to False.
+    callback (callable, *optional*):
+        A callback function to be called after each iteration. Defaults to None.
+    save_metadata (bool, *optional*):
+        Whether to save metadata in the image EXIF. Defaults to False.

+Returns:
+    List[Image.Image]: The generated images if `save_img` is False or `force_collect` is True.
+ +
get_last_conf(self)
+ +
get_last_file_prefix(self)
+ +
save_last_conf(self)
+ +
+Data descriptors defined here:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+

+ \ No newline at end of file diff --git a/docs/generated/multigen.util.html b/docs/generated/multigen.util.html new file mode 100644 index 0000000..d71af59 --- /dev/null +++ b/docs/generated/multigen.util.html @@ -0,0 +1,30 @@ + +Python: module multigen.util + + + + + +
 
+ 
multigen.util
index
/home/imgen/projects/metafusion/multigen/util.py
+

+

+ + + + + +
 
+Modules
       
PIL.Image
+

+ + + + + +
 
+Functions
       
create_exif_metadata(im: <module 'PIL.Image' from '/home/imgen/miniconda3/envs/py31/lib/python3.10/site-packages/PIL/Image.py'>, custom_metadata)
+
+ \ No newline at end of file diff --git a/docs/generated/multigen.worker.html b/docs/generated/multigen.worker.html new file mode 100644 index 0000000..b33deef --- /dev/null +++ b/docs/generated/multigen.worker.html @@ -0,0 +1,216 @@ + +Python: module multigen.worker + + + + + +
 
+ 
multigen.worker
index
/home/imgen/projects/metafusion/multigen/worker.py
+

+

+ + + + + +
 
+Modules
       
time
+
torch
+

+ + + + + +
 
+Classes
       
+
multigen.worker_base.ServiceThreadBase(threading.Thread) +
+
+
ServiceThread +
+
+
+

+ + + + + + + +
 
+class ServiceThread(multigen.worker_base.ServiceThreadBase)
   ServiceThread(cfg_file)

+
 
 
Method resolution order:
+
ServiceThread
+
multigen.worker_base.ServiceThreadBase
+
threading.Thread
+
builtins.object
+
+
+Methods defined here:
+
get_pipeline(self, pipe_name, model_id, cnet=None, xl=False)
+ +
run(self)
Method representing the thread's activity.

+You may override this method in a subclass. The standard run() method
+invokes the callable object passed to the object's constructor as the
+target argument, if any, with sequential and keyword arguments taken
+from the args and kwargs arguments, respectively.
+ +
+Methods inherited from multigen.worker_base.ServiceThreadBase:
+
__init__(self, cfg_file)
This constructor should always be called with keyword arguments. Arguments are:

+*group* should be None; reserved for future extension when a ThreadGroup
+class is implemented.

+*target* is the callable object to be invoked by the run()
+method. Defaults to None, meaning nothing is called.

+*name* is the thread name. By default, a unique name is constructed of
+the form "Thread-N" where N is a small decimal number.

+*args* is the argument tuple for the target invocation. Defaults to ().

+*kwargs* is a dictionary of keyword arguments for the target
+invocation. Defaults to {}.

+If a subclass overrides the constructor, it must make sure to invoke
+the base class constructor (Thread.__init__()) before doing anything
+else to the thread.
+ +
close_session(self, session_id)
+ +
get_image_count(self, session_id)
+ +
get_image_pathname(self, session_id, img_idx)
+ +
get_pipe_class(self, name: str) -> Type[ForwardRef('BasePipe')]
+ +
get_session_info(self, session_id)
+ +
open_session(self, **args)
Open a new session for a user.

+Parameters:
+   **args (dict): Keyword arguments containing the session details.
+       user (str): The username of the session owner.
+       model (str): The name of the model to use for the session, the one specified in config
+           file under "base" field.
+       pipe: (str): The name of the pipe to use for the session, the one specified in models config
+           file under "pipes" field.
+       project (str): The name of the project to generate images.

+Returns:
+   dict: A dictionary containing the session ID(session_id) and an error message if applicable.
+ +
queue_gen(self, **args)
+ +
stop(self)
+ +
+Readonly properties inherited from multigen.worker_base.ServiceThreadBase:
+
pipes
+
Get the list of available pipes.
+
+
+Methods inherited from threading.Thread:
+
__repr__(self)
Return repr(self).
+ +
getName(self)
Return a string used for identification purposes only.

+This method is deprecated, use the name attribute instead.
+ +
isDaemon(self)
Return whether this thread is a daemon.

+This method is deprecated, use the daemon attribute instead.
+ +
is_alive(self)
Return whether the thread is alive.

+This method returns True just before the run() method starts until just
+after the run() method terminates. See also the module function
+enumerate().
+ +
join(self, timeout=None)
Wait until the thread terminates.

+This blocks the calling thread until the thread whose join() method is
+called terminates -- either normally or through an unhandled exception
+or until the optional timeout occurs.

+When the timeout argument is present and not None, it should be a
+floating point number specifying a timeout for the operation in seconds
+(or fractions thereof). As join() always returns None, you must call
+is_alive() after join() to decide whether a timeout happened -- if the
+thread is still alive, the join() call timed out.

+When the timeout argument is not present or None, the operation will
+block until the thread terminates.

+A thread can be join()ed many times.

+join() raises a RuntimeError if an attempt is made to join the current
+thread as that would cause a deadlock. It is also an error to join() a
+thread before it has been started and attempts to do so raises the same
+exception.
+ +
setDaemon(self, daemonic)
Set whether this thread is a daemon.

+This method is deprecated, use the .daemon property instead.
+ +
setName(self, name)
Set the name string for this thread.

+This method is deprecated, use the name attribute instead.
+ +
start(self)
Start the thread's activity.

+It must be called at most once per thread object. It arranges for the
+object's run() method to be invoked in a separate thread of control.

+This method will raise a RuntimeError if called more than once on the
+same thread object.
+ +
+Readonly properties inherited from threading.Thread:
+
ident
+
Thread identifier of this thread or None if it has not been started.

+This is a nonzero integer. See the get_ident() function. Thread
+identifiers may be recycled when a thread exits and another thread is
+created. The identifier is available even after the thread has exited.
+
+
native_id
+
Native integral thread ID of this thread, or None if it has not been started.

+This is a non-negative integer. See the get_native_id() function.
+This represents the Thread ID as reported by the kernel.
+
+
+Data descriptors inherited from threading.Thread:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+
daemon
+
A boolean value indicating whether this thread is a daemon thread.

+This must be set before start() is called, otherwise RuntimeError is
+raised. Its initial value is inherited from the creating thread; the
+main thread is not a daemon thread and therefore all threads created in
+the main thread default to daemon = False.

+The entire Python program exits when only daemon threads are left.
+
+
name
+
A string used for identification purposes only.

+It has no semantics. Multiple threads may be given the same name. The
+initial name is set by the constructor.
+
+

+ \ No newline at end of file diff --git a/docs/generated/multigen.worker_base.html b/docs/generated/multigen.worker_base.html new file mode 100644 index 0000000..234211e --- /dev/null +++ b/docs/generated/multigen.worker_base.html @@ -0,0 +1,221 @@ + +Python: module multigen.worker_base + + + + + +
 
+ 
multigen.worker_base
index
/home/imgen/projects/metafusion/multigen/worker_base.py
+

+

+ + + + + +
 
+Modules
       
logging
+os
+
random
+threading
+
yaml
+

+ + + + + +
 
+Classes
       
+
threading.Thread(builtins.object) +
+
+
ServiceThreadBase +
+
+
+

+ + + + + + + +
 
+class ServiceThreadBase(threading.Thread)
   ServiceThreadBase(cfg_file)

+Base class implementing the worker thread for image generation
 
 
Method resolution order:
+
ServiceThreadBase
+
threading.Thread
+
builtins.object
+
+
+Methods defined here:
+
__init__(self, cfg_file)
This constructor should always be called with keyword arguments. Arguments are:

+*group* should be None; reserved for future extension when a ThreadGroup
+class is implemented.

+*target* is the callable object to be invoked by the run()
+method. Defaults to None, meaning nothing is called.

+*name* is the thread name. By default, a unique name is constructed of
+the form "Thread-N" where N is a small decimal number.

+*args* is the argument tuple for the target invocation. Defaults to ().

+*kwargs* is a dictionary of keyword arguments for the target
+invocation. Defaults to {}.

+If a subclass overrides the constructor, it must make sure to invoke
+the base class constructor (Thread.__init__()) before doing anything
+else to the thread.
+ +
close_session(self, session_id)
+ +
get_image_count(self, session_id)
+ +
get_image_pathname(self, session_id, img_idx)
+ +
get_pipe_class(self, name: str) -> Type[ForwardRef('BasePipe')]
+ +
get_session_info(self, session_id)
+ +
open_session(self, **args)
Open a new session for a user.

+Parameters:
+   **args (dict): Keyword arguments containing the session details.
+       user (str): The username of the session owner.
+       model (str): The name of the model to use for the session, the one specified in config
+           file under "base" field.
+       pipe: (str): The name of the pipe to use for the session, the one specified in models config
+           file under "pipes" field.
+       project (str): The name of the project to generate images.

+Returns:
+   dict: A dictionary containing the session ID(session_id) and an error message if applicable.
+ +
queue_gen(self, **args)
+ +
run(self)
Method representing the thread's activity.

+You may override this method in a subclass. The standard run() method
+invokes the callable object passed to the object's constructor as the
+target argument, if any, with sequential and keyword arguments taken
+from the args and kwargs arguments, respectively.
+ +
stop(self)
+ +
+Readonly properties defined here:
+
pipes
+
Get the list of available pipes.
+
+
+Methods inherited from threading.Thread:
+
__repr__(self)
Return repr(self).
+ +
getName(self)
Return a string used for identification purposes only.

+This method is deprecated, use the name attribute instead.
+ +
isDaemon(self)
Return whether this thread is a daemon.

+This method is deprecated, use the daemon attribute instead.
+ +
is_alive(self)
Return whether the thread is alive.

+This method returns True just before the run() method starts until just
+after the run() method terminates. See also the module function
+enumerate().
+ +
join(self, timeout=None)
Wait until the thread terminates.

+This blocks the calling thread until the thread whose join() method is
+called terminates -- either normally or through an unhandled exception
+or until the optional timeout occurs.

+When the timeout argument is present and not None, it should be a
+floating point number specifying a timeout for the operation in seconds
+(or fractions thereof). As join() always returns None, you must call
+is_alive() after join() to decide whether a timeout happened -- if the
+thread is still alive, the join() call timed out.

+When the timeout argument is not present or None, the operation will
+block until the thread terminates.

+A thread can be join()ed many times.

+join() raises a RuntimeError if an attempt is made to join the current
+thread as that would cause a deadlock. It is also an error to join() a
+thread before it has been started and attempts to do so raises the same
+exception.
+ +
setDaemon(self, daemonic)
Set whether this thread is a daemon.

+This method is deprecated, use the .daemon property instead.
+ +
setName(self, name)
Set the name string for this thread.

+This method is deprecated, use the name attribute instead.
+ +
start(self)
Start the thread's activity.

+It must be called at most once per thread object. It arranges for the
+object's run() method to be invoked in a separate thread of control.

+This method will raise a RuntimeError if called more than once on the
+same thread object.
+ +
+Readonly properties inherited from threading.Thread:
+
ident
+
Thread identifier of this thread or None if it has not been started.

+This is a nonzero integer. See the get_ident() function. Thread
+identifiers may be recycled when a thread exits and another thread is
+created. The identifier is available even after the thread has exited.
+
+
native_id
+
Native integral thread ID of this thread, or None if it has not been started.

+This is a non-negative integer. See the get_native_id() function.
+This represents the Thread ID as reported by the kernel.
+
+
+Data descriptors inherited from threading.Thread:
+
__dict__
+
dictionary for instance variables (if defined)
+
+
__weakref__
+
list of weak references to the object (if defined)
+
+
daemon
+
A boolean value indicating whether this thread is a daemon thread.

+This must be set before start() is called, otherwise RuntimeError is
+raised. Its initial value is inherited from the creating thread; the
+main thread is not a daemon thread and therefore all threads created in
+the main thread default to daemon = False.

+The entire Python program exits when only daemon threads are left.
+
+
name
+
A string used for identification purposes only.

+It has no semantics. Multiple threads may be given the same name. The
+initial name is set by the constructor.
+
+

+ + + + + +
 
+Data
       Type = typing.Type
+ \ No newline at end of file