text
stringlengths
1
1.02k
class_index
int64
0
1.38k
source
stringclasses
431 values
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_images_per_prompt, 1) prompt_embed...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
# get unconditional embeddings for classifier free guidance if do_classifier_free_guidance and negative_prompt_embeds is None: negative_prompt = negative_prompt or "" uncond_tokens = [negative_prompt] * batch_size if isinstance(negative_prompt, str) else negative_prompt max_l...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
if do_classifier_free_guidance: # duplicate unconditional embeddings for each generation per prompt, using mps friendly method seq_len = negative_prompt_embeds.shape[1] negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device) negative_prompt_embeds...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
# Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3.StableDiffusion3Pipeline.prepare_latents def prepare_latents( self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None, ):...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype) return latents # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.upcast_vae def upcast_vae(self): dtype = self.vae.dtype self.vae.to(dtype=torch.flo...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
@torch.no_grad() @replace_example_docstring(EXAMPLE_DOC_STRING) def __call__( self, prompt: Union[str, List[str]] = None, negative_prompt: Union[str, List[str]] = None, num_inference_steps: int = 50, sigmas: List[float] = None, guidance_scale: float = 3.5, ...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
Function invoked when calling the pipeline for generation.
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.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. negative_prompt (`str` or `List[str]`, *optional*): The prompt or prompts not to guide t...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
num_inference_steps (`int`, *optional*, defaults to 50): The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference. sigmas (`List[float]`, *optional*): Custom sigmas used to override the times...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
num_images_per_prompt (`int`, *optional*, defaults to 1): The number of images to generate per prompt. generator (`torch.Generator` or `List[torch.Generator]`, *optional*): One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) ...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
provided, text embeddings will be generated from `prompt` input argument. prompt_attention_mask (`torch.Tensor`, *optional*): Pre-generated attention mask for text embeddings. negative_prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated negative text em...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead of a plain tuple. max_sequence_length (`int` defaults to 256): Maximum sequence length to use with the `prompt`.
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.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. """ # 1. Check inputs. Raise error i...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
# 2. Determine batch size. 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] device = self._execution_device ...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
# 3. Encode input prompt ( prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask, ) = self.encode_prompt( prompt=prompt, negative_prompt=negative_prompt, do_classifier_free_guidance...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
# sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, sigmas=sigmas) # 5. Prepare latents. latent_channels = self.transformer.config.in_channels latents = self.prepare_la...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
# aura use timestep value between 0 and 1, with t=1 as noise and t=0 as the image # broadcast to batch dimension in a way that's compatible with ONNX/Core ML timestep = torch.tensor([t / 1000]).expand(latent_model_input.shape[0]) timestep = timestep.to(latents.device, dty...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
# compute the previous noisy sample x_t -> x_t-1 latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0] # call the callback, if provided if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): ...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
if output_type == "latent": image = latents else: # make sure the VAE is in float32 mode, as it overflows in float16 needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast if needs_upcasting: self.upcast_vae() ...
218
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py
class WuerstchenDiffNeXt(ModelMixin, ConfigMixin): @register_to_config def __init__( self, c_in=4, c_out=4, c_r=64, patch_size=2, c_cond=1024, c_hidden=[320, 640, 1280, 1280], nhead=[-1, 10, 20, 20], blocks=[4, 4, 14, 4], level_conf...
219
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py
# CONDITIONING self.clip_mapper = nn.Linear(clip_embd, c_cond) self.effnet_mappers = nn.ModuleList( [ nn.Conv2d(effnet_embd, c_cond, kernel_size=1) if inject else None for inject in inject_effnet + list(reversed(inject_effnet)) ] ) ...
219
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py
def get_block(block_type, c_hidden, nhead, c_skip=0, dropout=0): if block_type == "C": return ResBlockStageB(c_hidden, c_skip, kernel_size=kernel_size, dropout=dropout) elif block_type == "A": return AttnBlock(c_hidden, c_cond, nhead, self_attn=True, dropout=dropo...
219
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py
# BLOCKS # -- down blocks self.down_blocks = nn.ModuleList() for i in range(len(c_hidden)): down_block = nn.ModuleList() if i > 0: down_block.append( nn.Sequential( WuerstchenLayerNorm(c_hidden[i - 1], elementwis...
219
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py
# -- up blocks self.up_blocks = nn.ModuleList() for i in reversed(range(len(c_hidden))): up_block = nn.ModuleList() for j in range(blocks[i]): for k, block_type in enumerate(level_config[i]): c_skip = c_hidden[i] if i < len(c_hidden) - 1 and j ...
219
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py
# OUTPUT self.clf = nn.Sequential( WuerstchenLayerNorm(c_hidden[0], elementwise_affine=False, eps=1e-6), nn.Conv2d(c_hidden[0], 2 * c_out * (patch_size**2), kernel_size=1), nn.PixelShuffle(patch_size), ) # --- WEIGHT INIT --- self.apply(self._init_wei...
219
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py
# blocks for level_block in self.down_blocks + self.up_blocks: for block in level_block: if isinstance(block, ResBlockStageB): block.channelwise[-1].weight.data *= np.sqrt(1 / sum(self.config.blocks)) elif isinstance(block, TimestepBlock): ...
219
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py
def _down_encode(self, x, r_embed, effnet, clip=None): level_outputs = [] for i, down_block in enumerate(self.down_blocks): effnet_c = None for block in down_block: if isinstance(block, ResBlockStageB): if effnet_c is None and self.effnet_mappe...
219
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py
x = block(x) level_outputs.insert(0, x) return level_outputs
219
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py
def _up_decode(self, level_outputs, r_embed, effnet, clip=None): x = level_outputs[0] for i, up_block in enumerate(self.up_blocks): effnet_c = None for j, block in enumerate(up_block): if isinstance(block, ResBlockStageB): if effnet_c is None a...
219
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py
skip = effnet_c x = block(x, skip) elif isinstance(block, AttnBlock): x = block(x, clip) elif isinstance(block, TimestepBlock): x = block(x, r_embed) else: x = block(x) return x
219
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py
def forward(self, x, r, effnet, clip=None, x_cat=None, eps=1e-3, return_noise=True): if x_cat is not None: x = torch.cat([x, x_cat], dim=1) # Process the conditioning embeddings r_embed = self.gen_r_embedding(r) if clip is not None: clip = self.gen_c_embeddings(cl...
219
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py
class ResBlockStageB(nn.Module): def __init__(self, c, c_skip=0, kernel_size=3, dropout=0.0): super().__init__() self.depthwise = nn.Conv2d(c, c, kernel_size=kernel_size, padding=kernel_size // 2, groups=c) self.norm = WuerstchenLayerNorm(c, elementwise_affine=False, eps=1e-6) self.c...
220
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py
class MixingResidualBlock(nn.Module): """ Residual block with mixing used by Paella's VQ-VAE. """ def __init__(self, inp_channels, embed_dim): super().__init__() # depthwise self.norm1 = nn.LayerNorm(inp_channels, elementwise_affine=False, eps=1e-6) self.depthwise = nn.S...
221
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py
def forward(self, x): mods = self.gammas x_temp = self.norm1(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) * (1 + mods[0]) + mods[1] x = x + self.depthwise(x_temp) * mods[2] x_temp = self.norm2(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) * (1 + mods[3]) + mods[4] x = x + self.channel...
221
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py
class PaellaVQModel(ModelMixin, ConfigMixin): r"""VQ-VAE model from Paella model. This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library implements for all the model (such as downloading or saving, etc.)
222
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py
Parameters: in_channels (int, *optional*, defaults to 3): Number of channels in the input image. out_channels (int, *optional*, defaults to 3): Number of channels in the output. up_down_scale_factor (int, *optional*, defaults to 2): Up and Downscale factor of the input image. levels (i...
222
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py
@register_to_config def __init__( self, in_channels: int = 3, out_channels: int = 3, up_down_scale_factor: int = 2, levels: int = 2, bottleneck_blocks: int = 12, embed_dim: int = 384, latent_channels: int = 4, num_vq_embeddings: int = 8192, ...
222
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py
c_levels = [embed_dim // (2**i) for i in reversed(range(levels))] # Encoder blocks self.in_block = nn.Sequential( nn.PixelUnshuffle(up_down_scale_factor), nn.Conv2d(in_channels * up_down_scale_factor**2, c_levels[0], kernel_size=1), ) down_blocks = [] for ...
222
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py
# Vector Quantizer self.vquantizer = VectorQuantizer(num_vq_embeddings, vq_embed_dim=latent_channels, legacy=False, beta=0.25) # Decoder blocks up_blocks = [nn.Sequential(nn.Conv2d(latent_channels, c_levels[-1], kernel_size=1))] for i in range(levels): for j in range(bottlen...
222
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py
@apply_forward_hook def encode(self, x: torch.Tensor, return_dict: bool = True) -> VQEncoderOutput: h = self.in_block(x) h = self.down_blocks(h) if not return_dict: return (h,) return VQEncoderOutput(latents=h) @apply_forward_hook def decode( self, h: t...
222
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py
def forward(self, sample: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]: r""" Args: sample (`torch.Tensor`): Input sample. return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`DecoderOutput`] instead of...
222
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py
class WuerstchenLayerNorm(nn.LayerNorm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def forward(self, x): x = x.permute(0, 2, 3, 1) x = super().forward(x) return x.permute(0, 3, 1, 2)
223
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py
class TimestepBlock(nn.Module): def __init__(self, c, c_timestep): super().__init__() self.mapper = nn.Linear(c_timestep, c * 2) def forward(self, x, t): a, b = self.mapper(t)[:, :, None, None].chunk(2, dim=1) return x * (1 + a) + b
224
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py
class ResBlock(nn.Module): def __init__(self, c, c_skip=0, kernel_size=3, dropout=0.0): super().__init__() self.depthwise = nn.Conv2d(c + c_skip, c, kernel_size=kernel_size, padding=kernel_size // 2, groups=c) self.norm = WuerstchenLayerNorm(c, elementwise_affine=False, eps=1e-6) se...
225
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py
class GlobalResponseNorm(nn.Module): def __init__(self, dim): super().__init__() self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim)) self.beta = nn.Parameter(torch.zeros(1, 1, 1, dim)) def forward(self, x): agg_norm = torch.norm(x, p=2, dim=(1, 2), keepdim=True) stand_d...
226
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py
class AttnBlock(nn.Module): def __init__(self, c, c_cond, nhead, self_attn=True, dropout=0.0): super().__init__() self.self_attn = self_attn self.norm = WuerstchenLayerNorm(c, elementwise_affine=False, eps=1e-6) self.attention = Attention(query_dim=c, heads=nhead, dim_head=c // nhea...
227
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py
class WuerstchenPrior(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin, PeftAdapterMixin): unet_name = "prior" _supports_gradient_checkpointing = True @register_to_config def __init__(self, c_in=16, c=1280, c_cond=1024, c_r=64, depth=16, nhead=16, dropout=0.1): super().__init__() s...
228
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py
self.gradient_checkpointing = False self.set_default_attn_processor() @property # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors def attn_processors(self) -> Dict[str, AttentionProcessor]: r""" Returns: `dict` of attention proce...
228
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py
for name, module in self.named_children(): fn_recursive_add_processors(name, module, processors) return processors # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, Atte...
228
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py
if isinstance(processor, dict) and len(processor) != count: raise ValueError( f"A dict of processors was passed, but the number of processors {len(processor)} does not match the" f" number of attention layers: {count}. Please make sure to pass {count} processor classes." ...
228
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.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...
228
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py
def gen_r_embedding(self, r, max_positions=10000): r = r * max_positions half_dim = self.c_r // 2 emb = math.log(max_positions) / (half_dim - 1) emb = torch.arange(half_dim, device=r.device).float().mul(-emb).exp() emb = r[:, None] * emb[None, :] emb = torch.cat([emb.sin(...
228
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py
if is_torch_version(">=", "1.11.0"): for block in self.blocks: if isinstance(block, AttnBlock): x = torch.utils.checkpoint.checkpoint( create_custom_forward(block), x, c_embed, use_reentrant=False ) ...
228
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py
x = torch.utils.checkpoint.checkpoint(create_custom_forward(block), x, r_embed) else: x = torch.utils.checkpoint.checkpoint(create_custom_forward(block), x) else: for block in self.blocks: if isinstance(block, AttnBlock): ...
228
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py
class WuerstchenDecoderPipeline(DiffusionPipeline): """ Pipeline for generating images from the Wuerstchen model. 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, runni...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
Args: tokenizer (`CLIPTokenizer`): The CLIP tokenizer. text_encoder (`CLIPTextModel`): The CLIP text encoder. decoder ([`WuerstchenDiffNeXt`]): The WuerstchenDiffNeXt unet decoder. vqgan ([`PaellaVQModel`]): The VQGAN model. schedul...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
model_cpu_offload_seq = "text_encoder->decoder->vqgan" _callback_tensor_inputs = [ "latents", "text_encoder_hidden_states", "negative_prompt_embeds", "image_embeddings", ] def __init__( self, tokenizer: CLIPTokenizer, text_encoder: CLIPTextModel, ...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
# Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline.prepare_latents 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 ...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
def encode_prompt( self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt=None, ): batch_size = len(prompt) if isinstance(prompt, list) else 1 # get prompt text embeddings text_inputs = self.tokenizer( ...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.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]) logger.warning( "The following part of your input was truncated ...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
uncond_text_encoder_hidden_states = None if do_classifier_free_guidance: uncond_tokens: List[str] if negative_prompt is None: uncond_tokens = [""] * batch_size elif type(prompt) is not type(negative_prompt): raise TypeError( ...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
uncond_tokens = negative_prompt
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
uncond_input = self.tokenizer( uncond_tokens, padding="max_length", max_length=self.tokenizer.model_max_length, truncation=True, return_tensors="pt", ) negative_prompt_embeds_text_encoder_output = self.text_encoder( ...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method seq_len = uncond_text_encoder_hidden_states.shape[1] uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.repeat(1, num_images_per_prompt, 1) uncond_text_encoder_hidden_sta...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
@property def num_timesteps(self): return self._num_timesteps @torch.no_grad() @replace_example_docstring(EXAMPLE_DOC_STRING) def __call__( self, image_embeddings: Union[torch.Tensor, List[torch.Tensor]], prompt: Union[str, List[str]] = None, num_inference_steps:...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
Args: image_embedding (`torch.Tensor` or `List[torch.Tensor]`): Image Embeddings either extracted from an image or generated by a Prior Model. prompt (`str` or `List[str]`): The prompt or prompts to guide the image generation. num_inference_steps (`int...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `decoder_guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, usually at the expense of lower image quality. negative_prompt (`...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor will ge generated by sampling using the supplied random `generator`. ...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by `callback_on_step_end_tensor_inputs`. callback_on_step_end_tensor_inputs (`List`, *optional*): The list of tensor inputs for the `callback_on_step_end` function. The tensors specifie...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
Examples: Returns: [`~pipelines.ImagePipelineOutput`] or `tuple` [`~pipelines.ImagePipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated image embeddings. """ callback = kwargs....
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.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...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
if self.do_classifier_free_guidance: if negative_prompt is not None and not isinstance(negative_prompt, list): if isinstance(negative_prompt, str): negative_prompt = [negative_prompt] else: raise TypeError( f"'ne...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
if not isinstance(num_inference_steps, int): raise TypeError( f"'num_inference_steps' must be of type 'int', but got {type(num_inference_steps)}\ In Case you want to provide explicit timesteps, please use the 'timesteps' argument." ) # 2. Encod...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
# 3. Determine latent shape of latents latent_height = int(image_embeddings.size(2) * self.config.latent_dim_scale) latent_width = int(image_embeddings.size(3) * self.config.latent_dim_scale) latent_features_shape = (image_embeddings.size(0) * num_images_per_prompt, 4, latent_height, latent_widt...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
# 6. Run denoising loop self._num_timesteps = len(timesteps[:-1]) for i, t in enumerate(self.progress_bar(timesteps[:-1])): ratio = t.expand(latents.size(0)).to(dtype) # 7. Denoise latents predicted_latents = self.decoder( torch.cat([latents] * 2) if s...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
# 9. Renoise latents to next timestep latents = self.scheduler.step( model_output=predicted_latents, timestep=ratio, sample=latents, generator=generator, ).prev_sample if callback_on_step_end is not None: ...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
if callback is not None and i % callback_steps == 0: step_idx = i // getattr(self.scheduler, "order", 1) callback(step_idx, t, latents) if XLA_AVAILABLE: xm.mark_step() if output_type not in ["pt", "np", "pil", "latent"]: raise ValueError...
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
# Offload all models self.maybe_free_model_hooks() if not return_dict: return images return ImagePipelineOutput(images)
229
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py
class WuerstchenPriorPipelineOutput(BaseOutput): """ Output class for WuerstchenPriorPipeline. Args: image_embeddings (`torch.Tensor` or `np.ndarray`) Prior image embeddings for text prompt """ image_embeddings: Union[torch.Tensor, np.ndarray]
230
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
class WuerstchenPriorPipeline(DiffusionPipeline, StableDiffusionLoraLoaderMixin): """ Pipeline for generating image prior for Wuerstchen. This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the library implements for all the pipelines (such as down...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
Args: prior ([`Prior`]): The canonical unCLIP prior to approximate the image embedding from the text embedding. text_encoder ([`CLIPTextModelWithProjection`]): Frozen text-encoder. tokenizer (`CLIPTokenizer`): Tokenizer of class [CLIPTokenizer](htt...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
unet_name = "prior" text_encoder_name = "text_encoder" model_cpu_offload_seq = "text_encoder->prior" _callback_tensor_inputs = ["latents", "text_encoder_hidden_states", "negative_prompt_embeds"] _lora_loadable_modules = ["prior", "text_encoder"] def __init__( self, tokenizer: CLIPTo...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
# Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline.prepare_latents 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 ...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
def encode_prompt( self, device, num_images_per_prompt, do_classifier_free_guidance, prompt=None, negative_prompt=None, prompt_embeds: Optional[torch.Tensor] = None, negative_prompt_embeds: Optional[torch.Tensor] = None, ): if prompt is not Non...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids 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( ...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
text_encoder_output = self.text_encoder( text_input_ids.to(device), attention_mask=attention_mask.to(device) ) prompt_embeds = text_encoder_output.last_hidden_state prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device) prompt_embeds = pro...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
if negative_prompt_embeds is None and do_classifier_free_guidance: uncond_tokens: List[str] if negative_prompt is None: uncond_tokens = [""] * batch_size elif type(prompt) is not type(negative_prompt): raise TypeError( f"`negative_p...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
uncond_input = self.tokenizer( uncond_tokens, padding="max_length", max_length=self.tokenizer.model_max_length, truncation=True, return_tensors="pt", ) negative_prompt_embeds_text_encoder_output = self.text_encoder( ...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
if do_classifier_free_guidance: # duplicate unconditional embeddings for each generation per prompt, using mps friendly method seq_len = negative_prompt_embeds.shape[1] negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device) negati...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
def check_inputs( self, prompt, negative_prompt, num_inference_steps, do_classifier_free_guidance, prompt_embeds=None, negative_prompt_embeds=None, ): if prompt is not None and prompt_embeds is not None: raise ValueError( f"...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.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." ) ...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
if not isinstance(num_inference_steps, int): raise TypeError( f"'num_inference_steps' must be of type 'int', but got {type(num_inference_steps)}\ In Case you want to provide explicit timesteps, please use the 'timesteps' argument." ) @property ...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
@torch.no_grad() @replace_example_docstring(EXAMPLE_DOC_STRING) def __call__( self, prompt: Optional[Union[str, List[str]]] = None, height: int = 1024, width: int = 1024, num_inference_steps: int = 60, timesteps: List[float] = None, guidance_scale: float =...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
Function invoked when calling the pipeline for generation.
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
Args: prompt (`str` or `List[str]`): The prompt or prompts to guide the image generation. height (`int`, *optional*, defaults to 1024): The height in pixels of the generated image. width (`int`, *optional*, defaults to 1024): The width ...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
`decoder_guidance_scale` is defined as `w` of equation 2. of [Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `decoder_guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to the text `p...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input argument. num_images_per_prompt (`int`, *optional*, defaults to 1): ...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
output_type (`str`, *optional*, defaults to `"pil"`): The output format of the generate image. Choose between: `"pil"` (`PIL.Image.Image`), `"np"` (`np.array`) or `"pt"` (`torch.Tensor`). return_dict (`bool`, *optional*, defaults to `True`): Whether or not to ...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list 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.
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py
Examples: Returns: [`~pipelines.WuerstchenPriorPipelineOutput`] or `tuple` [`~pipelines.WuerstchenPriorPipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated image embeddings. """ ...
231
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py