Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
shivamshrirao
GitHub Repository: shivamshrirao/diffusers
Path: blob/main/tests/models/test_models_unet_1d.py
1448 views
1
# coding=utf-8
2
# Copyright 2023 HuggingFace Inc.
3
#
4
# Licensed under the Apache License, Version 2.0 (the "License");
5
# you may not use this file except in compliance with the License.
6
# You may obtain a copy of the License at
7
#
8
# http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
import unittest
17
18
import torch
19
20
from diffusers import UNet1DModel
21
from diffusers.utils import floats_tensor, slow, torch_device
22
23
from ..test_modeling_common import ModelTesterMixin
24
25
26
torch.backends.cuda.matmul.allow_tf32 = False
27
28
29
class UNet1DModelTests(ModelTesterMixin, unittest.TestCase):
30
model_class = UNet1DModel
31
32
@property
33
def dummy_input(self):
34
batch_size = 4
35
num_features = 14
36
seq_len = 16
37
38
noise = floats_tensor((batch_size, num_features, seq_len)).to(torch_device)
39
time_step = torch.tensor([10] * batch_size).to(torch_device)
40
41
return {"sample": noise, "timestep": time_step}
42
43
@property
44
def input_shape(self):
45
return (4, 14, 16)
46
47
@property
48
def output_shape(self):
49
return (4, 14, 16)
50
51
def test_ema_training(self):
52
pass
53
54
def test_training(self):
55
pass
56
57
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
58
def test_determinism(self):
59
super().test_determinism()
60
61
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
62
def test_outputs_equivalence(self):
63
super().test_outputs_equivalence()
64
65
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
66
def test_from_save_pretrained(self):
67
super().test_from_save_pretrained()
68
69
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
70
def test_from_save_pretrained_variant(self):
71
super().test_from_save_pretrained_variant()
72
73
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
74
def test_model_from_pretrained(self):
75
super().test_model_from_pretrained()
76
77
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
78
def test_output(self):
79
super().test_output()
80
81
def prepare_init_args_and_inputs_for_common(self):
82
init_dict = {
83
"block_out_channels": (32, 64, 128, 256),
84
"in_channels": 14,
85
"out_channels": 14,
86
"time_embedding_type": "positional",
87
"use_timestep_embedding": True,
88
"flip_sin_to_cos": False,
89
"freq_shift": 1.0,
90
"out_block_type": "OutConv1DBlock",
91
"mid_block_type": "MidResTemporalBlock1D",
92
"down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"),
93
"up_block_types": ("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D"),
94
"act_fn": "mish",
95
}
96
inputs_dict = self.dummy_input
97
return init_dict, inputs_dict
98
99
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
100
def test_from_pretrained_hub(self):
101
model, loading_info = UNet1DModel.from_pretrained(
102
"bglick13/hopper-medium-v2-value-function-hor32", output_loading_info=True, subfolder="unet"
103
)
104
self.assertIsNotNone(model)
105
self.assertEqual(len(loading_info["missing_keys"]), 0)
106
107
model.to(torch_device)
108
image = model(**self.dummy_input)
109
110
assert image is not None, "Make sure output is not None"
111
112
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
113
def test_output_pretrained(self):
114
model = UNet1DModel.from_pretrained("bglick13/hopper-medium-v2-value-function-hor32", subfolder="unet")
115
torch.manual_seed(0)
116
if torch.cuda.is_available():
117
torch.cuda.manual_seed_all(0)
118
119
num_features = model.in_channels
120
seq_len = 16
121
noise = torch.randn((1, seq_len, num_features)).permute(
122
0, 2, 1
123
) # match original, we can update values and remove
124
time_step = torch.full((num_features,), 0)
125
126
with torch.no_grad():
127
output = model(noise, time_step).sample.permute(0, 2, 1)
128
129
output_slice = output[0, -3:, -3:].flatten()
130
# fmt: off
131
expected_output_slice = torch.tensor([-2.137172, 1.1426016, 0.3688687, -0.766922, 0.7303146, 0.11038864, -0.4760633, 0.13270172, 0.02591348])
132
# fmt: on
133
self.assertTrue(torch.allclose(output_slice, expected_output_slice, rtol=1e-3))
134
135
def test_forward_with_norm_groups(self):
136
# Not implemented yet for this UNet
137
pass
138
139
@slow
140
def test_unet_1d_maestro(self):
141
model_id = "harmonai/maestro-150k"
142
model = UNet1DModel.from_pretrained(model_id, subfolder="unet")
143
model.to(torch_device)
144
145
sample_size = 65536
146
noise = torch.sin(torch.arange(sample_size)[None, None, :].repeat(1, 2, 1)).to(torch_device)
147
timestep = torch.tensor([1]).to(torch_device)
148
149
with torch.no_grad():
150
output = model(noise, timestep).sample
151
152
output_sum = output.abs().sum()
153
output_max = output.abs().max()
154
155
assert (output_sum - 224.0896).abs() < 4e-2
156
assert (output_max - 0.0607).abs() < 4e-4
157
158
159
class UNetRLModelTests(ModelTesterMixin, unittest.TestCase):
160
model_class = UNet1DModel
161
162
@property
163
def dummy_input(self):
164
batch_size = 4
165
num_features = 14
166
seq_len = 16
167
168
noise = floats_tensor((batch_size, num_features, seq_len)).to(torch_device)
169
time_step = torch.tensor([10] * batch_size).to(torch_device)
170
171
return {"sample": noise, "timestep": time_step}
172
173
@property
174
def input_shape(self):
175
return (4, 14, 16)
176
177
@property
178
def output_shape(self):
179
return (4, 14, 1)
180
181
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
182
def test_determinism(self):
183
super().test_determinism()
184
185
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
186
def test_outputs_equivalence(self):
187
super().test_outputs_equivalence()
188
189
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
190
def test_from_save_pretrained(self):
191
super().test_from_save_pretrained()
192
193
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
194
def test_from_save_pretrained_variant(self):
195
super().test_from_save_pretrained_variant()
196
197
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
198
def test_model_from_pretrained(self):
199
super().test_model_from_pretrained()
200
201
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
202
def test_output(self):
203
# UNetRL is a value-function is different output shape
204
init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
205
model = self.model_class(**init_dict)
206
model.to(torch_device)
207
model.eval()
208
209
with torch.no_grad():
210
output = model(**inputs_dict)
211
212
if isinstance(output, dict):
213
output = output.sample
214
215
self.assertIsNotNone(output)
216
expected_shape = torch.Size((inputs_dict["sample"].shape[0], 1))
217
self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match")
218
219
def test_ema_training(self):
220
pass
221
222
def test_training(self):
223
pass
224
225
def prepare_init_args_and_inputs_for_common(self):
226
init_dict = {
227
"in_channels": 14,
228
"out_channels": 14,
229
"down_block_types": ["DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"],
230
"up_block_types": [],
231
"out_block_type": "ValueFunction",
232
"mid_block_type": "ValueFunctionMidBlock1D",
233
"block_out_channels": [32, 64, 128, 256],
234
"layers_per_block": 1,
235
"downsample_each_block": True,
236
"use_timestep_embedding": True,
237
"freq_shift": 1.0,
238
"flip_sin_to_cos": False,
239
"time_embedding_type": "positional",
240
"act_fn": "mish",
241
}
242
inputs_dict = self.dummy_input
243
return init_dict, inputs_dict
244
245
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
246
def test_from_pretrained_hub(self):
247
value_function, vf_loading_info = UNet1DModel.from_pretrained(
248
"bglick13/hopper-medium-v2-value-function-hor32", output_loading_info=True, subfolder="value_function"
249
)
250
self.assertIsNotNone(value_function)
251
self.assertEqual(len(vf_loading_info["missing_keys"]), 0)
252
253
value_function.to(torch_device)
254
image = value_function(**self.dummy_input)
255
256
assert image is not None, "Make sure output is not None"
257
258
@unittest.skipIf(torch_device == "mps", "mish op not supported in MPS")
259
def test_output_pretrained(self):
260
value_function, vf_loading_info = UNet1DModel.from_pretrained(
261
"bglick13/hopper-medium-v2-value-function-hor32", output_loading_info=True, subfolder="value_function"
262
)
263
torch.manual_seed(0)
264
if torch.cuda.is_available():
265
torch.cuda.manual_seed_all(0)
266
267
num_features = value_function.in_channels
268
seq_len = 14
269
noise = torch.randn((1, seq_len, num_features)).permute(
270
0, 2, 1
271
) # match original, we can update values and remove
272
time_step = torch.full((num_features,), 0)
273
274
with torch.no_grad():
275
output = value_function(noise, time_step).sample
276
277
# fmt: off
278
expected_output_slice = torch.tensor([165.25] * seq_len)
279
# fmt: on
280
self.assertTrue(torch.allclose(output, expected_output_slice, rtol=1e-3))
281
282
def test_forward_with_norm_groups(self):
283
# Not implemented yet for this UNet
284
pass
285
286