text
stringlengths
1
1.02k
class_index
int64
0
1.38k
source
stringclasses
431 values
# NOTE: when a LCM is distilled from an LDM via latent consistency distillation (Algorithm 1) with guided # distillation, the forward pass of the LCM learns to approximate sampling from the LDM using CFG with the # unconditional prompt "" (the empty string). Due to this, LCMs currently do not support ne...
114
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py
# 5. Prepare timesteps timesteps, num_inference_steps = retrieve_timesteps( self.scheduler, num_inference_steps, device, timesteps, original_inference_steps=original_inference_steps, strength=strength, ) # 6. Prepare latent...
114
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py
# 6. Get Guidance Scale Embedding # NOTE: We use the Imagen CFG formulation that StableDiffusionPipeline uses rather than the original LCM paper # CFG formulation, so we need to subtract 1 from the input guidance_scale. # LCM CFG formulation: cfg_noise = noise_cond + cfg_scale * (noise_cond - n...
114
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py
# 8. LCM Multistep Sampling Loop num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order self._num_timesteps = len(timesteps) with self.progress_bar(total=num_inference_steps) as progress_bar: for i, t in enumerate(timesteps): latents = latents....
114
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py
# compute the previous noisy sample x_t -> x_t-1 latents, denoised = self.scheduler.step(model_pred, t, latents, **extra_step_kwargs, return_dict=False) if callback_on_step_end is not None: callback_kwargs = {} for k in callback_on_step_end_tensor_...
114
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py
# call the callback, if provided if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): progress_bar.update() if callback is not None and i % callback_steps == 0: step_idx = i // getattr(self.sch...
114
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py
if has_nsfw_concept is None: do_denormalize = [True] * image.shape[0] else: do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept] image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize) # Offload all models ...
114
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py
class LatentConsistencyModelPipeline( DiffusionPipeline, StableDiffusionMixin, TextualInversionLoaderMixin, IPAdapterMixin, StableDiffusionLoraLoaderMixin, FromSingleFileMixin, ): r""" Pipeline for text-to-image generation using a latent consistency model. This model inherits from [...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
The pipeline also inherits the following loading methods: - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights - [`~loaders.StableDiffusionLoraLoaderMixi...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
Args: vae ([`AutoencoderKL`]): Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations. text_encoder ([`~transformers.CLIPTextModel`]): Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14))...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details about a model's potential harms. feature_extractor ([`~transformers.CLIPImageProcessor`]): A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `saf...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
model_cpu_offload_seq = "text_encoder->unet->vae" _optional_components = ["safety_checker", "feature_extractor", "image_encoder"] _exclude_from_cpu_offload = ["safety_checker"] _callback_tensor_inputs = ["latents", "denoised", "prompt_embeds", "w_embedding"] def __init__( self, vae: Aut...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
if safety_checker is None and requires_safety_checker: logger.warning( f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
if safety_checker is not None and feature_extractor is None: raise ValueError( "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` i...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt def encode_prompt( self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt=None, prompt_embeds: Optional[torch....
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
Args: prompt (`str` or `List[str]`, *optional*): prompt to be encoded device: (`torch.device`): torch device num_images_per_prompt (`int`): number of images that should be generated per prompt do_classifier_free_guidance (`b...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
negative_prompt_embeds (`torch.Tensor`, *optional*): 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. lora...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# dynamically adjust the LoRA scale if not USE_PEFT_BACKEND: adjust_lora_scale_text_encoder(self.text_encoder, lora_scale) else: scale_lora_layers(self.text_encoder, lora_scale) if prompt is not None and isinstance(prompt, str): batch_size = 1...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
text_inputs = self.tokenizer( prompt, padding="max_length", max_length=self.tokenizer.model_max_length, truncation=True, return_tensors="pt", ) text_input_ids = text_inputs.input_ids untruncated_ids = sel...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: attention_mask = text_inputs.attention_mask.to(device) else: attention_mask = None
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
if clip_skip is None: prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask) prompt_embeds = prompt_embeds[0] else: prompt_embeds = self.text_encoder( text_input_ids.to(device), attention_mask=attention_...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
if self.text_encoder is not None: prompt_embeds_dtype = self.text_encoder.dtype elif self.unet is not None: prompt_embeds_dtype = self.unet.dtype else: prompt_embeds_dtype = prompt_embeds.dtype prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, devic...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# get unconditional embeddings for classifier free guidance if do_classifier_free_guidance and negative_prompt_embeds is None: uncond_tokens: List[str] if negative_prompt is None: uncond_tokens = [""] * batch_size elif prompt is not None and type(prompt) is no...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
" the batch size of `prompt`." ) else: uncond_tokens = negative_prompt
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# textual inversion: process multi-vector tokens if necessary if isinstance(self, TextualInversionLoaderMixin): uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer) max_length = prompt_embeds.shape[1] uncond_input = self.tokenizer( ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.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=prompt_embeds_dtype, device=device) negative...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None): dtype = next(self.image_encoder.parameters()).dtype if not isinstance(image, torch.Tensor): ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
image = image.to(device=device, dtype=dtype) if output_hidden_states: image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2] image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0) uncond_imag...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds def prepare_ip_adapter_image_embeds( self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance ): image_embeds = ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
for single_ip_adapter_image, image_proj_layer in zip( ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers ): output_hidden_state = not isinstance(image_proj_layer, ImageProjection) single_image_embeds, single_negative_image_embeds = self.encod...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
ip_adapter_image_embeds = [] for i, single_image_embeds in enumerate(image_embeds): single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0) if do_classifier_free_guidance: single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker def run_safety_checker(self, image, device, dtype): if self.safety_checker is None: has_nsfw_concept = None else: if torch.is_tensor(image): ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None): shape = ( batch_size, num_channels_latents, ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# scale the initial noise by the standard deviation required by the scheduler latents = latents * self.scheduler.init_noise_sigma return latents def get_guidance_scale_embedding( self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32 ) -> torch.Tensor: ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
Returns: `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`. """ assert len(w.shape) == 1 w = w * 1000.0 half_dim = embedding_dim // 2 emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, dtype=dty...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs def prepare_extra_step_kwargs(self, generator, eta): # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used w...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# Currently StableDiffusionPipeline.check_inputs with negative prompt stuff removed def check_inputs( self, prompt: Union[str, List[str]], height: int, width: int, callback_steps: int, prompt_embeds: Optional[torch.Tensor] = None, ip_adapter_image=None, ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.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...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.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: ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
if ip_adapter_image_embeds is not None: if not isinstance(ip_adapter_image_embeds, list): raise ValueError( f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}" ) elif ip_adapter_image_embeds[0].ndim not ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
@torch.no_grad() @replace_example_docstring(EXAMPLE_DOC_STRING) def __call__( self, prompt: Union[str, List[str]] = None, height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: int = 4, original_inference_steps: int = None, timeste...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
callback_on_step_end_tensor_inputs: List[str] = ["latents"], **kwargs, ): r""" The call function to the pipeline for generation.
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
Args: prompt (`str` or `List[str]`, *optional*): The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`. height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): The height in pixels...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
we will draw `num_inference_steps` evenly spaced timesteps from as our final timestep schedule, following the Skipping-Step method in the paper (see Section 4.3). If not set this will default to the scheduler's `original_inference_steps` attribute. timesteps (`List[int]`, *op...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
guidance scales are decreased by 1 (so in the paper formulation CFG is enabled when `guidance_scale > 0`). num_images_per_prompt (`int`, *optional*, defaults to 1): The number of images to generate per prompt. generator (`torch.Generator` or `List[torch.Generator]...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, text embeddings are generated from the `prompt` input argument. ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters. ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a plain tuple. cross_attention_kwargs (`dict`, *optional*): A kwargs dictionary that if specified is passe...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, 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...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
Examples: Returns: [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned, otherwise a `tuple` is returned where the first element is a list with ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
if callback is not None: deprecate( "callback", "1.0.0", "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`", ) if callback_steps is not None: deprecate( "ca...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# 1. Check inputs. Raise error if not correct self.check_inputs( prompt, height, width, callback_steps, prompt_embeds, ip_adapter_image, ip_adapter_image_embeds, callback_on_step_end_tensor_inputs, ) ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
if ip_adapter_image is not None or ip_adapter_image_embeds is not None: image_embeds = self.prepare_ip_adapter_image_embeds( ip_adapter_image, ip_adapter_image_embeds, device, batch_size * num_images_per_prompt, self.do_classifi...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# NOTE: when a LCM is distilled from an LDM via latent consistency distillation (Algorithm 1) with guided # distillation, the forward pass of the LCM learns to approximate sampling from the LDM using CFG with the # unconditional prompt "" (the empty string). Due to this, LCMs currently do not support ne...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# 5. Prepare latent variable num_channels_latents = self.unet.config.in_channels latents = self.prepare_latents( batch_size * num_images_per_prompt, num_channels_latents, height, width, prompt_embeds.dtype, device, gener...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline extra_step_kwargs = self.prepare_extra_step_kwargs(generator, None) # 7.1 Add image embeds for IP-Adapter added_cond_kwargs = ( {"image_embeds": image_embeds} if ip_adapter_image...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
# model prediction (v-prediction, eps, x) model_pred = self.unet( latents, t, timestep_cond=w_embedding, encoder_hidden_states=prompt_embeds, cross_attention_kwargs=self.cross_attention_kwargs, ...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
latents = callback_outputs.pop("latents", latents) prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) w_embedding = callback_outputs.pop("w_embedding", w_embedding) denoised = callback_outputs.pop("denoised", denoised) # call...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
denoised = denoised.to(prompt_embeds.dtype) if not output_type == "latent": image = self.vae.decode(denoised / self.vae.config.scaling_factor, return_dict=False)[0] image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype) else: image = den...
115
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py
class MarigoldImageProcessor(ConfigMixin): config_name = CONFIG_NAME @register_to_config def __init__( self, vae_scale_factor: int = 8, do_normalize: bool = True, do_range_check: bool = True, ): super().__init__()
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
@staticmethod def expand_tensor_or_array(images: Union[torch.Tensor, np.ndarray]) -> Union[torch.Tensor, np.ndarray]: """ Expand a tensor or array to a specified number of images. """ if isinstance(images, np.ndarray): if images.ndim == 2: # [H,W] -> [1,H,W,1] ...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
@staticmethod def pt_to_numpy(images: torch.Tensor) -> np.ndarray: """ Convert a PyTorch tensor to a NumPy image. """ images = images.cpu().permute(0, 2, 3, 1).float().numpy() return images @staticmethod def numpy_to_pt(images: np.ndarray) -> torch.Tensor: ""...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
@staticmethod def resize_antialias( image: torch.Tensor, size: Tuple[int, int], mode: str, is_aa: Optional[bool] = None ) -> torch.Tensor: if not torch.is_tensor(image): raise ValueError(f"Invalid input type={type(image)}.") if not torch.is_floating_point(image): ...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
@staticmethod def resize_to_max_edge(image: torch.Tensor, max_edge_sz: int, mode: str) -> torch.Tensor: if not torch.is_tensor(image): raise ValueError(f"Invalid input type={type(image)}.") if not torch.is_floating_point(image): raise ValueError(f"Invalid input dtype={image.d...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
@staticmethod def pad_image(image: torch.Tensor, align: int) -> Tuple[torch.Tensor, Tuple[int, int]]: if not torch.is_tensor(image): raise ValueError(f"Invalid input type={type(image)}.") if not torch.is_floating_point(image): raise ValueError(f"Invalid input dtype={image.dty...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
@staticmethod def unpad_image(image: torch.Tensor, padding: Tuple[int, int]) -> torch.Tensor: if not torch.is_tensor(image): raise ValueError(f"Invalid input type={type(image)}.") if not torch.is_floating_point(image): raise ValueError(f"Invalid input dtype={image.dtype}.") ...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
image_dtype_max = None if isinstance(image, (np.ndarray, torch.Tensor)): image = MarigoldImageProcessor.expand_tensor_or_array(image) if image.ndim != 4: raise ValueError("Input image is not 2-, 3-, or 4-dimensional.") if isinstance(image, np.ndarray): ...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
image = image.astype(np.float32) # because torch does not have unsigned dtypes beyond torch.uint8 image = MarigoldImageProcessor.numpy_to_pt(image)
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
if torch.is_tensor(image) and not torch.is_floating_point(image) and image_dtype_max is None: if image.dtype != torch.uint8: raise ValueError(f"Image dtype={image.dtype} is not supported.") image_dtype_max = 255 if not torch.is_tensor(image): raise ValueError...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
@staticmethod def check_image_values_range(image: torch.Tensor) -> None: if not torch.is_tensor(image): raise ValueError(f"Invalid input type={type(image)}.") if not torch.is_floating_point(image): raise ValueError(f"Invalid input dtype={image.dtype}.") if image.min()...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
def preprocess( self, image: PipelineImageInput, processing_resolution: Optional[int] = None, resample_method_input: str = "bilinear", device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.float32, ): if isinstance(image, list): im...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
image = self.load_image_canonical(image, device, dtype) # [N,3,H,W]
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
original_resolution = image.shape[2:] if self.config.do_range_check: self.check_image_values_range(image) if self.config.do_normalize: image = image * 2.0 - 1.0 if processing_resolution is not None and processing_resolution > 0: image = self.resize_to_max_e...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
@staticmethod def colormap( image: Union[np.ndarray, torch.Tensor], cmap: str = "Spectral", bytes: bool = False, _force_method: Optional[str] = None, ) -> Union[np.ndarray, torch.Tensor]: """ Converts a monochrome image into an RGB image by applying the specified ...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
Args: image: 2D tensor of values between 0 and 1, either as np.ndarray or torch.Tensor. cmap: Colormap name. bytes: Whether to return the output as uint8 or floating point image. _force_method: Can be used to specify whether to use the native implementatio...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
supported_cmaps = { "binary": [ (1.0, 1.0, 1.0), (0.0, 0.0, 0.0), ], "Spectral": [ # Taken from matplotlib/_cm.py (0.61960784313725492, 0.003921568627450980, 0.25882352941176473), # 0.0 -> [0] (0.83529411764705885, 0.2...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
(0.36862745098039218, 0.30980392156862746, 0.63529411764705879), # 1.0 -> [K-1] ], }
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
def method_matplotlib(image, cmap, bytes=False): if is_matplotlib_available(): import matplotlib else: return None arg_is_pt, device = torch.is_tensor(image), None if arg_is_pt: image, device = image.cpu().numpy(), image.de...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
def method_custom(image, cmap, bytes=False): arg_is_np = isinstance(image, np.ndarray) if arg_is_np: image = torch.tensor(image) if image.dtype == torch.uint8: image = image.float() / 255 else: image = image.float() ...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
d = (pos - left.float()).unsqueeze(-1) left_colors = cmap[left] right_colors = cmap[right] out = (1 - d) * left_colors + d * right_colors if bytes: out = (out * 255).to(torch.uint8) if arg_is_np: out = out.numpy() ...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
@staticmethod def visualize_depth( depth: Union[ PIL.Image.Image, np.ndarray, torch.Tensor, List[PIL.Image.Image], List[np.ndarray], List[torch.Tensor], ], val_min: float = 0.0, val_max: float = 1.0, colo...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
Args: depth (`Union[PIL.Image.Image, np.ndarray, torch.Tensor, List[PIL.Image.Image], List[np.ndarray], List[torch.Tensor]]`): Depth maps. val_min (`float`, *optional*, defaults to `0.0`): Minimum value of the visualized depth range. val_max (`float`, *optional*, defa...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
def visualize_depth_one(img, idx=None): prefix = "Depth" + (f"[{idx}]" if idx else "") if isinstance(img, PIL.Image.Image): if img.mode != "I;16": raise ValueError(f"{prefix}: invalid PIL mode={img.mode}.") img = np.array(img).astype(np.float32...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
img = MarigoldImageProcessor.colormap(img, cmap=color_map, bytes=True) # [H,W,3] img = PIL.Image.fromarray(img.cpu().numpy()) return img
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
if depth is None or isinstance(depth, list) and any(o is None for o in depth): raise ValueError("Input depth is `None`") if isinstance(depth, (np.ndarray, torch.Tensor)): depth = MarigoldImageProcessor.expand_tensor_or_array(depth) if isinstance(depth, np.ndarray): ...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
@staticmethod def export_depth_to_16bit_png( depth: Union[np.ndarray, torch.Tensor, List[np.ndarray], List[torch.Tensor]], val_min: float = 0.0, val_max: float = 1.0, ) -> Union[PIL.Image.Image, List[PIL.Image.Image]]: def export_depth_to_16bit_png_one(img, idx=None): ...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
img = PIL.Image.fromarray(img, mode="I;16") return img
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
if depth is None or isinstance(depth, list) and any(o is None for o in depth): raise ValueError("Input depth is `None`") if isinstance(depth, (np.ndarray, torch.Tensor)): depth = MarigoldImageProcessor.expand_tensor_or_array(depth) if isinstance(depth, np.ndarray): ...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
@staticmethod def visualize_normals( normals: Union[ np.ndarray, torch.Tensor, List[np.ndarray], List[torch.Tensor], ], flip_x: bool = False, flip_y: bool = False, flip_z: bool = False, ) -> Union[PIL.Image.Image, List[PIL.I...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
Args: normals (`Union[np.ndarray, torch.Tensor, List[np.ndarray], List[torch.Tensor]]`): Surface normals. flip_x (`bool`, *optional*, defaults to `False`): Flips the X axis of the normals frame of reference. Default direction is right. flip_y (`b...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
Returns: `PIL.Image.Image` or `List[PIL.Image.Image]` with surface normals visualization. """ flip_vec = None if any((flip_x, flip_y, flip_z)): flip_vec = torch.tensor( [ (-1) ** flip_x, (-1) ** flip_y, (-1) ...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
if normals is None or isinstance(normals, list) and any(o is None for o in normals): raise ValueError("Input normals is `None`") if isinstance(normals, (np.ndarray, torch.Tensor)): normals = MarigoldImageProcessor.expand_tensor_or_array(normals) if isinstance(normals, np.ndar...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
@staticmethod def visualize_uncertainty( uncertainty: Union[ np.ndarray, torch.Tensor, List[np.ndarray], List[torch.Tensor], ], saturation_percentile=95, ) -> Union[PIL.Image.Image, List[PIL.Image.Image]]: """ Visualizes den...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
def visualize_uncertainty_one(img, idx=None): prefix = "Uncertainty" + (f"[{idx}]" if idx else "") if img.min() < 0: raise ValueError(f"{prefix}: unexected data range, min={img.min()}.") img = img.squeeze(0).cpu().numpy() saturation_value = np.percentile(i...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
if uncertainty is None or isinstance(uncertainty, list) and any(o is None for o in uncertainty): raise ValueError("Input uncertainty is `None`") if isinstance(uncertainty, (np.ndarray, torch.Tensor)): uncertainty = MarigoldImageProcessor.expand_tensor_or_array(uncertainty) if...
116
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/marigold_image_processing.py
class MarigoldDepthOutput(BaseOutput): """ Output class for Marigold monocular depth prediction pipeline. Args: prediction (`np.ndarray`, `torch.Tensor`): Predicted depth maps with values in the range [0, 1]. The shape is always $numimages \times 1 \times height \times width...
117
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py
prediction: Union[np.ndarray, torch.Tensor] uncertainty: Union[None, np.ndarray, torch.Tensor] latent: Union[None, torch.Tensor]
117
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py
class MarigoldDepthPipeline(DiffusionPipeline): """ Pipeline for monocular depth estimation using the Marigold method: https://marigoldmonodepth.github.io. This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the library implements for all the pipel...
118
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py
Args: unet (`UNet2DConditionModel`): Conditional U-Net to denoise the depth latent, conditioned on image latent. vae (`AutoencoderKL`): Variational Auto-Encoder (VAE) Model to encode and decode images and predictions to and from latent representations. schedul...
118
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py
"affine-invariant". NB: overriding this value is not supported. shift_invariant (`bool`, *optional*): A model property specifying whether the predicted depth maps are shift-invariant. This value must be set in the model config. When used together with the `scale_invariant=True` flag, the...
118
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/marigold/pipeline_marigold_depth.py