test_modeling_utils.py 9.58 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# coding=utf-8
# Copyright 2022 HuggingFace Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Patrick von Platen's avatar
Patrick von Platen committed
16
17


18
19
20
import random
import tempfile
import unittest
Patrick von Platen's avatar
improve  
Patrick von Platen committed
21
22
import os
from distutils.util import strtobool
23
24

import torch
Patrick von Platen's avatar
Patrick von Platen committed
25
import numpy as np
26

Patrick von Platen's avatar
improve  
Patrick von Platen committed
27
from diffusers import GaussianDDPMScheduler, UNetModel
28
29
from diffusers.pipeline_utils import DiffusionPipeline
from models.vision.ddpm.modeling_ddpm import DDPM
30
31
32


global_rng = random.Random()
Patrick von Platen's avatar
improve  
Patrick von Platen committed
33
34
35
torch_device = "cuda" if torch.cuda.is_available() else "cpu"


Patrick von Platen's avatar
Patrick von Platen committed
36
37
38
def get_random_generator(seed):
    seed = 1234
    random.seed(seed)
Patrick von Platen's avatar
Patrick von Platen committed
39
    os.environ["PYTHONHASHSEED"] = str(seed)
Patrick von Platen's avatar
Patrick von Platen committed
40
41
42
43
44
45
46
47
48
49
50
51
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.enabled = False
    generator = torch.Generator()
    return generator



Patrick von Platen's avatar
improve  
Patrick von Platen committed
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
def parse_flag_from_env(key, default=False):
    try:
        value = os.environ[key]
    except KeyError:
        # KEY isn't set, default to `default`.
        _value = default
    else:
        # KEY is set, convert it to True or False.
        try:
            _value = strtobool(value)
        except ValueError:
            # More values are supported, but let's keep the message simple.
            raise ValueError(f"If set, {key} must be yes or no.")
    return _value


_run_slow_tests = parse_flag_from_env("RUN_SLOW", default=False)


def slow(test_case):
    """
    Decorator marking a test as slow.

    Slow tests are skipped by default. Set the RUN_SLOW environment variable to a truthy value to run them.

    """
    return unittest.skipUnless(_run_slow_tests, "test is slow")(test_case)
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97


def floats_tensor(shape, scale=1.0, rng=None, name=None):
    """Creates a random float32 tensor"""
    if rng is None:
        rng = global_rng

    total_dims = 1
    for dim in shape:
        total_dims *= dim

    values = []
    for _ in range(total_dims):
        values.append(rng.random() * scale)

    return torch.tensor(data=values, dtype=torch.float).view(shape).contiguous()


class ModelTesterMixin(unittest.TestCase):
Patrick von Platen's avatar
Patrick von Platen committed
98
99
    @property
    def dummy_input(self):
Patrick von Platen's avatar
up  
Patrick von Platen committed
100
        batch_size = 4
Patrick von Platen's avatar
Patrick von Platen committed
101
102
103
104
105
106
107
108
        num_channels = 3
        sizes = (32, 32)

        noise = floats_tensor((batch_size, num_channels) + sizes)
        time_step = torch.tensor([10])

        return (noise, time_step)

109
    def test_from_pretrained_save_pretrained(self):
Patrick von Platen's avatar
improve  
Patrick von Platen committed
110
        model = UNetModel(ch=32, ch_mult=(1, 2), num_res_blocks=2, attn_resolutions=(16,), resolution=32)
111
112
113
114
115

        with tempfile.TemporaryDirectory() as tmpdirname:
            model.save_pretrained(tmpdirname)
            new_model = UNetModel.from_pretrained(tmpdirname)

Patrick von Platen's avatar
Patrick von Platen committed
116
        dummy_input = self.dummy_input
117

Patrick von Platen's avatar
Patrick von Platen committed
118
119
        image = model(*dummy_input)
        new_image = new_model(*dummy_input)
120
121

        assert (image - new_image).abs().sum() < 1e-5, "Models don't give the same forward pass"
Patrick von Platen's avatar
Patrick von Platen committed
122
123
124
125
126
127
128

    def test_from_pretrained_hub(self):
        model = UNetModel.from_pretrained("fusing/ddpm_dummy")

        image = model(*self.dummy_input)

        assert image is not None, "Make sure output is not None"
129
130
131
132


class SamplerTesterMixin(unittest.TestCase):

Patrick von Platen's avatar
improve  
Patrick von Platen committed
133
134
    @slow
    def test_sample(self):
