File size: 2,043 Bytes
1d7666e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

# DDPM β€” Fashion-MNIST

A simple DDPM implementation built from scratch using PyTorch.

The model learns to predict the noise added to a real Fashion-MNIST image.

## Pipeline

Training:

    xβ‚€ β†’ add noise β†’ xβ‚œ β†’ U-Net β†’ predicted noise
                              ↓
                         MSE Loss

Sampling:

    Gaussian Noise
          ↓
        U-Net
          ↓
      Denoising
          ↓
        U-Net
          ↓
         ...
          ↓
     Generated Image

## Model

The U-Net takes:

    (xβ‚œ, t)

and predicts:

    Ρθ(xβ‚œ, t)

The U-Net contains:

- Time embedding
- Input convolution
- 2 downsampling blocks
- 2 middle ResBlocks
- 2 upsampling blocks
- Skip connections
- GroupNorm
- SiLU activation
- Final output convolution

Input:

    [B, 1, 28, 28]

Output:

    [B, 1, 28, 28]

The output represents predicted Gaussian noise.

## Forward Diffusion

We use:

    xβ‚œ = βˆšΞ±Μ„β‚œ xβ‚€ + √(1 - Ξ±Μ„β‚œ) Ξ΅

where:

    Ξ΅ ~ N(0, I)

## Training

For every batch:

1. Take a real image xβ‚€.
2. Select a random timestep t.
3. Generate Gaussian noise Ξ΅.
4. Create xβ‚œ using the forward diffusion process.
5. Give xβ‚œ and t to the U-Net.
6. Predict the noise.
7. Calculate MSE between predicted and actual noise.
8. Update the U-Net.

## Reverse Diffusion

During generation, we start from:

    xT ~ N(0, I)

and move backwards:

    xT β†’ xT-1 β†’ ... β†’ x1 β†’ x0

At every timestep, the U-Net predicts the noise and the DDPM scheduler performs one reverse step.

## Checkpoint

Model weights are saved using:

    .safetensors

Example:

    checkpoints/ddpm_fashion_mnist.safetensors

The model architecture must be recreated before loading the weights.

## Dataset

Dataset:

    Fashion-MNIST

Image size:

    28 Γ— 28

Channels:

    1

## Goal

The goal of this project is to understand DDPM from first principles:

    Forward Diffusion
          ↓
       U-Net
          ↓
    Noise Prediction
          ↓
    Reverse Diffusion
          ↓
    Image Generation