text stringlengths 1 1.02k | class_index int64 0 1.38k | source stringclasses 431
values |
|---|---|---|
class UnCLIPImageVariationPipeline(DiffusionPipeline):
"""
Pipeline to generate image variations from an input image using UnCLIP.
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
implemented for all pipelines (downloading, saving, running on a ... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
Args:
text_encoder ([`~transformers.CLIPTextModelWithProjection`]):
Frozen text-encoder.
tokenizer ([`~transformers.CLIPTokenizer`]):
A `CLIPTokenizer` to tokenize text.
feature_extractor ([`~transformers.CLIPImageProcessor`]):
Model that extracts features fro... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
super_res_last ([`UNet2DModel`]):
Super resolution UNet. Used in the last step of the super resolution diffusion process.
decoder_scheduler ([`UnCLIPScheduler`]):
Scheduler used in the decoder denoising process (a modified [`DDPMScheduler`]).
super_res_scheduler ([`UnCLIPSchedule... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
decoder: UNet2DConditionModel
text_proj: UnCLIPTextProjModel
text_encoder: CLIPTextModelWithProjection
tokenizer: CLIPTokenizer
feature_extractor: CLIPImageProcessor
image_encoder: CLIPVisionModelWithProjection
super_res_first: UNet2DModel
super_res_last: UNet2DModel
decoder_scheduler: ... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
self.register_modules(
decoder=decoder,
text_encoder=text_encoder,
tokenizer=tokenizer,
text_proj=text_proj,
feature_extractor=feature_extractor,
image_encoder=image_encoder,
super_res_first=super_res_first,
super_res_last=s... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
latents = latents * scheduler.init_noise_sigma
return latents
def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance):
batch_size = len(prompt) if isinstance(prompt, list) else 1
# get prompt text embeddings
text_inputs = self.tokenizer(
... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
prompt_embeds = prompt_embeds.repeat_interleave(num_images_per_prompt, dim=0)
text_encoder_hidden_states = text_encoder_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
text_mask = text_mask.repeat_interleave(num_images_per_prompt, dim=0)
if do_classifier_free_guidance:
... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
negative_prompt_embeds = negative_prompt_embeds_text_encoder_output.text_embeds
uncond_text_encoder_hidden_states = negative_prompt_embeds_text_encoder_output.last_hidden_state
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
seq_len = ... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
# done duplicates
# 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
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
image = image.to(device=device, dtype=dtype)
image_embeddings = self.image_encoder(image).image_embeds
image_embeddings = image_embeddings.repeat_interleave(num_images_per_prompt, dim=0)
return image_embeddings
@torch.no_grad()
def __call__(
self,
image: Optional[U... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
Args:
image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.Tensor`):
`Image` or tensor representing an image batch to be used as the starting point. If you provide a
tensor, it needs to be compatible with the [`CLIPImageProcessor`]
[configuration](htt... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
The number of denoising steps for super resolution. More denoising steps usually lead to a higher
quality image at the expense of slower inference.
generator (`torch.Generator`, *optional*):
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html)... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
image_embeddings (`torch.Tensor`, *optional*):
Pre-defined image embeddings that can be derived from the image encoder. Pre-defined image embeddings
can be passed for tasks li... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.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.
"""
if image is not None:
... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
image_embeddings = self._encode_image(image, device, num_images_per_prompt, image_embeddings)
# decoder
text_encoder_hidden_states, additive_clip_time_embeddings = self.text_proj(
image_embeddings=image_embeddings,
prompt_embeds=prompt_embeds,
text_encoder_hidden_sta... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
self.decoder_scheduler.set_timesteps(decoder_num_inference_steps, device=device)
decoder_timesteps_tensor = self.decoder_scheduler.timesteps
num_channels_latents = self.decoder.config.in_channels
height = self.decoder.config.sample_size
width = self.decoder.config.sample_size
i... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
noise_pred = self.decoder(
sample=latent_model_input,
timestep=t,
encoder_hidden_states=text_encoder_hidden_states,
class_labels=additive_clip_time_embeddings,
attention_mask=decoder_text_mask,
).sample
if do_classi... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
# compute the previous noisy sample x_t -> x_t-1
decoder_latents = self.decoder_scheduler.step(
noise_pred, t, decoder_latents, prev_timestep=prev_timestep, generator=generator
).prev_sample
decoder_latents = decoder_latents.clamp(-1, 1)
image_small = decoder_la... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
if super_res_latents is None:
super_res_latents = self.prepare_latents(
(batch_size, channels, height, width),
image_small.dtype,
device,
generator,
super_res_latents,
self.super_res_scheduler,
)
... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
if i == super_res_timesteps_tensor.shape[0] - 1:
unet = self.super_res_last
else:
unet = self.super_res_first
latent_model_input = torch.cat([super_res_latents, image_upscaled], dim=1)
noise_pred = unet(
sample=latent_model_input,
... | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
image = image * 0.5 + 0.5
image = image.clamp(0, 1)
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
if output_type == "pil":
image = self.numpy_to_pil(image)
if not return_dict:
return (image,)
return ImagePipelineOutput(images=image) | 336 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py |
class UnCLIPTextProjModel(ModelMixin, ConfigMixin):
"""
Utility class for CLIP embeddings. Used to combine the image and text embeddings into a format usable by the
decoder.
For more details, see the original paper: https://arxiv.org/abs/2204.06125 section 2.1
"""
@register_to_config
def _... | 337 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/text_proj.py |
# parameters for encoder hidden states
self.clip_extra_context_tokens = clip_extra_context_tokens
self.clip_extra_context_tokens_proj = nn.Linear(
clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim
)
self.encoder_hidden_states_proj = nn.Linear(clip_embe... | 337 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/text_proj.py |
def forward(self, *, image_embeddings, prompt_embeds, text_encoder_hidden_states, do_classifier_free_guidance):
if do_classifier_free_guidance:
# Add the classifier free guidance embeddings to the image embeddings
image_embeddings_batch_size = image_embeddings.shape[0]
classi... | 337 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/text_proj.py |
# "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and
# adding CLIP embeddings to the existing timestep embedding, ...
time_projected_prompt_embeds = self.embedding_proj(prompt_embeds)
time_projected_image_embeddings = self.clip_image_embeddings_project_... | 337 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/text_proj.py |
text_encoder_hidden_states = self.encoder_hidden_states_proj(text_encoder_hidden_states)
text_encoder_hidden_states = self.text_encoder_hidden_states_norm(text_encoder_hidden_states)
text_encoder_hidden_states = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states], dim=1)
return te... | 337 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/text_proj.py |
class UnCLIPPipeline(DiffusionPipeline):
"""
Pipeline for text-to-image generation using unCLIP.
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.). | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
Args:
text_encoder ([`~transformers.CLIPTextModelWithProjection`]):
Frozen text-encoder.
tokenizer ([`~transformers.CLIPTokenizer`]):
A `CLIPTokenizer` to tokenize text.
prior ([`PriorTransformer`]):
The canonical unCLIP prior to approximate the image embeddin... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
Scheduler used in the prior denoising process (a modified [`DDPMScheduler`]).
decoder_scheduler ([`UnCLIPScheduler`]):
Scheduler used in the decoder denoising process (a modified [`DDPMScheduler`]).
super_res_scheduler ([`UnCLIPScheduler`]):
Scheduler used in the super resolution... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
"""
_exclude_from_cpu_offload = ["prior"]
prior: PriorTransformer
decoder: UNet2DConditionModel
text_proj: UnCLIPTextProjModel
text_encoder: CLIPTextModelWithProjection
tokenizer: CLIPTokenizer
super_res_first: UNet2DModel
super_res_last: UNet2DModel
prior_scheduler: UnCLIPSchedul... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
self.register_modules(
prior=prior,
decoder=decoder,
text_encoder=text_encoder,
tokenizer=tokenizer,
text_proj=text_proj,
super_res_first=super_res_first,
super_res_last=super_res_last,
prior_scheduler=prior_scheduler,
... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
def _encode_prompt(
self,
prompt,
device,
num_images_per_prompt,
do_classifier_free_guidance,
text_model_output: Optional[Union[CLIPTextModelOutput, Tuple]] = None,
text_attention_mask: Optional[torch.Tensor] = None,
):
if text_model_output is None:
... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
text_input_ids, untruncated_ids
):
removed_text = self.tokenizer.batch_decode(
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
)
logg... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
else:
batch_size = text_model_output[0].shape[0]
prompt_embeds, text_enc_hid_states = text_model_output[0], text_model_output[1]
text_mask = text_attention_mask
prompt_embeds = prompt_embeds.repeat_interleave(num_images_per_prompt, dim=0)
text_enc_hid_states = text_e... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
negative_prompt_embeds = negative_prompt_embeds_text_encoder_output.text_embeds
uncond_text_enc_hid_states = negative_prompt_embeds_text_encoder_output.last_hidden_state
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
seq_len = negativ... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.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
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
text_enc_hid_states = t... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
@torch.no_grad()
def __call__(
self,
prompt: Optional[Union[str, List[str]]] = None,
num_images_per_prompt: int = 1,
prior_num_inference_steps: int = 25,
decoder_num_inference_steps: int = 25,
super_res_num_inference_steps: int = 7,
generator: Optional[Union[t... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
Args:
prompt (`str` or `List[str]`):
The prompt or prompts to guide image generation. This can only be left undefined if `text_model_output`
and `text_attention_mask` is passed.
num_images_per_prompt (`int`, *optional*, defaults to 1):
The number o... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
The number of denoising steps for super resolution. More denoising steps usually lead to a higher
quality image at the expense of slower inference.
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
A [`torch.Generator`](https://pytorch.org/docs/stable/gene... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
prior_guidance_scale (`float`, *optional*, defaults to 4.0):
A higher guidance scale value encourages the model to generate images closely linked to the text
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
decoder_guidance_... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
text_attention_mask (`torch.Tensor`, *optional*):
Pre-defined CLIP text attention mask that can be derived from the tokenizer. Pre-defined text attention
masks are necessary when passing `text_model_output`.
output_type (`str`, *optional*, defaults to `"pil"`):
... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.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.
"""
if prompt is not None:
... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
prompt_embeds, text_enc_hid_states, text_mask = self._encode_prompt(
prompt, device, num_images_per_prompt, do_classifier_free_guidance, text_model_output, text_attention_mask
)
# prior
self.prior_scheduler.set_timesteps(prior_num_inference_steps, device=device)
prior_times... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
predicted_image_embedding = self.prior(
latent_model_input,
timestep=t,
proj_embedding=prompt_embeds,
encoder_hidden_states=text_enc_hid_states,
attention_mask=text_mask,
).predicted_image_embedding
if do_classifier... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
prior_latents = self.prior_scheduler.step(
predicted_image_embedding,
timestep=t,
sample=prior_latents,
generator=generator,
prev_timestep=prev_timestep,
).prev_sample
prior_latents = self.prior.post_process_latents(pri... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
if device.type == "mps":
# HACK: MPS: There is a panic when padding bool tensors,
# so cast to int tensor for the pad and back to bool afterwards
text_mask = text_mask.type(torch.int)
decoder_text_mask = F.pad(text_mask, (self.text_proj.clip_extra_context_tokens, 0), valu... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
decoder_latents = self.prepare_latents(
(batch_size, num_channels_latents, height, width),
text_enc_hid_states.dtype,
device,
generator,
decoder_latents,
self.decoder_scheduler,
)
for i, t in enumerate(self.progress_bar(decoder_tim... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
if do_classifier_free_guidance:
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
noise_pred_uncond, _ = noise_pred_uncond.split(latent_model_input.shape[1], dim=1)
noise_pred_text, predicted_variance = noise_pred_text.split(latent_model_input.shape[1], dim=1)
... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
image_small = decoder_latents
# done decoder
# super res
self.super_res_scheduler.set_timesteps(super_res_num_inference_steps, device=device)
super_res_timesteps_tensor = self.super_res_scheduler.timesteps
channels = self.super_res_first.config.in_channels // 2
height... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
if device.type == "mps":
# MPS does not support many interpolations
image_upscaled = F.interpolate(image_small, size=[height, width])
else:
interpolate_antialias = {}
if "antialias" in inspect.signature(F.interpolate).parameters:
interpolate_antial... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
if i + 1 == super_res_timesteps_tensor.shape[0]:
prev_timestep = None
else:
prev_timestep = super_res_timesteps_tensor[i + 1]
# compute the previous noisy sample x_t -> x_t-1
super_res_latents = self.super_res_scheduler.step(
noise_pre... | 338 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/unclip/pipeline_unclip.py |
class AllegroPipelineOutput(BaseOutput):
r"""
Output class for Allegro 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
denoised PIL i... | 339 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_output.py |
class AllegroPipeline(DiffusionPipeline):
r"""
Pipeline for text-to-video generation using Allegro.
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
library implements for all the pipelines (such as downloading or saving, running on a partic... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
Args:
vae ([`AllegroAutoEncoderKL3D`]):
Variational Auto-Encoder (VAE) Model to encode and decode video to and from latent representations.
text_encoder ([`T5EncoderModel`]):
Frozen text-encoder. PixArt-Alpha uses
[T5](https://huggingface.co/docs/transformers/model_do... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
bad_punct_regex = re.compile(
r"["
+ "#®•©™&@·º½¾¿¡§~"
+ r"\)"
+ r"\("
+ r"\]"
+ r"\["
+ r"\}"
+ r"\{"
+ r"\|"
+ "\\"
+ r"\/"
+ r"\*"
+ r"]{1,}"
) # noqa
_optional_components = []
model_cpu_offload_seq ... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
self.register_modules(
tokenizer=tokenizer, text_encoder=text_encoder, vae=vae, transformer=transformer, scheduler=scheduler
)
self.vae_scale_factor_spatial = (
2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
)
self.vae_scal... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
# Copied from diffusers.pipelines.pixart_alpha.pipeline_pixart_alpha.PixArtAlphaPipeline.encode_prompt with 120->512, num_images_per_prompt->num_videos_per_prompt
def encode_prompt(
self,
prompt: Union[str, List[str]],
do_classifier_free_guidance: bool = True,
negative_prompt: str = ... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
Args:
prompt (`str` or `List[str]`, *optional*):
prompt to be encoded
negative_prompt (`str` or `List[str]`, *optional*):
The prompt not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`
instead. Ignored when n... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.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. For P... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
if "mask_feature" in kwargs:
deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
text_input_ids, untruncated_ids
):
removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_length - 1 : -1])
logger.warning(
"The following part of your... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
bs_embed, seq_len, _ = prompt_embeds.shape
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
prompt_embed... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
# get unconditional embeddings for classifier free guidance
if do_classifier_free_guidance and negative_prompt_embeds is None:
uncond_tokens = [negative_prompt] * bs_embed if isinstance(negative_prompt, str) else negative_prompt
uncond_tokens = self._text_preprocessing(uncond_tokens, cle... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
negative_prompt_embeds = self.text_encoder(
uncond_input.input_ids.to(device), attention_mask=negative_prompt_attention_mask
)
negative_prompt_embeds = negative_prompt_embeds[0]
if do_classifier_free_guidance:
# duplicate unconditional embeddings for each gen... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(1, num_videos_per_prompt)
negative_prompt_attention_mask = negative_prompt_attention_mask.view(bs_embed * num_videos_per_prompt, -1)
else:
negative_prompt_embeds = None
negative_prompt_attention_mask = Non... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
extra_step_kwargs = {}
if accepts_eta:
extra_step_kwargs["eta"] = eta
# check if the scheduler accepts generator
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step)... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
def check_inputs(
self,
prompt,
num_frames,
height,
width,
callback_on_step_end_tensor_inputs,
negative_prompt=None,
prompt_embeds=None,
negative_prompt_embeds=None,
prompt_attention_mask=None,
negative_prompt_attention_mask=None,
... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.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:
... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
if negative_prompt is not None and negative_prompt_embeds is not None:
raise ValueError(
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
)
... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.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... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
# Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._text_preprocessing
def _text_preprocessing(self, text, clean_caption=False):
if clean_caption and not is_bs4_available():
logger.warning(BACKENDS_MAPPING["bs4"][-1].format("Setting `clean_caption=True`"))
logger.w... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
# Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._clean_caption
def _clean_caption(self, caption):
caption = str(caption)
caption = ul.unquote_plus(caption)
caption = caption.strip().lower()
caption = re.sub("<person>", "person", caption)
# urls:
... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
# 31C0—31EF CJK Strokes
# 31F0—31FF Katakana Phonetic Extensions
# 3200—32FF Enclosed CJK Letters and Months
# 3300—33FF CJK Compatibility
# 3400—4DBF CJK Unified Ideographs Extension A
# 4DC0—4DFF Yijing Hexagram Symbols
# 4E00—9FFF CJK Unified Ideographs
caption... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
# все виды тире / all types of dash --> "-"
caption = re.sub(
r"[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+", # noqa
"-",
caption,
)
# кавычки к одному стандарту
caption... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
# "#123"
caption = re.sub(r"#\d{1,3}\b", "", caption)
# "#12345.."
caption = re.sub(r"#\d{5,}\b", "", caption)
# "123456.."
caption = re.sub(r"\b\d{6,}\b", "", caption)
# filenames:
caption = re.sub(r"[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)", "", caption)... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
caption = re.sub(r"\b[a-zA-Z]{1,3}\d{3,15}\b", "", caption) # jc6640
caption = re.sub(r"\b[a-zA-Z]+\d+[a-zA-Z]+\b", "", caption) # jc6640vc
caption = re.sub(r"\b\d+[a-zA-Z]+\d+\b", "", caption) # 6640vc231
caption = re.sub(r"(worldwide\s+)?(free\s+)?shipping", "", caption)
caption = ... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
caption = re.sub(r"^[\"\']([\w\W]+)[\"\']$", r"\1", caption)
caption = re.sub(r"^[\'\_,\-\:;]", r"", caption)
caption = re.sub(r"[\'\_,\-\:\-\+]$", r"", caption)
caption = re.sub(r"^\.\S+$", "", caption)
return caption.strip()
def prepare_latents(
self, batch_size, num_chan... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
shape = (
batch_size,
num_channels_latents,
num_frames,
height // self.vae_scale_factor_spatial,
width // self.vae_scale_factor_spatial,
)
if latents is None:
latents = randn_tensor(shape, generator=generator, device=device, dtype=... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
def _prepare_rotary_positional_embeddings(
self,
batch_size: int,
height: int,
width: int,
num_frames: int,
device: torch.device,
):
grid_height = height // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
grid_width = width // (sel... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
grid_t = grid_t.to(dtype=torch.long)
grid_h = grid_h.to(dtype=torch.long)
grid_w = grid_w.to(dtype=torch.long)
pos = torch.cartesian_prod(grid_t, grid_h, grid_w)
pos = pos.reshape(-1, 3).transpose(0, 1).reshape(3, 1, -1).contiguous()
grid_t, grid_h, grid_w = pos
return ... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
def enable_vae_tiling(self):
r"""
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
processing larger images.
""... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
@torch.no_grad()
@replace_example_docstring(EXAMPLE_DOC_STRING)
def __call__(
self,
prompt: Union[str, List[str]] = None,
negative_prompt: str = "",
num_inference_steps: int = 100,
timesteps: List[int] = None,
guidance_scale: float = 7.5,
num_frames: Optio... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
] = None,
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
clean_caption: bool = True,
max_sequence_length: int = 512,
) -> Union[AllegroPipelineOutput, Tuple]:
"""
Function ... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
Args:
prompt (`str` or `List[str]`, *optional*):
The prompt or prompts to guide the video generation. If not defined, one has to pass `prompt_embeds`.
instead.
negative_prompt (`str` or `List[str]`, *optional*):
The prompt or prompts not to guide t... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
guidance_scale (`float`, *optional*, defaults to 7.5):
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
`guidance_scale` is defined as `w` of equation 2. of [Imagen
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance ... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
width (`int`, *optional*, defaults to self.unet.config.sample_size):
The width in pixels of the generated video.
eta (`float`, *optional*, defaults to 0.0):
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
[... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
prompt_embeds (`torch.Tensor`, *optional*):
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.
prompt_attention_mask (`torch.Tensor`, *optional*): Pr... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
return_dict (`bool`, *optional*, defaults to `True`):
Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
callback (`Callable`, *optional*):
... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
be installed. If the dependencies are not installed, the embeddings will be created from the raw
prompt.
max_sequence_length (`int` defaults to `512`):
Maximum sequence length to use with the `prompt`. | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
Examples:
Returns:
[`~pipelines.allegro.pipeline_output.AllegroPipelineOutput`] or `tuple`:
If `return_dict` is `True`, [`~pipelines.allegro.pipeline_output.AllegroPipelineOutput`] is returned,
otherwise a `tuple` is returned where the first element is a list with th... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
self.check_inputs(
prompt,
num_frames,
height,
width,
callback_on_step_end_tensor_inputs,
negative_prompt,
prompt_embeds,
negative_prompt_embeds,
prompt_attention_mask,
negative_prompt_attention_mask,... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
# corresponds to doing no classifier free guidance.
do_classifier_free_guidance = guidance_scale > 1.0 | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
# 3. Encode input prompt
(
prompt_embeds,
prompt_attention_mask,
negative_prompt_embeds,
negative_prompt_attention_mask,
) = self.encode_prompt(
prompt,
do_classifier_free_guidance,
negative_prompt=negative_prompt,
... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
prompt_embeds = prompt_embeds.unsqueeze(1) # b l d -> b 1 l d | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
# 4. Prepare timesteps
timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
self.scheduler.set_timesteps(num_inference_steps, device=device)
# 5. Prepare latents.
latent_channels = self.transformer.config.in_channels
latents... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
# 8. Denoising loop
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
self._num_timesteps = len(timesteps)
with self.progress_bar(total=num_inference_steps) as progress_bar:
for i, t in enumerate(timesteps):
if self.interrupt:
... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
# predict noise model_output
noise_pred = self.transformer(
hidden_states=latent_model_input,
encoder_hidden_states=prompt_embeds,
encoder_attention_mask=prompt_attention_mask,
timestep=timestep,
image_ro... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
# call the callback, if provided
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,... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
if not output_type == "latent":
latents = latents.to(self.vae.dtype)
video = self.decode_latents(latents)
video = video[:, :, :num_frames, :height, :width]
video = self.video_processor.postprocess_video(video=video, output_type=output_type)
else:
video... | 340 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/allegro/pipeline_allegro.py |
class KolorsPAGPipeline(
DiffusionPipeline, StableDiffusionMixin, StableDiffusionXLLoraLoaderMixin, IPAdapterMixin, PAGMixin
):
r"""
Pipeline for text-to-image generation using Kolors.
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
lib... | 341 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pag/pipeline_pag_kolors.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.