我正在實作implement a conditional Denoising Diffusion Probabilistic Model (DDPM) to generate synthetic images according to multi-label conditions: Given a specific set of label conditions, your DDPM should generate the corresponding synthetic images (see Fig. 1). For example, “red sphere,” “yellow cube” and “gray cylinder” are given, your model should generate the synthetic images containing those objects. Meanwhile, you also need to input your generated images into a pre-trained classifier for evaluation.
Requirements
Prepare dataset ● Implement data loader ● Define your multi-label condition embedding method
Implement a conditional DDPM ● Choose your conditional DDPM setting, design your model architecture ● Design your noise schedule, time embeddings, sampling method, etc. You can also include the pretrained evaluator as a “classifier guidance” in sampling ● Choose your loss functions (e.g. reparameterization type) ● Implement the training function, testing function - Evaluate the results ● Evaluate the accuracy of test.json and new test.json, input the output images of each model to the pretrained evaluator to get the accuracies ● Show the synthetic images in grids for two models * two testing files ● Show the denoising process in a grid for sampling an image from your DDPM, with the label set ["red sphere", "cyan cylinder", "cyan cube"]
Basic Rules ● For each model, you can choose any architecture you like. Also, feel free to use any library that helps your work, but you need to mention the implementation details and include the reference in your report. ● Except for the provided files, you cannot use other training data. (e.g. background image) ● Use the function of a pre-trained evaluator to compute the accuracy of your synthetic images. ● The evaluator is based on ResNet18. By inputting synthesized images and one-hot GT labels, the evaluator will return accuracy. Its class script and pretrained weight are given. DO NOT modify any of them, BUT involving the classification result in your discriminator or classifier guidance is allowed. Please inherit the class if you need extra functionalities. ● The normalization of input images is transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)). You must input the normalized image into the pretrained classifier. You should apply denormalization to generate RGB images. ● The resolution of input for the pretrained evaluator is 64x64. You can design your own output resolution and resize it for evaluation ● Use make_grid(images) from torchvision.utils to generate grids for your testing image (8 images a row, 4 rows for each JSON file) and denoising process (at least 8 images in 1 row from noisy to clear). ● If you have no idea how to design your DDPM, follow 3.2 for simple suggestions.
Scoring Criteria
Report (60%) ● Introduction (5%) ● Implementation details (25%) o Describe how you implement your model, what is this step, including your choice of DDPM, noise schedule. (Please write in detail.) ● Results and discussion (30%) o Show your synthetic image grids (total 16%: 8% * 2 testing data) and a denoising process image with the label set ["red sphere", "cyan cylinder", "cyan cube"] (4%) o Discussion of your extra implementations or experiments (10%)
Experimental results (40%) (based on results shown in your report) ● Classification accuracy on test.json and new test.json (40%) ● Show your accuracy screenshots (20% * 2 testing data)
This is the specification file for conditional DDPM training and testing dataset - i-CLEVR
objects.json This file is a dictionary file that contains the number of objects and the idexes. There are totally 24 objects in i-CLEVR datasets with 3 shapes and 8 colors.
train.json The file is for training. The number off training data is 18009. train.json is a dictionary where keys are filenames and values are objects/ For example: {"CLEVR_train_001032_0.png": ["yellow sphere"], "CLEVR_train_001032_1.png": ["yellow sphere", "gray cylinder"], "CLEVR_train_001032_2.png": ["yellow sphere", "gray cylinder", "purple cube"], ... } One image can include objects from 1 to 3
test.json, new_test.json The file are for testing. The number of testing data is 32 for each file. Both file contain a list where each element includes multiple objects For example: [['gray cube'], ['red cube'], ['blue cube'], ['blue cube', 'green cube'], ...]
evlauator.py, checkpoint.pth Here are the pretrained classifier model's script and its weight for evaluating your synthetic images. More detail can be found in the script file.
Purpose:
For computing the classification accruacy.
Details:
The model is based on ResNet18 with only chaning the last linear layer. The model is trained on iclevr dataset with 1 to 5 objects and the resolution is the upsampled 64x64 images from 32x32 images.
It will capture the top k highest accuracy indexes on generated images and compare them with ground truth labels.
How to use
You may need to modify the checkpoint's path at line 40. You should call eval(images, labels) and to get total accuracy. images shape: (batch_size, 3, 64, 64) labels shape: (batch_size, 24) where labels are one-hot vectors e.g. [[1,1,0,...,0],[0,1,1,0,...],...] Images should be normalized with: transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
我現在要開始寫report,協助我完成
Assistant
以下是为您整理的报告框架和内容建议,结合您的项目需求和评分标准进行结构化设计:
Report: Conditional Denoising Diffusion Probabilistic Model for Multi-Label Image Generation
1. Introduction (5%)
Purpose:
This report presents the implementation of a conditional Denoising Diffusion Probabilistic Model (DDPM) for generating synthetic images based on multi-label conditions (e.g., "red sphere", "yellow cube"). The generated images are evaluated using a pre-trained ResNet18 classifier to measure their accuracy.
Motivation:
Diffusion models have shown strong performance in image generation, but their ability to handle multi-label conditions remains underexplored. This work bridges this gap by integrating label embeddings into the diffusion process and validating the results with a classifier.
Key Contributions:
A novel multi-label condition embedding method for DDPM.
Implementation of a conditional DDPM with classifier guidance.
Evaluation of synthetic images using a pre-trained classifier on the i-CLEVR dataset.
Visualization of generation and denoising processes.
2. Implementation Details (25%)
2.1 Dataset Preparation and Data Loader
Dataset:
i-CLEVR: Contains 18009 training images and 32 test images per file (test.json, new_test.json).
def forward(self, x, t_emb, cond_emb):
residual = x if self.res_conv is None else self.res_conv(x)
h = self.conv1(x)
h = self.norm1(h)
t_proj = self.time_dense(t_emb).unsqueeze(-1).unsqueeze(-1)
h = h + t_proj
h = self.act(h)
h = self.conv2(h)
h = self.norm2(h)
gamma_beta = self.cond_dense(cond_emb).unsqueeze(-1).unsqueeze(-1)
gamma, beta = gamma_beta.chunk(2, dim=1)
h = h * (1 + gamma) + beta
h = self.act(h)
return residual + h
-----------------------------
UNet Model
-----------------------------
Assistant
Report: Conditional Denoising Diffusion Probabilistic Model for Multi-Label Image Generation
1. Introduction (5%)
This report presents the implementation of a conditional Denoising Diffusion Probabilistic Model (DDPM) for generating synthetic images based on multi-label conditions (e.g., "red sphere", "yellow cube"). The generated images are evaluated using a pre-trained ResNet18 classifier on the i-CLEVR dataset. The model integrates multi-label condition embeddings, attention mechanisms, and classifier guidance to improve generation quality and alignment with labels.
2. Implementation Details (25%)
2.1 Dataset Preparation and Data Loader
Dataset:
i-CLEVR: Contains 18009 training images and 32 test images per file (test.json, new_test.json).
Objects: 3 shapes × 8 colors = 24 unique labels.
Data Loader:
Parse JSON files to extract object labels and convert them to one-hot vectors (e.g., "red sphere" → [1, 0, ..., 0]).
Resize images to 64×64 for compatibility with the pre-trained classifier.
def main():
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 載入模型
num_classes = 24
eps_model = SimpleEpsilonPredictor(
image_channels=3,
base_channels=64,
channel_mults=(1,2,4),
num_res_blocks=2,
time_emb_dim=128,
cond_emb_dim=128,
num_classes=num_classes
).to(device)
ddpm = DDPM(eps_model, image_size=64, image_channels=3, timesteps=1000).to(device)
ckpt = torch.load("checkpoints/ddpm_epoch290.pth", map_location=device, weights_only=True)
ddpm.load_state_dict(ckpt['model_state'], strict=False)
ddpm.eval()
evaluator = evaluation_model()
# test & new_test
for name in ["test", "new_test"]:
imgs, conds = sample_and_save(
ddpm,
json_path = f"data/{name}.json",
object_path = "data/objects.json",
out_path = f"outputs/{name}_generated.png",
device = device
)
acc = evaluate_generated(imgs, conds, evaluator)
print(f"{name}.json Accuracy: {acc*100:.2f}%")
# 去噪过程可视化
label = [["red sphere", "cyan cylinder", "cyan cube"]]
with open("data/objects.json", 'r') as f:
obj_dict = json.load(f)
cond = create_one_hot(label, obj_dict, num_classes).to(device)
steps = torch.linspace(999, 0, steps=50, dtype=torch.long).to(device)
x = torch.randn(1, 3, 64, 64, device=device)
imgs = []
checkpoints = [999, 750, 500, 250, 100, 50, 25, 10, 0]
with torch.no_grad():
for t in reversed(range(ddpm.timesteps)): # 999 到 0
t_tensor = torch.tensor([t], device=device)
x = ddpm.p_sample(x, t_tensor, cond, guidance_scale=4.0)
if t in checkpoints:
imgs.append(x.clamp(-1, 1)) # 儲存當前圖像
# 組合圖片並存檔
os.makedirs("outputs", exist_ok=True)
grid = make_grid(torch.cat(imgs, dim=0), nrow=len(checkpoints), normalize=True, value_range=(-1,1))
save_image(grid, "outputs/denoise_process.png")
print("Saved denoising process to outputs/denoise_process.png")
"""with torch.no_grad():
for t in steps:
imgs.append(x)
t = t.unsqueeze(0)
x = ddpm.p_sample(x, t, cond, guidance_scale=4.0)
os.makedirs("outputs", exist_ok=True)
grid = make_grid(torch.cat(imgs, 0), nrow=10, normalize=True, value_range=(-1,1))
save_image(grid, "outputs/denoise_process.png")
print("Saved denoising process to outputs/denoise_process.png")
"""
Assistant
以下是您提供的程式碼整合至報告中的完整內容,並補充必要的說明與結構化呈現。此報告已包含所有程式碼片段、關鍵實現細節與結果分析,可直接導出為 Word 文件。
Report: Conditional Denoising Diffusion Probabilistic Model for Multi-Label Image Generation
1. Introduction (5%)
This report presents the implementation of a conditional Denoising Diffusion Probabilistic Model (DDPM) for generating synthetic images based on multi-label conditions (e.g., "red sphere", "yellow cube"). The generated images are evaluated using a pre-trained ResNet18 classifier on the i-CLEVR dataset. The model integrates multi-label condition embeddings, attention mechanisms, and classifier guidance to improve generation quality and alignment with labels.
2. Implementation Details (25%)
2.1 Dataset Preparation and Data Loader
Dataset:
i-CLEVR: Contains 18009 training images and 32 test images per file (test.json, new_test.json).
Objects: 3 shapes × 8 colors = 24 unique labels.
Data Loader:
Parse JSON files to extract object labels and convert them to one-hot vectors (e.g., "red sphere" → [1, 0, ..., 0]).
Resize images to 64×64 for compatibility with the pre-trained classifier.
Visuals: Use torchvision.utils.make_grid for grids (e.g., 8×4 for test images).
Normalization: Always apply transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) for the evaluator.
Classifier Guidance: Adjust the scale factor (gamma) to balance fidelity and diversity.
Documentation: Clearly explain your condition embedding method and why it works.
This structure ensures compliance with the scoring criteria while emphasizing technical depth and reproducibility. Let me know if you need help with specific sections (e.g., code snippets or figures)!
Visuals: Use torchvision.utils.make_grid for grids (e.g., 8×4 for test images).
Normalization: Always apply transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) for the evaluator.
Classifier Guidance: Adjust the scale factor (gamma) to balance fidelity and diversity.
Documentation: Clearly explain your condition embedding method and why it works.
This structure ensures compliance with the scoring criteria while emphasizing technical depth and reproducibility. Let me know if you need help with specific sections (e.g., code snippets or figures)!
if name == "main":
main()
接下來還有dataloader.py,等全部看完再匯出word給我
Captures semantic relationships between labels (e.g., "red" and "sphere") and ensures the model understands the input conditions.
2.3 Conditional DDPM Architecture
Model:
U-Net: Modified to handle conditional inputs (labels).
Time Embedding: Uses sinusoidal positional encoding (see SinusoidalPositionEmb).
Attention Block: Adds self-attention to capture long-range dependencies (see AttentionBlock).
Residual Block with FiLM: Modulates features using gamma/beta parameters derived from condition embeddings (see ResidualBlock).
Noise Schedule:
Linear schedule from β0=1e−4 to βT=0.02.
Sampling Method:
Reverse diffusion process with 1000 steps.
Classifier Guidance: Integrates the pre-trained evaluator to refine generated images (see p_sample).