CoolFace
Modelpublic

ApoorvBrooklyn/stable-diffusion-implementation

sourceHugging Facemitupdated 1y agoView on Hugging Face
0likes
Model Card

PyTorch Stable Diffusion Implementation

A complete, from-scratch PyTorch implementation of Stable Diffusion v1.5, featuring both text-to-image and image-to-image generation capabilities. This project demonstrates the inner workings of diffusion models by implementing all components without relying on pre-built libraries.

๐Ÿš€ Features

  • โ€”Text-to-Image Generation: Create high-quality images from text descriptions
  • โ€”Image-to-Image Generation: Transform existing images using text prompts
  • โ€”Complete Implementation: All components built from scratch in PyTorch
  • โ€”Flexible Sampling: Configurable inference steps and CFG scale
  • โ€”Model Compatibility: Support for various fine-tuned Stable Diffusion models
  • โ€”Clean Architecture: Modular design with separate components for each part of the pipeline

๐Ÿ—๏ธ Architecture

This implementation includes all the core components of Stable Diffusion:

  • โ€”CLIP Text Encoder: Processes text prompts into embeddings
  • โ€”VAE Encoder/Decoder: Handles image compression and reconstruction
  • โ€”U-Net Diffusion Model: Core denoising network with attention mechanisms
  • โ€”DDPM Sampler: Implements the denoising diffusion probabilistic model
  • โ€”Pipeline Orchestration: Coordinates all components for generation

๐Ÿ“ Project Structure

โ”œโ”€โ”€ main/
โ”‚   โ”œโ”€โ”€ attention.py      # Multi-head attention implementation
โ”‚   โ”œโ”€โ”€ clip.py           # CLIP text encoder
โ”‚   โ”œโ”€โ”€ ddpm.py           # DDPM sampling algorithm
โ”‚   โ”œโ”€โ”€ decoder.py        # VAE decoder for image reconstruction
โ”‚   โ”œโ”€โ”€ diffusion.py      # U-Net diffusion model
โ”‚   โ”œโ”€โ”€ encoder.py        # VAE encoder for image compression
โ”‚   โ”œโ”€โ”€ model_converter.py # Converts checkpoint files to PyTorch format
โ”‚   โ”œโ”€โ”€ model_loader.py   # Loads and manages model weights
โ”‚   โ”œโ”€โ”€ pipeline.py       # Main generation pipeline
โ”‚   โ””โ”€โ”€ demo.py           # Example usage and demonstration
โ”œโ”€โ”€ data/                 # Model weights and tokenizer files
โ””โ”€โ”€ images/               # Input/output images

๐Ÿ› ๏ธ Installation

Prerequisites

  • โ€”Python 3.8+
  • โ€”PyTorch 1.12+
  • โ€”Transformers library
  • โ€”PIL (Pillow)
  • โ€”NumPy
  • โ€”tqdm

Setup

  1. 1.Clone the repository:
bash
   git clone https://github.com/https://github.com/ApoorvBrooklyn/Stable-Diffusion
   cd pytorch-stable-diffusion
  1. 1.Create virtual environment:
bash
   python -m venv venv
   source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. 1.Install dependencies:
bash
   pip install torch torchvision torchaudio
   pip install transformers pillow numpy tqdm
  1. 1.Download required model files:
  2. 2.Download vocab.json and merges.txt from Stable Diffusion v1.5 tokenizer
  3. 3.Download v1-5-pruned-emaonly.ckpt from Stable Diffusion v1.5
  4. 4.Place all files in the data/ folder

๐ŸŽฏ Usage

Basic Text-to-Image Generation

python
import model_loader
import pipeline
from transformers import CLIPTokenizer

# Initialize tokenizer and load models
tokenizer = CLIPTokenizer("data/vocab.json", merges_file="data/merges.txt")
models = model_loader.preload_models_from_standard_weights("data/v1-5-pruned-emaonly.ckpt", "cpu")

# Generate image from text
output_image = pipeline.generate(
    prompt="A beautiful sunset over mountains, highly detailed, 8k resolution",
    uncond_prompt="",  # Negative prompt
    do_cfg=True,
    cfg_scale=8,
    sampler_name="ddpm",
    n_inference_steps=50,
    seed=42,
    models=models,
    device="cpu",
    tokenizer=tokenizer
)

Image-to-Image Generation

python
from PIL import Image

# Load input image
input_image = Image.open("images/input.jpg")

# Generate transformed image
output_image = pipeline.generate(
    prompt="Transform this into a watercolor painting",
    input_image=input_image,
    strength=0.8,  # Controls how much to change the input
    # ... other parameters
)

Advanced Configuration

  • โ€”CFG Scale: Controls how closely the image follows the prompt (1-14)
  • โ€”Inference Steps: More steps = higher quality but slower generation
  • โ€”Strength: For image-to-image, controls transformation intensity (0-1)
  • โ€”Seed: Set for reproducible results

๐Ÿ”ง Model Conversion

The model_converter.py script converts Stable Diffusion checkpoint files to PyTorch format:

bash
python main/model_converter.py --checkpoint_path data/v1-5-pruned-emaonly.ckpt --output_dir converted_models/

๐ŸŽจ Supported Models

This implementation is compatible with:

  • โ€”Stable Diffusion v1.5: Base model
  • โ€”Fine-tuned Models: Any SD v1.5 compatible checkpoint
  • โ€”Custom Models: Models trained on specific datasets or styles

Tested Fine-tuned Models:

  • โ€”InkPunk Diffusion: Artistic ink-style images
  • โ€”Illustration Diffusion: Hollie Mengert's illustration style

๐Ÿš€ Performance Tips

  • โ€”Device Selection: Use CUDA for GPU acceleration, MPS for Apple Silicon
  • โ€”Batch Processing: Process multiple prompts simultaneously
  • โ€”Memory Management: Use idle_device="cpu" to free GPU memory
  • โ€”Optimization: Adjust inference steps based on quality vs. speed needs

๐Ÿ”ฌ Technical Details

Diffusion Process

  • โ€”Implements DDPM (Denoising Diffusion Probabilistic Models)
  • โ€”Uses U-Net architecture with cross-attention for text conditioning
  • โ€”VAE handles 512x512 image compression to 64x64 latents

Attention Mechanisms

  • โ€”Multi-head self-attention in U-Net
  • โ€”Cross-attention between text embeddings and image features
  • โ€”Efficient attention implementation for memory optimization

Sampling

  • โ€”Configurable number of denoising steps
  • โ€”Classifier-free guidance (CFG) for prompt adherence
  • โ€”Deterministic generation with seed control

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit pull requests or open issues for:

  • โ€”Bug fixes
  • โ€”Performance improvements
  • โ€”New sampling algorithms
  • โ€”Additional model support
  • โ€”Documentation improvements

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • โ€”Stability AI for the original Stable Diffusion model
  • โ€”OpenAI for the CLIP architecture
  • โ€”CompVis for the VAE implementation
  • โ€”Hugging Face for the transformers library

๐Ÿ“š References

๐Ÿ“ž Support

If you encounter any issues or have questions:

  • โ€”Open an issue on GitHub
  • โ€”Check the existing documentation
  • โ€”Review the demo code for examples

Note: This is a research and educational implementation. For production use, consider using the official Stable Diffusion implementations or cloud-based APIs.