text stringlengths 0 5.54k |
|---|
< |
source |
> |
( |
gpu_id = 0 |
) |
Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared |
to enable_sequential_cpu_offload, this method moves one whole model at a time to the GPU when its forward |
method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with |
enable_sequential_cpu_offload, but performance is much better due to the iterative execution of the unet. |
enable_sequential_cpu_offload |
< |
source |
> |
( |
gpu_id = 0 |
) |
Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet, |
text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a |
torch.device('meta') and loaded to GPU only when their specific submodule has its forwardmethod called. Note that offloading happens on a submodule basis. Memory savings are higher than withenable_model_cpu_offload`, but performance is lower. |
VQ Diffusion Vector Quantized Diffusion Model for Text-to-Image Synthesis is by Shuyang Gu, Dong Chen, Jianmin Bao, Fang Wen, Bo Zhang, Dongdong Chen, Lu Yuan, Baining Guo. The abstract from the paper is: We present the vector quantized diffusion (VQ-Diffusion) model for text-to-image generation. This method is based on a vector quantized variational autoencoder (VQ-VAE) whose latent space is modeled by a conditional variant of the recently developed Denoising Diffusion Probabilistic Model (DDPM). We find that this latent-space method is well-suited for text-to-image generation tasks because it not only eliminates the unidirectional bias with existing methods but also allows us to incorporate a mask-and-replace diffusion strategy to avoid the accumulation of errors, which is a serious problem with existing methods. Our experiments show that the VQ-Diffusion produces significantly better text-to-image generation results when compared with conventional autoregressive (AR) models with similar numbers of parameters. Compared with previous GAN-based text-to-image methods, our VQ-Diffusion can handle more complex scenes and improve the synthesized image quality by a large margin. Finally, we show that the image generation computation in our method can be made highly efficient by reparameterization. With traditional AR methods, the text-to-image generation time increases linearly with the output image resolution and hence is quite time consuming even for normal size images. The VQ-Diffusion allows us to achieve a better trade-off between quality and speed. Our experiments indicate that the VQ-Diffusion model with the reparameterization is fifteen times faster than traditional AR methods while achieving a better image quality. The original codebase can be found at microsoft/VQ-Diffusion. Make sure to check out the Schedulers guide to learn how to explore the tradeoff between scheduler speed and quality, and see the reuse components across pipelines section to learn how to efficiently load the same components into multiple pipelines. VQDiffusionPipeline class diffusers.VQDiffusionPipeline < source > ( vqvae: VQModel text_encoder: CLIPTextModel tokenizer: CLIPTokenizer transformer: Transformer2DModel scheduler: VQDiffusionScheduler learned_classifier_free_sampling_embeddings: LearnedClassifierFreeSamplingEmbeddings ) Parameters vqvae (VQModel) β |
Vector Quantized Variational Auto-Encoder (VAE) model to encode and decode images to and from latent |
representations. text_encoder (CLIPTextModel) β |
Frozen text-encoder (clip-vit-base-patch32). tokenizer (CLIPTokenizer) β |
A CLIPTokenizer to tokenize text. transformer (Transformer2DModel) β |
A conditional Transformer2DModel to denoise the encoded image latents. scheduler (VQDiffusionScheduler) β |
A scheduler to be used in combination with transformer to denoise the encoded image latents. Pipeline for text-to-image generation using VQ Diffusion. 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.). __call__ < source > ( prompt: typing.Union[str, typing.List[str]] num_inference_steps: int = 100 guidance_scale: float = 5.0 truncation_rate: float = 1.0 num_images_per_prompt: int = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Union[typing.Callable[[int, int, torch.FloatTensor], NoneType], NoneType] = None callback_steps: int = 1 ) β ImagePipelineOutput or tuple Parameters prompt (str or List[str]) β |
The prompt or prompts to guide image generation. num_inference_steps (int, optional, defaults to 100) β |
The number of denoising steps. More denoising steps usually lead to a higher quality image at the |
expense of slower inference. guidance_scale (float, optional, defaults to 7.5) β |
A higher guidance scale value encourages the model to generate images closely linked to the text |
prompt at the expense of lower image quality. Guidance scale is enabled when guidance_scale > 1. truncation_rate (float, optional, defaults to 1.0 (equivalent to no truncation)) β |
Used to βtruncateβ the predicted classes for x_0 such that the cumulative probability for a pixel is at |
most truncation_rate. The lowest probabilities that would increase the cumulative probability above |
truncation_rate are set to zero. num_images_per_prompt (int, optional, defaults to 1) β |
The number of images to generate per prompt. generator (torch.Generator, optional) β |
A torch.Generator to make |
generation deterministic. latents (torch.FloatTensor of shape (batch), optional) β |
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image |
generation. Must be valid embedding indices.If not provided, a latents tensor will be generated of |
completely masked latent pixels. output_type (str, optional, defaults to "pil") β |
The output format of the generated image. Choose between PIL.Image or np.array. return_dict (bool, optional, defaults to True) β |
Whether or not to return a ImagePipelineOutput instead of a plain tuple. callback (Callable, optional) β |
A function that calls every callback_steps steps during inference. The function is called with the |
following arguments: callback(step: int, timestep: int, latents: torch.FloatTensor). callback_steps (int, optional, defaults to 1) β |
The frequency at which the callback function is called. If not specified, the callback is called at |
every step. Returns |
ImagePipelineOutput or tuple |
If return_dict is True, ImagePipelineOutput is returned, otherwise a tuple is |
returned where the first element is a list with the generated images. |
The call function to the pipeline for generation. truncate < source > ( log_p_x_0: FloatTensor truncation_rate: float ) Truncates log_p_x_0 such that for each column vector, the total cumulative probability is truncation_rate |
The lowest probabilities that would increase the cumulative probability above truncation_rate are set to |
zero. ImagePipelineOutput class diffusers.ImagePipelineOutput < source > ( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] ) Parameters images (List[PIL.Image.Image] or np.ndarray) β |
List of denoised PIL images of length batch_size or NumPy array of shape (batch_size, height, width, num_channels). Output class for image pipelines. |
Models π€ Diffusers provides pretrained models for popular algorithms and modules to create custom diffusion systems. The primary function of models is to denoise an input sample as modeled by the distribution pΞΈ(xtβ1β£xt)p_{\theta}(x_{t-1}|x_{t})pΞΈβ(xtβ1ββ£xtβ). All models are built from the base ModelMixin class which is a torch.nn.Module providing basic functionality for saving and loading models, locally and from the Hugging Face Hub. ModelMixin class diffusers.ModelMixin < source > ( ) Base class for all models. ModelMixin takes care of storing the model configuration and provides methods for loading, downloading and |
saving models. config_name (str) β Filename to save a model to when calling save_pretrained(). disable_gradient_checkpointing < source > ( ) Deactivates gradient checkpointing for the current model (may be referred to as activation checkpointing or |
checkpoint activations in other frameworks). disable_xformers_memory_efficient_attention < source > ( ) Disable memory efficient attention from xFormers. enable_gradient_checkpointing < source > ( ) Activates gradient checkpointing for the current model (may be referred to as activation checkpointing or |
checkpoint activations in other frameworks). enable_xformers_memory_efficient_attention < source > ( attention_op: Optional = None ) Parameters attention_op (Callable, optional) β |
Override the default None operator for use as op argument to the |
memory_efficient_attention() |
function of xFormers. Enable memory efficient attention from xFormers. When this option is enabled, you should observe lower GPU memory usage and a potential speed up during |
inference. Speed up during training is not guaranteed. β οΈ When memory efficient attention and sliced attention are both enabled, memory efficient attention takes |
precedent. Examples: Copied >>> import torch |
>>> from diffusers import UNet2DConditionModel |
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp |
>>> model = UNet2DConditionModel.from_pretrained( |
... "stabilityai/stable-diffusion-2-1", subfolder="unet", torch_dtype=torch.float16 |
... ) |
>>> model = model.to("cuda") |
>>> model.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp) from_pretrained < source > ( pretrained_model_name_or_path: Union **kwargs ) 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 the model weights saved |
with save_pretrained(). |
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. torch_dtype (str or torch.dtype, optional) β |
Override the default torch.dtype and load the model with another dtype. If "auto" is passed, the |
dtype is automatically derived from the modelβs weights. 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) β |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.