Algorithm 2 — Full reverse sampling process. "Algorithm 2 Sampling 1: x_T ~ N(0, I) 2: for t = T, ..., 1 do 3: z ~ N(0, I) if t > 1, else z = 0 4: x_{t-1} = 1/√α_t (x_t - β_t/√(1-α̅_t) ε_θ(x_t, t)) + σ_t z 5: end for 6: return x_0" Args: model: noi
(
model: nn.Module,
schedule: Dict[str, torch.Tensor],
image_shape: tuple,
device: torch.device,
)
| 162 | |
| 163 | @torch.no_grad() |
| 164 | def sample( |
| 165 | model: nn.Module, |
| 166 | schedule: Dict[str, torch.Tensor], |
| 167 | image_shape: tuple, |
| 168 | device: torch.device, |
| 169 | ) -> torch.Tensor: |
| 170 | """Algorithm 2 — Full reverse sampling process. |
| 171 | |
| 172 | "Algorithm 2 Sampling |
| 173 | 1: x_T ~ N(0, I) |
| 174 | 2: for t = T, ..., 1 do |
| 175 | 3: z ~ N(0, I) if t > 1, else z = 0 |
| 176 | 4: x_{t-1} = 1/√α_t (x_t - β_t/√(1-α̅_t) ε_θ(x_t, t)) + σ_t z |
| 177 | 5: end for |
| 178 | 6: return x_0" |
| 179 | |
| 180 | Args: |
| 181 | model: noise prediction network ε_θ (should be in eval mode, ideally EMA weights) |
| 182 | schedule: precomputed noise schedule |
| 183 | image_shape: (batch, C, H, W) — shape of images to generate |
| 184 | device: torch device |
| 185 | |
| 186 | Returns: |
| 187 | x_0: (batch, C, H, W) — generated images |
| 188 | """ |
| 189 | model.eval() |
| 190 | timesteps = len(schedule["betas"]) |
| 191 | |
| 192 | # Algorithm 2, line 1: x_T ~ N(0, I) |
| 193 | x = torch.randn(image_shape, device=device) |
| 194 | |
| 195 | # Algorithm 2, lines 2-5: reverse iterate from t=T to t=1 |
| 196 | for t_index in reversed(range(timesteps)): |
| 197 | t = torch.full((image_shape[0],), t_index, device=device, dtype=torch.long) |
| 198 | x = p_sample(model, x, t, t_index, schedule) |
| 199 | |
| 200 | return x |
| 201 | |
| 202 | |
| 203 | class EMA: |
no test coverage detected