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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
library_name: diffusers
|
| 6 |
+
tags:
|
| 7 |
+
- diffusion
|
| 8 |
+
- Conditional Diffusion
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
Here is Custom Pipeline for Class conditioned diffusion model. For training script, pipeline, tutorial nb and sampling please check my Github Repo:- https://github.com/KetanMann/Class_Conditioned_Diffusion_Training_Script
|
| 13 |
+
Here is Class Conditional Diffusion Pipeline and Sampling.
|
| 14 |
+
|
| 15 |
+
<div align="center">
|
| 16 |
+
<img src="grid_images_fer.gif" alt="Class Conditioned Diffusion GIF">
|
| 17 |
+
</div>
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
## Firstly install Requirements:-
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
!pip install diffusers
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
## For Sampling run this:-
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
```bash
|
| 32 |
+
from diffusers import UNet2DModel, DDPMScheduler
|
| 33 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 34 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
| 35 |
+
from huggingface_hub import hf_hub_download
|
| 36 |
+
import torch
|
| 37 |
+
import os
|
| 38 |
+
from PIL import Image
|
| 39 |
+
import matplotlib.pyplot as plt
|
| 40 |
+
from typing import List, Optional, Tuple, Union
|
| 41 |
+
|
| 42 |
+
class DDPMPipelinenew(DiffusionPipeline):
|
| 43 |
+
def __init__(self, unet, scheduler, num_classes: int):
|
| 44 |
+
super().__init__()
|
| 45 |
+
self.register_modules(unet=unet, scheduler=scheduler)
|
| 46 |
+
self.num_classes = num_classes
|
| 47 |
+
self._device = unet.device # Ensure the pipeline knows the device
|
| 48 |
+
|
| 49 |
+
@torch.no_grad()
|
| 50 |
+
def __call__(
|
| 51 |
+
self,
|
| 52 |
+
batch_size: int = 64,
|
| 53 |
+
class_labels: Optional[torch.Tensor] = None,
|
| 54 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 55 |
+
num_inference_steps: int = 1000,
|
| 56 |
+
output_type: Optional[str] = "pil",
|
| 57 |
+
return_dict: bool = True,
|
| 58 |
+
) -> Union[ImagePipelineOutput, Tuple]:
|
| 59 |
+
|
| 60 |
+
# Ensure class_labels is on the same device as the model
|
| 61 |
+
class_labels = class_labels.to(self._device)
|
| 62 |
+
if class_labels.ndim == 0:
|
| 63 |
+
class_labels = class_labels.unsqueeze(0).expand(batch_size)
|
| 64 |
+
else:
|
| 65 |
+
class_labels = class_labels.expand(batch_size)
|
| 66 |
+
|
| 67 |
+
# Sample gaussian noise to begin loop
|
| 68 |
+
if isinstance(self.unet.config.sample_size, int):
|
| 69 |
+
image_shape = (
|
| 70 |
+
batch_size,
|
| 71 |
+
self.unet.config.in_channels,
|
| 72 |
+
self.unet.config.sample_size,
|
| 73 |
+
self.unet.config.sample_size,
|
| 74 |
+
)
|
| 75 |
+
else:
|
| 76 |
+
image_shape = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size)
|
| 77 |
+
|
| 78 |
+
image = randn_tensor(image_shape, generator=generator, device=self._device)
|
| 79 |
+
|
| 80 |
+
# Set step values
|
| 81 |
+
self.scheduler.set_timesteps(num_inference_steps)
|
| 82 |
+
|
| 83 |
+
for t in self.progress_bar(self.scheduler.timesteps):
|
| 84 |
+
# Ensure the class labels are correctly broadcast to match the input tensor shape
|
| 85 |
+
model_output = self.unet(image, t, class_labels).sample
|
| 86 |
+
|
| 87 |
+
image = self.scheduler.step(model_output, t, image, generator=generator).prev_sample
|
| 88 |
+
|
| 89 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 90 |
+
image = image.cpu().permute(0, 2, 3, 1).numpy()
|
| 91 |
+
if output_type == "pil":
|
| 92 |
+
image = self.numpy_to_pil(image)
|
| 93 |
+
|
| 94 |
+
if not return_dict:
|
| 95 |
+
return (image,)
|
| 96 |
+
|
| 97 |
+
return ImagePipelineOutput(images=image)
|
| 98 |
+
|
| 99 |
+
def to(self, device: torch.device):
|
| 100 |
+
self._device = device
|
| 101 |
+
self.unet.to(device)
|
| 102 |
+
return self
|
| 103 |
+
|
| 104 |
+
def load_pipeline(repo_id, num_classes, device):
|
| 105 |
+
unet = UNet2DModel.from_pretrained(repo_id, subfolder="unet").to(device)
|
| 106 |
+
scheduler = DDPMScheduler.from_pretrained(repo_id, subfolder="scheduler")
|
| 107 |
+
pipeline = DDPMPipelinenew(unet=unet, scheduler=scheduler, num_classes=num_classes)
|
| 108 |
+
return pipeline.to(device) # Move the entire pipeline to the device
|
| 109 |
+
|
| 110 |
+
def save_images_locally(images, save_dir, epoch, class_label):
|
| 111 |
+
os.makedirs(save_dir, exist_ok=True)
|
| 112 |
+
for i, image in enumerate(images):
|
| 113 |
+
image_path = os.path.join(save_dir, f"image_epoch{epoch}_class{class_label}_idx{i}.png")
|
| 114 |
+
image.save(image_path)
|
| 115 |
+
|
| 116 |
+
def generate_images(pipeline, class_label, batch_size, num_inference_steps, save_dir, epoch):
|
| 117 |
+
generator = torch.Generator(device=pipeline._device).manual_seed(0)
|
| 118 |
+
class_labels = torch.tensor([class_label] * batch_size).to(pipeline._device)
|
| 119 |
+
images = pipeline(
|
| 120 |
+
generator=generator,
|
| 121 |
+
batch_size=batch_size,
|
| 122 |
+
num_inference_steps=num_inference_steps,
|
| 123 |
+
class_labels=class_labels,
|
| 124 |
+
output_type="pil",
|
| 125 |
+
).images
|
| 126 |
+
save_images_locally(images, save_dir, epoch, class_label)
|
| 127 |
+
return images
|
| 128 |
+
|
| 129 |
+
def create_image_grid(images, grid_size, save_path):
|
| 130 |
+
total_images = grid_size ** 2
|
| 131 |
+
if len(images) < total_images:
|
| 132 |
+
padding_images = total_images - len(images)
|
| 133 |
+
images += [Image.new('RGB', images[0].size)] * padding_images # Pad with blank images
|
| 134 |
+
|
| 135 |
+
width, height = images[0].size
|
| 136 |
+
grid_img = Image.new('RGB', (grid_size * width, grid_size * height))
|
| 137 |
+
|
| 138 |
+
for i, image in enumerate(images):
|
| 139 |
+
x = i % grid_size * width
|
| 140 |
+
y = i // grid_size * height
|
| 141 |
+
grid_img.paste(image, (x, y))
|
| 142 |
+
|
| 143 |
+
grid_img.save(save_path)
|
| 144 |
+
return grid_img
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
repo_id = "Ketansomewhere/King"
|
| 148 |
+
num_classes = 7 # Adjust to your number of classes
|
| 149 |
+
batch_size = 64
|
| 150 |
+
num_inference_steps = 1000 # Can be as low as 50 for faster generation
|
| 151 |
+
save_dir = "generated_images"
|
| 152 |
+
epoch = 0
|
| 153 |
+
grid_size = 8 # 8x8 grid
|
| 154 |
+
|
| 155 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 156 |
+
pipeline = load_pipeline(repo_id, num_classes, device)
|
| 157 |
+
|
| 158 |
+
for class_label in range(num_classes):
|
| 159 |
+
images = generate_images(pipeline, class_label, batch_size, num_inference_steps, save_dir, epoch)
|
| 160 |
+
|
| 161 |
+
# Create and save the grid image
|
| 162 |
+
grid_img_path = os.path.join(save_dir, f"grid_image_class{class_label}.png")
|
| 163 |
+
grid_img = create_image_grid(images, grid_size, grid_img_path)
|
| 164 |
+
|
| 165 |
+
# Plot the grid image
|
| 166 |
+
plt.figure(figsize=(10, 10))
|
| 167 |
+
plt.imshow(grid_img)
|
| 168 |
+
plt.axis('off')
|
| 169 |
+
plt.title(f'Class {class_label}')
|
| 170 |
+
plt.savefig(os.path.join(save_dir, f"grid_image_class{class_label}.png"))
|
| 171 |
+
plt.show()
|
| 172 |
+
```
|