Instructions to use BiliSakura/ADM-diffusers with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use BiliSakura/ADM-diffusers with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("BiliSakura/ADM-diffusers", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
- Local Apps
- Draw Things
- DiffusionBee
Upload folder using huggingface_hub
Browse files- .gitattributes +1 -0
- ADM-G-512/classifier/__pycache__/classifier_adm.cpython-312.pyc +0 -0
- ADM-G-512/classifier/classifier_adm.py +132 -0
- ADM-G-512/classifier/config.json +13 -0
- ADM-G-512/classifier/diffusion_pytorch_model.safetensors +3 -0
- ADM-G-512/classifier/modeling_adm.py +772 -0
- ADM-G-512/scheduler/__pycache__/scheduling_adm.cpython-312.pyc +0 -0
- ADM-G-512/scheduler/scheduler_config.json +11 -0
- ADM-G-512/scheduler/scheduling_adm.py +590 -0
- ADM-G-512/unet/__pycache__/modeling_adm.cpython-312.pyc +0 -0
- ADM-G-512/unet/__pycache__/unet_adm.cpython-312.pyc +0 -0
- ADM-G-512/unet/config.json +22 -0
- ADM-G-512/unet/diffusion_pytorch_model.safetensors +3 -0
- ADM-G-512/unet/modeling_adm.py +772 -0
- ADM-G-512/unet/unet_adm.py +124 -0
- README.md +87 -0
- __pycache__/pipeline.cpython-312.pyc +0 -0
- demo.png +3 -0
- model_index.json +16 -0
- pipeline.py +388 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
demo.png filter=lfs diff=lfs merge=lfs -text
|
ADM-G-512/classifier/__pycache__/classifier_adm.cpython-312.pyc
ADDED
|
Binary file (6.37 kB). View file
|
|
|
ADM-G-512/classifier/classifier_adm.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import Optional, Tuple, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 13 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 14 |
+
from diffusers.utils import BaseOutput
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from modeling_adm import create_adm_classifier_model
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class ADMClassifierOutput(BaseOutput):
|
| 22 |
+
"""
|
| 23 |
+
Output of the ADM noisy image classifier.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
logits (`torch.Tensor` of shape `(batch_size, num_classes)`):
|
| 27 |
+
Class logits for the noisy input.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
logits: torch.FloatTensor
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ADMClassifierModel(ModelMixin, ConfigMixin):
|
| 34 |
+
"""
|
| 35 |
+
Noisy ImageNet classifier for ADM-G classifier guidance.
|
| 36 |
+
|
| 37 |
+
This model predicts class labels from noisy images `x_t` and is used to compute gradients that steer
|
| 38 |
+
an unconditional ADM diffusion model toward a target class.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
@register_to_config
|
| 42 |
+
def __init__(
|
| 43 |
+
self,
|
| 44 |
+
image_size: int = 128,
|
| 45 |
+
classifier_width: int = 128,
|
| 46 |
+
classifier_depth: int = 2,
|
| 47 |
+
classifier_attention_resolutions: str = "32,16,8",
|
| 48 |
+
classifier_use_scale_shift_norm: bool = True,
|
| 49 |
+
classifier_resblock_updown: bool = True,
|
| 50 |
+
classifier_pool: str = "attention",
|
| 51 |
+
use_fp16: bool = False,
|
| 52 |
+
num_classes: int = 1000,
|
| 53 |
+
):
|
| 54 |
+
super().__init__()
|
| 55 |
+
self.model = create_adm_classifier_model(
|
| 56 |
+
image_size=image_size,
|
| 57 |
+
classifier_width=classifier_width,
|
| 58 |
+
classifier_depth=classifier_depth,
|
| 59 |
+
classifier_attention_resolutions=classifier_attention_resolutions,
|
| 60 |
+
classifier_use_scale_shift_norm=classifier_use_scale_shift_norm,
|
| 61 |
+
classifier_resblock_updown=classifier_resblock_updown,
|
| 62 |
+
classifier_pool=classifier_pool,
|
| 63 |
+
use_fp16=use_fp16,
|
| 64 |
+
num_classes=num_classes,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
@property
|
| 68 |
+
def dtype(self) -> torch.dtype:
|
| 69 |
+
return next(self.parameters()).dtype
|
| 70 |
+
|
| 71 |
+
def forward(
|
| 72 |
+
self,
|
| 73 |
+
sample: torch.Tensor,
|
| 74 |
+
timestep: Union[torch.Tensor, float, int],
|
| 75 |
+
return_dict: bool = True,
|
| 76 |
+
) -> Union[ADMClassifierOutput, Tuple[torch.Tensor, ...]]:
|
| 77 |
+
"""
|
| 78 |
+
Args:
|
| 79 |
+
sample (`torch.Tensor`):
|
| 80 |
+
Noisy image `(batch_size, 3, height, width)` in `[-1, 1]`.
|
| 81 |
+
timestep (`torch.Tensor` or `float` or `int`):
|
| 82 |
+
Diffusion timestep indices (respaced indices during ADM-G sampling).
|
| 83 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 84 |
+
Whether to return an [`ADMClassifierOutput`].
|
| 85 |
+
|
| 86 |
+
Returns:
|
| 87 |
+
[`ADMClassifierOutput`] or `tuple`:
|
| 88 |
+
Classifier logits.
|
| 89 |
+
"""
|
| 90 |
+
if not torch.is_tensor(timestep):
|
| 91 |
+
timestep = torch.tensor([timestep], device=sample.device, dtype=torch.long)
|
| 92 |
+
elif timestep.ndim == 0:
|
| 93 |
+
timestep = timestep.reshape(1).to(device=sample.device)
|
| 94 |
+
if timestep.shape[0] == 1 and sample.shape[0] > 1:
|
| 95 |
+
timestep = timestep.expand(sample.shape[0])
|
| 96 |
+
|
| 97 |
+
logits = self.model(sample, timestep)
|
| 98 |
+
if not return_dict:
|
| 99 |
+
return (logits,)
|
| 100 |
+
return ADMClassifierOutput(logits=logits)
|
| 101 |
+
|
| 102 |
+
def guidance_gradient(
|
| 103 |
+
self,
|
| 104 |
+
sample: torch.Tensor,
|
| 105 |
+
timestep: torch.Tensor,
|
| 106 |
+
class_labels: torch.Tensor,
|
| 107 |
+
classifier_scale: float = 1.0,
|
| 108 |
+
) -> torch.Tensor:
|
| 109 |
+
"""
|
| 110 |
+
Compute `classifier_scale * grad_x log p(y | x_t)` for classifier guidance (ADM-G).
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
sample (`torch.Tensor`):
|
| 114 |
+
Current noisy sample `x_t`.
|
| 115 |
+
timestep (`torch.Tensor`):
|
| 116 |
+
Respaced diffusion timestep indices.
|
| 117 |
+
class_labels (`torch.Tensor`):
|
| 118 |
+
Target ImageNet class indices of shape `(batch_size,)`.
|
| 119 |
+
classifier_scale (`float`, *optional*, defaults to 1.0):
|
| 120 |
+
Guidance strength (OpenAI `classifier_scale`).
|
| 121 |
+
|
| 122 |
+
Returns:
|
| 123 |
+
`torch.Tensor`:
|
| 124 |
+
Gradient with respect to `sample`, same shape as `sample`.
|
| 125 |
+
"""
|
| 126 |
+
with torch.enable_grad():
|
| 127 |
+
x_in = sample.detach().requires_grad_(True)
|
| 128 |
+
logits = self.model(x_in, timestep)
|
| 129 |
+
log_probs = F.log_softmax(logits, dim=-1)
|
| 130 |
+
selected = log_probs[torch.arange(logits.shape[0], device=logits.device), class_labels.view(-1)]
|
| 131 |
+
grad = torch.autograd.grad(selected.sum(), x_in)[0]
|
| 132 |
+
return grad * classifier_scale
|
ADM-G-512/classifier/config.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "ADMClassifierModel",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"classifier_attention_resolutions": "32,16,8",
|
| 5 |
+
"classifier_depth": 2,
|
| 6 |
+
"classifier_pool": "attention",
|
| 7 |
+
"classifier_resblock_updown": true,
|
| 8 |
+
"classifier_use_scale_shift_norm": true,
|
| 9 |
+
"classifier_width": 128,
|
| 10 |
+
"image_size": 512,
|
| 11 |
+
"num_classes": 1000,
|
| 12 |
+
"use_fp16": true
|
| 13 |
+
}
|
ADM-G-512/classifier/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c7fcf8bb2545d8f93e0de2915c3144c78532c0707709ccf81366b9fbf22cb384
|
| 3 |
+
size 217824392
|
ADM-G-512/classifier/modeling_adm.py
ADDED
|
@@ -0,0 +1,772 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from abc import abstractmethod
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from torch.utils.checkpoint import checkpoint as torch_checkpoint
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
NUM_CLASSES = 1000
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def conv_nd(dims: int, *args, **kwargs):
|
| 15 |
+
if dims == 1:
|
| 16 |
+
return nn.Conv1d(*args, **kwargs)
|
| 17 |
+
if dims == 2:
|
| 18 |
+
return nn.Conv2d(*args, **kwargs)
|
| 19 |
+
if dims == 3:
|
| 20 |
+
return nn.Conv3d(*args, **kwargs)
|
| 21 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def linear(*args, **kwargs):
|
| 25 |
+
return nn.Linear(*args, **kwargs)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def avg_pool_nd(dims: int, *args, **kwargs):
|
| 29 |
+
if dims == 1:
|
| 30 |
+
return nn.AvgPool1d(*args, **kwargs)
|
| 31 |
+
if dims == 2:
|
| 32 |
+
return nn.AvgPool2d(*args, **kwargs)
|
| 33 |
+
if dims == 3:
|
| 34 |
+
return nn.AvgPool3d(*args, **kwargs)
|
| 35 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class GroupNorm32(nn.GroupNorm):
|
| 39 |
+
def forward(self, x):
|
| 40 |
+
return super().forward(x.float()).type(x.dtype)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def normalization(channels: int):
|
| 44 |
+
return GroupNorm32(32, channels)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def zero_module(module: nn.Module):
|
| 48 |
+
for p in module.parameters():
|
| 49 |
+
p.detach().zero_()
|
| 50 |
+
return module
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def timestep_embedding(timesteps: torch.Tensor, dim: int, max_period: int = 10000):
|
| 54 |
+
half = dim // 2
|
| 55 |
+
freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
|
| 56 |
+
device=timesteps.device
|
| 57 |
+
)
|
| 58 |
+
args = timesteps[:, None].float() * freqs[None]
|
| 59 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 60 |
+
if dim % 2:
|
| 61 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 62 |
+
return embedding
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def convert_module_to_f16(module: nn.Module):
|
| 66 |
+
if isinstance(module, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
|
| 67 |
+
module.weight.data = module.weight.data.half()
|
| 68 |
+
if module.bias is not None:
|
| 69 |
+
module.bias.data = module.bias.data.half()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def convert_module_to_f32(module: nn.Module):
|
| 73 |
+
if isinstance(module, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
|
| 74 |
+
module.weight.data = module.weight.data.float()
|
| 75 |
+
if module.bias is not None:
|
| 76 |
+
module.bias.data = module.bias.data.float()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class TimestepBlock(nn.Module):
|
| 80 |
+
@abstractmethod
|
| 81 |
+
def forward(self, x, emb):
|
| 82 |
+
raise NotImplementedError
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
|
| 86 |
+
def forward(self, x, emb):
|
| 87 |
+
for layer in self:
|
| 88 |
+
if isinstance(layer, TimestepBlock):
|
| 89 |
+
x = layer(x, emb)
|
| 90 |
+
else:
|
| 91 |
+
x = layer(x)
|
| 92 |
+
return x
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class Upsample(nn.Module):
|
| 96 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None):
|
| 97 |
+
super().__init__()
|
| 98 |
+
self.channels = channels
|
| 99 |
+
self.out_channels = out_channels or channels
|
| 100 |
+
self.use_conv = use_conv
|
| 101 |
+
self.dims = dims
|
| 102 |
+
if use_conv:
|
| 103 |
+
self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=1)
|
| 104 |
+
|
| 105 |
+
def forward(self, x):
|
| 106 |
+
assert x.shape[1] == self.channels
|
| 107 |
+
if self.dims == 3:
|
| 108 |
+
x = F.interpolate(x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest")
|
| 109 |
+
else:
|
| 110 |
+
x = F.interpolate(x, scale_factor=2, mode="nearest")
|
| 111 |
+
if self.use_conv:
|
| 112 |
+
x = self.conv(x)
|
| 113 |
+
return x
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class Downsample(nn.Module):
|
| 117 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.channels = channels
|
| 120 |
+
self.out_channels = out_channels or channels
|
| 121 |
+
self.use_conv = use_conv
|
| 122 |
+
stride = 2 if dims != 3 else (1, 2, 2)
|
| 123 |
+
if use_conv:
|
| 124 |
+
self.op = conv_nd(dims, self.channels, self.out_channels, 3, stride=stride, padding=1)
|
| 125 |
+
else:
|
| 126 |
+
assert self.channels == self.out_channels
|
| 127 |
+
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
|
| 128 |
+
|
| 129 |
+
def forward(self, x):
|
| 130 |
+
assert x.shape[1] == self.channels
|
| 131 |
+
return self.op(x)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class ResBlock(TimestepBlock):
|
| 135 |
+
def __init__(
|
| 136 |
+
self,
|
| 137 |
+
channels,
|
| 138 |
+
emb_channels,
|
| 139 |
+
dropout,
|
| 140 |
+
out_channels=None,
|
| 141 |
+
use_conv=False,
|
| 142 |
+
use_scale_shift_norm=False,
|
| 143 |
+
dims=2,
|
| 144 |
+
use_checkpoint=False,
|
| 145 |
+
up=False,
|
| 146 |
+
down=False,
|
| 147 |
+
):
|
| 148 |
+
super().__init__()
|
| 149 |
+
self.channels = channels
|
| 150 |
+
self.out_channels = out_channels or channels
|
| 151 |
+
self.use_checkpoint = use_checkpoint
|
| 152 |
+
self.use_scale_shift_norm = use_scale_shift_norm
|
| 153 |
+
self.in_layers = nn.Sequential(
|
| 154 |
+
normalization(channels),
|
| 155 |
+
nn.SiLU(),
|
| 156 |
+
conv_nd(dims, channels, self.out_channels, 3, padding=1),
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
self.updown = up or down
|
| 160 |
+
if up:
|
| 161 |
+
self.h_upd = Upsample(channels, False, dims)
|
| 162 |
+
self.x_upd = Upsample(channels, False, dims)
|
| 163 |
+
elif down:
|
| 164 |
+
self.h_upd = Downsample(channels, False, dims)
|
| 165 |
+
self.x_upd = Downsample(channels, False, dims)
|
| 166 |
+
else:
|
| 167 |
+
self.h_upd = self.x_upd = nn.Identity()
|
| 168 |
+
|
| 169 |
+
self.emb_layers = nn.Sequential(
|
| 170 |
+
nn.SiLU(),
|
| 171 |
+
linear(emb_channels, 2 * self.out_channels if use_scale_shift_norm else self.out_channels),
|
| 172 |
+
)
|
| 173 |
+
self.out_layers = nn.Sequential(
|
| 174 |
+
normalization(self.out_channels),
|
| 175 |
+
nn.SiLU(),
|
| 176 |
+
nn.Dropout(p=dropout),
|
| 177 |
+
zero_module(conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)),
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
if self.out_channels == channels:
|
| 181 |
+
self.skip_connection = nn.Identity()
|
| 182 |
+
elif use_conv:
|
| 183 |
+
self.skip_connection = conv_nd(dims, channels, self.out_channels, 3, padding=1)
|
| 184 |
+
else:
|
| 185 |
+
self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
|
| 186 |
+
|
| 187 |
+
def forward(self, x, emb):
|
| 188 |
+
if self.use_checkpoint and x.requires_grad:
|
| 189 |
+
return torch_checkpoint(self._forward, x, emb, use_reentrant=False)
|
| 190 |
+
return self._forward(x, emb)
|
| 191 |
+
|
| 192 |
+
def _forward(self, x, emb):
|
| 193 |
+
if self.updown:
|
| 194 |
+
in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
|
| 195 |
+
h = in_rest(x)
|
| 196 |
+
h = self.h_upd(h)
|
| 197 |
+
x = self.x_upd(x)
|
| 198 |
+
h = in_conv(h)
|
| 199 |
+
else:
|
| 200 |
+
h = self.in_layers(x)
|
| 201 |
+
|
| 202 |
+
emb_out = self.emb_layers(emb).type(h.dtype)
|
| 203 |
+
while len(emb_out.shape) < len(h.shape):
|
| 204 |
+
emb_out = emb_out[..., None]
|
| 205 |
+
if self.use_scale_shift_norm:
|
| 206 |
+
out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
|
| 207 |
+
scale, shift = torch.chunk(emb_out, 2, dim=1)
|
| 208 |
+
h = out_norm(h) * (1 + scale) + shift
|
| 209 |
+
h = out_rest(h)
|
| 210 |
+
else:
|
| 211 |
+
h = h + emb_out
|
| 212 |
+
h = self.out_layers(h)
|
| 213 |
+
return self.skip_connection(x) + h
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class QKVAttentionLegacy(nn.Module):
|
| 217 |
+
def __init__(self, n_heads):
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.n_heads = n_heads
|
| 220 |
+
|
| 221 |
+
def forward(self, qkv):
|
| 222 |
+
bs, width, length = qkv.shape
|
| 223 |
+
assert width % (3 * self.n_heads) == 0
|
| 224 |
+
ch = width // (3 * self.n_heads)
|
| 225 |
+
q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
|
| 226 |
+
scale = 1 / math.sqrt(math.sqrt(ch))
|
| 227 |
+
weight = torch.einsum("bct,bcs->bts", q * scale, k * scale)
|
| 228 |
+
weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
|
| 229 |
+
a = torch.einsum("bts,bcs->bct", weight, v)
|
| 230 |
+
return a.reshape(bs, -1, length)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class QKVAttention(nn.Module):
|
| 234 |
+
def __init__(self, n_heads):
|
| 235 |
+
super().__init__()
|
| 236 |
+
self.n_heads = n_heads
|
| 237 |
+
|
| 238 |
+
def forward(self, qkv):
|
| 239 |
+
bs, width, length = qkv.shape
|
| 240 |
+
assert width % (3 * self.n_heads) == 0
|
| 241 |
+
ch = width // (3 * self.n_heads)
|
| 242 |
+
q, k, v = qkv.chunk(3, dim=1)
|
| 243 |
+
scale = 1 / math.sqrt(math.sqrt(ch))
|
| 244 |
+
weight = torch.einsum(
|
| 245 |
+
"bct,bcs->bts",
|
| 246 |
+
(q * scale).view(bs * self.n_heads, ch, length),
|
| 247 |
+
(k * scale).view(bs * self.n_heads, ch, length),
|
| 248 |
+
)
|
| 249 |
+
weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
|
| 250 |
+
a = torch.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
|
| 251 |
+
return a.reshape(bs, -1, length)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class AttentionBlock(nn.Module):
|
| 255 |
+
def __init__(
|
| 256 |
+
self,
|
| 257 |
+
channels,
|
| 258 |
+
num_heads=1,
|
| 259 |
+
num_head_channels=-1,
|
| 260 |
+
use_checkpoint=False,
|
| 261 |
+
use_new_attention_order=False,
|
| 262 |
+
):
|
| 263 |
+
super().__init__()
|
| 264 |
+
if num_head_channels == -1:
|
| 265 |
+
self.num_heads = num_heads
|
| 266 |
+
else:
|
| 267 |
+
assert channels % num_head_channels == 0
|
| 268 |
+
self.num_heads = channels // num_head_channels
|
| 269 |
+
self.use_checkpoint = use_checkpoint
|
| 270 |
+
self.norm = normalization(channels)
|
| 271 |
+
self.qkv = conv_nd(1, channels, channels * 3, 1)
|
| 272 |
+
self.attention = QKVAttention(self.num_heads) if use_new_attention_order else QKVAttentionLegacy(self.num_heads)
|
| 273 |
+
self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
|
| 274 |
+
|
| 275 |
+
def forward(self, x):
|
| 276 |
+
if self.use_checkpoint and x.requires_grad:
|
| 277 |
+
return torch_checkpoint(self._forward, x, use_reentrant=False)
|
| 278 |
+
return self._forward(x)
|
| 279 |
+
|
| 280 |
+
def _forward(self, x):
|
| 281 |
+
b, c, *spatial = x.shape
|
| 282 |
+
x = x.reshape(b, c, -1)
|
| 283 |
+
qkv = self.qkv(self.norm(x))
|
| 284 |
+
h = self.attention(qkv)
|
| 285 |
+
h = self.proj_out(h)
|
| 286 |
+
return (x + h).reshape(b, c, *spatial)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
class AttentionPool2d(nn.Module):
|
| 290 |
+
"""CLIP-style attention pooling used by ADM noisy classifiers."""
|
| 291 |
+
|
| 292 |
+
def __init__(self, spacial_dim: int, embed_dim: int, num_heads_channels: int, output_dim: int = None):
|
| 293 |
+
super().__init__()
|
| 294 |
+
self.positional_embedding = nn.Parameter(torch.randn(embed_dim, spacial_dim**2 + 1) / embed_dim**0.5)
|
| 295 |
+
self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
|
| 296 |
+
self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
|
| 297 |
+
self.num_heads = embed_dim // num_heads_channels
|
| 298 |
+
self.attention = QKVAttention(self.num_heads)
|
| 299 |
+
|
| 300 |
+
def forward(self, x):
|
| 301 |
+
b, c, *_spatial = x.shape
|
| 302 |
+
x = x.reshape(b, c, -1)
|
| 303 |
+
x = torch.cat([x.mean(dim=-1, keepdim=True), x], dim=-1)
|
| 304 |
+
x = x + self.positional_embedding[None, :, :].to(x.dtype)
|
| 305 |
+
x = self.qkv_proj(x)
|
| 306 |
+
x = self.attention(x)
|
| 307 |
+
x = self.c_proj(x)
|
| 308 |
+
return x[:, :, 0]
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class EncoderUNetModel(nn.Module):
|
| 312 |
+
"""Noisy image classifier backbone for ADM-G (classifier guidance)."""
|
| 313 |
+
|
| 314 |
+
def __init__(
|
| 315 |
+
self,
|
| 316 |
+
image_size,
|
| 317 |
+
in_channels,
|
| 318 |
+
model_channels,
|
| 319 |
+
out_channels,
|
| 320 |
+
num_res_blocks,
|
| 321 |
+
attention_resolutions,
|
| 322 |
+
dropout=0,
|
| 323 |
+
channel_mult=(1, 2, 4, 8),
|
| 324 |
+
conv_resample=True,
|
| 325 |
+
dims=2,
|
| 326 |
+
use_checkpoint=False,
|
| 327 |
+
use_fp16=False,
|
| 328 |
+
num_heads=1,
|
| 329 |
+
num_head_channels=-1,
|
| 330 |
+
use_scale_shift_norm=False,
|
| 331 |
+
resblock_updown=False,
|
| 332 |
+
use_new_attention_order=False,
|
| 333 |
+
pool="adaptive",
|
| 334 |
+
):
|
| 335 |
+
super().__init__()
|
| 336 |
+
|
| 337 |
+
self.in_channels = in_channels
|
| 338 |
+
self.model_channels = model_channels
|
| 339 |
+
self.out_channels = out_channels
|
| 340 |
+
self.num_res_blocks = num_res_blocks
|
| 341 |
+
self.dropout = dropout
|
| 342 |
+
self.channel_mult = channel_mult
|
| 343 |
+
self.conv_resample = conv_resample
|
| 344 |
+
self.use_checkpoint = use_checkpoint
|
| 345 |
+
self.dtype = torch.float16 if use_fp16 else torch.float32
|
| 346 |
+
self.num_heads = num_heads
|
| 347 |
+
self.num_head_channels = num_head_channels
|
| 348 |
+
|
| 349 |
+
time_embed_dim = model_channels * 4
|
| 350 |
+
self.time_embed = nn.Sequential(
|
| 351 |
+
linear(model_channels, time_embed_dim),
|
| 352 |
+
nn.SiLU(),
|
| 353 |
+
linear(time_embed_dim, time_embed_dim),
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
ch = int(channel_mult[0] * model_channels)
|
| 357 |
+
self.input_blocks = nn.ModuleList([TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))])
|
| 358 |
+
self._feature_size = ch
|
| 359 |
+
input_block_chans = [ch]
|
| 360 |
+
ds = 1
|
| 361 |
+
for level, mult in enumerate(channel_mult):
|
| 362 |
+
for _ in range(num_res_blocks):
|
| 363 |
+
layers = [
|
| 364 |
+
ResBlock(
|
| 365 |
+
ch,
|
| 366 |
+
time_embed_dim,
|
| 367 |
+
dropout,
|
| 368 |
+
out_channels=int(mult * model_channels),
|
| 369 |
+
dims=dims,
|
| 370 |
+
use_checkpoint=use_checkpoint,
|
| 371 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 372 |
+
)
|
| 373 |
+
]
|
| 374 |
+
ch = int(mult * model_channels)
|
| 375 |
+
if ds in attention_resolutions:
|
| 376 |
+
layers.append(
|
| 377 |
+
AttentionBlock(
|
| 378 |
+
ch,
|
| 379 |
+
use_checkpoint=use_checkpoint,
|
| 380 |
+
num_heads=num_heads,
|
| 381 |
+
num_head_channels=num_head_channels,
|
| 382 |
+
use_new_attention_order=use_new_attention_order,
|
| 383 |
+
)
|
| 384 |
+
)
|
| 385 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
| 386 |
+
self._feature_size += ch
|
| 387 |
+
input_block_chans.append(ch)
|
| 388 |
+
if level != len(channel_mult) - 1:
|
| 389 |
+
out_ch = ch
|
| 390 |
+
self.input_blocks.append(
|
| 391 |
+
TimestepEmbedSequential(
|
| 392 |
+
ResBlock(
|
| 393 |
+
ch,
|
| 394 |
+
time_embed_dim,
|
| 395 |
+
dropout,
|
| 396 |
+
out_channels=out_ch,
|
| 397 |
+
dims=dims,
|
| 398 |
+
use_checkpoint=use_checkpoint,
|
| 399 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 400 |
+
down=True,
|
| 401 |
+
)
|
| 402 |
+
if resblock_updown
|
| 403 |
+
else Downsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
| 404 |
+
)
|
| 405 |
+
)
|
| 406 |
+
ch = out_ch
|
| 407 |
+
input_block_chans.append(ch)
|
| 408 |
+
ds *= 2
|
| 409 |
+
self._feature_size += ch
|
| 410 |
+
|
| 411 |
+
self.middle_block = TimestepEmbedSequential(
|
| 412 |
+
ResBlock(
|
| 413 |
+
ch,
|
| 414 |
+
time_embed_dim,
|
| 415 |
+
dropout,
|
| 416 |
+
dims=dims,
|
| 417 |
+
use_checkpoint=use_checkpoint,
|
| 418 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 419 |
+
),
|
| 420 |
+
AttentionBlock(
|
| 421 |
+
ch,
|
| 422 |
+
use_checkpoint=use_checkpoint,
|
| 423 |
+
num_heads=num_heads,
|
| 424 |
+
num_head_channels=num_head_channels,
|
| 425 |
+
use_new_attention_order=use_new_attention_order,
|
| 426 |
+
),
|
| 427 |
+
ResBlock(
|
| 428 |
+
ch,
|
| 429 |
+
time_embed_dim,
|
| 430 |
+
dropout,
|
| 431 |
+
dims=dims,
|
| 432 |
+
use_checkpoint=use_checkpoint,
|
| 433 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 434 |
+
),
|
| 435 |
+
)
|
| 436 |
+
self._feature_size += ch
|
| 437 |
+
self.pool = pool
|
| 438 |
+
if pool == "adaptive":
|
| 439 |
+
self.out = nn.Sequential(
|
| 440 |
+
normalization(ch),
|
| 441 |
+
nn.SiLU(),
|
| 442 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 443 |
+
zero_module(conv_nd(dims, ch, out_channels, 1)),
|
| 444 |
+
nn.Flatten(),
|
| 445 |
+
)
|
| 446 |
+
elif pool == "attention":
|
| 447 |
+
assert num_head_channels != -1
|
| 448 |
+
self.out = nn.Sequential(
|
| 449 |
+
normalization(ch),
|
| 450 |
+
nn.SiLU(),
|
| 451 |
+
AttentionPool2d((image_size // ds), ch, num_head_channels, out_channels),
|
| 452 |
+
)
|
| 453 |
+
elif pool == "spatial":
|
| 454 |
+
self.out = nn.Sequential(
|
| 455 |
+
nn.Linear(self._feature_size, 2048),
|
| 456 |
+
nn.ReLU(),
|
| 457 |
+
nn.Linear(2048, out_channels),
|
| 458 |
+
)
|
| 459 |
+
elif pool == "spatial_v2":
|
| 460 |
+
self.out = nn.Sequential(
|
| 461 |
+
nn.Linear(self._feature_size, 2048),
|
| 462 |
+
normalization(2048),
|
| 463 |
+
nn.SiLU(),
|
| 464 |
+
nn.Linear(2048, out_channels),
|
| 465 |
+
)
|
| 466 |
+
else:
|
| 467 |
+
raise NotImplementedError(f"Unexpected {pool} pooling")
|
| 468 |
+
|
| 469 |
+
def convert_to_fp16(self):
|
| 470 |
+
self.input_blocks.apply(convert_module_to_f16)
|
| 471 |
+
self.middle_block.apply(convert_module_to_f16)
|
| 472 |
+
|
| 473 |
+
def convert_to_fp32(self):
|
| 474 |
+
self.input_blocks.apply(convert_module_to_f32)
|
| 475 |
+
self.middle_block.apply(convert_module_to_f32)
|
| 476 |
+
|
| 477 |
+
def forward(self, x, timesteps):
|
| 478 |
+
emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
|
| 479 |
+
results = []
|
| 480 |
+
h = x.type(self.dtype)
|
| 481 |
+
for module in self.input_blocks:
|
| 482 |
+
h = module(h, emb)
|
| 483 |
+
if self.pool.startswith("spatial"):
|
| 484 |
+
results.append(h.type(x.dtype).mean(dim=(2, 3)))
|
| 485 |
+
h = self.middle_block(h, emb)
|
| 486 |
+
if self.pool.startswith("spatial"):
|
| 487 |
+
results.append(h.type(x.dtype).mean(dim=(2, 3)))
|
| 488 |
+
h = torch.cat(results, dim=-1)
|
| 489 |
+
return self.out(h)
|
| 490 |
+
h = h.type(x.dtype)
|
| 491 |
+
return self.out(h)
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
class UNetModel(nn.Module):
|
| 495 |
+
def __init__(
|
| 496 |
+
self,
|
| 497 |
+
image_size,
|
| 498 |
+
in_channels,
|
| 499 |
+
model_channels,
|
| 500 |
+
out_channels,
|
| 501 |
+
num_res_blocks,
|
| 502 |
+
attention_resolutions,
|
| 503 |
+
dropout=0,
|
| 504 |
+
channel_mult=(1, 2, 4, 8),
|
| 505 |
+
conv_resample=True,
|
| 506 |
+
dims=2,
|
| 507 |
+
num_classes=None,
|
| 508 |
+
use_checkpoint=False,
|
| 509 |
+
use_fp16=False,
|
| 510 |
+
num_heads=1,
|
| 511 |
+
num_head_channels=-1,
|
| 512 |
+
num_heads_upsample=-1,
|
| 513 |
+
use_scale_shift_norm=False,
|
| 514 |
+
resblock_updown=False,
|
| 515 |
+
use_new_attention_order=False,
|
| 516 |
+
):
|
| 517 |
+
super().__init__()
|
| 518 |
+
if num_heads_upsample == -1:
|
| 519 |
+
num_heads_upsample = num_heads
|
| 520 |
+
|
| 521 |
+
self.model_channels = model_channels
|
| 522 |
+
self.num_classes = num_classes
|
| 523 |
+
self.dtype = torch.float16 if use_fp16 else torch.float32
|
| 524 |
+
|
| 525 |
+
time_embed_dim = model_channels * 4
|
| 526 |
+
self.time_embed = nn.Sequential(
|
| 527 |
+
linear(model_channels, time_embed_dim),
|
| 528 |
+
nn.SiLU(),
|
| 529 |
+
linear(time_embed_dim, time_embed_dim),
|
| 530 |
+
)
|
| 531 |
+
if self.num_classes is not None:
|
| 532 |
+
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
|
| 533 |
+
|
| 534 |
+
ch = input_ch = int(channel_mult[0] * model_channels)
|
| 535 |
+
self.input_blocks = nn.ModuleList([TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))])
|
| 536 |
+
input_block_chans = [ch]
|
| 537 |
+
ds = 1
|
| 538 |
+
for level, mult in enumerate(channel_mult):
|
| 539 |
+
for _ in range(num_res_blocks):
|
| 540 |
+
layers = [
|
| 541 |
+
ResBlock(
|
| 542 |
+
ch,
|
| 543 |
+
time_embed_dim,
|
| 544 |
+
dropout,
|
| 545 |
+
out_channels=int(mult * model_channels),
|
| 546 |
+
dims=dims,
|
| 547 |
+
use_checkpoint=use_checkpoint,
|
| 548 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 549 |
+
)
|
| 550 |
+
]
|
| 551 |
+
ch = int(mult * model_channels)
|
| 552 |
+
if ds in attention_resolutions:
|
| 553 |
+
layers.append(
|
| 554 |
+
AttentionBlock(
|
| 555 |
+
ch,
|
| 556 |
+
use_checkpoint=use_checkpoint,
|
| 557 |
+
num_heads=num_heads,
|
| 558 |
+
num_head_channels=num_head_channels,
|
| 559 |
+
use_new_attention_order=use_new_attention_order,
|
| 560 |
+
)
|
| 561 |
+
)
|
| 562 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
| 563 |
+
input_block_chans.append(ch)
|
| 564 |
+
if level != len(channel_mult) - 1:
|
| 565 |
+
out_ch = ch
|
| 566 |
+
self.input_blocks.append(
|
| 567 |
+
TimestepEmbedSequential(
|
| 568 |
+
ResBlock(
|
| 569 |
+
ch,
|
| 570 |
+
time_embed_dim,
|
| 571 |
+
dropout,
|
| 572 |
+
out_channels=out_ch,
|
| 573 |
+
dims=dims,
|
| 574 |
+
use_checkpoint=use_checkpoint,
|
| 575 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 576 |
+
down=True,
|
| 577 |
+
)
|
| 578 |
+
if resblock_updown
|
| 579 |
+
else Downsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
| 580 |
+
)
|
| 581 |
+
)
|
| 582 |
+
ch = out_ch
|
| 583 |
+
input_block_chans.append(ch)
|
| 584 |
+
ds *= 2
|
| 585 |
+
|
| 586 |
+
self.middle_block = TimestepEmbedSequential(
|
| 587 |
+
ResBlock(
|
| 588 |
+
ch,
|
| 589 |
+
time_embed_dim,
|
| 590 |
+
dropout,
|
| 591 |
+
dims=dims,
|
| 592 |
+
use_checkpoint=use_checkpoint,
|
| 593 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 594 |
+
),
|
| 595 |
+
AttentionBlock(
|
| 596 |
+
ch,
|
| 597 |
+
use_checkpoint=use_checkpoint,
|
| 598 |
+
num_heads=num_heads,
|
| 599 |
+
num_head_channels=num_head_channels,
|
| 600 |
+
use_new_attention_order=use_new_attention_order,
|
| 601 |
+
),
|
| 602 |
+
ResBlock(
|
| 603 |
+
ch,
|
| 604 |
+
time_embed_dim,
|
| 605 |
+
dropout,
|
| 606 |
+
dims=dims,
|
| 607 |
+
use_checkpoint=use_checkpoint,
|
| 608 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 609 |
+
),
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
self.output_blocks = nn.ModuleList([])
|
| 613 |
+
for level, mult in list(enumerate(channel_mult))[::-1]:
|
| 614 |
+
for i in range(num_res_blocks + 1):
|
| 615 |
+
ich = input_block_chans.pop()
|
| 616 |
+
layers = [
|
| 617 |
+
ResBlock(
|
| 618 |
+
ch + ich,
|
| 619 |
+
time_embed_dim,
|
| 620 |
+
dropout,
|
| 621 |
+
out_channels=int(model_channels * mult),
|
| 622 |
+
dims=dims,
|
| 623 |
+
use_checkpoint=use_checkpoint,
|
| 624 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 625 |
+
)
|
| 626 |
+
]
|
| 627 |
+
ch = int(model_channels * mult)
|
| 628 |
+
if ds in attention_resolutions:
|
| 629 |
+
layers.append(
|
| 630 |
+
AttentionBlock(
|
| 631 |
+
ch,
|
| 632 |
+
use_checkpoint=use_checkpoint,
|
| 633 |
+
num_heads=num_heads_upsample,
|
| 634 |
+
num_head_channels=num_head_channels,
|
| 635 |
+
use_new_attention_order=use_new_attention_order,
|
| 636 |
+
)
|
| 637 |
+
)
|
| 638 |
+
if level and i == num_res_blocks:
|
| 639 |
+
out_ch = ch
|
| 640 |
+
layers.append(
|
| 641 |
+
ResBlock(
|
| 642 |
+
ch,
|
| 643 |
+
time_embed_dim,
|
| 644 |
+
dropout,
|
| 645 |
+
out_channels=out_ch,
|
| 646 |
+
dims=dims,
|
| 647 |
+
use_checkpoint=use_checkpoint,
|
| 648 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 649 |
+
up=True,
|
| 650 |
+
)
|
| 651 |
+
if resblock_updown
|
| 652 |
+
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
| 653 |
+
)
|
| 654 |
+
ds //= 2
|
| 655 |
+
self.output_blocks.append(TimestepEmbedSequential(*layers))
|
| 656 |
+
|
| 657 |
+
self.out = nn.Sequential(
|
| 658 |
+
normalization(ch),
|
| 659 |
+
nn.SiLU(),
|
| 660 |
+
zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),
|
| 661 |
+
)
|
| 662 |
+
|
| 663 |
+
def convert_to_fp16(self):
|
| 664 |
+
self.input_blocks.apply(convert_module_to_f16)
|
| 665 |
+
self.middle_block.apply(convert_module_to_f16)
|
| 666 |
+
self.output_blocks.apply(convert_module_to_f16)
|
| 667 |
+
|
| 668 |
+
def convert_to_fp32(self):
|
| 669 |
+
self.input_blocks.apply(convert_module_to_f32)
|
| 670 |
+
self.middle_block.apply(convert_module_to_f32)
|
| 671 |
+
self.output_blocks.apply(convert_module_to_f32)
|
| 672 |
+
|
| 673 |
+
def forward(self, x, timesteps, y: Optional[torch.Tensor] = None):
|
| 674 |
+
assert (y is not None) == (self.num_classes is not None)
|
| 675 |
+
hs = []
|
| 676 |
+
emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
|
| 677 |
+
if self.num_classes is not None:
|
| 678 |
+
assert y.shape == (x.shape[0],)
|
| 679 |
+
emb = emb + self.label_emb(y)
|
| 680 |
+
|
| 681 |
+
h = x.type(self.dtype)
|
| 682 |
+
for module in self.input_blocks:
|
| 683 |
+
h = module(h, emb)
|
| 684 |
+
hs.append(h)
|
| 685 |
+
h = self.middle_block(h, emb)
|
| 686 |
+
for module in self.output_blocks:
|
| 687 |
+
h = torch.cat([h, hs.pop()], dim=1)
|
| 688 |
+
h = module(h, emb)
|
| 689 |
+
h = h.type(x.dtype)
|
| 690 |
+
return self.out(h)
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
def _default_channel_mult(image_size: int):
|
| 694 |
+
if image_size == 512:
|
| 695 |
+
return (0.5, 1, 1, 2, 2, 4, 4)
|
| 696 |
+
if image_size == 256:
|
| 697 |
+
return (1, 1, 2, 2, 4, 4)
|
| 698 |
+
if image_size == 128:
|
| 699 |
+
return (1, 1, 2, 3, 4)
|
| 700 |
+
if image_size == 64:
|
| 701 |
+
return (1, 2, 3, 4)
|
| 702 |
+
raise ValueError(f"unsupported image size: {image_size}")
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
def create_adm_unet_model(
|
| 706 |
+
image_size,
|
| 707 |
+
num_channels,
|
| 708 |
+
num_res_blocks,
|
| 709 |
+
channel_mult="",
|
| 710 |
+
learn_sigma=False,
|
| 711 |
+
class_cond=False,
|
| 712 |
+
use_checkpoint=False,
|
| 713 |
+
attention_resolutions="16",
|
| 714 |
+
num_heads=1,
|
| 715 |
+
num_head_channels=-1,
|
| 716 |
+
num_heads_upsample=-1,
|
| 717 |
+
use_scale_shift_norm=False,
|
| 718 |
+
dropout=0.0,
|
| 719 |
+
resblock_updown=False,
|
| 720 |
+
use_fp16=False,
|
| 721 |
+
use_new_attention_order=False,
|
| 722 |
+
):
|
| 723 |
+
channel_mult = _default_channel_mult(image_size) if channel_mult == "" else tuple(int(v) for v in channel_mult.split(","))
|
| 724 |
+
attention_ds = tuple(image_size // int(res) for res in attention_resolutions.split(","))
|
| 725 |
+
return UNetModel(
|
| 726 |
+
image_size=image_size,
|
| 727 |
+
in_channels=3,
|
| 728 |
+
model_channels=num_channels,
|
| 729 |
+
out_channels=(3 if not learn_sigma else 6),
|
| 730 |
+
num_res_blocks=num_res_blocks,
|
| 731 |
+
attention_resolutions=attention_ds,
|
| 732 |
+
dropout=dropout,
|
| 733 |
+
channel_mult=channel_mult,
|
| 734 |
+
num_classes=(NUM_CLASSES if class_cond else None),
|
| 735 |
+
use_checkpoint=use_checkpoint,
|
| 736 |
+
use_fp16=use_fp16,
|
| 737 |
+
num_heads=num_heads,
|
| 738 |
+
num_head_channels=num_head_channels,
|
| 739 |
+
num_heads_upsample=num_heads_upsample,
|
| 740 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 741 |
+
resblock_updown=resblock_updown,
|
| 742 |
+
use_new_attention_order=use_new_attention_order,
|
| 743 |
+
)
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
def create_adm_classifier_model(
|
| 747 |
+
image_size: int,
|
| 748 |
+
classifier_width: int = 128,
|
| 749 |
+
classifier_depth: int = 2,
|
| 750 |
+
classifier_attention_resolutions: str = "32,16,8",
|
| 751 |
+
classifier_use_scale_shift_norm: bool = True,
|
| 752 |
+
classifier_resblock_updown: bool = True,
|
| 753 |
+
classifier_pool: str = "attention",
|
| 754 |
+
use_fp16: bool = False,
|
| 755 |
+
num_classes: int = NUM_CLASSES,
|
| 756 |
+
):
|
| 757 |
+
channel_mult = _default_channel_mult(image_size)
|
| 758 |
+
attention_ds = tuple(image_size // int(res) for res in classifier_attention_resolutions.split(","))
|
| 759 |
+
return EncoderUNetModel(
|
| 760 |
+
image_size=image_size,
|
| 761 |
+
in_channels=3,
|
| 762 |
+
model_channels=classifier_width,
|
| 763 |
+
out_channels=num_classes,
|
| 764 |
+
num_res_blocks=classifier_depth,
|
| 765 |
+
attention_resolutions=attention_ds,
|
| 766 |
+
channel_mult=channel_mult,
|
| 767 |
+
use_fp16=use_fp16,
|
| 768 |
+
num_head_channels=64,
|
| 769 |
+
use_scale_shift_norm=classifier_use_scale_shift_norm,
|
| 770 |
+
resblock_updown=classifier_resblock_updown,
|
| 771 |
+
pool=classifier_pool,
|
| 772 |
+
)
|
ADM-G-512/scheduler/__pycache__/scheduling_adm.cpython-312.pyc
ADDED
|
Binary file (33.7 kB). View file
|
|
|
ADM-G-512/scheduler/scheduler_config.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "ADMScheduler",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"learn_sigma": true,
|
| 5 |
+
"noise_schedule": "linear",
|
| 6 |
+
"predict_xstart": false,
|
| 7 |
+
"rescale_timesteps": false,
|
| 8 |
+
"sigma_small": false,
|
| 9 |
+
"steps": 1000,
|
| 10 |
+
"timestep_respacing": ""
|
| 11 |
+
}
|
ADM-G-512/scheduler/scheduling_adm.py
ADDED
|
@@ -0,0 +1,590 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
|
| 6 |
+
import enum
|
| 7 |
+
import math
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from typing import Optional, Tuple, Union
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 15 |
+
from diffusers.schedulers.scheduling_utils import SchedulerMixin
|
| 16 |
+
from diffusers.utils import BaseOutput
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 20 |
+
except ImportError: # pragma: no cover
|
| 21 |
+
def randn_tensor(shape, generator=None, device=None, dtype=None):
|
| 22 |
+
return torch.randn(shape, generator=generator, device=device, dtype=dtype)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
# Internal diffusion math (OpenAI ADM / improved-diffusion)
|
| 27 |
+
# ---------------------------------------------------------------------------
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _randn_like(tensor: torch.Tensor, generator: Optional[torch.Generator] = None) -> torch.Tensor:
|
| 31 |
+
return randn_tensor(tensor.shape, generator=generator, device=tensor.device, dtype=tensor.dtype)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _extract_into_tensor(arr, timesteps, broadcast_shape):
|
| 35 |
+
res = torch.from_numpy(arr).to(device=timesteps.device)[timesteps].float()
|
| 36 |
+
while len(res.shape) < len(broadcast_shape):
|
| 37 |
+
res = res[..., None]
|
| 38 |
+
return res.expand(broadcast_shape)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _get_named_beta_schedule(schedule_name: str, num_diffusion_timesteps: int):
|
| 42 |
+
if schedule_name == "linear":
|
| 43 |
+
scale = 1000 / num_diffusion_timesteps
|
| 44 |
+
return np.linspace(scale * 0.0001, scale * 0.02, num_diffusion_timesteps, dtype=np.float64)
|
| 45 |
+
if schedule_name == "cosine":
|
| 46 |
+
return _betas_for_alpha_bar(
|
| 47 |
+
num_diffusion_timesteps,
|
| 48 |
+
lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2,
|
| 49 |
+
)
|
| 50 |
+
raise NotImplementedError(f"unknown beta schedule: {schedule_name}")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _betas_for_alpha_bar(num_diffusion_timesteps: int, alpha_bar, max_beta: float = 0.999):
|
| 54 |
+
betas = []
|
| 55 |
+
for i in range(num_diffusion_timesteps):
|
| 56 |
+
t1 = i / num_diffusion_timesteps
|
| 57 |
+
t2 = (i + 1) / num_diffusion_timesteps
|
| 58 |
+
betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
|
| 59 |
+
return np.array(betas)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _space_timesteps(num_timesteps: int, section_counts):
|
| 63 |
+
if isinstance(section_counts, str):
|
| 64 |
+
if section_counts.startswith("ddim"):
|
| 65 |
+
desired_count = int(section_counts[len("ddim") :])
|
| 66 |
+
for i in range(1, num_timesteps):
|
| 67 |
+
if len(range(0, num_timesteps, i)) == desired_count:
|
| 68 |
+
return set(range(0, num_timesteps, i))
|
| 69 |
+
raise ValueError(f"cannot create exactly {num_timesteps} steps with an integer stride")
|
| 70 |
+
section_counts = [int(x) for x in section_counts.split(",")]
|
| 71 |
+
|
| 72 |
+
size_per = num_timesteps // len(section_counts)
|
| 73 |
+
extra = num_timesteps % len(section_counts)
|
| 74 |
+
start_idx = 0
|
| 75 |
+
all_steps = []
|
| 76 |
+
for i, section_count in enumerate(section_counts):
|
| 77 |
+
size = size_per + (1 if i < extra else 0)
|
| 78 |
+
if size < section_count:
|
| 79 |
+
raise ValueError(f"cannot divide section of {size} steps into {section_count}")
|
| 80 |
+
frac_stride = 1 if section_count <= 1 else (size - 1) / (section_count - 1)
|
| 81 |
+
cur_idx = 0.0
|
| 82 |
+
for _ in range(section_count):
|
| 83 |
+
all_steps.append(start_idx + round(cur_idx))
|
| 84 |
+
cur_idx += frac_stride
|
| 85 |
+
start_idx += size
|
| 86 |
+
return set(all_steps)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class _ModelMeanType(enum.Enum):
|
| 90 |
+
PREVIOUS_X = enum.auto()
|
| 91 |
+
START_X = enum.auto()
|
| 92 |
+
EPSILON = enum.auto()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class _ModelVarType(enum.Enum):
|
| 96 |
+
LEARNED = enum.auto()
|
| 97 |
+
FIXED_SMALL = enum.auto()
|
| 98 |
+
FIXED_LARGE = enum.auto()
|
| 99 |
+
LEARNED_RANGE = enum.auto()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class _GaussianDiffusion:
|
| 103 |
+
def __init__(self, *, betas, model_mean_type, model_var_type, rescale_timesteps: bool = False):
|
| 104 |
+
self.model_mean_type = model_mean_type
|
| 105 |
+
self.model_var_type = model_var_type
|
| 106 |
+
self.rescale_timesteps = rescale_timesteps
|
| 107 |
+
betas = np.array(betas, dtype=np.float64)
|
| 108 |
+
self.betas = betas
|
| 109 |
+
self.num_timesteps = int(betas.shape[0])
|
| 110 |
+
|
| 111 |
+
alphas = 1.0 - betas
|
| 112 |
+
self.alphas_cumprod = np.cumprod(alphas, axis=0)
|
| 113 |
+
self.alphas_cumprod_prev = np.append(1.0, self.alphas_cumprod[:-1])
|
| 114 |
+
self.sqrt_recip_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod)
|
| 115 |
+
self.sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod - 1)
|
| 116 |
+
self.posterior_variance = betas * (1.0 - self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)
|
| 117 |
+
self.posterior_log_variance_clipped = np.log(np.append(self.posterior_variance[1], self.posterior_variance[1:]))
|
| 118 |
+
self.posterior_mean_coef1 = betas * np.sqrt(self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)
|
| 119 |
+
self.posterior_mean_coef2 = (1.0 - self.alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - self.alphas_cumprod)
|
| 120 |
+
|
| 121 |
+
def _predict_xstart_from_eps(self, x_t, t, eps):
|
| 122 |
+
return _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - _extract_into_tensor(
|
| 123 |
+
self.sqrt_recipm1_alphas_cumprod, t, x_t.shape
|
| 124 |
+
) * eps
|
| 125 |
+
|
| 126 |
+
def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
|
| 127 |
+
return (
|
| 128 |
+
_extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart
|
| 129 |
+
) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
|
| 130 |
+
|
| 131 |
+
def _predict_xstart_from_xprev(self, x_t, t, xprev):
|
| 132 |
+
return _extract_into_tensor(1.0 / self.posterior_mean_coef1, t, x_t.shape) * xprev - _extract_into_tensor(
|
| 133 |
+
self.posterior_mean_coef2 / self.posterior_mean_coef1, t, x_t.shape
|
| 134 |
+
) * x_t
|
| 135 |
+
|
| 136 |
+
def q_posterior_mean_variance(self, x_start, x_t, t):
|
| 137 |
+
posterior_mean = _extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + _extract_into_tensor(
|
| 138 |
+
self.posterior_mean_coef2, t, x_t.shape
|
| 139 |
+
) * x_t
|
| 140 |
+
posterior_variance = _extract_into_tensor(self.posterior_variance, t, x_t.shape)
|
| 141 |
+
posterior_log_variance_clipped = _extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
|
| 142 |
+
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
| 143 |
+
|
| 144 |
+
def p_mean_variance_from_output(
|
| 145 |
+
self,
|
| 146 |
+
model_output: torch.Tensor,
|
| 147 |
+
x: torch.Tensor,
|
| 148 |
+
t: torch.Tensor,
|
| 149 |
+
clip_denoised: bool = True,
|
| 150 |
+
):
|
| 151 |
+
_, c = x.shape[:2]
|
| 152 |
+
|
| 153 |
+
if self.model_var_type == _ModelVarType.LEARNED_RANGE:
|
| 154 |
+
model_output, model_var_values = torch.split(model_output, c, dim=1)
|
| 155 |
+
min_log = _extract_into_tensor(self.posterior_log_variance_clipped, t, x.shape)
|
| 156 |
+
max_log = _extract_into_tensor(np.log(self.betas), t, x.shape)
|
| 157 |
+
frac = (model_var_values + 1) / 2
|
| 158 |
+
model_log_variance = frac * max_log + (1 - frac) * min_log
|
| 159 |
+
model_variance = torch.exp(model_log_variance)
|
| 160 |
+
else:
|
| 161 |
+
model_variance, model_log_variance = {
|
| 162 |
+
_ModelVarType.FIXED_LARGE: (
|
| 163 |
+
np.append(self.posterior_variance[1], self.betas[1:]),
|
| 164 |
+
np.log(np.append(self.posterior_variance[1], self.betas[1:])),
|
| 165 |
+
),
|
| 166 |
+
_ModelVarType.FIXED_SMALL: (self.posterior_variance, self.posterior_log_variance_clipped),
|
| 167 |
+
}[self.model_var_type]
|
| 168 |
+
model_variance = _extract_into_tensor(model_variance, t, x.shape)
|
| 169 |
+
model_log_variance = _extract_into_tensor(model_log_variance, t, x.shape)
|
| 170 |
+
|
| 171 |
+
if self.model_mean_type == _ModelMeanType.START_X:
|
| 172 |
+
pred_xstart = model_output
|
| 173 |
+
elif self.model_mean_type == _ModelMeanType.EPSILON:
|
| 174 |
+
pred_xstart = self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output)
|
| 175 |
+
else:
|
| 176 |
+
pred_xstart = self._predict_xstart_from_xprev(x_t=x, t=t, xprev=model_output)
|
| 177 |
+
if clip_denoised:
|
| 178 |
+
pred_xstart = pred_xstart.clamp(-1, 1)
|
| 179 |
+
model_mean, _, _ = self.q_posterior_mean_variance(x_start=pred_xstart, x_t=x, t=t)
|
| 180 |
+
return {"mean": model_mean, "variance": model_variance, "log_variance": model_log_variance, "pred_xstart": pred_xstart}
|
| 181 |
+
|
| 182 |
+
def p_mean_variance(self, model, x, t, clip_denoised: bool = True, model_kwargs=None):
|
| 183 |
+
model_kwargs = {} if model_kwargs is None else model_kwargs
|
| 184 |
+
if self.rescale_timesteps:
|
| 185 |
+
ts = t.float() * (1000.0 / self.num_timesteps)
|
| 186 |
+
else:
|
| 187 |
+
ts = t
|
| 188 |
+
model_output = model(x, ts, **model_kwargs)
|
| 189 |
+
return self.p_mean_variance_from_output(model_output, x, t, clip_denoised=clip_denoised)
|
| 190 |
+
|
| 191 |
+
def condition_mean(self, cond_grad: torch.Tensor, p_mean_var: dict, x: torch.Tensor) -> torch.Tensor:
|
| 192 |
+
"""Apply classifier guidance to the reverse-process mean (Sohl-Dickstein et al., 2015)."""
|
| 193 |
+
del x
|
| 194 |
+
return p_mean_var["mean"].float() + p_mean_var["variance"] * cond_grad.float()
|
| 195 |
+
|
| 196 |
+
def p_sample_from_output(
|
| 197 |
+
self,
|
| 198 |
+
model_output: torch.Tensor,
|
| 199 |
+
x: torch.Tensor,
|
| 200 |
+
t: torch.Tensor,
|
| 201 |
+
clip_denoised: bool = True,
|
| 202 |
+
generator: Optional[torch.Generator] = None,
|
| 203 |
+
cond_grad: Optional[torch.Tensor] = None,
|
| 204 |
+
):
|
| 205 |
+
out = self.p_mean_variance_from_output(model_output, x, t, clip_denoised=clip_denoised)
|
| 206 |
+
if cond_grad is not None:
|
| 207 |
+
out["mean"] = self.condition_mean(cond_grad, out, x)
|
| 208 |
+
noise = _randn_like(x, generator=generator)
|
| 209 |
+
nonzero_mask = (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
|
| 210 |
+
sample = out["mean"] + nonzero_mask * torch.exp(0.5 * out["log_variance"]) * noise
|
| 211 |
+
return {"sample": sample, "pred_xstart": out["pred_xstart"]}
|
| 212 |
+
|
| 213 |
+
def p_sample(self, model, x, t, clip_denoised=True, model_kwargs=None, generator: Optional[torch.Generator] = None):
|
| 214 |
+
out = self.p_mean_variance(model, x, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs)
|
| 215 |
+
noise = _randn_like(x, generator=generator)
|
| 216 |
+
nonzero_mask = (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
|
| 217 |
+
sample = out["mean"] + nonzero_mask * torch.exp(0.5 * out["log_variance"]) * noise
|
| 218 |
+
return {"sample": sample, "pred_xstart": out["pred_xstart"]}
|
| 219 |
+
|
| 220 |
+
def p_sample_loop(self, model, shape, noise=None, clip_denoised=True, model_kwargs=None, device=None, progress=False):
|
| 221 |
+
final = None
|
| 222 |
+
for sample in self.p_sample_loop_progressive(
|
| 223 |
+
model, shape, noise=noise, clip_denoised=clip_denoised, model_kwargs=model_kwargs, device=device, progress=progress
|
| 224 |
+
):
|
| 225 |
+
final = sample
|
| 226 |
+
return final["sample"]
|
| 227 |
+
|
| 228 |
+
def p_sample_loop_progressive(self, model, shape, noise=None, clip_denoised=True, model_kwargs=None, device=None, progress=False):
|
| 229 |
+
if device is None:
|
| 230 |
+
device = next(model.parameters()).device
|
| 231 |
+
img = noise if noise is not None else torch.randn(*shape, device=device)
|
| 232 |
+
indices = list(range(self.num_timesteps))[::-1]
|
| 233 |
+
if progress:
|
| 234 |
+
from tqdm.auto import tqdm
|
| 235 |
+
|
| 236 |
+
indices = tqdm(indices)
|
| 237 |
+
for i in indices:
|
| 238 |
+
t = torch.tensor([i] * shape[0], device=device)
|
| 239 |
+
with torch.no_grad():
|
| 240 |
+
out = self.p_sample(model, img, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs)
|
| 241 |
+
yield out
|
| 242 |
+
img = out["sample"]
|
| 243 |
+
|
| 244 |
+
def condition_score(self, cond_grad: torch.Tensor, p_mean_var: dict, x: torch.Tensor, t: torch.Tensor) -> dict:
|
| 245 |
+
"""Apply classifier guidance to the score (Song et al., 2020) for DDIM."""
|
| 246 |
+
alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
|
| 247 |
+
eps = self._predict_eps_from_xstart(x, t, p_mean_var["pred_xstart"])
|
| 248 |
+
eps = eps - (1 - alpha_bar).sqrt() * cond_grad
|
| 249 |
+
out = dict(p_mean_var)
|
| 250 |
+
out["pred_xstart"] = self._predict_xstart_from_eps(x_t=x, t=t, eps=eps)
|
| 251 |
+
out["mean"], _, _ = self.q_posterior_mean_variance(x_start=out["pred_xstart"], x_t=x, t=t)
|
| 252 |
+
return out
|
| 253 |
+
|
| 254 |
+
def ddim_sample_from_output(
|
| 255 |
+
self,
|
| 256 |
+
model_output: torch.Tensor,
|
| 257 |
+
x: torch.Tensor,
|
| 258 |
+
t: torch.Tensor,
|
| 259 |
+
clip_denoised: bool = True,
|
| 260 |
+
eta: float = 0.0,
|
| 261 |
+
generator: Optional[torch.Generator] = None,
|
| 262 |
+
cond_grad: Optional[torch.Tensor] = None,
|
| 263 |
+
):
|
| 264 |
+
out = self.p_mean_variance_from_output(model_output, x, t, clip_denoised=clip_denoised)
|
| 265 |
+
if cond_grad is not None:
|
| 266 |
+
out = self.condition_score(cond_grad, out, x, t)
|
| 267 |
+
pred_xstart = out["pred_xstart"]
|
| 268 |
+
eps = self._predict_eps_from_xstart(x, t, pred_xstart)
|
| 269 |
+
alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
|
| 270 |
+
alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape)
|
| 271 |
+
sigma = eta * torch.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar)) * torch.sqrt(1 - alpha_bar / alpha_bar_prev)
|
| 272 |
+
noise = _randn_like(x, generator=generator)
|
| 273 |
+
mean_pred = pred_xstart * torch.sqrt(alpha_bar_prev) + torch.sqrt(1 - alpha_bar_prev - sigma**2) * eps
|
| 274 |
+
nonzero_mask = (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
|
| 275 |
+
sample = mean_pred + nonzero_mask * sigma * noise
|
| 276 |
+
return {"sample": sample, "pred_xstart": pred_xstart}
|
| 277 |
+
|
| 278 |
+
def ddim_sample(
|
| 279 |
+
self,
|
| 280 |
+
model,
|
| 281 |
+
x,
|
| 282 |
+
t,
|
| 283 |
+
clip_denoised=True,
|
| 284 |
+
model_kwargs=None,
|
| 285 |
+
eta=0.0,
|
| 286 |
+
generator: Optional[torch.Generator] = None,
|
| 287 |
+
):
|
| 288 |
+
model_kwargs = {} if model_kwargs is None else model_kwargs
|
| 289 |
+
if self.rescale_timesteps:
|
| 290 |
+
ts = t.float() * (1000.0 / self.num_timesteps)
|
| 291 |
+
else:
|
| 292 |
+
ts = t
|
| 293 |
+
model_output = model(x, ts, **model_kwargs)
|
| 294 |
+
return self.ddim_sample_from_output(
|
| 295 |
+
model_output, x, t, clip_denoised=clip_denoised, eta=eta, generator=generator
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class _WrappedModel:
|
| 300 |
+
def __init__(self, model, timestep_map, rescale_timesteps, original_num_steps):
|
| 301 |
+
self.model = model
|
| 302 |
+
self.timestep_map = timestep_map
|
| 303 |
+
self.rescale_timesteps = rescale_timesteps
|
| 304 |
+
self.original_num_steps = original_num_steps
|
| 305 |
+
|
| 306 |
+
def __call__(self, x, ts, **kwargs):
|
| 307 |
+
map_tensor = torch.tensor(self.timestep_map, device=ts.device, dtype=ts.dtype)
|
| 308 |
+
new_ts = map_tensor[ts]
|
| 309 |
+
if self.rescale_timesteps:
|
| 310 |
+
new_ts = new_ts.float() * (1000.0 / self.original_num_steps)
|
| 311 |
+
return self.model(x, new_ts, **kwargs)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
class _SpacedDiffusion(_GaussianDiffusion):
|
| 315 |
+
def __init__(self, use_timesteps, **kwargs):
|
| 316 |
+
self.use_timesteps = set(use_timesteps)
|
| 317 |
+
self.timestep_map = []
|
| 318 |
+
self.original_num_steps = len(kwargs["betas"])
|
| 319 |
+
base_diffusion = _GaussianDiffusion(**kwargs)
|
| 320 |
+
last_alpha_cumprod = 1.0
|
| 321 |
+
new_betas = []
|
| 322 |
+
for i, alpha_cumprod in enumerate(base_diffusion.alphas_cumprod):
|
| 323 |
+
if i in self.use_timesteps:
|
| 324 |
+
new_betas.append(1 - alpha_cumprod / last_alpha_cumprod)
|
| 325 |
+
last_alpha_cumprod = alpha_cumprod
|
| 326 |
+
self.timestep_map.append(i)
|
| 327 |
+
kwargs["betas"] = np.array(new_betas)
|
| 328 |
+
super().__init__(**kwargs)
|
| 329 |
+
|
| 330 |
+
def p_mean_variance(self, model, *args, **kwargs):
|
| 331 |
+
return super().p_mean_variance(self._wrap_model(model), *args, **kwargs)
|
| 332 |
+
|
| 333 |
+
def _wrap_model(self, model):
|
| 334 |
+
if isinstance(model, _WrappedModel):
|
| 335 |
+
return model
|
| 336 |
+
return _WrappedModel(model, self.timestep_map, self.rescale_timesteps, self.original_num_steps)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def _create_spaced_diffusion(
|
| 340 |
+
*,
|
| 341 |
+
steps: int = 1000,
|
| 342 |
+
learn_sigma: bool = False,
|
| 343 |
+
sigma_small: bool = False,
|
| 344 |
+
noise_schedule: str = "linear",
|
| 345 |
+
predict_xstart: bool = False,
|
| 346 |
+
rescale_timesteps: bool = False,
|
| 347 |
+
timestep_respacing: str = "",
|
| 348 |
+
) -> _SpacedDiffusion:
|
| 349 |
+
betas = _get_named_beta_schedule(noise_schedule, steps)
|
| 350 |
+
if not timestep_respacing:
|
| 351 |
+
timestep_respacing = [steps]
|
| 352 |
+
return _SpacedDiffusion(
|
| 353 |
+
use_timesteps=_space_timesteps(steps, timestep_respacing),
|
| 354 |
+
betas=betas,
|
| 355 |
+
model_mean_type=_ModelMeanType.EPSILON if not predict_xstart else _ModelMeanType.START_X,
|
| 356 |
+
model_var_type=(_ModelVarType.FIXED_LARGE if not sigma_small else _ModelVarType.FIXED_SMALL)
|
| 357 |
+
if not learn_sigma
|
| 358 |
+
else _ModelVarType.LEARNED_RANGE,
|
| 359 |
+
rescale_timesteps=rescale_timesteps,
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
# ---------------------------------------------------------------------------
|
| 364 |
+
# Public Diffusers scheduler API
|
| 365 |
+
# ---------------------------------------------------------------------------
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
@dataclass
|
| 369 |
+
class ADMSchedulerOutput(BaseOutput):
|
| 370 |
+
"""
|
| 371 |
+
Output class for the ADM scheduler's `step` function.
|
| 372 |
+
|
| 373 |
+
Args:
|
| 374 |
+
prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
|
| 375 |
+
Computed sample `(x_{t-1})` of the previous timestep. `prev_sample` should be used as the next model input.
|
| 376 |
+
pred_original_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`, *optional*):
|
| 377 |
+
The predicted denoised sample `(x_{0})` based on the model output.
|
| 378 |
+
"""
|
| 379 |
+
|
| 380 |
+
prev_sample: torch.FloatTensor
|
| 381 |
+
pred_original_sample: Optional[torch.FloatTensor] = None
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
class ADMScheduler(SchedulerMixin, ConfigMixin):
|
| 385 |
+
"""
|
| 386 |
+
DDPM / DDIM scheduler for ADM (Ablated Diffusion Model) with OpenAI-style Gaussian diffusion.
|
| 387 |
+
|
| 388 |
+
This scheduler implements spaced diffusion used by ADM checkpoints. Call `set_timesteps` before inference, then
|
| 389 |
+
alternate UNet forward passes with `step`.
|
| 390 |
+
"""
|
| 391 |
+
|
| 392 |
+
config_name = "scheduler_config.json"
|
| 393 |
+
order = 1
|
| 394 |
+
|
| 395 |
+
@register_to_config
|
| 396 |
+
def __init__(
|
| 397 |
+
self,
|
| 398 |
+
steps: int = 1000,
|
| 399 |
+
learn_sigma: bool = False,
|
| 400 |
+
sigma_small: bool = False,
|
| 401 |
+
noise_schedule: str = "linear",
|
| 402 |
+
predict_xstart: bool = False,
|
| 403 |
+
rescale_timesteps: bool = False,
|
| 404 |
+
timestep_respacing: str = "",
|
| 405 |
+
):
|
| 406 |
+
self.timesteps = None
|
| 407 |
+
self.num_inference_steps = None
|
| 408 |
+
self._diffusion: Optional[_SpacedDiffusion] = None
|
| 409 |
+
self._use_ddim = False
|
| 410 |
+
self._eta = 0.0
|
| 411 |
+
|
| 412 |
+
def scale_model_input(self, sample: torch.Tensor, timestep: Optional[int] = None) -> torch.Tensor:
|
| 413 |
+
"""
|
| 414 |
+
Ensures interchangeability with schedulers that scale the denoising model input depending on the timestep.
|
| 415 |
+
|
| 416 |
+
Args:
|
| 417 |
+
sample (`torch.Tensor`):
|
| 418 |
+
The input sample.
|
| 419 |
+
timestep (`int`, *optional*):
|
| 420 |
+
The current timestep in the diffusion chain.
|
| 421 |
+
|
| 422 |
+
Returns:
|
| 423 |
+
`torch.Tensor`:
|
| 424 |
+
The (unchanged) input sample.
|
| 425 |
+
"""
|
| 426 |
+
del timestep
|
| 427 |
+
return sample
|
| 428 |
+
|
| 429 |
+
def set_timesteps(
|
| 430 |
+
self,
|
| 431 |
+
num_inference_steps: int,
|
| 432 |
+
device: Optional[Union[str, torch.device]] = None,
|
| 433 |
+
use_ddim: bool = False,
|
| 434 |
+
timestep_respacing: Optional[str] = None,
|
| 435 |
+
) -> torch.Tensor:
|
| 436 |
+
"""
|
| 437 |
+
Sets the discrete timesteps used for the diffusion chain (to be run before inference).
|
| 438 |
+
|
| 439 |
+
Args:
|
| 440 |
+
num_inference_steps (`int`):
|
| 441 |
+
The number of diffusion steps used when generating samples with a pre-trained model.
|
| 442 |
+
device (`str` or `torch.device`, *optional*):
|
| 443 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
| 444 |
+
use_ddim (`bool`, *optional*, defaults to `False`):
|
| 445 |
+
Whether to use DDIM sampling instead of DDPM.
|
| 446 |
+
timestep_respacing (`str`, *optional*):
|
| 447 |
+
Override for the respacing string. If `None`, respacing is derived from `num_inference_steps`.
|
| 448 |
+
|
| 449 |
+
Returns:
|
| 450 |
+
`torch.Tensor`:
|
| 451 |
+
Timestep indices used during denoising, in descending order.
|
| 452 |
+
"""
|
| 453 |
+
if timestep_respacing is None:
|
| 454 |
+
timestep_respacing = f"ddim{num_inference_steps}" if use_ddim else str(num_inference_steps)
|
| 455 |
+
|
| 456 |
+
self._diffusion = _create_spaced_diffusion(
|
| 457 |
+
steps=self.config.steps,
|
| 458 |
+
learn_sigma=self.config.learn_sigma,
|
| 459 |
+
sigma_small=self.config.sigma_small,
|
| 460 |
+
noise_schedule=self.config.noise_schedule,
|
| 461 |
+
predict_xstart=self.config.predict_xstart,
|
| 462 |
+
rescale_timesteps=self.config.rescale_timesteps,
|
| 463 |
+
timestep_respacing=timestep_respacing,
|
| 464 |
+
)
|
| 465 |
+
self._use_ddim = use_ddim
|
| 466 |
+
self.num_inference_steps = num_inference_steps
|
| 467 |
+
|
| 468 |
+
indices = list(range(self._diffusion.num_timesteps))[::-1]
|
| 469 |
+
timesteps = torch.tensor(indices, dtype=torch.long)
|
| 470 |
+
if device is not None:
|
| 471 |
+
timesteps = timesteps.to(device)
|
| 472 |
+
self.timesteps = timesteps
|
| 473 |
+
return self.timesteps
|
| 474 |
+
|
| 475 |
+
def scale_timesteps_for_model(self, timestep: torch.Tensor) -> torch.Tensor:
|
| 476 |
+
"""
|
| 477 |
+
Map respaced scheduler indices to the timestep embeddings expected by the ADM UNet.
|
| 478 |
+
|
| 479 |
+
Args:
|
| 480 |
+
timestep (`torch.Tensor`):
|
| 481 |
+
Current scheduler timestep indices of shape `(batch_size,)`.
|
| 482 |
+
|
| 483 |
+
Returns:
|
| 484 |
+
`torch.Tensor`:
|
| 485 |
+
Timesteps to pass to the UNet forward pass.
|
| 486 |
+
"""
|
| 487 |
+
if self._diffusion is None:
|
| 488 |
+
raise ValueError("Call `set_timesteps` before running the scheduler.")
|
| 489 |
+
|
| 490 |
+
map_tensor = torch.tensor(self._diffusion.timestep_map, device=timestep.device, dtype=timestep.dtype)
|
| 491 |
+
model_timesteps = map_tensor[timestep]
|
| 492 |
+
if self._diffusion.rescale_timesteps:
|
| 493 |
+
model_timesteps = model_timesteps.float() * (1000.0 / self._diffusion.original_num_steps)
|
| 494 |
+
return model_timesteps
|
| 495 |
+
|
| 496 |
+
def step(
|
| 497 |
+
self,
|
| 498 |
+
model_output: torch.Tensor,
|
| 499 |
+
timestep: Union[int, torch.Tensor],
|
| 500 |
+
sample: torch.Tensor,
|
| 501 |
+
generator: Optional[torch.Generator] = None,
|
| 502 |
+
return_dict: bool = True,
|
| 503 |
+
clip_denoised: bool = True,
|
| 504 |
+
eta: Optional[float] = None,
|
| 505 |
+
cond_grad: Optional[torch.Tensor] = None,
|
| 506 |
+
) -> Union[ADMSchedulerOutput, Tuple[torch.Tensor, ...]]:
|
| 507 |
+
"""
|
| 508 |
+
Predict the sample at the previous timestep from the model output.
|
| 509 |
+
|
| 510 |
+
Args:
|
| 511 |
+
model_output (`torch.Tensor`):
|
| 512 |
+
The direct output from the ADM UNet.
|
| 513 |
+
timestep (`int` or `torch.Tensor`):
|
| 514 |
+
The current discrete timestep index in the respaced diffusion chain.
|
| 515 |
+
sample (`torch.Tensor`):
|
| 516 |
+
A current instance of a sample created by the diffusion process.
|
| 517 |
+
generator (`torch.Generator`, *optional*):
|
| 518 |
+
A random number generator for the sampling noise.
|
| 519 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 520 |
+
Whether or not to return an [`ADMSchedulerOutput`] instead of a plain tuple.
|
| 521 |
+
clip_denoised (`bool`, *optional*, defaults to `True`):
|
| 522 |
+
Whether to clamp the predicted `x_0` to `[-1, 1]`.
|
| 523 |
+
eta (`float`, *optional*):
|
| 524 |
+
DDIM stochasticity parameter. Only used when `use_ddim=True` was passed to `set_timesteps`.
|
| 525 |
+
cond_grad (`torch.Tensor`, *optional*):
|
| 526 |
+
Classifier guidance gradient for ADM-G (`classifier_scale * grad log p(y|x_t)`).
|
| 527 |
+
|
| 528 |
+
Returns:
|
| 529 |
+
[`ADMSchedulerOutput`] or `tuple`:
|
| 530 |
+
If `return_dict` is `True`, an [`ADMSchedulerOutput`] is returned, otherwise a tuple is returned where
|
| 531 |
+
the first element is the previous sample.
|
| 532 |
+
"""
|
| 533 |
+
if self._diffusion is None:
|
| 534 |
+
raise ValueError("Call `set_timesteps` before `step`.")
|
| 535 |
+
|
| 536 |
+
if not torch.is_tensor(timestep):
|
| 537 |
+
timestep = torch.tensor([timestep], device=sample.device, dtype=torch.long)
|
| 538 |
+
elif timestep.ndim == 0:
|
| 539 |
+
timestep = timestep.reshape(1).to(device=sample.device, dtype=torch.long)
|
| 540 |
+
else:
|
| 541 |
+
timestep = timestep.to(device=sample.device, dtype=torch.long)
|
| 542 |
+
|
| 543 |
+
ddim_eta = self._eta if eta is None else eta
|
| 544 |
+
|
| 545 |
+
if self._use_ddim:
|
| 546 |
+
out = self._diffusion.ddim_sample_from_output(
|
| 547 |
+
model_output,
|
| 548 |
+
sample,
|
| 549 |
+
timestep,
|
| 550 |
+
clip_denoised=clip_denoised,
|
| 551 |
+
eta=ddim_eta,
|
| 552 |
+
generator=generator,
|
| 553 |
+
cond_grad=cond_grad,
|
| 554 |
+
)
|
| 555 |
+
else:
|
| 556 |
+
out = self._diffusion.p_sample_from_output(
|
| 557 |
+
model_output,
|
| 558 |
+
sample,
|
| 559 |
+
timestep,
|
| 560 |
+
clip_denoised=clip_denoised,
|
| 561 |
+
generator=generator,
|
| 562 |
+
cond_grad=cond_grad,
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
prev_sample = out["sample"]
|
| 566 |
+
pred_original_sample = out.get("pred_xstart")
|
| 567 |
+
|
| 568 |
+
if not return_dict:
|
| 569 |
+
return (prev_sample, pred_original_sample)
|
| 570 |
+
|
| 571 |
+
return ADMSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)
|
| 572 |
+
|
| 573 |
+
def create_runtime(self, num_inference_steps: Optional[int] = None, use_ddim: bool = False) -> _SpacedDiffusion:
|
| 574 |
+
"""
|
| 575 |
+
Build a spaced diffusion object for legacy loop-based sampling (`p_sample_loop`).
|
| 576 |
+
|
| 577 |
+
Prefer `set_timesteps` + `step` for Diffusers-style inference.
|
| 578 |
+
"""
|
| 579 |
+
timestep_respacing = self.config.timestep_respacing
|
| 580 |
+
if num_inference_steps is not None:
|
| 581 |
+
timestep_respacing = f"ddim{num_inference_steps}" if use_ddim else str(num_inference_steps)
|
| 582 |
+
return _create_spaced_diffusion(
|
| 583 |
+
steps=self.config.steps,
|
| 584 |
+
learn_sigma=self.config.learn_sigma,
|
| 585 |
+
sigma_small=self.config.sigma_small,
|
| 586 |
+
noise_schedule=self.config.noise_schedule,
|
| 587 |
+
predict_xstart=self.config.predict_xstart,
|
| 588 |
+
rescale_timesteps=self.config.rescale_timesteps,
|
| 589 |
+
timestep_respacing=timestep_respacing,
|
| 590 |
+
)
|
ADM-G-512/unet/__pycache__/modeling_adm.cpython-312.pyc
ADDED
|
Binary file (34.5 kB). View file
|
|
|
ADM-G-512/unet/__pycache__/unet_adm.cpython-312.pyc
ADDED
|
Binary file (5.35 kB). View file
|
|
|
ADM-G-512/unet/config.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "ADMUNet2DModel",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"attention_resolutions": "32,16,8",
|
| 5 |
+
"channel_mult": "",
|
| 6 |
+
"class_cond": true,
|
| 7 |
+
"dropout": 0.0,
|
| 8 |
+
"image_size": 512,
|
| 9 |
+
"in_channels": 3,
|
| 10 |
+
"learn_sigma": true,
|
| 11 |
+
"num_channels": 256,
|
| 12 |
+
"num_head_channels": 64,
|
| 13 |
+
"num_heads": 4,
|
| 14 |
+
"num_heads_upsample": -1,
|
| 15 |
+
"num_res_blocks": 2,
|
| 16 |
+
"out_channels": null,
|
| 17 |
+
"resblock_updown": true,
|
| 18 |
+
"use_checkpoint": false,
|
| 19 |
+
"use_fp16": false,
|
| 20 |
+
"use_new_attention_order": false,
|
| 21 |
+
"use_scale_shift_norm": true
|
| 22 |
+
}
|
ADM-G-512/unet/diffusion_pytorch_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0eca4ffe4398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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from abc import abstractmethod
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from torch.utils.checkpoint import checkpoint as torch_checkpoint
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
NUM_CLASSES = 1000
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def conv_nd(dims: int, *args, **kwargs):
|
| 15 |
+
if dims == 1:
|
| 16 |
+
return nn.Conv1d(*args, **kwargs)
|
| 17 |
+
if dims == 2:
|
| 18 |
+
return nn.Conv2d(*args, **kwargs)
|
| 19 |
+
if dims == 3:
|
| 20 |
+
return nn.Conv3d(*args, **kwargs)
|
| 21 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def linear(*args, **kwargs):
|
| 25 |
+
return nn.Linear(*args, **kwargs)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def avg_pool_nd(dims: int, *args, **kwargs):
|
| 29 |
+
if dims == 1:
|
| 30 |
+
return nn.AvgPool1d(*args, **kwargs)
|
| 31 |
+
if dims == 2:
|
| 32 |
+
return nn.AvgPool2d(*args, **kwargs)
|
| 33 |
+
if dims == 3:
|
| 34 |
+
return nn.AvgPool3d(*args, **kwargs)
|
| 35 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class GroupNorm32(nn.GroupNorm):
|
| 39 |
+
def forward(self, x):
|
| 40 |
+
return super().forward(x.float()).type(x.dtype)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def normalization(channels: int):
|
| 44 |
+
return GroupNorm32(32, channels)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def zero_module(module: nn.Module):
|
| 48 |
+
for p in module.parameters():
|
| 49 |
+
p.detach().zero_()
|
| 50 |
+
return module
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def timestep_embedding(timesteps: torch.Tensor, dim: int, max_period: int = 10000):
|
| 54 |
+
half = dim // 2
|
| 55 |
+
freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
|
| 56 |
+
device=timesteps.device
|
| 57 |
+
)
|
| 58 |
+
args = timesteps[:, None].float() * freqs[None]
|
| 59 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 60 |
+
if dim % 2:
|
| 61 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 62 |
+
return embedding
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def convert_module_to_f16(module: nn.Module):
|
| 66 |
+
if isinstance(module, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
|
| 67 |
+
module.weight.data = module.weight.data.half()
|
| 68 |
+
if module.bias is not None:
|
| 69 |
+
module.bias.data = module.bias.data.half()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def convert_module_to_f32(module: nn.Module):
|
| 73 |
+
if isinstance(module, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
|
| 74 |
+
module.weight.data = module.weight.data.float()
|
| 75 |
+
if module.bias is not None:
|
| 76 |
+
module.bias.data = module.bias.data.float()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class TimestepBlock(nn.Module):
|
| 80 |
+
@abstractmethod
|
| 81 |
+
def forward(self, x, emb):
|
| 82 |
+
raise NotImplementedError
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
|
| 86 |
+
def forward(self, x, emb):
|
| 87 |
+
for layer in self:
|
| 88 |
+
if isinstance(layer, TimestepBlock):
|
| 89 |
+
x = layer(x, emb)
|
| 90 |
+
else:
|
| 91 |
+
x = layer(x)
|
| 92 |
+
return x
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class Upsample(nn.Module):
|
| 96 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None):
|
| 97 |
+
super().__init__()
|
| 98 |
+
self.channels = channels
|
| 99 |
+
self.out_channels = out_channels or channels
|
| 100 |
+
self.use_conv = use_conv
|
| 101 |
+
self.dims = dims
|
| 102 |
+
if use_conv:
|
| 103 |
+
self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=1)
|
| 104 |
+
|
| 105 |
+
def forward(self, x):
|
| 106 |
+
assert x.shape[1] == self.channels
|
| 107 |
+
if self.dims == 3:
|
| 108 |
+
x = F.interpolate(x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest")
|
| 109 |
+
else:
|
| 110 |
+
x = F.interpolate(x, scale_factor=2, mode="nearest")
|
| 111 |
+
if self.use_conv:
|
| 112 |
+
x = self.conv(x)
|
| 113 |
+
return x
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class Downsample(nn.Module):
|
| 117 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.channels = channels
|
| 120 |
+
self.out_channels = out_channels or channels
|
| 121 |
+
self.use_conv = use_conv
|
| 122 |
+
stride = 2 if dims != 3 else (1, 2, 2)
|
| 123 |
+
if use_conv:
|
| 124 |
+
self.op = conv_nd(dims, self.channels, self.out_channels, 3, stride=stride, padding=1)
|
| 125 |
+
else:
|
| 126 |
+
assert self.channels == self.out_channels
|
| 127 |
+
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
|
| 128 |
+
|
| 129 |
+
def forward(self, x):
|
| 130 |
+
assert x.shape[1] == self.channels
|
| 131 |
+
return self.op(x)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class ResBlock(TimestepBlock):
|
| 135 |
+
def __init__(
|
| 136 |
+
self,
|
| 137 |
+
channels,
|
| 138 |
+
emb_channels,
|
| 139 |
+
dropout,
|
| 140 |
+
out_channels=None,
|
| 141 |
+
use_conv=False,
|
| 142 |
+
use_scale_shift_norm=False,
|
| 143 |
+
dims=2,
|
| 144 |
+
use_checkpoint=False,
|
| 145 |
+
up=False,
|
| 146 |
+
down=False,
|
| 147 |
+
):
|
| 148 |
+
super().__init__()
|
| 149 |
+
self.channels = channels
|
| 150 |
+
self.out_channels = out_channels or channels
|
| 151 |
+
self.use_checkpoint = use_checkpoint
|
| 152 |
+
self.use_scale_shift_norm = use_scale_shift_norm
|
| 153 |
+
self.in_layers = nn.Sequential(
|
| 154 |
+
normalization(channels),
|
| 155 |
+
nn.SiLU(),
|
| 156 |
+
conv_nd(dims, channels, self.out_channels, 3, padding=1),
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
self.updown = up or down
|
| 160 |
+
if up:
|
| 161 |
+
self.h_upd = Upsample(channels, False, dims)
|
| 162 |
+
self.x_upd = Upsample(channels, False, dims)
|
| 163 |
+
elif down:
|
| 164 |
+
self.h_upd = Downsample(channels, False, dims)
|
| 165 |
+
self.x_upd = Downsample(channels, False, dims)
|
| 166 |
+
else:
|
| 167 |
+
self.h_upd = self.x_upd = nn.Identity()
|
| 168 |
+
|
| 169 |
+
self.emb_layers = nn.Sequential(
|
| 170 |
+
nn.SiLU(),
|
| 171 |
+
linear(emb_channels, 2 * self.out_channels if use_scale_shift_norm else self.out_channels),
|
| 172 |
+
)
|
| 173 |
+
self.out_layers = nn.Sequential(
|
| 174 |
+
normalization(self.out_channels),
|
| 175 |
+
nn.SiLU(),
|
| 176 |
+
nn.Dropout(p=dropout),
|
| 177 |
+
zero_module(conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)),
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
if self.out_channels == channels:
|
| 181 |
+
self.skip_connection = nn.Identity()
|
| 182 |
+
elif use_conv:
|
| 183 |
+
self.skip_connection = conv_nd(dims, channels, self.out_channels, 3, padding=1)
|
| 184 |
+
else:
|
| 185 |
+
self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
|
| 186 |
+
|
| 187 |
+
def forward(self, x, emb):
|
| 188 |
+
if self.use_checkpoint and x.requires_grad:
|
| 189 |
+
return torch_checkpoint(self._forward, x, emb, use_reentrant=False)
|
| 190 |
+
return self._forward(x, emb)
|
| 191 |
+
|
| 192 |
+
def _forward(self, x, emb):
|
| 193 |
+
if self.updown:
|
| 194 |
+
in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
|
| 195 |
+
h = in_rest(x)
|
| 196 |
+
h = self.h_upd(h)
|
| 197 |
+
x = self.x_upd(x)
|
| 198 |
+
h = in_conv(h)
|
| 199 |
+
else:
|
| 200 |
+
h = self.in_layers(x)
|
| 201 |
+
|
| 202 |
+
emb_out = self.emb_layers(emb).type(h.dtype)
|
| 203 |
+
while len(emb_out.shape) < len(h.shape):
|
| 204 |
+
emb_out = emb_out[..., None]
|
| 205 |
+
if self.use_scale_shift_norm:
|
| 206 |
+
out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
|
| 207 |
+
scale, shift = torch.chunk(emb_out, 2, dim=1)
|
| 208 |
+
h = out_norm(h) * (1 + scale) + shift
|
| 209 |
+
h = out_rest(h)
|
| 210 |
+
else:
|
| 211 |
+
h = h + emb_out
|
| 212 |
+
h = self.out_layers(h)
|
| 213 |
+
return self.skip_connection(x) + h
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class QKVAttentionLegacy(nn.Module):
|
| 217 |
+
def __init__(self, n_heads):
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.n_heads = n_heads
|
| 220 |
+
|
| 221 |
+
def forward(self, qkv):
|
| 222 |
+
bs, width, length = qkv.shape
|
| 223 |
+
assert width % (3 * self.n_heads) == 0
|
| 224 |
+
ch = width // (3 * self.n_heads)
|
| 225 |
+
q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
|
| 226 |
+
scale = 1 / math.sqrt(math.sqrt(ch))
|
| 227 |
+
weight = torch.einsum("bct,bcs->bts", q * scale, k * scale)
|
| 228 |
+
weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
|
| 229 |
+
a = torch.einsum("bts,bcs->bct", weight, v)
|
| 230 |
+
return a.reshape(bs, -1, length)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class QKVAttention(nn.Module):
|
| 234 |
+
def __init__(self, n_heads):
|
| 235 |
+
super().__init__()
|
| 236 |
+
self.n_heads = n_heads
|
| 237 |
+
|
| 238 |
+
def forward(self, qkv):
|
| 239 |
+
bs, width, length = qkv.shape
|
| 240 |
+
assert width % (3 * self.n_heads) == 0
|
| 241 |
+
ch = width // (3 * self.n_heads)
|
| 242 |
+
q, k, v = qkv.chunk(3, dim=1)
|
| 243 |
+
scale = 1 / math.sqrt(math.sqrt(ch))
|
| 244 |
+
weight = torch.einsum(
|
| 245 |
+
"bct,bcs->bts",
|
| 246 |
+
(q * scale).view(bs * self.n_heads, ch, length),
|
| 247 |
+
(k * scale).view(bs * self.n_heads, ch, length),
|
| 248 |
+
)
|
| 249 |
+
weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
|
| 250 |
+
a = torch.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
|
| 251 |
+
return a.reshape(bs, -1, length)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class AttentionBlock(nn.Module):
|
| 255 |
+
def __init__(
|
| 256 |
+
self,
|
| 257 |
+
channels,
|
| 258 |
+
num_heads=1,
|
| 259 |
+
num_head_channels=-1,
|
| 260 |
+
use_checkpoint=False,
|
| 261 |
+
use_new_attention_order=False,
|
| 262 |
+
):
|
| 263 |
+
super().__init__()
|
| 264 |
+
if num_head_channels == -1:
|
| 265 |
+
self.num_heads = num_heads
|
| 266 |
+
else:
|
| 267 |
+
assert channels % num_head_channels == 0
|
| 268 |
+
self.num_heads = channels // num_head_channels
|
| 269 |
+
self.use_checkpoint = use_checkpoint
|
| 270 |
+
self.norm = normalization(channels)
|
| 271 |
+
self.qkv = conv_nd(1, channels, channels * 3, 1)
|
| 272 |
+
self.attention = QKVAttention(self.num_heads) if use_new_attention_order else QKVAttentionLegacy(self.num_heads)
|
| 273 |
+
self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
|
| 274 |
+
|
| 275 |
+
def forward(self, x):
|
| 276 |
+
if self.use_checkpoint and x.requires_grad:
|
| 277 |
+
return torch_checkpoint(self._forward, x, use_reentrant=False)
|
| 278 |
+
return self._forward(x)
|
| 279 |
+
|
| 280 |
+
def _forward(self, x):
|
| 281 |
+
b, c, *spatial = x.shape
|
| 282 |
+
x = x.reshape(b, c, -1)
|
| 283 |
+
qkv = self.qkv(self.norm(x))
|
| 284 |
+
h = self.attention(qkv)
|
| 285 |
+
h = self.proj_out(h)
|
| 286 |
+
return (x + h).reshape(b, c, *spatial)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
class AttentionPool2d(nn.Module):
|
| 290 |
+
"""CLIP-style attention pooling used by ADM noisy classifiers."""
|
| 291 |
+
|
| 292 |
+
def __init__(self, spacial_dim: int, embed_dim: int, num_heads_channels: int, output_dim: int = None):
|
| 293 |
+
super().__init__()
|
| 294 |
+
self.positional_embedding = nn.Parameter(torch.randn(embed_dim, spacial_dim**2 + 1) / embed_dim**0.5)
|
| 295 |
+
self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
|
| 296 |
+
self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
|
| 297 |
+
self.num_heads = embed_dim // num_heads_channels
|
| 298 |
+
self.attention = QKVAttention(self.num_heads)
|
| 299 |
+
|
| 300 |
+
def forward(self, x):
|
| 301 |
+
b, c, *_spatial = x.shape
|
| 302 |
+
x = x.reshape(b, c, -1)
|
| 303 |
+
x = torch.cat([x.mean(dim=-1, keepdim=True), x], dim=-1)
|
| 304 |
+
x = x + self.positional_embedding[None, :, :].to(x.dtype)
|
| 305 |
+
x = self.qkv_proj(x)
|
| 306 |
+
x = self.attention(x)
|
| 307 |
+
x = self.c_proj(x)
|
| 308 |
+
return x[:, :, 0]
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class EncoderUNetModel(nn.Module):
|
| 312 |
+
"""Noisy image classifier backbone for ADM-G (classifier guidance)."""
|
| 313 |
+
|
| 314 |
+
def __init__(
|
| 315 |
+
self,
|
| 316 |
+
image_size,
|
| 317 |
+
in_channels,
|
| 318 |
+
model_channels,
|
| 319 |
+
out_channels,
|
| 320 |
+
num_res_blocks,
|
| 321 |
+
attention_resolutions,
|
| 322 |
+
dropout=0,
|
| 323 |
+
channel_mult=(1, 2, 4, 8),
|
| 324 |
+
conv_resample=True,
|
| 325 |
+
dims=2,
|
| 326 |
+
use_checkpoint=False,
|
| 327 |
+
use_fp16=False,
|
| 328 |
+
num_heads=1,
|
| 329 |
+
num_head_channels=-1,
|
| 330 |
+
use_scale_shift_norm=False,
|
| 331 |
+
resblock_updown=False,
|
| 332 |
+
use_new_attention_order=False,
|
| 333 |
+
pool="adaptive",
|
| 334 |
+
):
|
| 335 |
+
super().__init__()
|
| 336 |
+
|
| 337 |
+
self.in_channels = in_channels
|
| 338 |
+
self.model_channels = model_channels
|
| 339 |
+
self.out_channels = out_channels
|
| 340 |
+
self.num_res_blocks = num_res_blocks
|
| 341 |
+
self.dropout = dropout
|
| 342 |
+
self.channel_mult = channel_mult
|
| 343 |
+
self.conv_resample = conv_resample
|
| 344 |
+
self.use_checkpoint = use_checkpoint
|
| 345 |
+
self.dtype = torch.float16 if use_fp16 else torch.float32
|
| 346 |
+
self.num_heads = num_heads
|
| 347 |
+
self.num_head_channels = num_head_channels
|
| 348 |
+
|
| 349 |
+
time_embed_dim = model_channels * 4
|
| 350 |
+
self.time_embed = nn.Sequential(
|
| 351 |
+
linear(model_channels, time_embed_dim),
|
| 352 |
+
nn.SiLU(),
|
| 353 |
+
linear(time_embed_dim, time_embed_dim),
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
ch = int(channel_mult[0] * model_channels)
|
| 357 |
+
self.input_blocks = nn.ModuleList([TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))])
|
| 358 |
+
self._feature_size = ch
|
| 359 |
+
input_block_chans = [ch]
|
| 360 |
+
ds = 1
|
| 361 |
+
for level, mult in enumerate(channel_mult):
|
| 362 |
+
for _ in range(num_res_blocks):
|
| 363 |
+
layers = [
|
| 364 |
+
ResBlock(
|
| 365 |
+
ch,
|
| 366 |
+
time_embed_dim,
|
| 367 |
+
dropout,
|
| 368 |
+
out_channels=int(mult * model_channels),
|
| 369 |
+
dims=dims,
|
| 370 |
+
use_checkpoint=use_checkpoint,
|
| 371 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 372 |
+
)
|
| 373 |
+
]
|
| 374 |
+
ch = int(mult * model_channels)
|
| 375 |
+
if ds in attention_resolutions:
|
| 376 |
+
layers.append(
|
| 377 |
+
AttentionBlock(
|
| 378 |
+
ch,
|
| 379 |
+
use_checkpoint=use_checkpoint,
|
| 380 |
+
num_heads=num_heads,
|
| 381 |
+
num_head_channels=num_head_channels,
|
| 382 |
+
use_new_attention_order=use_new_attention_order,
|
| 383 |
+
)
|
| 384 |
+
)
|
| 385 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
| 386 |
+
self._feature_size += ch
|
| 387 |
+
input_block_chans.append(ch)
|
| 388 |
+
if level != len(channel_mult) - 1:
|
| 389 |
+
out_ch = ch
|
| 390 |
+
self.input_blocks.append(
|
| 391 |
+
TimestepEmbedSequential(
|
| 392 |
+
ResBlock(
|
| 393 |
+
ch,
|
| 394 |
+
time_embed_dim,
|
| 395 |
+
dropout,
|
| 396 |
+
out_channels=out_ch,
|
| 397 |
+
dims=dims,
|
| 398 |
+
use_checkpoint=use_checkpoint,
|
| 399 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 400 |
+
down=True,
|
| 401 |
+
)
|
| 402 |
+
if resblock_updown
|
| 403 |
+
else Downsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
| 404 |
+
)
|
| 405 |
+
)
|
| 406 |
+
ch = out_ch
|
| 407 |
+
input_block_chans.append(ch)
|
| 408 |
+
ds *= 2
|
| 409 |
+
self._feature_size += ch
|
| 410 |
+
|
| 411 |
+
self.middle_block = TimestepEmbedSequential(
|
| 412 |
+
ResBlock(
|
| 413 |
+
ch,
|
| 414 |
+
time_embed_dim,
|
| 415 |
+
dropout,
|
| 416 |
+
dims=dims,
|
| 417 |
+
use_checkpoint=use_checkpoint,
|
| 418 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 419 |
+
),
|
| 420 |
+
AttentionBlock(
|
| 421 |
+
ch,
|
| 422 |
+
use_checkpoint=use_checkpoint,
|
| 423 |
+
num_heads=num_heads,
|
| 424 |
+
num_head_channels=num_head_channels,
|
| 425 |
+
use_new_attention_order=use_new_attention_order,
|
| 426 |
+
),
|
| 427 |
+
ResBlock(
|
| 428 |
+
ch,
|
| 429 |
+
time_embed_dim,
|
| 430 |
+
dropout,
|
| 431 |
+
dims=dims,
|
| 432 |
+
use_checkpoint=use_checkpoint,
|
| 433 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 434 |
+
),
|
| 435 |
+
)
|
| 436 |
+
self._feature_size += ch
|
| 437 |
+
self.pool = pool
|
| 438 |
+
if pool == "adaptive":
|
| 439 |
+
self.out = nn.Sequential(
|
| 440 |
+
normalization(ch),
|
| 441 |
+
nn.SiLU(),
|
| 442 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 443 |
+
zero_module(conv_nd(dims, ch, out_channels, 1)),
|
| 444 |
+
nn.Flatten(),
|
| 445 |
+
)
|
| 446 |
+
elif pool == "attention":
|
| 447 |
+
assert num_head_channels != -1
|
| 448 |
+
self.out = nn.Sequential(
|
| 449 |
+
normalization(ch),
|
| 450 |
+
nn.SiLU(),
|
| 451 |
+
AttentionPool2d((image_size // ds), ch, num_head_channels, out_channels),
|
| 452 |
+
)
|
| 453 |
+
elif pool == "spatial":
|
| 454 |
+
self.out = nn.Sequential(
|
| 455 |
+
nn.Linear(self._feature_size, 2048),
|
| 456 |
+
nn.ReLU(),
|
| 457 |
+
nn.Linear(2048, out_channels),
|
| 458 |
+
)
|
| 459 |
+
elif pool == "spatial_v2":
|
| 460 |
+
self.out = nn.Sequential(
|
| 461 |
+
nn.Linear(self._feature_size, 2048),
|
| 462 |
+
normalization(2048),
|
| 463 |
+
nn.SiLU(),
|
| 464 |
+
nn.Linear(2048, out_channels),
|
| 465 |
+
)
|
| 466 |
+
else:
|
| 467 |
+
raise NotImplementedError(f"Unexpected {pool} pooling")
|
| 468 |
+
|
| 469 |
+
def convert_to_fp16(self):
|
| 470 |
+
self.input_blocks.apply(convert_module_to_f16)
|
| 471 |
+
self.middle_block.apply(convert_module_to_f16)
|
| 472 |
+
|
| 473 |
+
def convert_to_fp32(self):
|
| 474 |
+
self.input_blocks.apply(convert_module_to_f32)
|
| 475 |
+
self.middle_block.apply(convert_module_to_f32)
|
| 476 |
+
|
| 477 |
+
def forward(self, x, timesteps):
|
| 478 |
+
emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
|
| 479 |
+
results = []
|
| 480 |
+
h = x.type(self.dtype)
|
| 481 |
+
for module in self.input_blocks:
|
| 482 |
+
h = module(h, emb)
|
| 483 |
+
if self.pool.startswith("spatial"):
|
| 484 |
+
results.append(h.type(x.dtype).mean(dim=(2, 3)))
|
| 485 |
+
h = self.middle_block(h, emb)
|
| 486 |
+
if self.pool.startswith("spatial"):
|
| 487 |
+
results.append(h.type(x.dtype).mean(dim=(2, 3)))
|
| 488 |
+
h = torch.cat(results, dim=-1)
|
| 489 |
+
return self.out(h)
|
| 490 |
+
h = h.type(x.dtype)
|
| 491 |
+
return self.out(h)
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
class UNetModel(nn.Module):
|
| 495 |
+
def __init__(
|
| 496 |
+
self,
|
| 497 |
+
image_size,
|
| 498 |
+
in_channels,
|
| 499 |
+
model_channels,
|
| 500 |
+
out_channels,
|
| 501 |
+
num_res_blocks,
|
| 502 |
+
attention_resolutions,
|
| 503 |
+
dropout=0,
|
| 504 |
+
channel_mult=(1, 2, 4, 8),
|
| 505 |
+
conv_resample=True,
|
| 506 |
+
dims=2,
|
| 507 |
+
num_classes=None,
|
| 508 |
+
use_checkpoint=False,
|
| 509 |
+
use_fp16=False,
|
| 510 |
+
num_heads=1,
|
| 511 |
+
num_head_channels=-1,
|
| 512 |
+
num_heads_upsample=-1,
|
| 513 |
+
use_scale_shift_norm=False,
|
| 514 |
+
resblock_updown=False,
|
| 515 |
+
use_new_attention_order=False,
|
| 516 |
+
):
|
| 517 |
+
super().__init__()
|
| 518 |
+
if num_heads_upsample == -1:
|
| 519 |
+
num_heads_upsample = num_heads
|
| 520 |
+
|
| 521 |
+
self.model_channels = model_channels
|
| 522 |
+
self.num_classes = num_classes
|
| 523 |
+
self.dtype = torch.float16 if use_fp16 else torch.float32
|
| 524 |
+
|
| 525 |
+
time_embed_dim = model_channels * 4
|
| 526 |
+
self.time_embed = nn.Sequential(
|
| 527 |
+
linear(model_channels, time_embed_dim),
|
| 528 |
+
nn.SiLU(),
|
| 529 |
+
linear(time_embed_dim, time_embed_dim),
|
| 530 |
+
)
|
| 531 |
+
if self.num_classes is not None:
|
| 532 |
+
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
|
| 533 |
+
|
| 534 |
+
ch = input_ch = int(channel_mult[0] * model_channels)
|
| 535 |
+
self.input_blocks = nn.ModuleList([TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))])
|
| 536 |
+
input_block_chans = [ch]
|
| 537 |
+
ds = 1
|
| 538 |
+
for level, mult in enumerate(channel_mult):
|
| 539 |
+
for _ in range(num_res_blocks):
|
| 540 |
+
layers = [
|
| 541 |
+
ResBlock(
|
| 542 |
+
ch,
|
| 543 |
+
time_embed_dim,
|
| 544 |
+
dropout,
|
| 545 |
+
out_channels=int(mult * model_channels),
|
| 546 |
+
dims=dims,
|
| 547 |
+
use_checkpoint=use_checkpoint,
|
| 548 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 549 |
+
)
|
| 550 |
+
]
|
| 551 |
+
ch = int(mult * model_channels)
|
| 552 |
+
if ds in attention_resolutions:
|
| 553 |
+
layers.append(
|
| 554 |
+
AttentionBlock(
|
| 555 |
+
ch,
|
| 556 |
+
use_checkpoint=use_checkpoint,
|
| 557 |
+
num_heads=num_heads,
|
| 558 |
+
num_head_channels=num_head_channels,
|
| 559 |
+
use_new_attention_order=use_new_attention_order,
|
| 560 |
+
)
|
| 561 |
+
)
|
| 562 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
| 563 |
+
input_block_chans.append(ch)
|
| 564 |
+
if level != len(channel_mult) - 1:
|
| 565 |
+
out_ch = ch
|
| 566 |
+
self.input_blocks.append(
|
| 567 |
+
TimestepEmbedSequential(
|
| 568 |
+
ResBlock(
|
| 569 |
+
ch,
|
| 570 |
+
time_embed_dim,
|
| 571 |
+
dropout,
|
| 572 |
+
out_channels=out_ch,
|
| 573 |
+
dims=dims,
|
| 574 |
+
use_checkpoint=use_checkpoint,
|
| 575 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 576 |
+
down=True,
|
| 577 |
+
)
|
| 578 |
+
if resblock_updown
|
| 579 |
+
else Downsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
| 580 |
+
)
|
| 581 |
+
)
|
| 582 |
+
ch = out_ch
|
| 583 |
+
input_block_chans.append(ch)
|
| 584 |
+
ds *= 2
|
| 585 |
+
|
| 586 |
+
self.middle_block = TimestepEmbedSequential(
|
| 587 |
+
ResBlock(
|
| 588 |
+
ch,
|
| 589 |
+
time_embed_dim,
|
| 590 |
+
dropout,
|
| 591 |
+
dims=dims,
|
| 592 |
+
use_checkpoint=use_checkpoint,
|
| 593 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 594 |
+
),
|
| 595 |
+
AttentionBlock(
|
| 596 |
+
ch,
|
| 597 |
+
use_checkpoint=use_checkpoint,
|
| 598 |
+
num_heads=num_heads,
|
| 599 |
+
num_head_channels=num_head_channels,
|
| 600 |
+
use_new_attention_order=use_new_attention_order,
|
| 601 |
+
),
|
| 602 |
+
ResBlock(
|
| 603 |
+
ch,
|
| 604 |
+
time_embed_dim,
|
| 605 |
+
dropout,
|
| 606 |
+
dims=dims,
|
| 607 |
+
use_checkpoint=use_checkpoint,
|
| 608 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 609 |
+
),
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
self.output_blocks = nn.ModuleList([])
|
| 613 |
+
for level, mult in list(enumerate(channel_mult))[::-1]:
|
| 614 |
+
for i in range(num_res_blocks + 1):
|
| 615 |
+
ich = input_block_chans.pop()
|
| 616 |
+
layers = [
|
| 617 |
+
ResBlock(
|
| 618 |
+
ch + ich,
|
| 619 |
+
time_embed_dim,
|
| 620 |
+
dropout,
|
| 621 |
+
out_channels=int(model_channels * mult),
|
| 622 |
+
dims=dims,
|
| 623 |
+
use_checkpoint=use_checkpoint,
|
| 624 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 625 |
+
)
|
| 626 |
+
]
|
| 627 |
+
ch = int(model_channels * mult)
|
| 628 |
+
if ds in attention_resolutions:
|
| 629 |
+
layers.append(
|
| 630 |
+
AttentionBlock(
|
| 631 |
+
ch,
|
| 632 |
+
use_checkpoint=use_checkpoint,
|
| 633 |
+
num_heads=num_heads_upsample,
|
| 634 |
+
num_head_channels=num_head_channels,
|
| 635 |
+
use_new_attention_order=use_new_attention_order,
|
| 636 |
+
)
|
| 637 |
+
)
|
| 638 |
+
if level and i == num_res_blocks:
|
| 639 |
+
out_ch = ch
|
| 640 |
+
layers.append(
|
| 641 |
+
ResBlock(
|
| 642 |
+
ch,
|
| 643 |
+
time_embed_dim,
|
| 644 |
+
dropout,
|
| 645 |
+
out_channels=out_ch,
|
| 646 |
+
dims=dims,
|
| 647 |
+
use_checkpoint=use_checkpoint,
|
| 648 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 649 |
+
up=True,
|
| 650 |
+
)
|
| 651 |
+
if resblock_updown
|
| 652 |
+
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
|
| 653 |
+
)
|
| 654 |
+
ds //= 2
|
| 655 |
+
self.output_blocks.append(TimestepEmbedSequential(*layers))
|
| 656 |
+
|
| 657 |
+
self.out = nn.Sequential(
|
| 658 |
+
normalization(ch),
|
| 659 |
+
nn.SiLU(),
|
| 660 |
+
zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),
|
| 661 |
+
)
|
| 662 |
+
|
| 663 |
+
def convert_to_fp16(self):
|
| 664 |
+
self.input_blocks.apply(convert_module_to_f16)
|
| 665 |
+
self.middle_block.apply(convert_module_to_f16)
|
| 666 |
+
self.output_blocks.apply(convert_module_to_f16)
|
| 667 |
+
|
| 668 |
+
def convert_to_fp32(self):
|
| 669 |
+
self.input_blocks.apply(convert_module_to_f32)
|
| 670 |
+
self.middle_block.apply(convert_module_to_f32)
|
| 671 |
+
self.output_blocks.apply(convert_module_to_f32)
|
| 672 |
+
|
| 673 |
+
def forward(self, x, timesteps, y: Optional[torch.Tensor] = None):
|
| 674 |
+
assert (y is not None) == (self.num_classes is not None)
|
| 675 |
+
hs = []
|
| 676 |
+
emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
|
| 677 |
+
if self.num_classes is not None:
|
| 678 |
+
assert y.shape == (x.shape[0],)
|
| 679 |
+
emb = emb + self.label_emb(y)
|
| 680 |
+
|
| 681 |
+
h = x.type(self.dtype)
|
| 682 |
+
for module in self.input_blocks:
|
| 683 |
+
h = module(h, emb)
|
| 684 |
+
hs.append(h)
|
| 685 |
+
h = self.middle_block(h, emb)
|
| 686 |
+
for module in self.output_blocks:
|
| 687 |
+
h = torch.cat([h, hs.pop()], dim=1)
|
| 688 |
+
h = module(h, emb)
|
| 689 |
+
h = h.type(x.dtype)
|
| 690 |
+
return self.out(h)
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
def _default_channel_mult(image_size: int):
|
| 694 |
+
if image_size == 512:
|
| 695 |
+
return (0.5, 1, 1, 2, 2, 4, 4)
|
| 696 |
+
if image_size == 256:
|
| 697 |
+
return (1, 1, 2, 2, 4, 4)
|
| 698 |
+
if image_size == 128:
|
| 699 |
+
return (1, 1, 2, 3, 4)
|
| 700 |
+
if image_size == 64:
|
| 701 |
+
return (1, 2, 3, 4)
|
| 702 |
+
raise ValueError(f"unsupported image size: {image_size}")
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
def create_adm_unet_model(
|
| 706 |
+
image_size,
|
| 707 |
+
num_channels,
|
| 708 |
+
num_res_blocks,
|
| 709 |
+
channel_mult="",
|
| 710 |
+
learn_sigma=False,
|
| 711 |
+
class_cond=False,
|
| 712 |
+
use_checkpoint=False,
|
| 713 |
+
attention_resolutions="16",
|
| 714 |
+
num_heads=1,
|
| 715 |
+
num_head_channels=-1,
|
| 716 |
+
num_heads_upsample=-1,
|
| 717 |
+
use_scale_shift_norm=False,
|
| 718 |
+
dropout=0.0,
|
| 719 |
+
resblock_updown=False,
|
| 720 |
+
use_fp16=False,
|
| 721 |
+
use_new_attention_order=False,
|
| 722 |
+
):
|
| 723 |
+
channel_mult = _default_channel_mult(image_size) if channel_mult == "" else tuple(int(v) for v in channel_mult.split(","))
|
| 724 |
+
attention_ds = tuple(image_size // int(res) for res in attention_resolutions.split(","))
|
| 725 |
+
return UNetModel(
|
| 726 |
+
image_size=image_size,
|
| 727 |
+
in_channels=3,
|
| 728 |
+
model_channels=num_channels,
|
| 729 |
+
out_channels=(3 if not learn_sigma else 6),
|
| 730 |
+
num_res_blocks=num_res_blocks,
|
| 731 |
+
attention_resolutions=attention_ds,
|
| 732 |
+
dropout=dropout,
|
| 733 |
+
channel_mult=channel_mult,
|
| 734 |
+
num_classes=(NUM_CLASSES if class_cond else None),
|
| 735 |
+
use_checkpoint=use_checkpoint,
|
| 736 |
+
use_fp16=use_fp16,
|
| 737 |
+
num_heads=num_heads,
|
| 738 |
+
num_head_channels=num_head_channels,
|
| 739 |
+
num_heads_upsample=num_heads_upsample,
|
| 740 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 741 |
+
resblock_updown=resblock_updown,
|
| 742 |
+
use_new_attention_order=use_new_attention_order,
|
| 743 |
+
)
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
def create_adm_classifier_model(
|
| 747 |
+
image_size: int,
|
| 748 |
+
classifier_width: int = 128,
|
| 749 |
+
classifier_depth: int = 2,
|
| 750 |
+
classifier_attention_resolutions: str = "32,16,8",
|
| 751 |
+
classifier_use_scale_shift_norm: bool = True,
|
| 752 |
+
classifier_resblock_updown: bool = True,
|
| 753 |
+
classifier_pool: str = "attention",
|
| 754 |
+
use_fp16: bool = False,
|
| 755 |
+
num_classes: int = NUM_CLASSES,
|
| 756 |
+
):
|
| 757 |
+
channel_mult = _default_channel_mult(image_size)
|
| 758 |
+
attention_ds = tuple(image_size // int(res) for res in classifier_attention_resolutions.split(","))
|
| 759 |
+
return EncoderUNetModel(
|
| 760 |
+
image_size=image_size,
|
| 761 |
+
in_channels=3,
|
| 762 |
+
model_channels=classifier_width,
|
| 763 |
+
out_channels=num_classes,
|
| 764 |
+
num_res_blocks=classifier_depth,
|
| 765 |
+
attention_resolutions=attention_ds,
|
| 766 |
+
channel_mult=channel_mult,
|
| 767 |
+
use_fp16=use_fp16,
|
| 768 |
+
num_head_channels=64,
|
| 769 |
+
use_scale_shift_norm=classifier_use_scale_shift_norm,
|
| 770 |
+
resblock_updown=classifier_resblock_updown,
|
| 771 |
+
pool=classifier_pool,
|
| 772 |
+
)
|
ADM-G-512/unet/unet_adm.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import Optional, Tuple, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 12 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 13 |
+
from diffusers.utils import BaseOutput
|
| 14 |
+
|
| 15 |
+
from modeling_adm import create_adm_unet_model
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass
|
| 19 |
+
class ADMUNetOutput(BaseOutput):
|
| 20 |
+
"""
|
| 21 |
+
Output of the ADM UNet model.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
sample (`torch.Tensor` of shape `(batch_size, out_channels, height, width)`):
|
| 25 |
+
The denoised or noise-predicting tensor from the UNet.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
sample: torch.FloatTensor
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ADMUNet2DModel(ModelMixin, ConfigMixin):
|
| 32 |
+
"""
|
| 33 |
+
ADM UNet model for class-conditional image diffusion in pixel space.
|
| 34 |
+
|
| 35 |
+
This wraps the OpenAI ADM `UNetModel` architecture with Diffusers `ModelMixin` / `ConfigMixin` for Hub
|
| 36 |
+
serialization.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
@register_to_config
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
image_size: int = 64,
|
| 43 |
+
num_channels: int = 128,
|
| 44 |
+
num_res_blocks: int = 2,
|
| 45 |
+
channel_mult: str = "",
|
| 46 |
+
learn_sigma: bool = False,
|
| 47 |
+
class_cond: bool = False,
|
| 48 |
+
use_checkpoint: bool = False,
|
| 49 |
+
attention_resolutions: str = "16,8",
|
| 50 |
+
num_heads: int = 4,
|
| 51 |
+
num_head_channels: int = -1,
|
| 52 |
+
num_heads_upsample: int = -1,
|
| 53 |
+
use_scale_shift_norm: bool = True,
|
| 54 |
+
dropout: float = 0.0,
|
| 55 |
+
resblock_updown: bool = False,
|
| 56 |
+
use_fp16: bool = False,
|
| 57 |
+
use_new_attention_order: bool = False,
|
| 58 |
+
in_channels: int = 3,
|
| 59 |
+
out_channels: Optional[int] = None,
|
| 60 |
+
):
|
| 61 |
+
super().__init__()
|
| 62 |
+
if out_channels is None:
|
| 63 |
+
out_channels = 6 if learn_sigma else 3
|
| 64 |
+
|
| 65 |
+
self.model = create_adm_unet_model(
|
| 66 |
+
image_size=image_size,
|
| 67 |
+
num_channels=num_channels,
|
| 68 |
+
num_res_blocks=num_res_blocks,
|
| 69 |
+
channel_mult=channel_mult,
|
| 70 |
+
learn_sigma=learn_sigma,
|
| 71 |
+
class_cond=class_cond,
|
| 72 |
+
use_checkpoint=use_checkpoint,
|
| 73 |
+
attention_resolutions=attention_resolutions,
|
| 74 |
+
num_heads=num_heads,
|
| 75 |
+
num_head_channels=num_head_channels,
|
| 76 |
+
num_heads_upsample=num_heads_upsample,
|
| 77 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
| 78 |
+
dropout=dropout,
|
| 79 |
+
resblock_updown=resblock_updown,
|
| 80 |
+
use_fp16=use_fp16,
|
| 81 |
+
use_new_attention_order=use_new_attention_order,
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def dtype(self) -> torch.dtype:
|
| 86 |
+
return next(self.parameters()).dtype
|
| 87 |
+
|
| 88 |
+
def forward(
|
| 89 |
+
self,
|
| 90 |
+
sample: torch.Tensor,
|
| 91 |
+
timestep: Union[torch.Tensor, float, int],
|
| 92 |
+
class_labels: Optional[torch.Tensor] = None,
|
| 93 |
+
return_dict: bool = True,
|
| 94 |
+
) -> Union[ADMUNetOutput, Tuple[torch.Tensor, ...]]:
|
| 95 |
+
"""
|
| 96 |
+
Forward pass of the ADM UNet.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
sample (`torch.Tensor`):
|
| 100 |
+
Noisy input tensor of shape `(batch_size, in_channels, height, width)`.
|
| 101 |
+
timestep (`torch.Tensor` or `float` or `int`):
|
| 102 |
+
Timestep indices or embeddings broadcastable to batch size.
|
| 103 |
+
class_labels (`torch.Tensor`, *optional*):
|
| 104 |
+
Class indices of shape `(batch_size,)` for class-conditional models.
|
| 105 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 106 |
+
Whether to return an [`ADMUNetOutput`] instead of a tuple.
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
[`ADMUNetOutput`] or `tuple`:
|
| 110 |
+
If `return_dict` is `True`, an [`ADMUNetOutput`] is returned, otherwise a tuple `(sample,)`.
|
| 111 |
+
"""
|
| 112 |
+
if not torch.is_tensor(timestep):
|
| 113 |
+
timestep = torch.tensor([timestep], device=sample.device, dtype=torch.long)
|
| 114 |
+
elif timestep.ndim == 0:
|
| 115 |
+
timestep = timestep.reshape(1).to(device=sample.device)
|
| 116 |
+
if timestep.shape[0] == 1 and sample.shape[0] > 1:
|
| 117 |
+
timestep = timestep.expand(sample.shape[0])
|
| 118 |
+
|
| 119 |
+
output = self.model(sample, timestep, y=class_labels)
|
| 120 |
+
|
| 121 |
+
if not return_dict:
|
| 122 |
+
return (output,)
|
| 123 |
+
|
| 124 |
+
return ADMUNetOutput(sample=output)
|
README.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
library_name: diffusers
|
| 4 |
+
pipeline_tag: text-to-image
|
| 5 |
+
tags:
|
| 6 |
+
- diffusers
|
| 7 |
+
- adm
|
| 8 |
+
- adm-g
|
| 9 |
+
- image-generation
|
| 10 |
+
- class-conditional
|
| 11 |
+
widget:
|
| 12 |
+
- output:
|
| 13 |
+
url: demo.png
|
| 14 |
+
language:
|
| 15 |
+
- en
|
| 16 |
+
---
|
| 17 |
+
|
| 18 |
+
# ADM-G-512 (Diffusers)
|
| 19 |
+
|
| 20 |
+
OpenAI ADM-G at 512×512, converted for the custom pipeline in `src/diffusers/ADM`.
|
| 21 |
+
|
| 22 |
+
## Demo
|
| 23 |
+
|
| 24 |
+

|
| 25 |
+
|
| 26 |
+
## Layout
|
| 27 |
+
|
| 28 |
+
```text
|
| 29 |
+
ADM-diffusers/
|
| 30 |
+
├── README.md
|
| 31 |
+
├── pipeline.py
|
| 32 |
+
├── model_index.json
|
| 33 |
+
├── demo.png
|
| 34 |
+
└── ADM-G-512/
|
| 35 |
+
├── classifier/ # 512x512_classifier.pt
|
| 36 |
+
├── scheduler/
|
| 37 |
+
└── unet/ # 512x512_diffusion.pt
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
ADM-G-512 uses **both** OpenAI checkpoints together, matching [classifier_sample.py](https://github.com/openai/guided-diffusion/blob/main/scripts/classifier_sample.py):
|
| 41 |
+
|
| 42 |
+
- `unet/` — class-conditional diffusion model (`512x512_diffusion.pt`, `class_cond=True`)
|
| 43 |
+
- `classifier/` — noisy ImageNet classifier (`512x512_classifier.pt`)
|
| 44 |
+
- `scheduler/` — DDPM/DDIM scheduler
|
| 45 |
+
|
| 46 |
+
## Load
|
| 47 |
+
|
| 48 |
+
Run from this directory:
|
| 49 |
+
|
| 50 |
+
```python
|
| 51 |
+
import sys
|
| 52 |
+
from pathlib import Path
|
| 53 |
+
import torch
|
| 54 |
+
|
| 55 |
+
repo = Path(__file__).resolve().parent
|
| 56 |
+
sys.path.insert(0, str(repo))
|
| 57 |
+
from pipeline import ADMPipeline
|
| 58 |
+
|
| 59 |
+
pipe = ADMPipeline.from_pretrained("ADM-G-512")
|
| 60 |
+
pipe.to("cuda")
|
| 61 |
+
pipe.unet.float()
|
| 62 |
+
pipe.classifier.float()
|
| 63 |
+
pipe.classifier.model.dtype = torch.float32
|
| 64 |
+
|
| 65 |
+
generator = torch.Generator(device="cuda").manual_seed(42)
|
| 66 |
+
images = pipe(
|
| 67 |
+
class_labels=207,
|
| 68 |
+
num_inference_steps=250,
|
| 69 |
+
use_ddim=False,
|
| 70 |
+
classifier_guidance_scale=4.0,
|
| 71 |
+
generator=generator,
|
| 72 |
+
).images
|
| 73 |
+
images[0].save("demo.png")
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
Both the UNet and classifier receive the target class. The UNet uses embedded class conditioning; the classifier adds gradient guidance on top.
|
| 77 |
+
|
| 78 |
+
Set `classifier_guidance_scale=0.0` to disable classifier guidance and sample from the base class-conditional diffusion model only.
|
| 79 |
+
|
| 80 |
+
## Demo settings
|
| 81 |
+
|
| 82 |
+
| Setting | Value |
|
| 83 |
+
| --- | --- |
|
| 84 |
+
| Class | 207 (golden retriever) |
|
| 85 |
+
| Steps | 250 (DDPM) |
|
| 86 |
+
| Classifier scale | 4.0 |
|
| 87 |
+
| Seed | 42 |
|
__pycache__/pipeline.cpython-312.pyc
ADDED
|
Binary file (16.7 kB). View file
|
|
|
demo.png
ADDED
|
Git LFS Details
|
model_index.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_class_name": "ADMPipeline",
|
| 3 |
+
"_diffusers_version": "0.36.0",
|
| 4 |
+
"scheduler": [
|
| 5 |
+
"scheduling_adm",
|
| 6 |
+
"ADMScheduler"
|
| 7 |
+
],
|
| 8 |
+
"unet": [
|
| 9 |
+
"unet_adm",
|
| 10 |
+
"ADMUNet2DModel"
|
| 11 |
+
],
|
| 12 |
+
"classifier": [
|
| 13 |
+
"classifier_adm",
|
| 14 |
+
"ADMClassifierModel"
|
| 15 |
+
]
|
| 16 |
+
}
|
pipeline.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
|
| 6 |
+
"""Hub custom pipeline: ADMPipeline.
|
| 7 |
+
|
| 8 |
+
Load with native Hugging Face diffusers and `trust_remote_code=True`.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import importlib
|
| 14 |
+
import sys
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import List, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from tqdm.auto import tqdm
|
| 22 |
+
|
| 23 |
+
from diffusers.image_processor import VaeImageProcessor
|
| 24 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 25 |
+
from diffusers.utils import BaseOutput, replace_example_docstring
|
| 26 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
EXAMPLE_DOC_STRING = """
|
| 30 |
+
Examples:
|
| 31 |
+
```py
|
| 32 |
+
>>> import torch
|
| 33 |
+
>>> from diffusers import DiffusionPipeline
|
| 34 |
+
|
| 35 |
+
>>> from pipeline import ADMPipeline
|
| 36 |
+
|
| 37 |
+
>>> pipe = ADMPipeline.from_pretrained("./ADM-G-512", torch_dtype=torch.float16)
|
| 38 |
+
>>> pipe.to("cuda")
|
| 39 |
+
|
| 40 |
+
>>> # ADM-G (classifier guidance)
|
| 41 |
+
>>> images = pipe(class_labels=207, classifier_guidance_scale=1.0, num_inference_steps=250).images
|
| 42 |
+
```
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@dataclass
|
| 47 |
+
class ADMPipelineOutput(BaseOutput):
|
| 48 |
+
"""
|
| 49 |
+
Output class for ADM pipelines.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
images (`torch.Tensor` or `list[PIL.Image.Image]` or `np.ndarray`):
|
| 53 |
+
Generated images of shape `(batch_size, num_channels, height, width)` when `output_type="pt"`,
|
| 54 |
+
or a list of PIL images / NumPy array when post-processed.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
images: Union[torch.Tensor, List, np.ndarray]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class ADMPipeline(DiffusionPipeline):
|
| 61 |
+
r"""
|
| 62 |
+
Pipeline for image generation with ADM (Ablated Diffusion Model).
|
| 63 |
+
|
| 64 |
+
Supports class-conditional ADM (labels embedded in the UNet) and **ADM-G** (unconditional UNet + noisy
|
| 65 |
+
classifier guidance). For ADM-G, pass `classifier_guidance_scale > 0` and provide `class_labels`; the
|
| 66 |
+
optional `classifier` predicts `p(y | x_t)` and steers sampling.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
unet ([`ADMUNet2DModel`]):
|
| 70 |
+
A UNet model to denoise image samples (typically unconditional for ADM-G).
|
| 71 |
+
scheduler ([`ADMScheduler`]):
|
| 72 |
+
A scheduler used with the UNet to denoise image samples.
|
| 73 |
+
classifier ([`ADMClassifierModel`], *optional*):
|
| 74 |
+
Noisy ImageNet classifier for ADM-G guidance.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
model_cpu_offload_seq = "classifier->unet"
|
| 78 |
+
_optional_components = ["classifier"]
|
| 79 |
+
|
| 80 |
+
@classmethod
|
| 81 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 82 |
+
"""Load a variant folder (e.g. `./ADM-G-512`) with `unet/`, `scheduler/`, `classifier/` subfolders."""
|
| 83 |
+
repo_root = Path(__file__).resolve().parent
|
| 84 |
+
variant = Path(pretrained_model_name_or_path)
|
| 85 |
+
if not variant.is_absolute():
|
| 86 |
+
variant = (repo_root / variant).resolve()
|
| 87 |
+
|
| 88 |
+
model_kwargs = dict(kwargs)
|
| 89 |
+
inserted: List[str] = []
|
| 90 |
+
|
| 91 |
+
def _load_component(folder: str, module_name: str, class_name: str):
|
| 92 |
+
comp_dir = variant / folder
|
| 93 |
+
module_path = comp_dir / f"{module_name}.py"
|
| 94 |
+
has_weights = (comp_dir / "config.json").exists() or (comp_dir / "scheduler_config.json").exists()
|
| 95 |
+
if not module_path.exists() or not has_weights:
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
comp_path = str(comp_dir)
|
| 99 |
+
if comp_path not in sys.path:
|
| 100 |
+
sys.path.insert(0, comp_path)
|
| 101 |
+
inserted.append(comp_path)
|
| 102 |
+
|
| 103 |
+
module = importlib.import_module(module_name)
|
| 104 |
+
component_cls = getattr(module, class_name)
|
| 105 |
+
return component_cls.from_pretrained(str(comp_dir), **model_kwargs)
|
| 106 |
+
|
| 107 |
+
try:
|
| 108 |
+
unet = _load_component("unet", "unet_adm", "ADMUNet2DModel")
|
| 109 |
+
scheduler = _load_component("scheduler", "scheduling_adm", "ADMScheduler")
|
| 110 |
+
classifier = _load_component("classifier", "classifier_adm", "ADMClassifierModel")
|
| 111 |
+
|
| 112 |
+
if scheduler is None:
|
| 113 |
+
sched_dir = variant / "scheduler"
|
| 114 |
+
if (sched_dir / "scheduling_adm.py").exists():
|
| 115 |
+
sched_path = str(sched_dir)
|
| 116 |
+
if sched_path not in sys.path:
|
| 117 |
+
sys.path.insert(0, sched_path)
|
| 118 |
+
inserted.append(sched_path)
|
| 119 |
+
scheduler = importlib.import_module("scheduling_adm").ADMScheduler()
|
| 120 |
+
|
| 121 |
+
if unet is None and classifier is None:
|
| 122 |
+
raise ValueError(f"No loadable components found under {variant}")
|
| 123 |
+
|
| 124 |
+
return cls(unet=unet, scheduler=scheduler, classifier=classifier)
|
| 125 |
+
finally:
|
| 126 |
+
for comp_path in inserted:
|
| 127 |
+
if comp_path in sys.path:
|
| 128 |
+
sys.path.remove(comp_path)
|
| 129 |
+
|
| 130 |
+
def __init__(
|
| 131 |
+
self,
|
| 132 |
+
unet,
|
| 133 |
+
scheduler,
|
| 134 |
+
classifier=None,
|
| 135 |
+
):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.register_modules(unet=unet, scheduler=scheduler, classifier=classifier)
|
| 138 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=1, do_normalize=False)
|
| 139 |
+
|
| 140 |
+
@property
|
| 141 |
+
def do_classifier_guidance(self) -> bool:
|
| 142 |
+
return self.classifier is not None and getattr(self, "_classifier_guidance_scale", 0.0) > 0
|
| 143 |
+
|
| 144 |
+
def check_inputs(
|
| 145 |
+
self,
|
| 146 |
+
class_labels: Optional[Union[int, List[int], torch.Tensor]],
|
| 147 |
+
height: Optional[int],
|
| 148 |
+
width: Optional[int],
|
| 149 |
+
):
|
| 150 |
+
if class_labels is None and self.unet.config.class_cond:
|
| 151 |
+
raise ValueError("`class_labels` are required for class-conditional ADM checkpoints.")
|
| 152 |
+
|
| 153 |
+
if class_labels is not None and self.classifier is None and not self.unet.config.class_cond:
|
| 154 |
+
raise ValueError(
|
| 155 |
+
"This checkpoint is unconditional and has no classifier. Load an ADM-G repo with a "
|
| 156 |
+
"`classifier/` subfolder, or use a class-conditional UNet."
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
if height is not None and height % 8 != 0:
|
| 160 |
+
raise ValueError(f"`height` must be divisible by 8 but is {height}.")
|
| 161 |
+
if width is not None and width % 8 != 0:
|
| 162 |
+
raise ValueError(f"`width` must be divisible by 8 but is {width}.")
|
| 163 |
+
|
| 164 |
+
def _prepare_class_labels(
|
| 165 |
+
self,
|
| 166 |
+
class_labels: Optional[Union[int, List[int], torch.Tensor]],
|
| 167 |
+
batch_size: int,
|
| 168 |
+
device: torch.device,
|
| 169 |
+
) -> Optional[torch.Tensor]:
|
| 170 |
+
if class_labels is None:
|
| 171 |
+
return None
|
| 172 |
+
|
| 173 |
+
if isinstance(class_labels, int):
|
| 174 |
+
class_labels = [class_labels]
|
| 175 |
+
if not torch.is_tensor(class_labels):
|
| 176 |
+
class_labels = torch.tensor(class_labels, device=device, dtype=torch.long)
|
| 177 |
+
else:
|
| 178 |
+
class_labels = class_labels.to(device=device, dtype=torch.long)
|
| 179 |
+
|
| 180 |
+
if class_labels.shape[0] != batch_size:
|
| 181 |
+
raise ValueError(
|
| 182 |
+
f"`class_labels` batch ({class_labels.shape[0]}) must match requested batch size ({batch_size})."
|
| 183 |
+
)
|
| 184 |
+
return class_labels
|
| 185 |
+
|
| 186 |
+
def _get_classifier_grad(
|
| 187 |
+
self,
|
| 188 |
+
sample: torch.Tensor,
|
| 189 |
+
timestep: torch.Tensor,
|
| 190 |
+
class_labels: torch.Tensor,
|
| 191 |
+
classifier_scale: float,
|
| 192 |
+
) -> torch.Tensor:
|
| 193 |
+
return self.classifier.guidance_gradient(
|
| 194 |
+
sample,
|
| 195 |
+
timestep,
|
| 196 |
+
class_labels,
|
| 197 |
+
classifier_scale=classifier_scale,
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
def prepare_latents(
|
| 201 |
+
self,
|
| 202 |
+
batch_size: int,
|
| 203 |
+
num_channels: int,
|
| 204 |
+
height: int,
|
| 205 |
+
width: int,
|
| 206 |
+
dtype: torch.dtype,
|
| 207 |
+
device: torch.device,
|
| 208 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 209 |
+
latents: Optional[torch.Tensor] = None,
|
| 210 |
+
) -> torch.Tensor:
|
| 211 |
+
"""
|
| 212 |
+
Prepare initial Gaussian noise for pixel-space sampling.
|
| 213 |
+
|
| 214 |
+
Args:
|
| 215 |
+
batch_size (`int`):
|
| 216 |
+
Number of images to generate.
|
| 217 |
+
num_channels (`int`):
|
| 218 |
+
Number of image channels (typically 3).
|
| 219 |
+
height (`int`):
|
| 220 |
+
Image height in pixels.
|
| 221 |
+
width (`int`):
|
| 222 |
+
Image width in pixels.
|
| 223 |
+
dtype (`torch.dtype`):
|
| 224 |
+
Data type for the latent tensor.
|
| 225 |
+
device (`torch.device`):
|
| 226 |
+
Target device.
|
| 227 |
+
generator (`torch.Generator` or `list[torch.Generator]`, *optional*):
|
| 228 |
+
RNG for deterministic sampling.
|
| 229 |
+
latents (`torch.Tensor`, *optional*):
|
| 230 |
+
Pre-generated noise tensor.
|
| 231 |
+
|
| 232 |
+
Returns:
|
| 233 |
+
`torch.Tensor`:
|
| 234 |
+
Initial noise of shape `(batch_size, num_channels, height, width)`.
|
| 235 |
+
"""
|
| 236 |
+
shape = (batch_size, num_channels, height, width)
|
| 237 |
+
if latents is None:
|
| 238 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 239 |
+
else:
|
| 240 |
+
latents = latents.to(device=device, dtype=dtype)
|
| 241 |
+
return latents
|
| 242 |
+
|
| 243 |
+
@torch.no_grad()
|
| 244 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 245 |
+
def __call__(
|
| 246 |
+
self,
|
| 247 |
+
class_labels: Optional[Union[int, List[int], torch.Tensor]] = None,
|
| 248 |
+
batch_size: int = 1,
|
| 249 |
+
height: Optional[int] = None,
|
| 250 |
+
width: Optional[int] = None,
|
| 251 |
+
num_inference_steps: int = 250,
|
| 252 |
+
use_ddim: bool = False,
|
| 253 |
+
eta: float = 0.0,
|
| 254 |
+
clip_denoised: bool = True,
|
| 255 |
+
classifier_guidance_scale: float = 0.0,
|
| 256 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 257 |
+
latents: Optional[torch.Tensor] = None,
|
| 258 |
+
output_type: str = "pil",
|
| 259 |
+
return_dict: bool = True,
|
| 260 |
+
) -> Union[ADMPipelineOutput, Tuple]:
|
| 261 |
+
r"""
|
| 262 |
+
Generate images with ADM.
|
| 263 |
+
|
| 264 |
+
Args:
|
| 265 |
+
class_labels (`int` or `list[int]` or `torch.Tensor`, *optional*):
|
| 266 |
+
ImageNet class indices. Required for class-conditional UNets and for ADM-G classifier guidance.
|
| 267 |
+
batch_size (`int`, *optional*, defaults to 1):
|
| 268 |
+
Number of images to generate when `class_labels` is not provided.
|
| 269 |
+
height (`int`, *optional*):
|
| 270 |
+
Height in pixels. Defaults to `unet.config.image_size`.
|
| 271 |
+
width (`int`, *optional*):
|
| 272 |
+
Width in pixels. Defaults to `unet.config.image_size`.
|
| 273 |
+
num_inference_steps (`int`, *optional*, defaults to 250):
|
| 274 |
+
Number of denoising steps.
|
| 275 |
+
use_ddim (`bool`, *optional*, defaults to `False`):
|
| 276 |
+
Use DDIM sampling instead of DDPM.
|
| 277 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 278 |
+
DDIM stochasticity parameter. Only used when `use_ddim=True`.
|
| 279 |
+
clip_denoised (`bool`, *optional*, defaults to `True`):
|
| 280 |
+
Clamp predicted `x_0` to `[-1, 1]` inside the scheduler.
|
| 281 |
+
classifier_guidance_scale (`float`, *optional*, defaults to 0.0):
|
| 282 |
+
ADM-G guidance strength. Values `> 0` require a loaded `classifier` (OpenAI `classifier_scale`).
|
| 283 |
+
generator (`torch.Generator` or `list[torch.Generator]`, *optional*):
|
| 284 |
+
RNG for reproducible generation.
|
| 285 |
+
latents (`torch.Tensor`, *optional*):
|
| 286 |
+
Pre-generated initial noise.
|
| 287 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 288 |
+
Output format: `"pil"`, `"np"`, or `"pt"`.
|
| 289 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 290 |
+
Return an [`ADMPipelineOutput`] instead of a tuple.
|
| 291 |
+
|
| 292 |
+
Examples:
|
| 293 |
+
|
| 294 |
+
Returns:
|
| 295 |
+
[`ADMPipelineOutput`] or `tuple`:
|
| 296 |
+
Generated images.
|
| 297 |
+
"""
|
| 298 |
+
if height is None:
|
| 299 |
+
height = int(self.unet.config.image_size)
|
| 300 |
+
if width is None:
|
| 301 |
+
width = int(self.unet.config.image_size)
|
| 302 |
+
|
| 303 |
+
self.check_inputs(class_labels, height, width)
|
| 304 |
+
|
| 305 |
+
if classifier_guidance_scale > 0 and self.classifier is None:
|
| 306 |
+
raise ValueError("`classifier_guidance_scale > 0` requires a loaded `classifier` (ADM-G checkpoint).")
|
| 307 |
+
if classifier_guidance_scale > 0 and class_labels is None:
|
| 308 |
+
raise ValueError("`class_labels` are required when using classifier guidance.")
|
| 309 |
+
|
| 310 |
+
self._classifier_guidance_scale = classifier_guidance_scale
|
| 311 |
+
device = self._execution_device
|
| 312 |
+
model_dtype = self.unet.dtype
|
| 313 |
+
|
| 314 |
+
if class_labels is not None:
|
| 315 |
+
if isinstance(class_labels, int):
|
| 316 |
+
batch_size = 1
|
| 317 |
+
elif isinstance(class_labels, list):
|
| 318 |
+
batch_size = len(class_labels)
|
| 319 |
+
elif torch.is_tensor(class_labels):
|
| 320 |
+
batch_size = class_labels.shape[0]
|
| 321 |
+
|
| 322 |
+
class_labels = self._prepare_class_labels(class_labels, batch_size, device)
|
| 323 |
+
|
| 324 |
+
latents = self.prepare_latents(
|
| 325 |
+
batch_size,
|
| 326 |
+
3,
|
| 327 |
+
height,
|
| 328 |
+
width,
|
| 329 |
+
model_dtype,
|
| 330 |
+
device,
|
| 331 |
+
generator,
|
| 332 |
+
latents,
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device, use_ddim=use_ddim)
|
| 336 |
+
self.scheduler._eta = eta
|
| 337 |
+
|
| 338 |
+
self._num_timesteps = len(self.scheduler.timesteps)
|
| 339 |
+
|
| 340 |
+
unet_class_labels = class_labels if self.unet.config.class_cond else None
|
| 341 |
+
|
| 342 |
+
for t in tqdm(self.scheduler.timesteps, desc="Denoising"):
|
| 343 |
+
timestep = torch.full((batch_size,), t, device=device, dtype=torch.long)
|
| 344 |
+
model_timesteps = self.scheduler.scale_timesteps_for_model(timestep)
|
| 345 |
+
|
| 346 |
+
model_output = self.unet(
|
| 347 |
+
latents,
|
| 348 |
+
model_timesteps,
|
| 349 |
+
class_labels=unet_class_labels,
|
| 350 |
+
return_dict=True,
|
| 351 |
+
).sample
|
| 352 |
+
|
| 353 |
+
cond_grad = None
|
| 354 |
+
if self.do_classifier_guidance:
|
| 355 |
+
cond_grad = self._get_classifier_grad(
|
| 356 |
+
latents,
|
| 357 |
+
timestep,
|
| 358 |
+
class_labels,
|
| 359 |
+
classifier_guidance_scale,
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
latents = self.scheduler.step(
|
| 363 |
+
model_output,
|
| 364 |
+
t,
|
| 365 |
+
latents,
|
| 366 |
+
generator=generator,
|
| 367 |
+
clip_denoised=clip_denoised,
|
| 368 |
+
eta=eta,
|
| 369 |
+
cond_grad=cond_grad,
|
| 370 |
+
).prev_sample
|
| 371 |
+
|
| 372 |
+
image = latents
|
| 373 |
+
has_nsfw_concept = None
|
| 374 |
+
|
| 375 |
+
if output_type == "latent":
|
| 376 |
+
image = latents
|
| 377 |
+
elif output_type == "pt":
|
| 378 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 379 |
+
elif output_type in ("pil", "np"):
|
| 380 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 381 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 382 |
+
|
| 383 |
+
self.maybe_free_model_hooks()
|
| 384 |
+
|
| 385 |
+
if not return_dict:
|
| 386 |
+
return (image, has_nsfw_concept)
|
| 387 |
+
|
| 388 |
+
return ADMPipelineOutput(images=image)
|