# Imagen-pytorch

> PyTorch implementation of Google's Imagen text-to-image diffusion model

- Category: Multimodal Generation / Image Generation
- Language: Python
- Licence: MIT
- Repository: https://github.com/lucidrains/imagen-pytorch
- Canonical page: https://ai-tldr.dev/tools/imagen-pytorch/

## In short

Imagen-pytorch is an open-source PyTorch implementation of Imagen, Google's text-to-image neural network. It turns a text prompt into an image using diffusion models guided by text embeddings from a large pretrained T5 language model. It sits in the Image Generation category of the Multimodal Generation tools and is open-source, written in Python and licensed MIT.

## Overview

Imagen-pytorch is an open-source PyTorch implementation of Imagen, Google's text-to-image neural network. It turns a text prompt into an image using diffusion models guided by text embeddings from a large pretrained T5 language model.

Architecturally it is a cascading DDPM (denoising diffusion probabilistic model): a base U-Net generates a small image, then super-resolution U-Nets upscale it. The design adds dynamic clipping for better classifier-free guidance, noise-level conditioning, and a memory-efficient U-Net. Notably, it needs neither CLIP nor a prior network.

The project is built for researchers and engineers who want to train or experiment with Imagen-style models themselves. It ships a simple API plus an ImagenTrainer wrapper that handles details like exponential moving averages and gradient accumulation across the U-Net cascade.

## What it does

- Cascading diffusion architecture: a base U-Net plus super-resolution U-Nets that progressively upscale generated images (for example 64px to 256px)
- Text conditioning on embeddings from a large pretrained T5 encoder, with model names like t5-large selectable
- Dynamic thresholding and classifier-free guidance via a cond_scale argument for stronger prompt adherence
- ImagenTrainer wrapper that automates exponential moving averages, checkpointing, and gradient accumulation with max_batch_size
- Accepts raw text strings directly, or precomputed text embeddings and masks for scaling up training
- Supports unconditional (text-free) image generation and a memory-efficient U-Net design for lower VRAM use

## Getting started

Install the package from PyPI, then define your U-Nets, wrap them in an Imagen model, train each U-Net in the cascade, and sample images from text prompts.

1. Install the package

   Install imagen-pytorch from PyPI with pip.

```bash
$ pip install imagen-pytorch
```

2. Build the U-Net cascade and Imagen model

   Define a base U-Net and a super-resolution U-Net, then pass them to Imagen along with the target image sizes. Move it to the GPU with .cuda().

```python
import torch
from imagen_pytorch import Unet, Imagen

unet1 = Unet(
    dim = 32,
    cond_dim = 512,
    dim_mults = (1, 2, 4, 8),
    num_resnet_blocks = 3,
    layer_attns = (False, True, True, True),
    layer_cross_attns = (False, True, True, True)
)

unet2 = Unet(
    dim = 32,
    cond_dim = 512,
    dim_mults = (1, 2, 4, 8),
    num_resnet_blocks = (2, 4, 8, 8),
    layer_attns = (False, False, False, True),
    layer_cross_attns = (False, False, False, True)
)

imagen = Imagen(
    unets = (unet1, unet2),
    image_sizes = (64, 256),
    timesteps = 1000,
    cond_drop_prob = 0.1
).cuda()
```

3. Train each U-Net on images and text

   Feed images and T5 text embeddings into Imagen, training each U-Net in the cascade by passing its unet_number. Repeat for many steps.

```python
text_embeds = torch.randn(4, 256, 768).cuda()
images = torch.randn(4, 3, 256, 256).cuda()

for i in (1, 2):
    loss = imagen(images, text_embeds = text_embeds, unet_number = i)
    loss.backward()
```

4. Sample images from text prompts

   Once trained, generate images from a list of text prompts. The cond_scale argument controls classifier-free guidance strength.

```python
images = imagen.sample(texts = [
    'a whale breaching from afar',
    'young girl blowing out candles on her birthday cake',
    'fireworks with blue and green sparkles'
], cond_scale = 3.)

images.shape # (3, 3, 256, 256)
```

## When to use it

- Train an Imagen-style text-to-image diffusion model from scratch on your own image and caption dataset
- Research and experiment with cascading DDPMs, T5 text conditioning, and classifier-free guidance
- Generate images from text prompts after training, with adjustable guidance strength
- Run unconditional image generation when you do not have paired text captions
