text
stringlengths
0
5.54k
If set to None, the safetensors weights are downloaded if they’re available and if the
safetensors library is installed. If set to True, the model is forcibly loaded from safetensors
weights. If set to False, safetensors weights are not loaded. kwargs (remaining dictionary of keyword arguments, optional) —
Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
class). The overwritten components are passed directly to the pipelines __init__ method. See example
below for more information. variant (str, optional) —
Load weights from a specified variant filename such as "fp16" or "ema". This is ignored when
loading from_flax. Instantiates a inpainting Pytorch diffusion pipeline from pretrained pipeline weight. The from_pretrained() method takes care of returning the correct pipeline class instance by: Detect the pipeline class of the pretrained_model_or_path based on the _class_name property of its
config object Find the inpainting pipeline linked to the pipeline class using pattern matching on pipeline class name. If a controlnet argument is passed, it will instantiate a StableDiffusionControlNetInpaintPipeline
object. The pipeline is set in evaluation mode (model.eval()) by default. If you get the error message below, you need to finetune the weights for your downstream task: Copied Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
- conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference. To use private or gated models, log-in with
huggingface-cli login. Examples: Copied >>> from diffusers import AutoPipelineForInpainting
>>> pipeline = AutoPipelineForInpainting.from_pretrained("runwayml/stable-diffusion-v1-5")
>>> image = pipeline(prompt, image=init_image, mask_image=mask_image).images[0] from_pipe < source > ( pipeline **kwargs ) Parameters pipeline (DiffusionPipeline) —
an instantiated DiffusionPipeline object Instantiates a inpainting Pytorch diffusion pipeline from another instantiated diffusion pipeline class. The from_pipe() method takes care of returning the correct pipeline class instance by finding the inpainting
pipeline linked to the pipeline class using pattern matching on pipeline class name. All the modules the pipeline class contain will be used to initialize the new pipeline without reallocating
additional memory. The pipeline is set in evaluation mode (model.eval()) by default. Examples: Copied >>> from diffusers import AutoPipelineForText2Image, AutoPipelineForInpainting
>>> pipe_t2i = AutoPipelineForText2Image.from_pretrained(
... "DeepFloyd/IF-I-XL-v1.0", requires_safety_checker=False
... )
>>> pipe_inpaint = AutoPipelineForInpainting.from_pipe(pipe_t2i)
>>> image = pipe_inpaint(prompt, image=init_image, mask_image=mask_image).images[0]
DDIMInverseScheduler DDIMInverseScheduler is the inverted scheduler from Denoising Diffusion Implicit Models (DDIM) by Jiaming Song, Chenlin Meng and Stefano Ermon.
The implementation is mostly based on the DDIM inversion definition from Null-text Inversion for Editing Real Images using Guided Diffusion Models. DDIMInverseScheduler class diffusers.DDIMInverseScheduler < source > ( num_train_timesteps: int = 1000 beta_start: float = 0.0001 beta_end: float = 0.02 beta_schedule: str = 'linear' trained_betas: Union = None clip_sample: bool = True set_alpha_to_one: bool = True steps_offset: int = 0 prediction_type: str = 'epsilon' clip_sample_range: float = 1.0 timestep_spacing: str = 'leading' rescale_betas_zero_snr: bool = False **kwargs ) Parameters num_train_timesteps (int, defaults to 1000) —
The number of diffusion steps to train the model. beta_start (float, defaults to 0.0001) —
The starting beta value of inference. beta_end (float, defaults to 0.02) —
The final beta value. beta_schedule (str, defaults to "linear") —
The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
linear, scaled_linear, or squaredcos_cap_v2. trained_betas (np.ndarray, optional) —
Pass an array of betas directly to the constructor to bypass beta_start and beta_end. clip_sample (bool, defaults to True) —
Clip the predicted sample for numerical stability. clip_sample_range (float, defaults to 1.0) —
The maximum magnitude for sample clipping. Valid only when clip_sample=True. set_alpha_to_one (bool, defaults to True) —
Each diffusion step uses the alphas product value at that step and at the previous one. For the final step
there is no previous alpha. When this option is True the previous alpha product is fixed to 0, otherwise
it uses the alpha value at step num_train_timesteps - 1. steps_offset (int, defaults to 0) —
An offset added to the inference steps. You can use a combination of offset=1 and
set_alpha_to_one=False to make the last step use num_train_timesteps - 1 for the previous alpha
product. prediction_type (str, defaults to epsilon, optional) —
Prediction type of the scheduler function; can be epsilon (predicts the noise of the diffusion process),
sample (directly predicts the noisy sample) or v_prediction` (see section 2.4 of Imagen
Video paper). timestep_spacing (str, defaults to "leading") —
The way the timesteps should be scaled. Refer to Table 2 of the Common Diffusion Noise Schedules and
Sample Steps are Flawed for more information. rescale_betas_zero_snr (bool, defaults to False) —
Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
dark samples instead of limiting it to samples with medium brightness. Loosely related to
--offset_noise. DDIMInverseScheduler is the reverse scheduler of DDIMScheduler. This model inherits from SchedulerMixin and ConfigMixin. Check the superclass documentation for the generic
methods the library implements for all schedulers such as loading and saving. scale_model_input < source > ( sample: FloatTensor timestep: Optional = None ) → torch.FloatTensor Parameters sample (torch.FloatTensor) —
The input sample. timestep (int, optional) —
The current timestep in the diffusion chain. Returns
torch.FloatTensor
A scaled input sample.
Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
current timestep. set_timesteps < source > ( num_inference_steps: int device: Union = None ) Parameters num_inference_steps (int) —
The number of diffusion steps used when generating samples with a pre-trained model. Sets the discrete timesteps used for the diffusion chain (to be run before inference). step < source > ( model_output: FloatTensor timestep: int sample: FloatTensor return_dict: bool = True ) → ~schedulers.scheduling_ddim_inverse.DDIMInverseSchedulerOutput or tuple Parameters model_output (torch.FloatTensor) —
The direct output from learned diffusion model. timestep (float) —
The current discrete timestep in the diffusion chain. sample (torch.FloatTensor) —
A current instance of a sample created by the diffusion process. eta (float) —
The weight of noise for added noise in diffusion step. use_clipped_model_output (bool, defaults to False) —
If True, computes “corrected” model_output from the clipped predicted original sample. Necessary
because predicted original sample is clipped to [-1, 1] when self.config.clip_sample is True. If no
clipping has happened, “corrected” model_output would coincide with the one provided as input and
use_clipped_model_output has no effect. variance_noise (torch.FloatTensor) —
Alternative to generating noise with generator by directly providing the noise for the variance
itself. Useful for methods such as CycleDiffusion. return_dict (bool, optional, defaults to True) —
Whether or not to return a ~schedulers.scheduling_ddim_inverse.DDIMInverseSchedulerOutput or
tuple. Returns
~schedulers.scheduling_ddim_inverse.DDIMInverseSchedulerOutput or tuple
If return_dict is True, ~schedulers.scheduling_ddim_inverse.DDIMInverseSchedulerOutput is
returned, otherwise a tuple is returned where the first element is the sample tensor.
Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
process from the learned model outputs (most often the predicted noise).
DiffEdit DiffEdit: Diffusion-based semantic image editing with mask guidance is by Guillaume Couairon, Jakob Verbeek, Holger Schwenk, and Matthieu Cord. The abstract from the paper is: Image generation has recently seen tremendous advances, with diffusion models allowing to synthesize convincing images for a large variety of text prompts. In this article, we propose DiffEdit, a method to take advantage of text-conditioned diffusion models for the task of semantic image editing, where the goal is to edit an image based on a text query. Semantic image editing is an extension of image generation, with the additional constraint that the generated image should be as similar as possible to a given input image. Current editing methods based on diffusion models usually require to provide a mask, making the task much easier by treating it as a conditional inpainting task. In contrast, our main contribution is able to automatically generate a mask highlighting regions of the input image that need to be edited, by contrasting predictions of a diffusion model conditioned on different text prompts. Moreover, we rely on latent inference to preserve content in those regions of interest and show excellent synergies with mask-based diffusion. DiffEdit achieves state-of-the-art editing performance on ImageNet. In addition, we evaluate semantic image editing in more challenging settings, using images from the COCO dataset as well as text-based generated images. The original codebase can be found at Xiang-cd/DiffEdit-stable-diffusion, and you can try it out in this demo. This pipeline was contributed by clarencechen. ❤️ Tips The pipeline can generate masks that can be fed into other inpainting pipelines. In order to generate an image using this pipeline, both an image mask (source and target prompts can be manually specified or generated, and passed to generate_mask())
and a set of partially inverted latents (generated using invert()) must be provided as arguments when calling the pipeline to generate the final edited image. The function generate_mask() exposes two prompt arguments, source_prompt and target_prompt
that let you control the locations of the semantic edits in the final image to be generated. Let’s say,
you wanted to translate from “cat” to “dog”. In this case, the edit direction will be “cat -> dog”. To reflect
this in the generated mask, you simply have to set the embeddings related to the phrases including “cat” to
source_prompt and “dog” to target_prompt. When generating partially inverted latents using invert, assign a caption or text embedding describing the
overall image to the prompt argument to help guide the inverse latent sampling process. In most cases, the
source concept is sufficiently descriptive to yield good results, but feel free to explore alternatives. When calling the pipeline to generate the final edited image, assign the source concept to negative_prompt
and the target concept to prompt. Taking the above example, you simply have to set the embeddings related to
the phrases including “cat” to negative_prompt and “dog” to prompt. If you wanted to reverse the direction in the example above, i.e., “dog -> cat”, then it’s recommended to:Swap the source_prompt and target_prompt in the arguments to generate_mask. Change the input prompt in invert() to include “dog”. Swap the prompt and negative_prompt in the arguments to call the pipeline to generate the final edited image. The source and target prompts, or their corresponding embeddings, can also be automatically generated. Please refer to the DiffEdit guide for more details. StableDiffusionDiffEditPipeline class diffusers.StableDiffusionDiffEditPipeline < source > ( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor inverse_scheduler: DDIMInverseScheduler requires_safety_checker: bool = True ) Parameters vae (AutoencoderKL) —
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations. text_encoder (CLIPTextModel) —
Frozen text-encoder (clip-vit-large-patch14). tokenizer (CLIPTokenizer) —
A CLIPTokenizer to tokenize text. unet (UNet2DConditionModel) —
A UNet2DConditionModel to denoise the encoded image latents. scheduler (SchedulerMixin) —
A scheduler to be used in combination with unet to denoise the encoded image latents. inverse_scheduler (DDIMInverseScheduler) —
A scheduler to be used in combination with unet to fill in the unmasked part of the input latents. safety_checker (StableDiffusionSafetyChecker) —
Classification module that estimates whether generated images could be considered offensive or harmful.
Please refer to the model card for more details
about a model’s potential harms. feature_extractor (CLIPImageProcessor) —
A CLIPImageProcessor to extract features from generated images; used as inputs to the safety_checker. This is an experimental feature! Pipeline for text-guided image inpainting using Stable Diffusion and DiffEdit. 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.). The pipeline also inherits the following loading and saving methods: load_textual_inversion() for loading textual inversion embeddings load_lora_weights() for loading LoRA weights save_lora_weights() for saving LoRA weights generate_mask < source > ( image: Union = None target_prompt: Union = None target_negative_prompt: Union = None target_prompt_embeds: Optional = None target_negative_prompt_embeds: Optional = None source_prompt: Union = None source_negative_prompt: Union = None source_prompt_embeds: Optional = None source_negative_prompt_embeds: Optional = None num_maps_per_mask: Optional = 10 mask_encode_strength: Optional = 0.5 mask_thresholding_ratio: Optional = 3.0 num_inference_steps: int = 50 guidance_scale: float = 7.5 generator: Union = None output_type: Optional = 'np' cross_attention_kwargs: Optional = None ) → List[PIL.Image.Image] or np.array Parameters image (PIL.Image.Image) —
Image or tensor representing an image batch to be used for computing the mask. target_prompt (str or List[str], optional) —
The prompt or prompts to guide semantic mask generation. If not defined, you need to pass