text stringlengths 1 1.02k | class_index int64 0 1.38k | source stringclasses 431
values |
|---|---|---|
encoder_hid_dim_type: Optional[str] = None,
attention_head_dim: Union[int, Tuple[int, ...]] = 8,
num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
use_linear_projection: bool = False,
class_embed_type: Optional[str] = None,
addition_embed_type: Optional[str] = No... | 828 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet.py |
deprecation_message = "Importing `ControlNetModel` from `diffusers.models.controlnet` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet import ControlNetModel`, instead."
deprecate("diffusers.models.controlnet.ControlNetModel", "0.34", deprecati... | 828 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet.py |
cross_attention_dim=cross_attention_dim,
transformer_layers_per_block=transformer_layers_per_block,
encoder_hid_dim=encoder_hid_dim,
encoder_hid_dim_type=encoder_hid_dim_type,
attention_head_dim=attention_head_dim,
num_attention_heads=num_attention_heads,
... | 828 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet.py |
addition_embed_type_num_heads=addition_embed_type_num_heads,
) | 828 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet.py |
class ControlNetConditioningEmbedding(ControlNetConditioningEmbedding):
def __init__(self, *args, **kwargs):
deprecation_message = "Importing `ControlNetConditioningEmbedding` from `diffusers.models.controlnet` is deprecated and this will be removed in a future version. Please use `from diffusers.models.con... | 829 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet.py |
class FlaxModelMixin(PushToHubMixin):
r"""
Base class for all Flax models.
[`FlaxModelMixin`] takes care of storing the model configuration and provides methods for loading, downloading and
saving models.
- **config_name** ([`str`]) -- Filename to save a model to when calling [`~FlaxModelMixin... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
# taken from https://github.com/deepmind/jmp/blob/3a8318abc3292be38582794dbf7b094e6583b192/jmp/_src/policy.py#L27
def conditional_cast(param):
if isinstance(param, jnp.ndarray) and jnp.issubdtype(param.dtype, jnp.floating):
param = param.astype(dtype)
return param
... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
This method can be used on a TPU to explicitly convert the model parameters to bfloat16 precision to do full
half-precision training or to save weights in bfloat16 for inference in order to save memory and improve speed.
Arguments:
params (`Union[Dict, FrozenDict]`):
A `PyTr... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
>>> # load model
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
>>> # By default, the model parameters will be in fp32 precision, to cast these to bfloat16 precision
>>> params = model.to_bf16(params)
>>> # If you don't want to cast certain... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
def to_fp32(self, params: Union[Dict, FrozenDict], mask: Any = None):
r"""
Cast the floating-point `params` to `jax.numpy.float32`. This method can be used to explicitly convert the
model parameters to fp32 precision. This returns a new `params` tree and does not cast the `params` in place.
... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
>>> # Download model and configuration from huggingface.co
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
>>> # By default, the model params will be in fp32, to illustrate the use of this method,
>>> # we'll first cast to fp16 and back to fp32
... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
Arguments:
params (`Union[Dict, FrozenDict]`):
A `PyTree` of model parameters.
mask (`Union[Dict, FrozenDict]`):
A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`
for params you want to cast, an... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
>>> flat_params = traverse_util.flatten_dict(params)
>>> mask = {
... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
... for path in flat_params
... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
Parameters:
pretrained_model_name_or_path (`str` or `os.PathLike`):
Can be either:
- A string, the *model id* (for example `runwayml/stable-diffusion-v1-5`) of a pretrained model
hosted on the Hub.
- A path to a *directory* (for ... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
This only specifies the dtype of the *computation* and does not influence the dtype of model
parameters.
If you wish to change the dtype of the model parameters, see [`~FlaxModelMixin.to_fp16`] and
[`~FlaxModelMixin.to_bf16`].
</Tip>
model_a... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
local_files_only(`bool`, *optional*, defaults to `False`):
... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
Can be used to update the configuration object (after it is loaded) and initiate the model (for
example, `output_attentions=True`). Behaves differently depending on whether a `config` is provided or
automatically loaded: | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
- If a configuration is provided with `config`, `kwargs` are directly passed to the underlying
model's `__init__` method (we assume all relevant updates to the configuration have already been
done).
- If a configuration is not provided, `kwargs` are first ... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
>>> # Download model and configuration from huggingface.co and cache.
>>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
>>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable).
>>> model, params = Flax... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
```bash
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... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
user_agent = {
"diffusers": __version__,
"file_type": "model",
"framework": "flax",
}
# Load config if we don't provide one
if config is None:
config, unused_kwargs = cls.load_config(
pretrained_model_name_or_path,
... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
# Load model
pretrained_path_with_subfolder = (
pretrained_model_name_or_path
if subfolder is None
else os.path.join(pretrained_model_name_or_path, subfolder)
)
if os.path.isdir(pretrained_path_with_subfolder):
if from_pt:
if not os... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):
raise EnvironmentError(
f"{WEIGHTS_NAME} file found in directory {pretrained_path_with_subfolder}. Please load the model"
" using `from_pt=True`."
)
else:
... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
subfolder=subfolder,
revision=revision,
) | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
except RepositoryNotFoundError:
raise EnvironmentError(
f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier "
"listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a "
... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
f"{pretrained_model_name_or_path} does not appear to have a file named {FLAX_WEIGHTS_NAME}."
)
except HTTPError as err:
raise EnvironmentError(
f"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n"
... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
except EnvironmentError:
raise EnvironmentError(
f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from "
"'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
if from_pt:
if is_torch_available():
from .modeling_utils import load_state_dict
else:
raise EnvironmentError(
"Can't load the model in PyTorch format because PyTorch is not installed. "
"Please, install PyTorch or use nativ... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
# Step 2: Convert the weights
state = convert_pytorch_state_dict_to_flax(pytorch_model_file, model)
else:
try:
with open(model_file, "rb") as state_f:
state = from_bytes(cls, state_f.read())
except (UnpicklingError, msgpack.exceptions.Extra... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
raise EnvironmentError(f"Unable to convert {model_file} to Flax deserializable object. ")
# make sure all arrays are stored as jnp.ndarray
# NOTE: This is to prevent a bug this will be fixed in Flax >= v0.3.4:
# https://github.com/google/flax/issues/1261
state = jax.tree_util... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
# flatten dicts
state = flatten_dict(state)
params_shape_tree = jax.eval_shape(model.init_weights, rng=jax.random.PRNGKey(0))
required_params = set(flatten_dict(unfreeze(params_shape_tree)).keys())
shape_state = flatten_dict(unfreeze(params_shape_tree))
missing_keys = required... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
for key in state.keys():
if key in shape_state and state[key].shape != shape_state[key].shape:
raise ValueError(
f"Trying to load the pretrained weight for {key} failed: checkpoint has shape "
f"{state[key].shape} which is incompatible with the model s... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
if len(unexpected_keys) > 0:
logger.warning(
f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when"
f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are"
f" initializing {model.__cl... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
if len(missing_keys) > 0:
logger.warning(
f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably"
" TRAIN this model on a... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
def save_pretrained(
self,
save_directory: Union[str, os.PathLike],
params: Union[Dict, FrozenDict],
is_main_process: bool = True,
push_to_hub: bool = False,
**kwargs,
):
"""
Save a model and its configuration file to a directory so that it can be relo... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
Arguments:
save_directory (`str` or `os.PathLike`):
Directory to save a model and its configuration file to. Will be created if it doesn't exist.
params (`Union[Dict, FrozenDict]`):
A `PyTree` of model parameters.
is_main_process (`bool`, *optional*, d... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
"""
if os.path.isfile(save_directory):
logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
return | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
os.makedirs(save_directory, exist_ok=True)
if push_to_hub:
commit_message = kwargs.pop("commit_message", None)
private = kwargs.pop("private", None)
create_pr = kwargs.pop("create_pr", False)
token = kwargs.pop("token", None)
repo_id = kwargs.pop("rep... | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
if push_to_hub:
self._upload_folder(
save_directory,
repo_id,
token=token,
commit_message=commit_message,
create_pr=create_pr,
) | 830 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_flax_utils.py |
class SD3ControlNetOutput(SD3ControlNetOutput):
def __init__(self, *args, **kwargs):
deprecation_message = "Importing `SD3ControlNetOutput` from `diffusers.models.controlnet_sd3` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_sd3 import S... | 831 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet_sd3.py |
class SD3ControlNetModel(SD3ControlNetModel):
def __init__(
self,
sample_size: int = 128,
patch_size: int = 2,
in_channels: int = 16,
num_layers: int = 18,
attention_head_dim: int = 64,
num_attention_heads: int = 18,
joint_attention_dim: int = 4096,
... | 832 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet_sd3.py |
num_layers=num_layers,
attention_head_dim=attention_head_dim,
num_attention_heads=num_attention_heads,
joint_attention_dim=joint_attention_dim,
caption_projection_dim=caption_projection_dim,
pooled_projection_dim=pooled_projection_dim,
out_channels... | 832 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet_sd3.py |
class SD3MultiControlNetModel(SD3MultiControlNetModel):
def __init__(self, *args, **kwargs):
deprecation_message = "Importing `SD3MultiControlNetModel` from `diffusers.models.controlnet_sd3` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_... | 833 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet_sd3.py |
class FP32SiLU(nn.Module):
r"""
SiLU activation function with input upcasted to torch.float32.
"""
def __init__(self):
super().__init__()
def forward(self, inputs: torch.Tensor) -> torch.Tensor:
return F.silu(inputs.float(), inplace=False).to(inputs.dtype) | 834 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/activations.py |
class GELU(nn.Module):
r"""
GELU activation function with tanh approximation support with `approximate="tanh"`.
Parameters:
dim_in (`int`): The number of channels in the input.
dim_out (`int`): The number of channels in the output.
approximate (`str`, *optional*, defaults to `"none"... | 835 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/activations.py |
def gelu(self, gate: torch.Tensor) -> torch.Tensor:
if gate.device.type == "mps" and is_torch_version("<", "2.0.0"):
# fp16 gelu not supported on mps before torch 2.0
return F.gelu(gate.to(dtype=torch.float32), approximate=self.approximate).to(dtype=gate.dtype)
return F.gelu(gate... | 835 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/activations.py |
class GEGLU(nn.Module):
r"""
A [variant](https://arxiv.org/abs/2002.05202) of the gated linear unit activation function.
Parameters:
dim_in (`int`): The number of channels in the input.
dim_out (`int`): The number of channels in the output.
bias (`bool`, defaults to True): Whether t... | 836 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/activations.py |
def forward(self, hidden_states, *args, **kwargs):
if len(args) > 0 or kwargs.get("scale", None) is not None:
deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while call... | 836 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/activations.py |
class SwiGLU(nn.Module):
r"""
A [variant](https://arxiv.org/abs/2002.05202) of the gated linear unit activation function. It's similar to `GEGLU`
but uses SiLU / Swish instead of GeLU.
Parameters:
dim_in (`int`): The number of channels in the input.
dim_out (`int`): The number of channe... | 837 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/activations.py |
class ApproximateGELU(nn.Module):
r"""
The approximate form of the Gaussian Error Linear Unit (GELU). For more details, see section 2 of this
[paper](https://arxiv.org/abs/1606.08415).
Parameters:
dim_in (`int`): The number of channels in the input.
dim_out (`int`): The number of channe... | 838 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/activations.py |
class LinearActivation(nn.Module):
def __init__(self, dim_in: int, dim_out: int, bias: bool = True, activation: str = "silu"):
super().__init__()
self.proj = nn.Linear(dim_in, dim_out, bias=bias)
self.activation = get_activation(activation)
def forward(self, hidden_states):
hid... | 839 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/activations.py |
class MultiAdapter(ModelMixin):
r"""
MultiAdapter is a wrapper model that contains multiple adapter models and merges their outputs according to
user-assigned weighting.
This model inherits from [`ModelMixin`]. Check the superclass documentation for common methods such as downloading
or saving.
... | 840 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
# The outputs from each adapter are added together with a weight.
# This means that the change in dimensions from downsampling must
# be the same for all adapters. Inductively, it also means the
# downscale_factor and total_downscale_factor must be the same for all
# adapters.
fi... | 840 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
f"adapters[0].downscale_factor={first_adapter_downscale_factor}\n"
f"adapter[`{idx}`].total_downscale_factor={adapters[idx].total_downscale_factor}\n"
f"adapter[`{idx}`].downscale_factor={adapters[idx].downscale_factor}"
) | 840 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
self.total_downscale_factor = first_adapter_total_downscale_factor
self.downscale_factor = first_adapter_downscale_factor
def forward(self, xs: torch.Tensor, adapter_weights: Optional[List[float]] = None) -> List[torch.Tensor]:
r"""
Args:
xs (`torch.Tensor`):
A t... | 840 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
adapter_weights (`List[float]`, *optional*, defaults to None):
A list of floats representing the weights which will be multiplied by each adapter's output before
summing them together. If `None`, equal weights will be used for all adapters.
"""
if adapter_weights is None:... | 840 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
def save_pretrained(
self,
save_directory: Union[str, os.PathLike],
is_main_process: bool = True,
save_function: Callable = None,
safe_serialization: bool = True,
variant: Optional[str] = None,
):
"""
Save a model and its configuration file to a specif... | 840 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
Args:
save_directory (`str` or `os.PathLike`):
The directory where the model will be saved. If the directory does not exist, it will be created.
is_main_process (`bool`, optional, defaults=True):
Indicates whether current process is the main process or not. Useful... | 840 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
variant (`str`, *optional*):
If specified, weights are saved in the format `pytorch_model.<variant>.bin`.
"""
idx = 0
model_path_to_save = save_directory
for adapter in self.adapters:
adapter.save_pretrained(
model_path_to_save,
... | 840 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
idx += 1
model_path_to_save = model_path_to_save + f"_{idx}"
@classmethod
def from_pretrained(cls, pretrained_model_path: Optional[Union[str, os.PathLike]], **kwargs):
r"""
Instantiate a pretrained `MultiAdapter` model from multiple pre-trained adapter models.
The model is ... | 840 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
Args:
pretrained_model_path (`os.PathLike`):
A path to a *directory* containing model weights saved using
[`~diffusers.models.adapter.MultiAdapter.save_pretrained`], e.g., `./my_model_directory/adapter`.
torch_dtype (`str` or `torch.dtype`, *optional*):
... | 840 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
same device. | 840 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. 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`, ... | 840 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
setting this argument to `True` will raise an error.
variant (`str`, *optional*):
If specified, load weights from a `variant` file (*e.g.* pytorch_model.<variant>.bin). `variant` will
be ignored when using `from_flax`.
use_safetensors (`bool`, *optional*, defaults... | 840 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
# load adapter and append to list until no adapter directory exists anymore
# first adapter has to be saved under `./mydirectory/adapter` to be compliant with `DiffusionPipeline.from_pretrained`
# second, third, ... adapters have to be saved under `./mydirectory/adapter_1`, `./mydirectory/adapter_2`, ..... | 840 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
class T2IAdapter(ModelMixin, ConfigMixin):
r"""
A simple ResNet-like model that accepts images containing control signals such as keyposes and depth. The model
generates multiple feature maps that are used as additional conditioning in [`UNet2DConditionModel`]. The model's
architecture follows the origi... | 841 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
Args:
in_channels (`int`, *optional*, defaults to `3`):
The number of channels in the adapter's input (*control image*). Set it to 1 if you're using a gray scale
image.
channels (`List[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
The number of channels in... | 841 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
@register_to_config
def __init__(
self,
in_channels: int = 3,
channels: List[int] = [320, 640, 1280, 1280],
num_res_blocks: int = 2,
downscale_factor: int = 8,
adapter_type: str = "full_adapter",
):
super().__init__()
if adapter_type == "full_adap... | 841 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
r"""
This function processes the input tensor `x` through the adapter model and returns a list of feature tensors,
each representing information extracted at a different scale from the input. The length of the list is
determined b... | 841 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
class FullAdapter(nn.Module):
r"""
See [`T2IAdapter`] for more information.
"""
def __init__(
self,
in_channels: int = 3,
channels: List[int] = [320, 640, 1280, 1280],
num_res_blocks: int = 2,
downscale_factor: int = 8,
):
super().__init__()
... | 842 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
r"""
This method processes the input tensor `x` through the FullAdapter model and performs operations including
pixel unshuffling, convolution, and a stack of AdapterBlocks. It returns a list of feature tensors, each
capturing inf... | 842 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
class FullAdapterXL(nn.Module):
r"""
See [`T2IAdapter`] for more information.
"""
def __init__(
self,
in_channels: int = 3,
channels: List[int] = [320, 640, 1280, 1280],
num_res_blocks: int = 2,
downscale_factor: int = 16,
):
super().__init__()
... | 843 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
self.body = []
# blocks to extract XL features with dimensions of [320, 64, 64], [640, 64, 64], [1280, 32, 32], [1280, 32, 32]
for i in range(len(channels)):
if i == 1:
self.body.append(AdapterBlock(channels[i - 1], channels[i], num_res_blocks))
elif i == 2:
... | 843 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
r"""
This method takes the tensor x as input and processes it through FullAdapterXL model. It consists of operations
including unshuffling pixels, applying convolution layer and appending each block into list of feature tensors.
"... | 843 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
class AdapterBlock(nn.Module):
r"""
An AdapterBlock is a helper model that contains multiple ResNet-like blocks. It is used in the `FullAdapter` and
`FullAdapterXL` models.
Args:
in_channels (`int`):
Number of channels of AdapterBlock's input.
out_channels (`int`):
... | 844 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
self.resnets = nn.Sequential(
*[AdapterResnetBlock(out_channels) for _ in range(num_res_blocks)],
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
r"""
This method takes tensor x as input and performs operations downsampling and convolutional layers if the
self.down... | 844 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
class AdapterResnetBlock(nn.Module):
r"""
An `AdapterResnetBlock` is a helper model that implements a ResNet-like block.
Args:
channels (`int`):
Number of channels of AdapterResnetBlock's input and output.
"""
def __init__(self, channels: int):
super().__init__()
... | 845 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
class LightAdapter(nn.Module):
r"""
See [`T2IAdapter`] for more information.
"""
def __init__(
self,
in_channels: int = 3,
channels: List[int] = [320, 640, 1280],
num_res_blocks: int = 4,
downscale_factor: int = 8,
):
super().__init__()
in_ch... | 846 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
r"""
This method takes the input tensor x and performs downscaling and appends it in list of feature tensors. Each
feature tensor corresponds to a different level of processing within the LightAdapter.
"""
x = self.unshuff... | 846 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
class LightAdapterBlock(nn.Module):
r"""
A `LightAdapterBlock` is a helper model that contains multiple `LightAdapterResnetBlocks`. It is used in the
`LightAdapter` model.
Args:
in_channels (`int`):
Number of channels of LightAdapterBlock's input.
out_channels (`int`):
... | 847 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
self.in_conv = nn.Conv2d(in_channels, mid_channels, kernel_size=1)
self.resnets = nn.Sequential(*[LightAdapterResnetBlock(mid_channels) for _ in range(num_res_blocks)])
self.out_conv = nn.Conv2d(mid_channels, out_channels, kernel_size=1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
r... | 847 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
class LightAdapterResnetBlock(nn.Module):
"""
A `LightAdapterResnetBlock` is a helper model that implements a ResNet-like block with a slightly different
architecture than `AdapterResnetBlock`.
Args:
channels (`int`):
Number of channels of LightAdapterResnetBlock's input and output.... | 848 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/adapter.py |
class SparseControlNetOutput(SparseControlNetOutput):
def __init__(self, *args, **kwargs):
deprecation_message = "Importing `SparseControlNetOutput` from `diffusers.models.controlnet_sparsectrl` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.control... | 849 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet_sparsectrl.py |
class SparseControlNetConditioningEmbedding(SparseControlNetConditioningEmbedding):
def __init__(self, *args, **kwargs):
deprecation_message = "Importing `SparseControlNetConditioningEmbedding` from `diffusers.models.controlnet_sparsectrl` is deprecated and this will be removed in a future version. Please u... | 850 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet_sparsectrl.py |
class SparseControlNetModel(SparseControlNetModel):
def __init__(
self,
in_channels: int = 4,
conditioning_channels: int = 4,
flip_sin_to_cos: bool = True,
freq_shift: int = 0,
down_block_types: Tuple[str, ...] = (
"CrossAttnDownBlockMotion",
"... | 851 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet_sparsectrl.py |
temporal_transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
attention_head_dim: Union[int, Tuple[int, ...]] = 8,
num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
use_linear_projection: bool = False,
upcast_attention: bool = False,
resnet_time_scale_s... | 851 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet_sparsectrl.py |
deprecation_message = "Importing `SparseControlNetModel` from `diffusers.models.controlnet_sparsectrl` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_sparsectrl import SparseControlNetModel`, instead."
deprecate("diffusers.models.controlnet_s... | 851 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet_sparsectrl.py |
cross_attention_dim=cross_attention_dim,
transformer_layers_per_block=transformer_layers_per_block,
transformer_layers_per_mid_block=transformer_layers_per_mid_block,
temporal_transformer_layers_per_block=temporal_transformer_layers_per_block,
attention_head_dim=attention... | 851 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet_sparsectrl.py |
use_simplified_condition_embedding=use_simplified_condition_embedding,
) | 851 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/controlnet_sparsectrl.py |
class FlaxAttention(nn.Module):
r"""
A Flax multi-head attention module as described in: https://arxiv.org/abs/1706.03762 | 852 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/attention_flax.py |
Parameters:
query_dim (:obj:`int`):
Input hidden states dimension
heads (:obj:`int`, *optional*, defaults to 8):
Number of heads
dim_head (:obj:`int`, *optional*, defaults to 64):
Hidden states dimension inside each head
dropout (:obj:`float`, *optiona... | 852 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/attention_flax.py |
query_dim: int
heads: int = 8
dim_head: int = 64
dropout: float = 0.0
use_memory_efficient_attention: bool = False
split_head_dim: bool = False
dtype: jnp.dtype = jnp.float32
def setup(self):
inner_dim = self.dim_head * self.heads
self.scale = self.dim_head**-0.5
# ... | 852 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/attention_flax.py |
def reshape_heads_to_batch_dim(self, tensor):
batch_size, seq_len, dim = tensor.shape
head_size = self.heads
tensor = tensor.reshape(batch_size, seq_len, head_size, dim // head_size)
tensor = jnp.transpose(tensor, (0, 2, 1, 3))
tensor = tensor.reshape(batch_size * head_size, seq_... | 852 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/attention_flax.py |
if self.split_head_dim:
b = hidden_states.shape[0]
query_states = jnp.reshape(query_proj, (b, -1, self.heads, self.dim_head))
key_states = jnp.reshape(key_proj, (b, -1, self.heads, self.dim_head))
value_states = jnp.reshape(value_proj, (b, -1, self.heads, self.dim_head))
... | 852 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/attention_flax.py |
flatten_latent_dim = query_states.shape[-3]
if flatten_latent_dim % 64 == 0:
query_chunk_size = int(flatten_latent_dim / 64)
elif flatten_latent_dim % 16 == 0:
query_chunk_size = int(flatten_latent_dim / 16)
elif flatten_latent_dim % 4 == 0:
... | 852 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/attention_flax.py |
hidden_states = jax_memory_efficient_attention(
query_states, key_states, value_states, query_chunk_size=query_chunk_size, key_chunk_size=4096 * 4
)
hidden_states = hidden_states.transpose(1, 0, 2)
hidden_states = self.reshape_batch_dim_to_heads(hidden_states)
... | 852 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/attention_flax.py |
# attend to values
if self.split_head_dim:
hidden_states = jnp.einsum("b n f t, b t n h -> b f n h", attention_probs, value_states)
b = hidden_states.shape[0]
hidden_states = jnp.reshape(hidden_states, (b, -1, self.heads * self.dim_head))
else:
... | 852 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/attention_flax.py |
class FlaxBasicTransformerBlock(nn.Module):
r"""
A Flax transformer block layer with `GLU` (Gated Linear Unit) activation function as described in:
https://arxiv.org/abs/1706.03762 | 853 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/attention_flax.py |
Parameters:
dim (:obj:`int`):
Inner hidden states dimension
n_heads (:obj:`int`):
Number of heads
d_head (:obj:`int`):
Hidden states dimension inside each head
dropout (:obj:`float`, *optional*, defaults to 0.0):
Dropout rate
only_c... | 853 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/attention_flax.py |
dim: int
n_heads: int
d_head: int
dropout: float = 0.0
only_cross_attention: bool = False
dtype: jnp.dtype = jnp.float32
use_memory_efficient_attention: bool = False
split_head_dim: bool = False | 853 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/attention_flax.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.