text stringlengths 1 1.02k | class_index int64 0 1.38k | source stringclasses 431
values |
|---|---|---|
class IPAdapterFaceIDPlusImageProjection(nn.Module):
"""FacePerceiverResampler of IP-Adapter Plus.
Args:
embed_dims (int): The feature dimension. Defaults to 768. output_dims (int): The number of output channels,
that is the same
number of the channels in the `unet.config.cross_atte... | 894 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
def __init__(
self,
embed_dims: int = 768,
output_dims: int = 768,
hidden_dims: int = 1280,
id_embeddings_dim: int = 512,
depth: int = 4,
dim_head: int = 64,
heads: int = 16,
num_tokens: int = 4,
num_queries: int = 8,
ffn_ratio: flo... | 894 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
self.layers = nn.ModuleList(
[IPAdapterPlusImageProjectionBlock(embed_dims, dim_head, heads, ffn_ratio) for _ in range(depth)]
)
def forward(self, id_embeds: torch.Tensor) -> torch.Tensor:
"""Forward pass.
Args:
id_embeds (torch.Tensor): Input Tensor (ID embeds).
... | 894 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
latents = self.proj_out(latents)
out = self.norm_out(latents)
if self.shortcut:
out = id_embeds + self.shortcut_scale * out
return out | 894 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
class IPAdapterTimeImageProjectionBlock(nn.Module):
"""Block for IPAdapterTimeImageProjection.
Args:
hidden_dim (`int`, defaults to 1280):
The number of hidden channels.
dim_head (`int`, defaults to 64):
The number of head channels.
heads (`int`, defaults to 20):... | 895 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
self.ln0 = nn.LayerNorm(hidden_dim)
self.ln1 = nn.LayerNorm(hidden_dim)
self.attn = Attention(
query_dim=hidden_dim,
cross_attention_dim=hidden_dim,
dim_head=dim_head,
heads=heads,
bias=False,
out_bias=False,
)
self.... | 895 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
Args:
x (`torch.Tensor`):
Image features.
latents (`torch.Tensor`):
Latent features.
timestep_emb (`torch.Tensor`):
Timestep embedding.
Returns:
`torch.Tensor`: Output latent features.
"""
# Shift a... | 895 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
query = query.view(batch_size, -1, self.attn.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, self.attn.heads, head_dim).transpose(1, 2)
value = value.view(batch_size, -1, self.attn.heads, head_dim).transpose(1, 2)
weight = (query * self.attn.scale) @ (key * self.attn.scale).tran... | 895 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
class IPAdapterTimeImageProjection(nn.Module):
"""Resampler of SD3 IP-Adapter with timestep embedding. | 896 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
Args:
embed_dim (`int`, defaults to 1152):
The feature dimension.
output_dim (`int`, defaults to 2432):
The number of output channels.
hidden_dim (`int`, defaults to 1280):
The number of hidden channels.
depth (`int`, defaults to 4):
The nu... | 896 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
timestep_freq_shift (`int`, defaults to 0):
Controls the timestep delta between frequencies between dimensions.
""" | 896 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
def __init__(
self,
embed_dim: int = 1152,
output_dim: int = 2432,
hidden_dim: int = 1280,
depth: int = 4,
dim_head: int = 64,
heads: int = 20,
num_queries: int = 64,
ffn_ratio: int = 4,
timestep_in_dim: int = 320,
timestep_flip_sin... | 896 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
self.time_embedding = TimestepEmbedding(timestep_in_dim, hidden_dim, act_fn="silu") | 896 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
def forward(self, x: torch.Tensor, timestep: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Forward pass.
Args:
x (`torch.Tensor`):
Image features.
timestep (`torch.Tensor`):
Timestep in denoising process.
Returns:
`Tup... | 896 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
class MultiIPAdapterImageProjection(nn.Module):
def __init__(self, IPAdapterImageProjectionLayers: Union[List[nn.Module], Tuple[nn.Module]]):
super().__init__()
self.image_projection_layers = nn.ModuleList(IPAdapterImageProjectionLayers)
def forward(self, image_embeds: List[torch.Tensor]):
... | 897 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
# currently, we accept `image_embeds` as
# 1. a tensor (deprecated) with shape [batch_size, embed_dim] or [batch_size, sequence_length, embed_dim]
# 2. list of `n` tensors where `n` is number of ip-adapters, each tensor can hae shape [batch_size, num_images, embed_dim] or [batch_size, num_images, sequ... | 897 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
if len(image_embeds) != len(self.image_projection_layers):
raise ValueError(
f"image_embeds must have the same length as image_projection_layers, got {len(image_embeds)} and {len(self.image_projection_layers)}"
)
for image_embed, image_projection_layer in zip(image_embed... | 897 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings.py |
class ResnetBlockCondNorm2D(nn.Module):
r"""
A Resnet block that use normalization layer that incorporate conditioning information. | 898 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
Parameters:
in_channels (`int`): The number of channels in the input.
out_channels (`int`, *optional*, default to be `None`):
The number of output channels for the first conv2d layer. If None, same as `in_channels`.
dropout (`float`, *optional*, defaults to `0.0`): The dropout probab... | 898 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
The normalization layer for time embedding `temb`. Currently only support "ada_group" or "spatial".
kernel (`torch.Tensor`, optional, default to None): FIR filter, see
[`~models.resnet.FirUpsample2D`] and [`~models.resnet.FirDownsample2D`].
output_scale_factor (`float`, *optional*, default t... | 898 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
def __init__(
self,
*,
in_channels: int,
out_channels: Optional[int] = None,
conv_shortcut: bool = False,
dropout: float = 0.0,
temb_channels: int = 512,
groups: int = 32,
groups_out: Optional[int] = None,
eps: float = 1e-6,
non_lin... | 898 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
self.time_embedding_norm = time_embedding_norm | 898 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
if groups_out is None:
groups_out = groups
if self.time_embedding_norm == "ada_group": # ada_group
self.norm1 = AdaGroupNorm(temb_channels, in_channels, groups, eps=eps)
elif self.time_embedding_norm == "spatial":
self.norm1 = SpatialNorm(in_channels, temb_channels)... | 898 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
conv_2d_out_channels = conv_2d_out_channels or out_channels
self.conv2 = nn.Conv2d(out_channels, conv_2d_out_channels, kernel_size=3, stride=1, padding=1)
self.nonlinearity = get_activation(non_linearity)
self.upsample = self.downsample = None
if self.up:
self.upsample = Up... | 898 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
def forward(self, input_tensor: torch.Tensor, temb: torch.Tensor, *args, **kwargs) -> torch.Tensor:
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 fut... | 898 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
if self.upsample is not None:
# upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
if hidden_states.shape[0] >= 64:
input_tensor = input_tensor.contiguous()
hidden_states = hidden_states.contiguous()
... | 898 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
output_tensor = (input_tensor + hidden_states) / self.output_scale_factor
return output_tensor | 898 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
class ResnetBlock2D(nn.Module):
r"""
A Resnet block. | 899 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
Parameters:
in_channels (`int`): The number of channels in the input.
out_channels (`int`, *optional*, default to be `None`):
The number of output channels for the first conv2d layer. If None, same as `in_channels`.
dropout (`float`, *optional*, defaults to `0.0`): The dropout probab... | 899 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
By default, apply timestep embedding conditioning with a simple shift mechanism. Choose "scale_shift" for a
stronger conditioning with scale and shift.
kernel (`torch.Tensor`, optional, default to None): FIR filter, see
[`~models.resnet.FirUpsample2D`] and [`~models.resnet.FirDownsample2... | 899 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
If None, same as `out_channels`.
""" | 899 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
def __init__(
self,
*,
in_channels: int,
out_channels: Optional[int] = None,
conv_shortcut: bool = False,
dropout: float = 0.0,
temb_channels: int = 512,
groups: int = 32,
groups_out: Optional[int] = None,
pre_norm: bool = True,
eps... | 899 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
if time_embedding_norm == "spatial":
raise ValueError(
"This class cannot be used with `time_embedding_norm==spatial`, please use `ResnetBlockCondNorm2D` instead",
) | 899 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
self.pre_norm = True
self.in_channels = in_channels
out_channels = in_channels if out_channels is None else out_channels
self.out_channels = out_channels
self.use_conv_shortcut = conv_shortcut
self.up = up
self.down = down
self.output_scale_factor = output_scale_f... | 899 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
if temb_channels is not None:
if self.time_embedding_norm == "default":
self.time_emb_proj = nn.Linear(temb_channels, out_channels)
elif self.time_embedding_norm == "scale_shift":
self.time_emb_proj = nn.Linear(temb_channels, 2 * out_channels)
else:
... | 899 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
self.upsample = self.downsample = None
if self.up:
if kernel == "fir":
fir_kernel = (1, 3, 3, 1)
self.upsample = lambda x: upsample_2d(x, kernel=fir_kernel)
elif kernel == "sde_vp":
self.upsample = partial(F.interpolate, scale_factor=2.0, m... | 899 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
self.conv_shortcut = None
if self.use_in_shortcut:
self.conv_shortcut = nn.Conv2d(
in_channels,
conv_2d_out_channels,
kernel_size=1,
stride=1,
padding=0,
bias=conv_shortcut_bias,
)
def fo... | 899 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
if self.upsample is not None:
# upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
if hidden_states.shape[0] >= 64:
input_tensor = input_tensor.contiguous()
hidden_states = hidden_states.contiguous()
... | 899 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
if self.time_embedding_norm == "default":
if temb is not None:
hidden_states = hidden_states + temb
hidden_states = self.norm2(hidden_states)
elif self.time_embedding_norm == "scale_shift":
if temb is None:
raise ValueError(
... | 899 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
output_tensor = (input_tensor + hidden_states) / self.output_scale_factor
return output_tensor | 899 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
class Conv1dBlock(nn.Module):
"""
Conv1d --> GroupNorm --> Mish
Parameters:
inp_channels (`int`): Number of input channels.
out_channels (`int`): Number of output channels.
kernel_size (`int` or `tuple`): Size of the convolving kernel.
n_groups (`int`, default `8`): Number o... | 900 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
def forward(self, inputs: torch.Tensor) -> torch.Tensor:
intermediate_repr = self.conv1d(inputs)
intermediate_repr = rearrange_dims(intermediate_repr)
intermediate_repr = self.group_norm(intermediate_repr)
intermediate_repr = rearrange_dims(intermediate_repr)
output = self.mish(i... | 900 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
class ResidualTemporalBlock1D(nn.Module):
"""
Residual 1D block with temporal convolutions.
Parameters:
inp_channels (`int`): Number of input channels.
out_channels (`int`): Number of output channels.
embed_dim (`int`): Embedding dimension.
kernel_size (`int` or `tuple`): Si... | 901 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
self.residual_conv = (
nn.Conv1d(inp_channels, out_channels, 1) if inp_channels != out_channels else nn.Identity()
)
def forward(self, inputs: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
"""
Args:
inputs : [ batch_size x inp_channels x horizon ]
t : [... | 901 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
class TemporalConvLayer(nn.Module):
"""
Temporal convolutional layer that can be used for video (sequence of images) input Code mostly copied from:
https://github.com/modelscope/modelscope/blob/1509fdb973e5871f37148a4b5e5964cafd43e64d/modelscope/models/multi_modal/video_synthesis/unet_sd.py#L1016
Param... | 902 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
# conv layers
self.conv1 = nn.Sequential(
nn.GroupNorm(norm_num_groups, in_dim),
nn.SiLU(),
nn.Conv3d(in_dim, out_dim, (3, 1, 1), padding=(1, 0, 0)),
)
self.conv2 = nn.Sequential(
nn.GroupNorm(norm_num_groups, out_dim),
nn.SiLU(),
... | 902 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
# zero out the last layer params,so the conv block is identity
nn.init.zeros_(self.conv4[-1].weight)
nn.init.zeros_(self.conv4[-1].bias)
def forward(self, hidden_states: torch.Tensor, num_frames: int = 1) -> torch.Tensor:
hidden_states = (
hidden_states[None, :].reshape((-1, num... | 902 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
class TemporalResnetBlock(nn.Module):
r"""
A Resnet block.
Parameters:
in_channels (`int`): The number of channels in the input.
out_channels (`int`, *optional*, default to be `None`):
The number of output channels for the first conv2d layer. If None, same as `in_channels`.
... | 903 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
self.norm1 = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=eps, affine=True)
self.conv1 = nn.Conv3d(
in_channels,
out_channels,
kernel_size=kernel_size,
stride=1,
padding=padding,
)
if temb_channels is not None:
... | 903 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
self.conv_shortcut = None
if self.use_in_shortcut:
self.conv_shortcut = nn.Conv3d(
in_channels,
out_channels,
kernel_size=1,
stride=1,
padding=0,
)
def forward(self, input_tensor: torch.Tensor, temb: tor... | 903 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
if self.conv_shortcut is not None:
input_tensor = self.conv_shortcut(input_tensor)
output_tensor = input_tensor + hidden_states
return output_tensor | 903 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
class SpatioTemporalResBlock(nn.Module):
r"""
A SpatioTemporal Resnet block. | 904 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
Parameters:
in_channels (`int`): The number of channels in the input.
out_channels (`int`, *optional*, default to be `None`):
The number of output channels for the first conv2d layer. If None, same as `in_channels`.
temb_channels (`int`, *optional*, default to `512`): the number of c... | 904 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
def __init__(
self,
in_channels: int,
out_channels: Optional[int] = None,
temb_channels: int = 512,
eps: float = 1e-6,
temporal_eps: Optional[float] = None,
merge_factor: float = 0.5,
merge_strategy="learned_with_images",
switch_spatial_to_temporal... | 904 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
self.time_mixer = AlphaBlender(
alpha=merge_factor,
merge_strategy=merge_strategy,
switch_spatial_to_temporal_mix=switch_spatial_to_temporal_mix,
)
def forward(
self,
hidden_states: torch.Tensor,
temb: Optional[torch.Tensor] = None,
image_... | 904 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
hidden_states = self.temporal_res_block(hidden_states, temb)
hidden_states = self.time_mixer(
x_spatial=hidden_states_mix,
x_temporal=hidden_states,
image_only_indicator=image_only_indicator,
)
hidden_states = hidden_states.permute(0, 2, 1, 3, 4).reshape(batc... | 904 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
class AlphaBlender(nn.Module):
r"""
A module to blend spatial and temporal features.
Parameters:
alpha (`float`): The initial value of the blending factor.
merge_strategy (`str`, *optional*, defaults to `learned_with_images`):
The merge strategy to use for the temporal mixing.
... | 905 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
if self.merge_strategy == "fixed":
self.register_buffer("mix_factor", torch.Tensor([alpha]))
elif self.merge_strategy == "learned" or self.merge_strategy == "learned_with_images":
self.register_parameter("mix_factor", torch.nn.Parameter(torch.Tensor([alpha])))
else:
r... | 905 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
alpha = torch.where(
image_only_indicator.bool(),
torch.ones(1, 1, device=image_only_indicator.device),
torch.sigmoid(self.mix_factor)[..., None],
)
# (batch, channel, frames, height, width)
if ndims == 5:
alpha = alpha... | 905 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
if self.switch_spatial_to_temporal_mix:
alpha = 1.0 - alpha
x = alpha * x_spatial + (1.0 - alpha) * x_temporal
return x | 905 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/resnet.py |
class ModelMixin(torch.nn.Module, PushToHubMixin):
r"""
Base class for all models.
[`ModelMixin`] 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 [`~models.Mod... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
def __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 We need to overwrite
__getattr__ here in addition so that we don't trigger `torch.nn.Mod... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
if is_in_config and not is_attribute:
deprecation_message = f"Accessing config attribute `{name}` directly via '{type(self).__name__}' object attribute is deprecated. Please access '{name}' over '{type(self).__name__}'s config object instead, e.g. 'unet.config.{name}'."
deprecate("direct config ... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
def enable_gradient_checkpointing(self) -> None:
"""
Activates gradient checkpointing for the current model (may be referred to as *activation checkpointing* or
*checkpoint activations* in other frameworks).
"""
if not self._supports_gradient_checkpointing:
raise Valu... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
def fn_recursive_set_npu_flash_attention(module: torch.nn.Module):
if hasattr(module, "set_use_npu_flash_attention"):
module.set_use_npu_flash_attention(valid)
for child in module.children():
fn_recursive_set_npu_flash_attention(child)
for module in self... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
def set_use_xla_flash_attention(
self, use_xla_flash_attention: bool, partition_spec: Optional[Callable] = None, **kwargs
) -> None:
# Recursively walk through all the children.
# Any children which exposes the set_use_xla_flash_attention method
# gets the message
def fn_recu... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
def enable_xla_flash_attention(self, partition_spec: Optional[Callable] = None, **kwargs):
r"""
Enable the flash attention pallals kernel for torch_xla.
"""
self.set_use_xla_flash_attention(True, partition_spec, **kwargs)
def disable_xla_flash_attention(self):
r"""
D... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
for child in module.children():
fn_recursive_set_mem_eff(child)
for module in self.children():
if isinstance(module, torch.nn.Module):
fn_recursive_set_mem_eff(module)
def enable_xformers_memory_efficient_attention(self, attention_op: Optional[Callable] = None) ... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
Parameters:
attention_op (`Callable`, *optional*):
Override the default `None` operator for use as `op` argument to the
[`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention)
fu... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
def disable_xformers_memory_efficient_attention(self) -> None:
r"""
Disable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).
"""
self.set_use_memory_efficient_attention_xformers(False)
def save_pretrained(
self,
save_directory... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_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.
is_main_process (`bool`, *optional*, defaults to `True`):
Whether the process calling this is the main process or not.... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
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`.
max_shard_size (`int` or `str`, defaults to `"10GB"`):
The maximum... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
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).
... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
hf_quantizer = getattr(self, "hf_quantizer", None)
if hf_quantizer is not None:
quantization_serializable = (
hf_quantizer is not None
and isinstance(hf_quantizer, DiffusersQuantizer)
and hf_quantizer.is_serializable
)
if not qu... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_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... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
# Clean the folder from a previous save
if is_main_process:
for filename in os.listdir(save_directory):
if filename in state_dict_split.filename_to_tensors.keys():
continue
full_filename = os.path.join(save_directory, filename)
if n... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
for filename, tensors in state_dict_split.filename_to_tensors.items():
shard = {tensor: state_dict[tensor] for tensor in tensors}
filepath = os.path.join(save_directory, filename)
if safe_serialization:
# At some point we will need to deal better with save_function (u... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
if state_dict_split.is_sharded:
index = {
"metadata": state_dict_split.metadata,
"weight_map": state_dict_split.tensor_to_filename,
}
save_index_file = SAFE_WEIGHTS_INDEX_NAME if safe_serialization else WEIGHTS_INDEX_NAME
save_index_file = ... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
path_to_weights = os.path.join(save_directory, weights_name)
logger.info(f"Model weights saved in {path_to_weights}") | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
if push_to_hub:
# Create a new empty model card and eventually tag it
model_card = load_or_create_model_card(repo_id, token=token)
model_card = populate_model_card(model_card)
model_card.save(Path(save_directory, "README.md").as_posix())
self._upload_folder(
... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
@classmethod
@validate_hf_hub_args
def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
r"""
Instantiate a pretrained PyTorch model from a pretrained model configuration.
The model is set in evaluation mode - `model.eval()` - by default, ... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
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.
torch_dtype (`str` or `torch.dtype`, *optional*):
Override the default `torch.dtype` and load ... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
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 confi... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
Load the model weights from a Flax checkpoint save file.
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 accessibil... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
more information about each option see [designing a device
map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
max_memory (`Dict`... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
when there is some disk offload.
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
tries to not use more than 1x model size ... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
`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.
disable_mmap ('bool', *optional*, defaults to 'False'):
Whether to disable mmap when loading a Safetensors m... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
<Tip>
To use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models), log-in with
`huggingface-cli login`. You can also activate the special
["offline-mode"](https://huggingface.co/diffusers/installation.html#offline-mode) to use this method in a
firewalled ... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_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... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
torch_dtype = kwargs.pop("torch_dtype", None)
subfolder = kwargs.pop("subfolder", None)
device_map = kwargs.pop("device_map", None)
max_memory = kwargs.pop("max_memory", None)
offload_folder = kwargs.pop("offload_folder", None)
offload_state_dict = kwargs.pop("offload_state_dict"... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
allow_pickle = False
if use_safetensors is None:
use_safetensors = True
allow_pickle = True
if low_cpu_mem_usage and not is_accelerate_available():
low_cpu_mem_usage = False
logger.warning(
"Cannot initialize model with low cpu memory usag... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
# Check if we can handle device_map and dispatching the weights
if device_map is not None and not is_torch_version(">=", "1.9.0"):
raise NotImplementedError(
"Loading and dispatching requires torch >= 1.9.0. Please either update your PyTorch version or set"
" `device_... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
# change device_map into a map if we passed an int, a str or a torch.device
if isinstance(device_map, torch.device):
device_map = {"": device_map}
elif isinstance(device_map, str) and device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
try:
dev... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
if device_map is not None:
if low_cpu_mem_usage is None:
low_cpu_mem_usage = True
elif not low_cpu_mem_usage:
raise ValueError("Passing along a `device_map` requires `low_cpu_mem_usage=True`")
if low_cpu_mem_usage:
if device_map is not None an... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
# load config
config, unused_kwargs, commit_hash = cls.load_config(
config_path,
cache_dir=cache_dir,
return_unused_kwargs=True,
return_commit_hash=True,
force_download=force_download,
proxies=proxies,
local_files_only=local_fil... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
# determine initial quantization config.
#######################################
pre_quantized = "quantization_config" in config and config["quantization_config"] is not None
if pre_quantized or quantization_config is not None:
if pre_quantized:
config["quantization_c... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
if hf_quantizer is not None:
if device_map is not None:
raise NotImplementedError(
"Currently, providing `device_map` is not supported for quantized models. Providing `device_map` as an input will be added in the future."
)
hf_quantizer.valida... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
# Force-set to `True` for more mem efficiency
if low_cpu_mem_usage is None:
low_cpu_mem_usage = True
logger.info("Set `low_cpu_mem_usage` to True as `hf_quantizer` is not None.")
elif not low_cpu_mem_usage:
raise ValueError("`low_cpu_mem_usage` can... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
if low_cpu_mem_usage is None:
low_cpu_mem_usage = True
logger.info("Set `low_cpu_mem_usage` to True as `_keep_in_fp32_modules` is not None.")
elif not low_cpu_mem_usage:
raise ValueError("`low_cpu_mem_usage` cannot be False when `keep_in_fp32_modules` is True.... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
# Determine if we're loading from a directory of sharded checkpoints.
is_sharded = False
index_file = None
is_local = os.path.isdir(pretrained_model_name_or_path)
index_file_kwargs = {
"is_local": is_local,
"pretrained_model_name_or_path": pretrained_model_name_or... | 906 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.