text stringlengths 1 1.02k | class_index int64 0 1.38k | source stringclasses 431
values |
|---|---|---|
class LDMBertAttention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
head_dim: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = False,
):
su... | 267 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
def forward(
self,
hidden_states: torch.Tensor,
key_value_states: Optional[torch.Tensor] = None,
past_key_value: Optio... | 267 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
# get query proj
query_states = self.q_proj(hidden_states) * self.scaling
# get key, value proj
if is_cross_attention and past_key_value is not None:
# reuse k,v, cross_attentions
key_states = past_key_value[0]
value_states = past_key_value[1]
elif is_... | 267 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
value_states = self._shape(self.v_proj(hidden_states), -1, bsz) | 267 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
if self.is_decoder:
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
# Further calls to cross_attention layer can then reuse all cross-attention
# key/value_states (first "if" case)
# if uni-directional self-attention (d... | 267 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
src_len = key_states.size(1)
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
raise ValueError(
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
... | 267 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
if layer_head_mask is not None:
if layer_head_mask.size() != (self.num_heads,):
raise ValueError(
f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
f" {layer_head_mask.size()}"
)
attn_weights = la... | 267 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
if output_attentions:
# this operation is a bit awkward, but it's required to
# make sure that attn_weights keeps its gradient.
# In order to do so, attn_weights have to be reshaped
# twice and have to be reused in the following
attn_weights_reshaped = attn_we... | 267 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
attn_output = attn_output.transpose(1, 2)
# Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
# partitioned across GPUs when using tensor-parallelism.
... | 267 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
class LDMBertEncoderLayer(nn.Module):
def __init__(self, config: LDMBertConfig):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = LDMBertAttention(
embed_dim=self.embed_dim,
num_heads=config.encoder_attention_heads,
head_dim=config.head_... | 268 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
layer_head_mask: torch.Tensor,
output_attentions: Optional[bool] = False,
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
"""
Args:
hidden_states (`torch.Tensor`): inpu... | 268 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
hidden_states = self.self_attn_layer_norm(hidden_states)
hidden_states, attn_weights, _ = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
layer_head_mask=layer_head_mask,
output_attentions=output_attentions,
)
hidden_sta... | 268 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
residual = hidden_states
hidden_states = self.final_layer_norm(hidden_states)
hidden_states = self.activation_fn(self.fc1(hidden_states))
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
hidden_states = self.fc2(hidden_states)
... | 268 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
class LDMBertPreTrainedModel(PreTrainedModel):
config_class = LDMBertConfig
base_model_prefix = "model"
_supports_gradient_checkpointing = True
_keys_to_ignore_on_load_unexpected = [r"encoder\.version", r"decoder\.version"]
def _init_weights(self, module):
std = self.config.init_std
... | 269 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
@property
def dummy_inputs(self):
pad_token = self.config.pad_token_id
input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
dummy_inputs = {
"attention_mask": input_ids.ne(pad_token),
"input_ids": input_ids,
}
retu... | 269 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
class LDMBertEncoder(LDMBertPreTrainedModel):
"""
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
[`LDMBertEncoderLayer`].
Args:
config: LDMBertConfig
embed_tokens (nn.Embedding): output embedding
"""
def __init__(self, config: L... | 270 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
def get_input_embeddings(self):
return self.embed_tokens
def set_input_embeddings(self, value):
self.embed_tokens = value
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTenso... | 270 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
Indices can be obtained using [`BartTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
... | 270 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
inputs_embeds (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert `input_ids` indices into as... | 270 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None els... | 270 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
# retrieve input_ids and inputs_embeds
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is not None:
input_shape = input_ids.size()
input_ids = input_ids.vie... | 270 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
# expand attention_mask
if attention_mask is not None:
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
attention_mask = _expand_mask(attention_mask, inputs_embeds.dtype)
encoder_states = () if output_hidden_states else None
all_attentions = () if output_attentions... | 270 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
def create_custom_forward(module):
def custom_forward(*inputs):
return module(*inputs, output_attentions)
return custom_forward
layer_outputs = torch.utils.checkpoint.checkpoint(
create_custom_forward(encoder_layer),
... | 270 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
return BaseModelOutput(
last_hidden_state=hidden_states, hidden_states=encoder_st... | 270 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
class LDMBertModel(LDMBertPreTrainedModel):
_no_split_modules = []
def __init__(self, config: LDMBertConfig):
super().__init__(config)
self.model = LDMBertEncoder(config)
self.to_logits = nn.Linear(config.hidden_size, config.vocab_size)
def forward(
self,
input_ids=... | 271 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py |
class HunyuanVideoPipelineOutput(BaseOutput):
r"""
Output class for HunyuanVideo pipelines.
Args:
frames (`torch.Tensor`, `np.ndarray`, or List[List[PIL.Image.Image]]):
List of video outputs - It can be a nested list of length `batch_size,` with each sub-list containing
deno... | 272 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_output.py |
class HunyuanVideoPipeline(DiffusionPipeline, HunyuanVideoLoraLoaderMixin):
r"""
Pipeline for text-to-video generation using HunyuanVideo.
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
implemented for all pipelines (downloading, saving, runni... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
Args:
text_encoder ([`LlamaModel`]):
[Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers).
tokenizer (`LlamaTokenizer`):
Tokenizer from [Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers).
transformer ([`Hunyu... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
tokenizer_2 (`CLIPTokenizer`):
Tokenizer of class
[CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
""" | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
_callback_tensor_inputs = ["latents", "prompt_embeds"]
def __init__(
self,
text_encoder: LlamaModel,
tokenizer: LlamaTokenizerFast,
transformer: HunyuanVideoTransformer3DModel,
vae: AutoencoderKLHun... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
self.vae_scale_factor_temporal = self.vae.temporal_compression_ratio if getattr(self, "vae", None) else 4
self.vae_scale_factor_spatial = self.vae.spatial_compression_ratio if getattr(self, "vae", None) else 8
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
def... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
crop_start = prompt_template.get("crop_start", None)
if crop_start is None:
prompt_template_input = self.tokenizer(
prompt_template["template"],
padding="max_length",
return_tensors="pt",
return_length=False,
return_over... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
max_sequence_length += crop_start
text_inputs = self.tokenizer(
prompt,
max_length=max_sequence_length,
padding="max_length",
truncation=True,
return_tensors="pt",
return_length=False,
return_overflowing_tokens=False,
... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
# duplicate text embeddings for each generation per prompt, using mps friendly method
_, seq_len, _ = prompt_embeds.shape
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
prompt_attention... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
prompt = [prompt] if isinstance(prompt, str) else prompt
batch_size = len(prompt)
text_inputs = self.tokenizer_2(
prompt,
padding="max_length",
max_length=max_sequence_length,
truncation=True,
return_tensors="pt",
)
text_input... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
# duplicate text embeddings for each generation per prompt, using mps friendly method
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt)
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, -1)
return prompt_embeds | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
def encode_prompt(
self,
prompt: Union[str, List[str]],
prompt_2: Union[str, List[str]] = None,
prompt_template: Dict[str, Any] = DEFAULT_PROMPT_TEMPLATE,
num_videos_per_prompt: int = 1,
prompt_embeds: Optional[torch.Tensor] = None,
pooled_prompt_embeds: Optional[... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
if pooled_prompt_embeds is None:
if prompt_2 is None and pooled_prompt_embeds is None:
prompt_2 = prompt
pooled_prompt_embeds = self._get_clip_prompt_embeds(
prompt,
num_videos_per_prompt,
device=device,
dtype=dtype,... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
if callback_on_step_end_tensor_inputs is not None and not all(
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
):
raise ValueError(
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in cal... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
if prompt is not None and prompt_embeds is not None:
raise ValueError(
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
" only forward one of the two."
)
elif prompt_2 is not None and prompt_embeds is not ... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}") | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
if prompt_template is not None:
if not isinstance(prompt_template, dict):
raise ValueError(f"`prompt_template` has to be of type `dict` but is {type(prompt_template)}")
if "template" not in prompt_template:
raise ValueError(
f"`prompt_template`... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
shape = (
batch_size,
num_channels_latents,
num_frames,
int(height) // self.vae_scale_factor_spatial,
int(width) // self.vae_scale_factor_spatial,
)
if isinstance(generator, list) and len(generator) != batch_size:
raise ValueError(
... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
def disable_vae_slicing(self):
r"""
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
computing decoding in one step.
"""
self.vae.disable_slicing()
def enable_vae_tiling(self):
r"""
Enable tiled VAE deco... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
@property
def attention_kwargs(self):
return self._attention_kwargs
@property
def interrupt(self):
return self._interrupt | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
@torch.no_grad()
@replace_example_docstring(EXAMPLE_DOC_STRING)
def __call__(
self,
prompt: Union[str, List[str]] = None,
prompt_2: Union[str, List[str]] = None,
height: int = 720,
width: int = 1280,
num_frames: int = 129,
num_inference_steps: int = 50,
... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
] = None,
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
prompt_template: Dict[str, Any] = DEFAULT_PROMPT_TEMPLATE,
max_sequence_length: int = 256,
):
r"""
The call functio... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
Args:
prompt (`str` or `List[str]`, *optional*):
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
instead.
prompt_2 (`str` or `List[str]`, *optional*):
The prompt or prompts to be sent to `tokeni... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
will be used.
guidance_scale (`float`, defaults to `6.0`):
... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
num_videos_per_prompt (`int`, *optional*, defaults to 1):
The number of images to generate per prompt.
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
output_type (`str`, *optional*, defaults to `"pil"`):
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
return_dict (`bool`, *optional*, defaults to `True`):
Whether or not to return a [`HunyuanVideoPipelineOutput`] instead of a plain tuple.
... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
each denoising step during the inference. with the following arguments: `callback_on_step_e... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
Examples:
Returns:
[`~HunyuanVideoPipelineOutput`] or `tuple`:
If `return_dict` is `True`, [`HunyuanVideoPipelineOutput`] is returned, otherwise a `tuple` is returned
where the first element is a list with the generated images and the second element is a list of `boo... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
self._guidance_scale = guidance_scale
self._attention_kwargs = attention_kwargs
self._interrupt = False
device = self._execution_device
# 2. Define call parameters
if prompt is not None and isinstance(prompt, str):
batch_size = 1
elif prompt is not None and ... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
transformer_dtype = self.transformer.dtype
prompt_embeds = prompt_embeds.to(transformer_dtype)
prompt_attention_mask = prompt_attention_mask.to(transformer_dtype)
if pooled_prompt_embeds is not None:
pooled_prompt_embeds = pooled_prompt_embeds.to(transformer_dtype)
# 4. Prep... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
# 5. Prepare latent variables
num_channels_latents = self.transformer.config.in_channels
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
latents = self.prepare_latents(
batch_size * num_videos_per_prompt,
num_channels_latents,
height... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
latent_model_input = latents.to(transformer_dtype)
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
timestep = t.expand(latents.shape[0]).to(latents.dtype)
noise_pred = self.transformer(
hidden_states=latent_model_input,
... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
if callback_on_step_end is not None:
callback_kwargs = {}
for k in callback_on_step_end_tensor_inputs:
callback_kwargs[k] = locals()[k]
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
latents = ... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
if not output_type == "latent":
latents = latents.to(self.vae.dtype) / self.vae.config.scaling_factor
video = self.vae.decode(latents, return_dict=False)[0]
video = self.video_processor.postprocess_video(video, output_type=output_type)
else:
video = latents
... | 273 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py |
class ConsistencyModelPipeline(DiffusionPipeline):
r"""
Pipeline for unconditional or class-conditional image generation.
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
implemented for all pipelines (downloading, saving, running on a particula... | 274 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/consistency_models/pipeline_consistency_models.py |
def prepare_latents(self, batch_size, num_channels, height, width, dtype, device, generator, latents=None):
shape = (batch_size, num_channels, height, width)
if isinstance(generator, list) and len(generator) != batch_size:
raise ValueError(
f"You have passed a list of generat... | 274 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/consistency_models/pipeline_consistency_models.py |
# Follows diffusers.VaeImageProcessor.postprocess
def postprocess_image(self, sample: torch.Tensor, output_type: str = "pil"):
if output_type not in ["pt", "np", "pil"]:
raise ValueError(
f"output_type={output_type} is not supported. Make sure to choose one of ['pt', 'np', or 'pi... | 274 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/consistency_models/pipeline_consistency_models.py |
def prepare_class_labels(self, batch_size, device, class_labels=None):
if self.unet.config.num_class_embeds is not None:
if isinstance(class_labels, list):
class_labels = torch.tensor(class_labels, dtype=torch.int)
elif isinstance(class_labels, int):
asser... | 274 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/consistency_models/pipeline_consistency_models.py |
def check_inputs(self, num_inference_steps, timesteps, latents, batch_size, img_size, callback_steps):
if num_inference_steps is None and timesteps is None:
raise ValueError("Exactly one of `num_inference_steps` or `timesteps` must be supplied.")
if num_inference_steps is not None and times... | 274 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/consistency_models/pipeline_consistency_models.py |
if (callback_steps is None) or (
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
):
raise ValueError(
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
f" {type(callback_steps)}."
... | 274 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/consistency_models/pipeline_consistency_models.py |
@torch.no_grad()
@replace_example_docstring(EXAMPLE_DOC_STRING)
def __call__(
self,
batch_size: int = 1,
class_labels: Optional[Union[torch.Tensor, List[int], int]] = None,
num_inference_steps: int = 1,
timesteps: List[int] = None,
generator: Optional[Union[torch.... | 274 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/consistency_models/pipeline_consistency_models.py |
num_inference_steps (`int`, *optional*, defaults to 1):
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference.
timesteps (`List[int]`, *optional*):
Custom timesteps to use for the denoisin... | 274 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/consistency_models/pipeline_consistency_models.py |
tensor is generated by sampling using the supplied random `generator`.
output_type (`str`, *optional*, defaults to `"pil"`):
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
return_dict (`bool`, *optional*, defaults to `True`):
W... | 274 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/consistency_models/pipeline_consistency_models.py |
Examples:
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.
"""
# 0. Prepare... | 274 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/consistency_models/pipeline_consistency_models.py |
# 3. Handle class_labels for class-conditional models
class_labels = self.prepare_class_labels(batch_size, device, class_labels=class_labels)
# 4. Prepare timesteps
if timesteps is not None:
self.scheduler.set_timesteps(timesteps=timesteps, device=device)
timesteps = sel... | 274 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/consistency_models/pipeline_consistency_models.py |
# call the callback, if provided
progress_bar.update()
if callback is not None and i % callback_steps == 0:
callback(i, t, sample)
if XLA_AVAILABLE:
xm.mark_step()
# 6. Post-process image sample
image = self.postpr... | 274 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/consistency_models/pipeline_consistency_models.py |
class DanceDiffusionPipeline(DiffusionPipeline):
r"""
Pipeline for audio 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:
... | 275 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py |
@torch.no_grad()
def __call__(
self,
batch_size: int = 1,
num_inference_steps: int = 100,
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
audio_length_in_s: Optional[float] = None,
return_dict: bool = True,
) -> Union[AudioPipelineOutput... | 275 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py |
Args:
batch_size (`int`, *optional*, defaults to 1):
The number of audio samples to generate.
num_inference_steps (`int`, *optional*, defaults to 50):
The number of denoising steps. More denoising steps usually lead to a higher-quality audio sample at
... | 275 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py |
```py
from diffusers import DiffusionPipeline
from scipy.io.wavfile import write
model_id = "harmonai/maestro-150k"
pipe = DiffusionPipeline.from_pretrained(model_id)
pipe = pipe.to("cuda")
audios = pipe(audio_length_in_s=4.0).audios
# To save locally
f... | 275 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py |
if audio_length_in_s is None:
audio_length_in_s = self.unet.config.sample_size / self.unet.config.sample_rate
sample_size = audio_length_in_s * self.unet.config.sample_rate
down_scale_factor = 2 ** len(self.unet.up_blocks)
if sample_size < 3 * down_scale_factor:
raise V... | 275 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py |
original_sample_size = int(sample_size)
if sample_size % down_scale_factor != 0:
sample_size = (
(audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1
) * down_scale_factor
logger.info(
f"{audio_length_in_s} is increased t... | 275 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py |
dtype = next(self.unet.parameters()).dtype
shape = (batch_size, self.unet.config.in_channels, sample_size)
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 ef... | 275 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py |
# 2. compute previous audio sample: x_t -> t_t-1
audio = self.scheduler.step(model_output, t, audio).prev_sample
if XLA_AVAILABLE:
xm.mark_step()
audio = audio.clamp(-1, 1).float().cpu().numpy()
audio = audio[:, :, :original_sample_size]
if not return_... | 275 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py |
class Kandinsky3Pipeline(DiffusionPipeline, StableDiffusionLoraLoaderMixin):
model_cpu_offload_seq = "text_encoder->unet->movq"
_callback_tensor_inputs = [
"latents",
"prompt_embeds",
"negative_prompt_embeds",
"negative_attention_mask",
"attention_mask",
]
def __... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
def process_embeds(self, embeddings, attention_mask, cut_context):
if cut_context:
embeddings[attention_mask == 0] = torch.zeros_like(embeddings[attention_mask == 0])
max_seq_length = attention_mask.sum(-1).max() + 1
embeddings = embeddings[:, :max_seq_length]
att... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
Args:
prompt (`str` or `List[str]`, *optional*):
prompt to be encoded
device: (`torch.device`, *optional*):
torch device to place the resulting embeddings on
num_images_per_prompt (`int`, *optional*, defaults to 1):
number of images tha... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
provided, text embeddings will be generated from `prompt` input argument.
negative_prompt_embeds (`torch.Tensor`, *optional*):
Pre-generated negative text embeddings. Can b... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
raise TypeError(
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
f" {type(prompt)}."
) | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
if device is None:
device = self._execution_device
if prompt is not None and isinstance(prompt, str):
batch_size = 1
elif prompt is not None and isinstance(prompt, list):
batch_size = len(prompt)
else:
batch_size = prompt_embeds.shape[0]
... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
if prompt_embeds is None:
text_inputs = self.tokenizer(
prompt,
padding="max_length",
max_length=max_length,
truncation=True,
return_tensors="pt",
)
text_input_ids = text_inputs.input_ids.to(device)
... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
bs_embed, seq_len, _ = prompt_embeds.shape
# duplicate text embeddings for each generation per prompt, using mps friendly method
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
attention_m... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
if negative_prompt is None:
uncond_tokens = [""] * batch_size
elif isinstance(negative_prompt, str):
uncond_tokens = [negative_prompt]
elif batch_size != len(negative_prompt):
raise ValueError(
f"`negative_prompt`: {negative_pro... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
text_input_ids = uncond_input.input_ids.to(device)
negative_attention_mask = uncond_input.attention_mask.to(device) | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
negative_prompt_embeds = self.text_encoder(
text_input_ids,
attention_mask=negative_attention_mask,
)
negative_prompt_embeds = negative_prompt_embeds[0]
negative_prompt_embeds = negative_prompt_embeds[:, : prompt_embeds.shape[1]]
... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
if negative_prompt_embeds.shape != prompt_embeds.shape:
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
negative_prompt_embeds = negative_prompt_embeds.view(batc... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
def prepare_latents(self, shape, dtype, device, generator, latents, scheduler):
if latents is None:
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
else:
if latents.shape != shape:
raise ValueError(f"Unexpected latents shape, got {la... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
def check_inputs(
self,
prompt,
callback_steps,
negative_prompt=None,
prompt_embeds=None,
negative_prompt_embeds=None,
callback_on_step_end_tensor_inputs=None,
attention_mask=None,
negative_attention_mask=None,
):
if callback_steps is n... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
if prompt is not None and prompt_embeds is not None:
raise ValueError(
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
" only forward one of the two."
)
elif prompt is None and prompt_embeds is None:
... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
if prompt_embeds is not None and negative_prompt_embeds is not None:
if prompt_embeds.shape != negative_prompt_embeds.shape:
raise ValueError(
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
f" got: `pr... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
if negative_prompt_embeds is not None and negative_attention_mask is not None:
if negative_prompt_embeds.shape[:2] != negative_attention_mask.shape:
raise ValueError(
"`negative_prompt_embeds` and `negative_attention_mask` must have the same batch_size and token length wh... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
if prompt_embeds is not None and attention_mask is not None:
if prompt_embeds.shape[:2] != attention_mask.shape:
raise ValueError(
"`prompt_embeds` and `attention_mask` must have the same batch_size and token length when passed directly, but"
f" got: `... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
@torch.no_grad()
@replace_example_docstring(EXAMPLE_DOC_STRING)
def __call__(
self,
prompt: Union[str, List[str]] = None,
num_inference_steps: int = 25,
guidance_scale: float = 3.0,
negative_prompt: Optional[Union[str, List[str]]] = None,
num_images_per_prompt: Op... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
Function invoked when calling the pipeline for generation. | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
Args:
prompt (`str` or `List[str]`, *optional*):
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
instead.
num_inference_steps (`int`, *optional*, defaults to 25):
The number of denoising steps. ... | 276 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.