text stringlengths 1 1.02k | class_index int64 0 1.38k | source stringclasses 431
values |
|---|---|---|
resnet_time_scale_shift=resnet_time_scale_shift,
attention_type=attention_type,
resnet_skip_time_act=resnet_skip_time_act,
resnet_out_scale_factor=resnet_out_scale_factor,
cross_attention_norm=cross_attention_norm,
attention_head_dim=attent... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
# out
if norm_num_groups is not None:
self.conv_norm_out = nn.GroupNorm(
num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
)
self.conv_act = get_activation(act_fn)
else:
self.conv_norm_out = None
sel... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
def _check_config(
self,
down_block_types: Tuple[str],
up_block_types: Tuple[str],
only_cross_attention: Union[bool, Tuple[bool]],
block_out_channels: Tuple[int],
layers_per_block: Union[int, Tuple[int]],
cross_attention_dim: Union[int, Tuple[int]],
transf... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
if len(block_out_channels) != len(down_block_types):
raise ValueError(
f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
)
if not isinstance(only_cross_attent... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
raise ValueError(
f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
)
... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
raise ValueError(
f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}."
)
if... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
def _set_time_proj(
self,
time_embedding_type: str,
block_out_channels: int,
flip_sin_to_cos: bool,
freq_shift: float,
time_embedding_dim: int,
) -> Tuple[int, int]:
if time_embedding_type == "fourier":
time_embed_dim = time_embedding_dim or block_... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
timestep_input_dim = block_out_channels[0]
else:
raise ValueError(
f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`."
)
retu... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
if encoder_hid_dim is None and encoder_hid_dim_type is not None:
raise ValueError(
f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
) | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
if encoder_hid_dim_type == "text_proj":
self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
elif encoder_hid_dim_type == "text_image_proj":
# image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
# they are set to `... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
elif encoder_hid_dim_type is not None:
raise ValueError(
f"`encoder_hid_dim_type`: {encoder_hid_dim_type} must be None, 'text_proj', 'text_image_proj', or 'image_proj'."
)
else:
self.encoder_hid_proj = None | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
def _set_class_embedding(
self,
class_embed_type: Optional[str],
act_fn: str,
num_class_embeds: Optional[int],
projection_class_embeddings_input_dim: Optional[int],
time_embed_dim: int,
timestep_input_dim: int,
):
if class_embed_type is None and num_cl... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
# The projection `class_embed_type` is the same as the timestep `class_embed_type` except
# 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
# 2. it projects from an arbitrary input dimension.
#
# Note that `TimestepEmbedding` is quite general... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim)
else:
self.class_embedding = None | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
def _set_add_embedding(
self,
addition_embed_type: str,
addition_embed_type_num_heads: int,
addition_time_embed_dim: Optional[int],
flip_sin_to_cos: bool,
freq_shift: float,
cross_attention_dim: Optional[int],
encoder_hid_dim: Optional[int],
projec... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
self.add_embedding = TextTimeEmbedding(
text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
)
elif addition_embed_type == "text_image":
# text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
elif addition_embed_type == "image":
# Kandinsky 2.2
self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)
elif addition_embed_type == "image_hint":
# Kandinsky 2.2 ControlNet
self.add_embedding = ImageHintTimeEmbe... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
def _set_pos_net_if_use_gligen(self, attention_type: str, cross_attention_dim: int):
if attention_type in ["gated", "gated-text-image"]:
positive_len = 768
if isinstance(cross_attention_dim, int):
positive_len = cross_attention_dim
elif isinstance(cross_attent... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
if hasattr(module, "get_processor"):
processors[f"{name}.processor"] = module.get_processor()
for sub_name, child in module.named_children():
fn_recurs... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
processor. This is strongly recommended when setting trainable attention processors.
"""
count = len(self.attn_processors.keys())
if isinstance(processor, dict) and len(processor) !=... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
for sub_name, child in module.named_children():
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
for name, module in self.named_children():
fn_recursive_attn_processor(name, module, processor)
def set_default_attn_processor(self):
"""
Disables... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
def set_attention_slice(self, slice_size: Union[str, int, List[int]] = "auto"):
r"""
Enable sliced attention computation.
When this option is enabled, the attention module splits the input tensor in slices to compute attention in
several steps. This is useful for saving some memory in e... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
if hasattr(module, "set_attention_slice"):
sliceable_head_dims.append(module.sliceable_head_dim)
for child in module.children():
fn_recursive_retrieve_sliceable_dims(child)
# retrieve num... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
if len(slice_size) != len(sliceable_head_dims):
raise ValueError(
f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
)
... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
for child in module.children():
fn_recursive_set_attention_slice(child, slice_size)
reversed_slice_size = list(reversed(slice_size))
for module in self.children():
fn_recursive_set_attention_slice(module, reversed_slice_size)
def _set_gradient_checkpointing(self, module... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
Args:
s1 (`float`):
Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
mitigate the "oversmoothing effect" in the enhanced denoising process.
s2 (`float`):
Scaling factor for stage 2 to attenuate the con... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
def disable_freeu(self):
"""Disables the FreeU mechanism."""
freeu_keys = {"s1", "s2", "b1", "b2"}
for i, upsample_block in enumerate(self.up_blocks):
for k in freeu_keys:
if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None:
... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
self.original_attn_processors = self.attn_processors
for module in self.modules():
if isinstance(module, Attention):
module.fuse_projections(fuse=True)
self.set_attn_processor(FusedAttnProcessor2_0())
def unfuse_qkv_projections(self):
"""Disables the fused QKV ... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
def get_time_embed(
self, sample: torch.Tensor, timestep: Union[torch.Tensor, float, int]
) -> Optional[torch.Tensor]:
timesteps = timestep
if not torch.is_tensor(timesteps):
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
t_emb = self.time_proj(timesteps)
# `Timesteps` does not contain any weights and will always return f32 tensors
# but time_embedding might actually be running in fp16. so we need to cast here.
# there might be better ways to encapsulate this.
t_emb = t_emb.to(dtype=sample.dtype)
... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype)
return class_emb
def get_aug_embed(
self, emb: torch.Tensor, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
) -> Optional[torch.Tensor]:
aug_emb = None
if self.config.addition_embed_typ... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
image_embs = added_cond_kwargs.get("image_embeds")
text_embs = added_cond_kwargs.get("text_embeds", encoder_hidden_states)
aug_emb = self.add_embedding(text_embs, image_embs)
elif self.config.addition_embed_type == "text_time":
# SDXL - style
if "text_embeds" not ... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
time_embeds = self.add_time_proj(time_ids.flatten())
time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
add_embeds = add_embeds.to(emb.dtype)
aug_emb = self.add_embedding(add_embeds)
elif sel... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
raise ValueError(
f"{self.__class__} has the config param `addition_embed_type` set to 'image_hint' which requires the keyword arguments `image_embeds` and `hint` to be passed in `added_cond_kwargs`"
)
image_embs = added_cond_kwargs.get("image_embeds")
hint = ... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
def process_encoder_hidden_states(
self, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
) -> torch.Tensor:
if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj":
encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
image_embeds = added_cond_kwargs.get("image_embeds")
encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds)
elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj":
# Kandinsky 2.2 - style
if "image_embeds" not i... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'ip_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`"
) | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
if hasattr(self, "text_encoder_hid_proj") and self.text_encoder_hid_proj is not None:
encoder_hidden_states = self.text_encoder_hid_proj(encoder_hidden_states)
image_embeds = added_cond_kwargs.get("image_embeds")
image_embeds = self.encoder_hid_proj(image_embeds)
enc... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
def forward(
self,
sample: torch.Tensor,
timestep: Union[torch.Tensor, float, int],
encoder_hidden_states: torch.Tensor,
class_labels: Optional[torch.Tensor] = None,
timestep_cond: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
Args:
sample (`torch.Tensor`):
The noisy input tensor with the following shape `(batch, channel, height, width)`.
timestep (`torch.Tensor` or `float` or `int`): The number of timesteps to denoise an input.
encoder_hidden_states (`torch.Tensor`):
The en... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
negative values to the attention scores corresponding to "discard" tokens.
c... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
A tuple of tensors that if specified are added to the residuals of down unet blocks.
mid_block_additional_residual: (`torch.Tensor`, *optional*):
A tensor that if specified is added to the residual of the middle unet block.
down_intrablock_additional_residuals (`tuple` of `torch.... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
tuple. | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
Returns:
[`~models.unets.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
If `return_dict` is True, an [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] is returned,
otherwise a `tuple` is returned where the first element is the sample tensor.
"""
... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
for dim in sample.shape[-2:]:
if dim % default_overall_up_factor != 0:
# Forward upsample size to force interpolation output size.
forward_upsample_size = True
break | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
# ensure attention_mask is a bias, and give it a singleton query_tokens dimension
# expects mask of shape:
# [batch, key_tokens]
# adds singleton query_tokens dimension:
# [batch, 1, key_tokens]
# this helps to broadcast it as a bias over attention scores, ... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
# convert encoder_attention_mask to a bias the same way we do for attention_mask
if encoder_attention_mask is not None:
encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0
encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
# 0. center inpu... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
aug_emb = self.get_aug_embed(
emb=emb, encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
)
if self.config.addition_embed_type == "image_hint":
aug_emb, hint = aug_emb
sample = torch.cat([sample, hint], dim=1)
emb = emb + aug_emb... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
# 2.5 GLIGEN position net
if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None:
cross_attention_kwargs = cross_attention_kwargs.copy()
gligen_args = cross_attention_kwargs.pop("gligen")
cross_attention_kwargs["gligen"] = {"objs": se... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None
# using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets
is_adapter = down_intrablock_additional_residuals is not None
# maintain backward compa... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. ",
standard_warn=False,
)
down_intrablock_additional_residuals = down_block_additional_residuals
is_adapter = True | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
down_block_res_samples = (sample,)
for downsample_block in self.down_blocks:
if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
# For t2i-adapter CrossAttnDownBlock2D
additional_residuals = {}
if is_adapter an... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
sample, res_samples = downsample_block(
hidden_states=sample,
temb=emb,
encoder_hidden_states=encoder_hidden_states,
attention_mask=attention_mask,
cross_attention_kwargs=cross_attention_kwargs,
encod... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
for down_block_res_sample, down_block_additional_residual in zip(
down_block_res_samples, down_block_additional_residuals
):
down_block_res_sample = down_block_res_sample + down_block_additional_residual
new_down_block_res_samples = new_down_block_res_samples ... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
# To support T2I-Adapter-XL
if (
is_adapter
and len(down_intrablock_additional_residuals) > 0
and sample.shape == down_intrablock_additional_residuals[0].shape
):
sample += down_intrablock_additional_residuals.pop(0)
if is_... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
sample = upsample_block(
hidden_states=sample,
temb=emb,
res_hidden_states_tuple=res_samples,
encoder_hidden_states=encoder_hidden_sta... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
# 6. post-process
if self.conv_norm_out:
sample = self.conv_norm_out(sample)
sample = self.conv_act(sample)
sample = self.conv_out(sample)
if USE_PEFT_BACKEND:
# remove `lora_scale` from each PEFT layer
unscale_lora_layers(self, lora_scale)
... | 968 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_2d_condition.py |
class SDCascadeLayerNorm(nn.LayerNorm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def forward(self, x):
x = x.permute(0, 2, 3, 1)
x = super().forward(x)
return x.permute(0, 3, 1, 2) | 969 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
class SDCascadeTimestepBlock(nn.Module):
def __init__(self, c, c_timestep, conds=[]):
super().__init__()
self.mapper = nn.Linear(c_timestep, c * 2)
self.conds = conds
for cname in conds:
setattr(self, f"mapper_{cname}", nn.Linear(c_timestep, c * 2))
def forward(self... | 970 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
class SDCascadeResBlock(nn.Module):
def __init__(self, c, c_skip=0, kernel_size=3, dropout=0.0):
super().__init__()
self.depthwise = nn.Conv2d(c, c, kernel_size=kernel_size, padding=kernel_size // 2, groups=c)
self.norm = SDCascadeLayerNorm(c, elementwise_affine=False, eps=1e-6)
self... | 971 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
class GlobalResponseNorm(nn.Module):
def __init__(self, dim):
super().__init__()
self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim))
self.beta = nn.Parameter(torch.zeros(1, 1, 1, dim))
def forward(self, x):
agg_norm = torch.norm(x, p=2, dim=(1, 2), keepdim=True)
stand_d... | 972 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
class SDCascadeAttnBlock(nn.Module):
def __init__(self, c, c_cond, nhead, self_attn=True, dropout=0.0):
super().__init__()
self.self_attn = self_attn
self.norm = SDCascadeLayerNorm(c, elementwise_affine=False, eps=1e-6)
self.attention = Attention(query_dim=c, heads=nhead, dim_head=c... | 973 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
class UpDownBlock2d(nn.Module):
def __init__(self, in_channels, out_channels, mode, enabled=True):
super().__init__()
if mode not in ["up", "down"]:
raise ValueError(f"{mode} not supported")
interpolation = (
nn.Upsample(scale_factor=2 if mode == "up" else 0.5, mode="... | 974 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
class StableCascadeUNetOutput(BaseOutput):
sample: torch.Tensor = None | 975 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
class StableCascadeUNet(ModelMixin, ConfigMixin, FromOriginalModelMixin):
_supports_gradient_checkpointing = True | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
@register_to_config
def __init__(
self,
in_channels: int = 16,
out_channels: int = 16,
timestep_ratio_embedding_dim: int = 64,
patch_size: int = 1,
conditioning_dim: int = 2048,
block_out_channels: Tuple[int] = (2048, 2048),
num_attention_heads: Tuple[... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
effnet_in_channels: Optional[int] = None,
pixel_mapper_in_channels: Optional[int] = None,
kernel_size=3,
dropout: Union[float, Tuple[float]] = (0.1, 0.1),
self_attn: Union[bool, Tuple[bool]] = True,
timestep_conditioning_type: Tuple[str] = ("sca", "crp"),
switch_level: Op... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
Parameters:
in_channels (`int`, defaults to 16):
Number of channels in the input sample.
out_channels (`int`, defaults to 16):
Number of channels in the output sample.
timestep_ratio_embedding_dim (`int`, defaults to 64):
Dimension of t... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
Number of layers in each down block.
up_num_layers_per_block (Tuple[int], defaults to [24, 8]):
Number of layers in each up block.
down_blocks_repeat_mappers (Tuple[int], optional, defaults to [1, 1]):
Number of 1x1 Convolutional layers to repeat in each down bloc... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
clip_text_pooled_in_channels (`int`, *optional*, defaults to 1280):
Number of input channels for pooled CLIP text embeddings.
clip_image_in_channels (`int`, *optional*):
Number of input channels for CLIP based image conditioning.
clip_seq (`int`, *optional*, defau... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
timestep_conditioning_type (Tuple[str], defaults to ("sca", "crp")):
Timestep conditioning type.
switch_level (Optional[Tuple[bool]], *optional*, defaults to `None`):
Tuple that indicates whether upsampling or downsampling should be applied in a block
""" | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
super().__init__()
if len(block_out_channels) != len(down_num_layers_per_block):
raise ValueError(
f"Number of elements in `down_num_layers_per_block` must match the length of `block_out_channels`: {len(block_out_channels)}"
)
elif len(block_out_channels) != len... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
elif len(block_out_channels) != len(up_blocks_repeat_mappers):
raise ValueError(
f"Number of elements in `up_blocks_repeat_mappers` must match the length of `block_out_channels`: {len(block_out_channels)}"
)
elif len(block_out_channels) != len(block_types_per_layer):
... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
# CONDITIONING
if effnet_in_channels is not None:
self.effnet_mapper = nn.Sequential(
nn.Conv2d(effnet_in_channels, block_out_channels[0] * 4, kernel_size=1),
nn.GELU(),
nn.Conv2d(block_out_channels[0] * 4, block_out_channels[0], kernel_size=1),
... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
self.clip_txt_pooled_mapper = nn.Linear(clip_text_pooled_in_channels, conditioning_dim * clip_seq)
if clip_text_in_channels is not None:
self.clip_txt_mapper = nn.Linear(clip_text_in_channels, conditioning_dim)
if clip_image_in_channels is not None:
self.clip_img_mapper = nn.Line... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
def get_block(block_type, in_channels, nhead, c_skip=0, dropout=0, self_attn=True):
if block_type == "SDCascadeResBlock":
return SDCascadeResBlock(in_channels, c_skip, kernel_size=kernel_size, dropout=dropout)
elif block_type == "SDCascadeAttnBlock":
return SDCasc... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
# BLOCKS
# -- down blocks
self.down_blocks = nn.ModuleList()
self.down_downscalers = nn.ModuleList()
self.down_repeat_mappers = nn.ModuleList()
for i in range(len(block_out_channels)):
if i > 0:
self.down_downscalers.append(
nn.Sequ... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
down_block = nn.ModuleList()
for _ in range(down_num_layers_per_block[i]):
for block_type in block_types_per_layer[i]:
block = get_block(
block_type,
block_out_channels[i],
num_attention_heads[i],
... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
# -- up blocks
self.up_blocks = nn.ModuleList()
self.up_upscalers = nn.ModuleList()
self.up_repeat_mappers = nn.ModuleList()
for i in reversed(range(len(block_out_channels))):
if i > 0:
self.up_upscalers.append(
nn.Sequential(
... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
up_block = nn.ModuleList()
for j in range(up_num_layers_per_block[::-1][i]):
for k, block_type in enumerate(block_types_per_layer[i]):
c_skip = block_out_channels[i] if i < len(block_out_channels) - 1 and j == k == 0 else 0
block = get_block(
... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
if up_blocks_repeat_mappers is not None:
block_repeat_mappers = nn.ModuleList()
for _ in range(up_blocks_repeat_mappers[::-1][i] - 1):
block_repeat_mappers.append(nn.Conv2d(block_out_channels[i], block_out_channels[i], kernel_size=1))
self.up_repeat_ma... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
nn.init.normal_(self.clip_txt_pooled_mapper.weight, std=0.02)
nn.init.normal_(self.clip_txt_mapper.weight, std=0.02) if hasattr(self, "clip_txt_mapper") else None
nn.init.normal_(self.clip_img_mapper.weight, std=0.02) if hasattr(self, "clip_img_mapper") else None
if hasattr(self, "effnet_mapper... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
# blocks
for level_block in self.down_blocks + self.up_blocks:
for block in level_block:
if isinstance(block, SDCascadeResBlock):
block.channelwise[-1].weight.data *= np.sqrt(1 / sum(self.config.blocks[0]))
elif isinstance(block, SDCascadeTimestepB... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
def get_clip_embeddings(self, clip_txt_pooled, clip_txt=None, clip_img=None):
if len(clip_txt_pooled.shape) == 2:
clip_txt_pool = clip_txt_pooled.unsqueeze(1)
clip_txt_pool = self.clip_txt_pooled_mapper(clip_txt_pooled).view(
clip_txt_pooled.size(0), clip_txt_pooled.size(1) * sel... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
def _down_encode(self, x, r_embed, clip):
level_outputs = []
block_group = zip(self.down_blocks, self.down_downscalers, self.down_repeat_mappers)
if torch.is_grad_enabled() and self.gradient_checkpointing:
def create_custom_forward(module):
def custom_forward(*input... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
for down_block, downscaler, repmap in block_group:
x = downscaler(x)
for i in range(len(repmap) + 1):
for block in down_block:
if isinstance(block, SDCascadeResBlock):
x = torch.utils.checkpoint.checkpoint(create_cus... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
x = torch.utils.checkpoint.checkpoint(create_custom_forward(block), use_reentrant=False)
if i < len(repmap):
x = repmap[i](x)
level_outputs.insert(0, x)
else:
for down_block, downscaler, repmap in block_group:
x = downscaler... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
def _up_decode(self, level_outputs, r_embed, clip):
x = level_outputs[0]
block_group = zip(self.up_blocks, self.up_upscalers, self.up_repeat_mappers)
if torch.is_grad_enabled() and self.gradient_checkpointing:
def create_custom_forward(module):
def custom_forward(*i... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
for i, (up_block, upscaler, repmap) in enumerate(block_group):
for j in range(len(repmap) + 1):
for k, block in enumerate(up_block):
if isinstance(block, SDCascadeResBlock):
skip = level_outputs[i] if k == 0 and i > 0 else None
... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
x = torch.utils.checkpoint.checkpoint(
create_custom_forward(block), x, clip, use_reentrant=False
)
elif isinstance(block, SDCascadeTimestepBlock):
x = torch.utils.checkpoint.checkpoint(
... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
skip = level_outputs[i] if k == 0 and i > 0 else None
if skip is not None and (x.size(-1) != skip.size(-1) or x.size(-2) != skip.size(-2)):
orig_type = x.dtype
x = torch.nn.functional.interpolate(
... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
def forward(
self,
sample,
timestep_ratio,
clip_text_pooled,
clip_text=None,
clip_img=None,
effnet=None,
pixels=None,
sca=None,
crp=None,
return_dict=True,
):
if pixels is None:
pixels = sample.new_zeros(samp... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
# Model Blocks
x = self.embedding(sample)
if hasattr(self, "effnet_mapper") and effnet is not None:
x = x + self.effnet_mapper(
nn.functional.interpolate(effnet, size=x.shape[-2:], mode="bilinear", align_corners=True)
)
if hasattr(self, "pixels_mapper"):
... | 976 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_stable_cascade.py |
class DownBlockMotion(DownBlockMotion):
def __init__(self, *args, **kwargs):
deprecation_message = "Importing `DownBlockMotion` from `diffusers.models.unets.unet_3d_blocks` is deprecated and this will be removed in a future version. Please use `from diffusers.models.unets.unet_motion_model import DownBlockM... | 977 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_3d_blocks.py |
class CrossAttnDownBlockMotion(CrossAttnDownBlockMotion):
def __init__(self, *args, **kwargs):
deprecation_message = "Importing `CrossAttnDownBlockMotion` from `diffusers.models.unets.unet_3d_blocks` is deprecated and this will be removed in a future version. Please use `from diffusers.models.unets.unet_mot... | 978 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_3d_blocks.py |
class UpBlockMotion(UpBlockMotion):
def __init__(self, *args, **kwargs):
deprecation_message = "Importing `UpBlockMotion` from `diffusers.models.unets.unet_3d_blocks` is deprecated and this will be removed in a future version. Please use `from diffusers.models.unets.unet_motion_model import UpBlockMotion` i... | 979 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_3d_blocks.py |
class CrossAttnUpBlockMotion(CrossAttnUpBlockMotion):
def __init__(self, *args, **kwargs):
deprecation_message = "Importing `CrossAttnUpBlockMotion` from `diffusers.models.unets.unet_3d_blocks` is deprecated and this will be removed in a future version. Please use `from diffusers.models.unets.unet_motion_mo... | 980 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_3d_blocks.py |
class UNetMidBlockCrossAttnMotion(UNetMidBlockCrossAttnMotion):
def __init__(self, *args, **kwargs):
deprecation_message = "Importing `UNetMidBlockCrossAttnMotion` from `diffusers.models.unets.unet_3d_blocks` is deprecated and this will be removed in a future version. Please use `from diffusers.models.unets... | 981 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_3d_blocks.py |
class UNetMidBlock3DCrossAttn(nn.Module):
def __init__(
self,
in_channels: int,
temb_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
resnet_eps: float = 1e-6,
resnet_time_scale_shift: str = "default",
resnet_act_fn: str = "swish",
res... | 982 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_3d_blocks.py |
# there is always at least one resnet
resnets = [
ResnetBlock2D(
in_channels=in_channels,
out_channels=in_channels,
temb_channels=temb_channels,
eps=resnet_eps,
groups=resnet_groups,
dropout=dropout,
... | 982 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/unets/unet_3d_blocks.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.