Patrick von Platen's avatar
Patrick von Platen committed
135
        generator = get_random_generator(0)
Patrick von Platen's avatar
improve  
Patrick von Platen committed
136
137
138
139
140
141
142
143
144
145
146

        # 1. Load models
        scheduler = GaussianDDPMScheduler.from_config("fusing/ddpm-lsun-church")
        model = UNetModel.from_pretrained("fusing/ddpm-lsun-church").to(torch_device)

        # 2. Sample gaussian noise
        image = scheduler.sample_noise((1, model.in_channels, model.resolution, model.resolution), device=torch_device, generator=generator)

        # 3. Denoise
        for t in reversed(range(len(scheduler))):
            # i) define coefficients for time step t
patil-suraj's avatar
patil-suraj committed
147
148
            clipped_image_coeff = 1 / torch.sqrt(scheduler.get_alpha_prod(t))
            clipped_noise_coeff = torch.sqrt(1 / scheduler.get_alpha_prod(t) - 1)
Patrick von Platen's avatar
improve  
Patrick von Platen committed
149
            image_coeff = (1 - scheduler.get_alpha_prod(t - 1)) * torch.sqrt(scheduler.get_alpha(t)) / (1 - scheduler.get_alpha_prod(t))
patil-suraj's avatar
patil-suraj committed
150
            clipped_coeff = torch.sqrt(scheduler.get_alpha_prod(t - 1)) * scheduler.get_beta(t) / (1 - scheduler.get_alpha_prod(t))
Patrick von Platen's avatar
improve  
Patrick von Platen committed
151
152
153
154
155
156
157

            # ii) predict noise residual
            with torch.no_grad():
                noise_residual = model(image, t)

            # iii) compute predicted image from residual
            # See 2nd formula at https://github.com/hojonathanho/diffusion/issues/5#issue-896554416 for comparison
patil-suraj's avatar
patil-suraj committed
158
            pred_mean = clipped_image_coeff * image - clipped_noise_coeff * noise_residual
Patrick von Platen's avatar
improve  
Patrick von Platen committed
159
            pred_mean = torch.clamp(pred_mean, -1, 1)
patil-suraj's avatar
patil-suraj committed
160
            prev_image = clipped_coeff * pred_mean + image_coeff * image
Patrick von Platen's avatar
improve  
Patrick von Platen committed
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179

            # iv) sample variance
            prev_variance = scheduler.sample_variance(t, prev_image.shape, device=torch_device, generator=generator)

            # v) sample  x_{t-1} ~ N(prev_image, prev_variance)
            sampled_prev_image = prev_image + prev_variance
            image = sampled_prev_image

        # Note: The better test is to simply check with the following lines of code that the image is sensible
        # import PIL
        # import numpy as np
        # image_processed = image.cpu().permute(0, 2, 3, 1)
        # image_processed = (image_processed + 1.0) * 127.5
        # image_processed = image_processed.numpy().astype(np.uint8)
        # image_pil = PIL.Image.fromarray(image_processed[0])
        # image_pil.save("test.png")

        assert image.shape == (1, 3, 256, 256)
        image_slice = image[0, -1, -3:, -3:].cpu()
Patrick von Platen's avatar
Patrick von Platen committed
180
        import ipdb; ipdb.set_trace()
Patrick von Platen's avatar
improve  
Patrick von Platen committed
181
182
183
184
        assert (image_slice - torch.tensor([[-0.0598, -0.0611, -0.0506], [-0.0726, 0.0220, 0.0103], [-0.0723, -0.1310, -0.2458]])).abs().sum() < 1e-3

    def test_sample_fast(self):
        # 1. Load models
Patrick von Platen's avatar
Patrick von Platen committed
185
        generator = get_random_generator(0)
Patrick von Platen's avatar
improve  
Patrick von Platen committed
186
187
188
189
190

        scheduler = GaussianDDPMScheduler.from_config("fusing/ddpm-lsun-church", timesteps=10)
        model = UNetModel.from_pretrained("fusing/ddpm-lsun-church").to(torch_device)

        # 2. Sample gaussian noise
191
        torch.manual_seed(0)
Patrick von Platen's avatar
improve  
Patrick von Platen committed
192
193
194
195
196
        image = scheduler.sample_noise((1, model.in_channels, model.resolution, model.resolution), device=torch_device, generator=generator)

        # 3. Denoise
        for t in reversed(range(len(scheduler))):
            # i) define coefficients for time step t
