text stringlengths 1 1.02k | class_index int64 0 1.38k | source stringclasses 431
values |
|---|---|---|
The ControlNet input condition to provide guidance to the `unet` for generation. If multiple
ControlNets are specified, images must be passed as a list such that each element of the list can be
correctly batched for input to a single ControlNet.
output_type (`str`, *optional*... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can se... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
clip_skip (`int`, *optional*):
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
the output of the pre-final layer will be used for computing the prompt embeddings.
callback_on_step_end (`Callable`, *optional*):
... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
`._callback_tensor_inputs` attribute of your pipeline class. | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
Examples:
Returns:
[`~pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput`] or `tuple`:
If `return_dict` is `True`, [`~pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput`] is
returned, otherwise a `tuple` is returned where the first element i... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
# align format for control guidance
if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
control_guidance_start = len(control_guidance_end) * [control_guidance_start]
elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start,... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
num_videos_per_prompt = 1
# 1. Check inputs. Raise error if not correct
self.check_inputs(
prompt=prompt,
height=height,
width=width,
num_frames=num_frames,
negative_prompt=negative_prompt,
callback_on_step_end_tensor_inputs=callba... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
# 2. Define call parameters
if prompt is not None and isinstance(prompt, (str, dict)):
batch_size = 1
elif prompt is not None and isinstance(prompt, list):
batch_size = len(prompt)
else:
batch_size = prompt_embeds.shape[0]
device = self._execution_dev... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
# 3. Encode input prompt
text_encoder_lora_scale = (
cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
)
if self.free_noise_enabled:
prompt_embeds, negative_prompt_embeds = self._encode_prompt_free_noise(
prompt=prom... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
self.do_classifier_free_guidance,
negative_prompt,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_prompt_embeds,
lora_scale=text_encoder_lora_scale,
clip_skip=self.clip_skip,
) | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
if self.do_classifier_free_guidance:
prompt_embeds = torch.cat([negative_prompt_embeds... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
if isinstance(controlnet, ControlNetModel):
conditioning_frames = self.prepare_video(
video=conditioning_frames,
width=width,
height=height,
batch_size=batch_size * num_videos_per_prompt * num_frames,
num_videos_per_prompt=num_v... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
device=device,
dtype=controlnet.dtype,
do_classifier_free_guidance=self.do_classifier_free_guidance,
guess_mode=guess_mode,
)
cond_prepared_videos.append(prepared_video)
conditioning_frames = cond_prepared_videos
... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
# 4. Prepare timesteps
self.scheduler.set_timesteps(num_inference_steps, device=device)
timesteps = self.scheduler.timesteps
# 5. Prepare latent variables
num_channels_latents = self.unet.config.in_channels
latents = self.prepare_latents(
batch_size * num_videos_per_... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
# 7.1 Create tensor stating which controlnets to keep
controlnet_keep = []
for i in range(len(timesteps)):
keeps = [
1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
for s, e in zip(control_guidance_start, control_guidance_end)
]... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
# 8. Denoising loop
with self.progress_bar(total=self._num_timesteps) as progress_bar:
for i, t in enumerate(timesteps):
if self.interrupt:
continue
# expand the latents if we are doing classifier free guidance
... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
if guess_mode and self.do_classifier_free_guidance:
# Infer ControlNet only for the conditional batch.
control_model_input = latents
control_model_input = self.scheduler.scale_model_input(control_model_input, t)
controlnet_p... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
if isinstance(controlnet_keep[i], list):
cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
else:
controlnet_cond_scale = controlnet_conditioning_scale
if isinstance(controlnet_cond_scale, li... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
down_block_res_samples, mid_block_res_sample = self.controlnet(
control_model_input,
t,
encoder_hidden_states=controlnet_prompt_embeds,
controlnet_cond=conditioning_frames,
conditioning_scale=cond_sca... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
# perform guidance
if self.do_classifier_free_guidance:
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# compute the previous noisy s... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
latents = callback_outputs.pop("latents", latents)
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
# call the callback, if provided
... | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
return AnimateDiffPipelineOutput(frames=video) | 151 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py |
class DDIMPipeline(DiffusionPipeline):
r"""
Pipeline for image generation.
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
Parameters:
unet ... | 152 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/ddim/pipeline_ddim.py |
@torch.no_grad()
def __call__(
self,
batch_size: int = 1,
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
eta: float = 0.0,
num_inference_steps: int = 50,
use_clipped_model_output: Optional[bool] = None,
output_type: Optional[str] = ... | 152 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/ddim/pipeline_ddim.py |
Args:
batch_size (`int`, *optional*, defaults to 1):
The number of images to generate.
generator (`torch.Generator`, *optional*):
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
generation deterministic... | 152 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/ddim/pipeline_ddim.py |
If `True` or `False`, see documentation for [`DDIMScheduler.step`]. If `None`, nothing is passed
downstream to the scheduler (use `None` for schedulers which don't support this argument).
output_type (`str`, *optional*, defaults to `"pil"`):
The output format of the generated... | 152 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/ddim/pipeline_ddim.py |
Example:
```py
>>> from diffusers import DDIMPipeline
>>> import PIL.Image
>>> import numpy as np
>>> # load model and scheduler
>>> pipe = DDIMPipeline.from_pretrained("fusing/ddim-lsun-bedroom")
>>> # run pipeline in inference (sample random noise and denoise... | 152 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/ddim/pipeline_ddim.py |
Returns:
[`~pipelines.ImagePipelineOutput`] or `tuple`:
If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
returned where the first element is a list with the generated images
"""
# Sample gaussian noise to begi... | 152 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/ddim/pipeline_ddim.py |
if isinstance(generator, list) and len(generator) != batch_size:
raise ValueError(
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
... | 152 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/ddim/pipeline_ddim.py |
# 2. predict previous mean of image x_t-1 and add variance depending on eta
# eta corresponds to η in paper and should be between [0, 1]
# do x_t -> x_t-1
image = self.scheduler.step(
model_output, t, image, eta=eta, use_clipped_model_output=use_clipped_model_output, ... | 152 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/ddim/pipeline_ddim.py |
class AudioLDM2ProjectionModelOutput(BaseOutput):
"""
Args:
Class for AudioLDM2 projection layer's outputs.
hidden_states (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states obtained by linearly projecting the hidden-states for each of the te... | 153 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
class AudioLDM2ProjectionModel(ModelMixin, ConfigMixin):
"""
A simple linear projection model to map two text embeddings to a shared latent space. It also inserts learned
embedding vectors at the start and end of each text embedding sequence respectively. Each variable appended with
`_1` refers to that ... | 154 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
@register_to_config
def __init__(
self,
text_encoder_dim,
text_encoder_1_dim,
langauge_model_dim,
use_learned_position_embedding=None,
max_seq_length=None,
):
super().__init__()
# additional projection layers for each text encoder
self.proj... | 154 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
# learable positional embedding for vits encoder
if self.use_learned_position_embedding is not None:
self.learnable_positional_embedding = torch.nn.Parameter(
torch.zeros((1, text_encoder_1_dim, max_seq_length))
)
def forward(
self,
hidden_states: Opt... | 154 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
hidden_states_1 = self.projection_1(hidden_states_1)
hidden_states_1, attention_mask_1 = add_special_tokens(
hidden_states_1, attention_mask_1, sos_token=self.sos_embed_1, eos_token=self.eos_embed_1
)
# concatenate clap and t5 text encoding
hidden_states = torch.cat([hidden_... | 154 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
return AudioLDM2ProjectionModelOutput(
hidden_states=hidden_states,
attention_mask=attention_mask,
) | 154 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
class AudioLDM2UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
r"""
A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
shaped output. Compared to the vanilla [`UNet2DConditionModel`], this variant optionally includes an a... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
Parameters:
sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
Height and width of input/output sample.
in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.
out_channels (`int`, *optional*, defaults to 4): Number of channels i... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
The tuple of upsample blocks to use.
only_cross_attention (`bool` or `Tuple[bool]`, *optional*, default to `False`):
Whether to include self-attention... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
If `None`, normalization and activation layers is skipped in post-processing.
norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
cross_attention_di... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
The number of attention heads. If not defined, defaults to `attention_head_dim`
resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
class_embed_type (`s... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
time_embedding_dim (`int`, *optional*, defaults to `None`):
An optional override for the dimension of the projected time embedding.
time_embedding_act_fn (`str`, *optional*, defaults to `None`):
Optional activation function to use only once on the time embeddings before they are passed t... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when
`class_embed_type="projection"`. Required when `class_embed_type="projection"`.
class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time
emb... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
_supports_gradient_checkpointing = True | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
@register_to_config
def __init__(
self,
sample_size: Optional[int] = None,
in_channels: int = 4,
out_channels: int = 4,
flip_sin_to_cos: bool = True,
freq_shift: int = 0,
down_block_types: Tuple[str] = (
"CrossAttnDownBlock2D",
"CrossAt... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
cross_attention_dim: Union[int, Tuple[int]] = 1280,
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,
class_embed_type: Optio... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
self.sample_size = sample_size
if num_attention_heads is not None:
raise ValueError(
"At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#iss... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
# If `num_attention_heads` is not defined (which is the case for most models)
# it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
# The reason for this behavior is to correct for incorrectly named variables that were introduced
# when this library was cre... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.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... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.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}."
)
... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
# input
conv_in_padding = (conv_in_kernel - 1) // 2
self.conv_in = nn.Conv2d(
in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
)
# time
if time_embedding_type == "positional":
time_embed_dim = time_embedding_dim or b... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
# class embedding
if class_embed_type is None and num_class_embeds is not None:
self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
elif class_embed_type == "timestep":
self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn)
... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
# Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
# When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
# As a result, `TimestepEmbedding` can be passed arbitrary vectors.
self.class_embeddi... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
if time_embedding_act_fn is None:
self.time_embed_act = None
else:
self.time_embed_act = get_activation(time_embedding_act_fn)
self.down_blocks = nn.ModuleList([])
self.up_blocks = nn.ModuleList([])
if isinstance(only_cross_attention, bool):
only_cro... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
if class_embeddings_concat:
# The time embeddings are concatenated with the class embeddings. The dimension of the
# time embeddings passed to the down, middle, and up blocks is twice the dimension of the
# regular time embeddings
blocks_time_embed_dim = time_embed_dim * ... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
down_block = get_down_block(
down_block_type,
num_layers=layers_per_block[i],
transformer_layers_per_block=transformer_layers_per_block[i],
in_channels=input_channel,
out_channels=output_channel,
temb_channels=blocks_time_em... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
# mid
if mid_block_type == "UNetMidBlock2DCrossAttn":
self.mid_block = UNetMidBlock2DCrossAttn(
transformer_layers_per_block=transformer_layers_per_block[-1],
in_channels=block_out_channels[-1],
temb_channels=blocks_time_embed_dim,
resn... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
# count how many layers upsample the images
self.num_upsamplers = 0
# up
reversed_block_out_channels = list(reversed(block_out_channels))
reversed_num_attention_heads = list(reversed(num_attention_heads))
reversed_layers_per_block = list(reversed(layers_per_block))
rever... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
# add upsample block for all BUT final layer
if not is_final_block:
add_upsample = True
self.num_upsamplers += 1
else:
add_upsample = False | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
up_block = get_up_block(
up_block_type,
num_layers=reversed_layers_per_block[i] + 1,
transformer_layers_per_block=reversed_transformer_layers_per_block[i],
in_channels=input_channel,
out_channels=output_channel,
prev_output_... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
prev_output_channel = output_channel | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.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... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.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... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
Parameters:
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
The instantiated processor class or a dictionary of processor classes that will be set as the processor
for **all** `Attention` layers.
If `processor` is a dict, the key need... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
if hasattr(module, "set_processor"):
if not isinstance(processor, dict):
module.set_processor(processor)
else:
module.set_processor(processor.pop(f"{name}.p... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
def set_default_attn_processor(self):
"""
Disables custom attention processors and sets the default attention implementation.
"""
if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESS... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
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 exchange for a small decrease in speed.
Args:
slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
for child in module.children():
fn_recursive_retrieve_sliceable_dims(child)
# retrieve number of attention layers
for module in self.children():
fn_recursive_retrieve_sliceable_dims(module)
num_sliceable_layers = len(sliceable_head_dims)
if slice_size == "a... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.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)}."
)
... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.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)
# Copied from diffusers.models.unets.unet_2d... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.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,
... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.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... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
cross_attention_kwargs (`dict`, *optional*):
A kwargs dictionary that if specified is passed along to the [`AttnProcessor`].
encoder_hidden_states_1 (`torch.Tensor`, *optional*):
A second set of encoder hidden states with shape `(batch, sequence_length_2, feature_dim_2)`. Can... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.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.
"""
... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):
logger.info("Forward upsample size to force interpolation output size.")
forward_upsample_size = True | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.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, ... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.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)
if encoder_atten... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
# 1. time
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
# This would be a good case for the `match` statement (Python 3.10+)
is_mps = sample.device.type == "mps"
... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
# `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)
emb = self.time_embedding(t_emb, timestep... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
if self.config.class_embeddings_concat:
emb = torch.cat([emb, class_emb], dim=-1)
else:
emb = emb + class_emb
emb = emb + aug_emb if aug_emb is not None else emb
if self.time_embed_act is not None:
emb = self.time_embed_act(emb)
# 2. pre... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
# 3. down
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:
sample, res_samples = downsample_block(
hidden_states=sample,
... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
# 4. mid
if self.mid_block is not None:
sample = self.mid_block(
sample,
emb,
encoder_hidden_states=encoder_hidden_states,
attention_mask=attention_mask,
cross_attention_kwargs=cross_attention_kwargs,
enc... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
# if we have not reached the final block and need to forward the
# upsample size, we do it here
if not is_final_block and forward_upsample_size:
upsample_size = down_block_res_samples[-1].shape[2:] | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.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... | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.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 not return_dict:
return (sample,)
return UNet2DConditionOutput(sample=sample) | 155 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
class CrossAttnDownBlock2D(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
temb_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
transformer_layers_per_block: int = 1,
resnet_eps: float = 1e-6,
resnet_time_scale_sh... | 156 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
if isinstance(cross_attention_dim, int):
cross_attention_dim = (cross_attention_dim,)
if isinstance(cross_attention_dim, (list, tuple)) and len(cross_attention_dim) > 4:
raise ValueError(
"Only up to 4 cross-attention layers are supported. Ensure that the length of cross-... | 156 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
for i in range(num_layers):
in_channels = in_channels if i == 0 else out_channels
resnets.append(
ResnetBlock2D(
in_channels=in_channels,
out_channels=out_channels,
temb_channels=temb_channels,
eps=re... | 156 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
cross_attention_dim=cross_attention_dim[j],
norm_num_groups=resnet_groups,
use_linear_projection=use_linear_projection,
only_cross_attention=only_cross_attention,
upcast_attention=upcast_attention,
do... | 156 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
if add_downsample:
self.downsamplers = nn.ModuleList(
[
Downsample2D(
out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
)
]
)
else:
self... | 156 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
def forward(
self,
hidden_states: torch.Tensor,
temb: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
encoder_attention_mas... | 156 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
for i in range(num_layers):
if torch.is_grad_enabled() and self.gradient_checkpointing:
def create_custom_forward(module, return_dict=None):
def custom_forward(*inputs):
if return_dict is not None:
return module(*inputs... | 156 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
hidden_states = torch.utils.checkpoint.checkpoint(
create_custom_forward(self.resnets[i]),
hidden_states,
temb,
**ckpt_kwargs... | 156 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
forward_encoder_attention_mask = None
hidden_states = torch.utils.checkpoint.checkpoint(
create_custom_forward(self.attentions[i * num_attention_per_layer + idx], return_dict=False),
hidden_states,
forward_encoder_hidden_states,... | 156 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
forward_encoder_attention_mask = encoder_attention_mask
elif cross_attention_dim is not None and idx > 1:
forward_encoder_hidden_states = encoder_hidden_states_1
forward_encoder_attention_mask = encoder_attention_mask_1
else:
... | 156 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
output_states = output_states + (hidden_states,)
if self.downsamplers is not None:
for downsampler in self.downsamplers:
hidden_states = downsampler(hidden_states)
output_states = output_states + (hidden_states,)
return hidden_states, output_states | 156 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
class UNetMidBlock2DCrossAttn(nn.Module):
def __init__(
self,
in_channels: int,
temb_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
transformer_layers_per_block: int = 1,
resnet_eps: float = 1e-6,
resnet_time_scale_shift: str = "default",
... | 157 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
if isinstance(cross_attention_dim, int):
cross_attention_dim = (cross_attention_dim,)
if isinstance(cross_attention_dim, (list, tuple)) and len(cross_attention_dim) > 4:
raise ValueError(
"Only up to 4 cross-attention layers are supported. Ensure that the length of cross-... | 157 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.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,
... | 157 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
for i in range(num_layers):
for j in range(len(cross_attention_dim)):
attentions.append(
Transformer2DModel(
num_attention_heads,
in_channels // num_attention_heads,
in_channels=in_channels,
... | 157 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/audioldm2/modeling_audioldm2.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.