text
stringlengths
0
5.54k
sent,
padding="max_length",
max_length=tokenizer.model_max_length,
truncation=True,
return_tensors="pt",
)
text_input_ids = text_inputs.input_ids
prompt_embeds = text_encoder(text_input_ids.to(device), attention_mask=None)[0]
embeddings.append(prompt_embeds)
return torch.concatenate(embeddings, dim=0).mean(dim=0).unsqueeze(0)
source_embeds = embed_prompts(source_prompts, pipeline.tokenizer, pipeline.text_encoder)
target_embeds = embed_prompts(target_prompts, pipeline.tokenizer, pipeline.text_encoder) Finally, pass the embeddings to the generate_mask() and invert() functions, and pipeline to generate the image: Copied from diffusers import DDIMInverseScheduler, DDIMScheduler
from diffusers.utils import load_image, make_image_grid
from PIL import Image
pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)
img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"
raw_image = load_image(img_url).resize((768, 768))
mask_image = pipeline.generate_mask(
image=raw_image,
- source_prompt=source_prompt,
- target_prompt=target_prompt,
+ source_prompt_embeds=source_embeds,
+ target_prompt_embeds=target_embeds,
)
inv_latents = pipeline.invert(
- prompt=source_prompt,
+ prompt_embeds=source_embeds,
image=raw_image,
).latents
output_image = pipeline(
mask_image=mask_image,
image_latents=inv_latents,
- prompt=target_prompt,
- negative_prompt=source_prompt,
+ prompt_embeds=target_embeds,
+ negative_prompt_embeds=source_embeds,
).images[0]
mask_image = Image.fromarray((mask_image.squeeze()*255).astype("uint8"), "L")
make_image_grid([raw_image, mask_image, output_image], rows=1, cols=3) Generate a caption for inversion While you can use the source_prompt as a caption to help generate the partially inverted latents, you can also use the BLIP model to automatically generate a caption. Load the BLIP model and processor from the πŸ€— Transformers library: Copied import torch
from transformers import BlipForConditionalGeneration, BlipProcessor
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base", torch_dtype=torch.float16, low_cpu_mem_usage=True) Create a utility function to generate a caption from the input image: Copied @torch.no_grad()
def generate_caption(images, caption_generator, caption_processor):
text = "a photograph of"
inputs = caption_processor(images, text, return_tensors="pt").to(device="cuda", dtype=caption_generator.dtype)
caption_generator.to("cuda")
outputs = caption_generator.generate(**inputs, max_new_tokens=128)
# offload caption generator
caption_generator.to("cpu")
caption = caption_processor.batch_decode(outputs, skip_special_tokens=True)[0]
return caption Load an input image and generate a caption for it using the generate_caption function: Copied from diffusers.utils import load_image
img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"
raw_image = load_image(img_url).resize((768, 768))
caption = generate_caption(raw_image, model, processor) generated caption: "a photograph of a bowl of fruit on a table" Now you can drop the caption into the invert() function to generate the partially inverted latents!
Configuration Schedulers from SchedulerMixin and models from ModelMixin inherit from ConfigMixin which stores all the parameters that are passed to their respective __init__ methods in a JSON-configuration file. To use private or gated models, log-in with huggingface-cli login. ConfigMixin class diffusers.ConfigMixin < source > ( ) Base class for all configuration classes. All configuration parameters are stored under self.config. Also
provides the from_config() and save_config() methods for loading, downloading, and
saving classes that inherit from ConfigMixin. Class attributes: config_name (str) β€” A filename under which the config should stored when calling
save_config() (should be overridden by parent class). ignore_for_config (List[str]) β€” A list of attributes that should not be saved in the config (should be
overridden by subclass). has_compatibles (bool) β€” Whether the class has compatible classes (should be overridden by subclass). _deprecated_kwargs (List[str]) β€” Keyword arguments that are deprecated. Note that the init function
should only have a kwargs argument if at least one argument is deprecated (should be overridden by
subclass). load_config < source > ( pretrained_model_name_or_path: Union return_unused_kwargs = False return_commit_hash = False **kwargs ) β†’ dict Parameters pretrained_model_name_or_path (str or os.PathLike, optional) β€”
Can be either:
A string, the model id (for example google/ddpm-celebahq-256) of a pretrained model hosted on
the Hub.
A path to a directory (for example ./my_model_directory) containing model weights saved with
save_config().
cache_dir (Union[str, os.PathLike], optional) β€”
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
is not used. force_download (bool, optional, defaults to False) β€”
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
cached versions if they exist. resume_download (bool, optional, defaults to False) β€”
Whether or not to resume downloading the model weights and configuration files. If set to False, any
incompletely downloaded files are deleted. proxies (Dict[str, str], optional) β€”
A dictionary of proxy servers to use by protocol or endpoint, for example, {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. The proxies are used on each request. output_loading_info(bool, optional, defaults to False) β€”
Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages. local_files_only (bool, optional, defaults to False) β€”
Whether to only load local model weights and configuration files or not. If set to True, the model
won’t be downloaded from the Hub. token (str or bool, optional) β€”
The token to use as HTTP bearer authorization for remote files. If True, the token generated from
diffusers-cli login (stored in ~/.huggingface) is used. revision (str, optional, defaults to "main") β€”
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
allowed by Git. subfolder (str, optional, defaults to "") β€”
The subfolder location of a model file within a larger model repository on the Hub or locally. return_unused_kwargs (bool, optional, defaults to `False) β€”
Whether unused keyword arguments of the config are returned. return_commit_hash (bool, optional, defaults to False) -- Whether the commit_hash` of the loaded configuration are returned. Returns
dict
A dictionary of all the parameters stored in a JSON configuration file.
Load a model or scheduler configuration. from_config < source > ( config: Union = None return_unused_kwargs = False **kwargs ) β†’ ModelMixin or SchedulerMixin Parameters config (Dict[str, Any]) β€”