patil-suraj's avatar
patil-suraj committed
197
198
            clipped_image_coeff = 1 / torch.sqrt(scheduler.get_alpha_prod(t))
            clipped_noise_coeff = torch.sqrt(1 / scheduler.get_alpha_prod(t) - 1)
Patrick von Platen's avatar
improve  
Patrick von Platen committed
199
            image_coeff = (1 - scheduler.get_alpha_prod(t - 1)) * torch.sqrt(scheduler.get_alpha(t)) / (1 - scheduler.get_alpha_prod(t))
patil-suraj's avatar
patil-suraj committed
200
            clipped_coeff = torch.sqrt(scheduler.get_alpha_prod(t - 1)) * scheduler.get_beta(t) / (1 - scheduler.get_alpha_prod(t))
Patrick von Platen's avatar
improve  
Patrick von Platen committed
201
202
203
204
205
206
207

            # ii) predict noise residual
            with torch.no_grad():
                noise_residual = model(image, t)

            # iii) compute predicted image from residual
            # See 2nd formula at https://github.com/hojonathanho/diffusion/issues/5#issue-896554416 for comparison
patil-suraj's avatar
patil-suraj committed
208
            pred_mean = clipped_image_coeff * image - clipped_noise_coeff * noise_residual
Patrick von Platen's avatar
improve  
Patrick von Platen committed
209
            pred_mean = torch.clamp(pred_mean, -1, 1)
patil-suraj's avatar
patil-suraj committed
210
            prev_image = clipped_coeff * pred_mean + image_coeff * image
Patrick von Platen's avatar
improve  
Patrick von Platen committed
211
212
213
214
215
216
217
218
219
220

            # iv) sample variance
            prev_variance = scheduler.sample_variance(t, prev_image.shape, device=torch_device, generator=generator)

            # v) sample  x_{t-1} ~ N(prev_image, prev_variance)
            sampled_prev_image = prev_image + prev_variance
            image = sampled_prev_image

        assert image.shape == (1, 3, 256, 256)
        image_slice = image[0, -1, -3:, -3:].cpu()
Patrick von Platen's avatar
Patrick von Platen committed
221
        import ipdb; ipdb.set_trace()
Patrick von Platen's avatar
improve  
Patrick von Platen committed
222
        assert (image_slice - torch.tensor([[0.1746, 0.5125, -0.7920], [-0.5734, -0.2910, -0.1984], [0.4090, -0.7740, -0.3941]])).abs().sum() < 1e-3
223
224
225
226
227
228
229
230
231
232
233
234
235


class PipelineTesterMixin(unittest.TestCase):
    def test_from_pretrained_save_pretrained(self):
        # 1. Load models
        model = UNetModel(ch=32, ch_mult=(1, 2), num_res_blocks=2, attn_resolutions=(16,), resolution=32)
        schedular = GaussianDDPMScheduler(timesteps=10)

        ddpm = DDPM(model, schedular)

        with tempfile.TemporaryDirectory() as tmpdirname:
            ddpm.save_pretrained(tmpdirname)
            new_ddpm = DDPM.from_pretrained(tmpdirname)
Patrick von Platen's avatar
Patrick von Platen committed
236
237

        generator = torch.manual_seed(0)
238

patil-suraj's avatar
patil-suraj committed
239
        image = ddpm(generator=generator)
Patrick von Platen's avatar
Patrick von Platen committed
240
        generator = generator.manual_seed(0)
patil-suraj's avatar
patil-suraj committed
241
        new_image = new_ddpm(generator=generator)
242
243
244
245
246
247
248
249
250
251
252
253
254

        assert (image - new_image).abs().sum() < 1e-5, "Models don't give the same forward pass"

    @slow
    def test_from_pretrained_hub(self):
        model_path = "fusing/ddpm-cifar10"

        ddpm = DDPM.from_pretrained(model_path)
        ddpm_from_hub = DiffusionPipeline.from_pretrained(model_path)

        ddpm.noise_scheduler.num_timesteps = 10
        ddpm_from_hub.noise_scheduler.num_timesteps = 10

Patrick von Platen's avatar
Patrick von Platen committed
255
        generator = torch.manual_seed(0)
256

patil-suraj's avatar
patil-suraj committed
257
        image = ddpm(generator=generator)
Patrick von Platen's avatar
Patrick von Platen committed
258
        generator = generator.manual_seed(0)
patil-suraj's avatar
patil-suraj committed
259
        new_image = ddpm_from_hub(generator=generator)
260
261

        assert (image - new_image).abs().sum() < 1e-5, "Models don't give the same forward pass"