Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Support uniform timesteps sampler for DDPM #153

Merged
merged 2 commits into from
Nov 29, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions mmgen/models/diffusions/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .sampler import UniformTimeStepSampler

__all__ = ['UniformTimeStepSampler']
32 changes: 32 additions & 0 deletions mmgen/models/diffusions/sampler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import numpy as np
import torch

from ..builder import MODULES


@MODULES.register_module()
class UniformTimeStepSampler:
"""Timestep sampler for DDPM-based models. This sampler sample all
timesteps with the same probabilistic.

Args:
num_timesteps (int): Total timesteps of the diffusion process.
"""

def __init__(self, num_timesteps):
self.num_timesteps = num_timesteps

def sample(self, batch_size):
"""Sample timesteps.
Args:
batch_size (int): The desired batch size of the sampled timesteps.

Returns:
torch.Tensor: Sampled timesteps.
"""
p = [1 / self.num_timesteps for _ in range(self.num_timesteps)]
LeoXing1996 marked this conversation as resolved.
Show resolved Hide resolved
return torch.from_numpy(
np.random.choice(self.num_timesteps, size=(batch_size, ), p=p))

def __call__(self, batch_size):
return self.sample(batch_size)
18 changes: 18 additions & 0 deletions tests/test_models/test_base_ddpm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import torch

from mmgen.models.diffusions import UniformTimeStepSampler


def test_uniform_sampler():
sampler = UniformTimeStepSampler(10)
timesteps = sampler(2)
assert timesteps.shape == torch.Size([
2,
])
assert timesteps.max() < 10 and timesteps.min() >= 0

timesteps = sampler.__call__(2)
assert timesteps.shape == torch.Size([
2,
])
assert timesteps.max() < 10 and timesteps.min() >= 0