1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
|
"""
Data loading utilities for MNIST diffusion training.
"""
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import datasets, transforms
from .config import DEVICE, DIFFU_STEPS, NB_LABEL, DATA_DIR
from .diffusion import q_xt_x0
def get_mnist_dataset(train: bool = True) -> datasets.MNIST:
"""
Load MNIST dataset.
Args:
train: If True, load training set. Otherwise load test set.
Returns:
MNIST dataset
"""
return datasets.MNIST(
root=DATA_DIR,
train=train,
download=True,
transform=transforms.ToTensor(),
)
class DiffusionDataset(Dataset):
"""
Dataset wrapper for diffusion training.
Returns noisy image, timestep, label, and target noise.
Args:
dataset: Base image dataset (e.g., MNIST)
autoencoder: Optional autoencoder for latent diffusion
"""
def __init__(self, dataset: Dataset, autoencoder: torch.nn.Module = None):
super().__init__()
self.dataset = dataset
self.autoencoder = autoencoder
def __getitem__(self, index: int) -> tuple[torch.Tensor, ...]:
# Get image and label
img, label = self.dataset[index]
img = img.to(DEVICE)
# Optionally encode to latent space
if self.autoencoder is not None:
with torch.no_grad():
img = self.autoencoder.encode(img.unsqueeze(0)).squeeze(0)
# Normalize to [-1, 1]
img = img * 2 - 1
# Sample random timestep and add noise
t = torch.randint(1, DIFFU_STEPS + 1, (1,), device=DEVICE)
xt, eps = q_xt_x0(img, t)
# Convert label to one-hot vector
vec = torch.nn.functional.one_hot(
torch.tensor(min(label, NB_LABEL - 1)),
num_classes=NB_LABEL,
)
return (
xt.clone().detach().to(dtype=torch.float32, device=DEVICE),
t.clone().detach().to(dtype=torch.float32, device=DEVICE),
vec.clone().detach().to(dtype=torch.float32, device=DEVICE),
eps, # Target: the noise that was added
)
def __len__(self) -> int:
return len(self.dataset)
class DiffusionDatasetX0(Dataset):
"""
Dataset wrapper for diffusion training where model predicts x0 instead of noise.
Returns noisy image, timestep, label, and target clean image.
Args:
dataset: Base image dataset (e.g., MNIST)
autoencoder: Optional autoencoder for latent diffusion
"""
def __init__(self, dataset: Dataset, autoencoder: torch.nn.Module = None):
super().__init__()
self.dataset = dataset
self.autoencoder = autoencoder
def __getitem__(self, index: int) -> tuple[torch.Tensor, ...]:
# Get image and label
img, label = self.dataset[index]
img = img.to(DEVICE)
# Optionally encode to latent space
if self.autoencoder is not None:
with torch.no_grad():
img = self.autoencoder.encode(img.unsqueeze(0)).squeeze(0)
# Normalize to [-1, 1]
img = img * 2 - 1
# Sample random timestep and add noise
t = torch.randint(1, DIFFU_STEPS + 1, (1,), device=DEVICE)
xt, _ = q_xt_x0(img, t)
# Convert label to one-hot vector
vec = torch.nn.functional.one_hot(
torch.tensor(min(label, NB_LABEL - 1)),
num_classes=NB_LABEL,
)
return (
xt.clone().detach().to(dtype=torch.float32, device=DEVICE),
t.clone().detach().to(dtype=torch.float32, device=DEVICE),
vec.clone().detach().to(dtype=torch.float32, device=DEVICE),
img.clone().detach().to(dtype=torch.float32, device=DEVICE), # Target: clean image
)
def __len__(self) -> int:
return len(self.dataset)
class AutoencoderDataset(Dataset):
"""
Dataset wrapper for autoencoder training.
Returns image as both input and target.
Args:
dataset: Base image dataset
"""
def __init__(self, dataset: Dataset):
self.dataset = dataset
def __len__(self) -> int:
return len(self.dataset)
def __getitem__(self, idx: int) -> tuple[torch.Tensor, torch.Tensor]:
data = self.dataset[idx][0].to(DEVICE)
return data, data
def get_diffusion_dataloader(
predict_x0: bool = True,
batch_size: int = 64,
shuffle: bool = True,
num_workers: int = 4,
autoencoder: torch.nn.Module = None,
) -> DataLoader:
"""
Create a DataLoader for diffusion training.
Args:
predict_x0: If True, model predicts x0. Otherwise predicts noise.
batch_size: Batch size
shuffle: Whether to shuffle data
num_workers: Number of data loading workers
autoencoder: Optional autoencoder for latent diffusion
Returns:
DataLoader for training
"""
mnist = get_mnist_dataset(train=True)
if predict_x0:
dataset = DiffusionDatasetX0(mnist, autoencoder)
else:
dataset = DiffusionDataset(mnist, autoencoder)
return DataLoader(
dataset,
batch_size=batch_size,
shuffle=shuffle,
num_workers=num_workers,
persistent_workers=True if num_workers > 0 else False,
)
def get_autoencoder_dataloader(
batch_size: int = 64,
shuffle: bool = True,
num_workers: int = 4,
) -> DataLoader:
"""
Create a DataLoader for autoencoder training.
Args:
batch_size: Batch size
shuffle: Whether to shuffle data
num_workers: Number of data loading workers
Returns:
DataLoader for training
"""
mnist = get_mnist_dataset(train=True)
dataset = AutoencoderDataset(mnist)
return DataLoader(
dataset,
batch_size=batch_size,
shuffle=shuffle,
num_workers=num_workers,
persistent_workers=True if num_workers > 0 else False,
)
|