Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
shivamshrirao
GitHub Repository: shivamshrirao/diffusers
Path: blob/main/tests/models/test_models_unet_3d_condition.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 numpy as np
19
import torch
20
21
from diffusers.models import ModelMixin, UNet3DConditionModel
22
from diffusers.models.attention_processor import LoRAAttnProcessor
23
from diffusers.utils import (
24
floats_tensor,
25
logging,
26
skip_mps,
27
torch_device,
28
)
29
from diffusers.utils.import_utils import is_xformers_available
30
31
from ..test_modeling_common import ModelTesterMixin
32
33
34
logger = logging.get_logger(__name__)
35
torch.backends.cuda.matmul.allow_tf32 = False
36
37
38
def create_lora_layers(model):
39
lora_attn_procs = {}
40
for name in model.attn_processors.keys():
41
cross_attention_dim = None if name.endswith("attn1.processor") else model.config.cross_attention_dim
42
if name.startswith("mid_block"):
43
hidden_size = model.config.block_out_channels[-1]
44
elif name.startswith("up_blocks"):
45
block_id = int(name[len("up_blocks.")])
46
hidden_size = list(reversed(model.config.block_out_channels))[block_id]
47
elif name.startswith("down_blocks"):
48
block_id = int(name[len("down_blocks.")])
49
hidden_size = model.config.block_out_channels[block_id]
50
51
lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim)
52
lora_attn_procs[name] = lora_attn_procs[name].to(model.device)
53
54
# add 1 to weights to mock trained weights
55
with torch.no_grad():
56
lora_attn_procs[name].to_q_lora.up.weight += 1
57
lora_attn_procs[name].to_k_lora.up.weight += 1
58
lora_attn_procs[name].to_v_lora.up.weight += 1
59
lora_attn_procs[name].to_out_lora.up.weight += 1
60
61
return lora_attn_procs
62
63
64
@skip_mps
65
class UNet3DConditionModelTests(ModelTesterMixin, unittest.TestCase):
66
model_class = UNet3DConditionModel
67
68
@property
69
def dummy_input(self):
70
batch_size = 4
71
num_channels = 4
72
num_frames = 4
73
sizes = (32, 32)
74
75
noise = floats_tensor((batch_size, num_channels, num_frames) + sizes).to(torch_device)
76
time_step = torch.tensor([10]).to(torch_device)
77
encoder_hidden_states = floats_tensor((batch_size, 4, 32)).to(torch_device)
78
79
return {"sample": noise, "timestep": time_step, "encoder_hidden_states": encoder_hidden_states}
80
81
@property
82
def input_shape(self):
83
return (4, 4, 32, 32)
84
85
@property
86
def output_shape(self):
87
return (4, 4, 32, 32)
88
89
def prepare_init_args_and_inputs_for_common(self):
90
init_dict = {
91
"block_out_channels": (32, 64, 64, 64),
92
"down_block_types": (
93
"CrossAttnDownBlock3D",
94
"CrossAttnDownBlock3D",
95
"CrossAttnDownBlock3D",
96
"DownBlock3D",
97
),
98
"up_block_types": ("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D"),
99
"cross_attention_dim": 32,
100
"attention_head_dim": 4,
101
"out_channels": 4,
102
"in_channels": 4,
103
"layers_per_block": 2,
104
"sample_size": 32,
105
}
106
inputs_dict = self.dummy_input
107
return init_dict, inputs_dict
108
109
@unittest.skipIf(
110
torch_device != "cuda" or not is_xformers_available(),
111
reason="XFormers attention is only available with CUDA and `xformers` installed",
112
)
113
def test_xformers_enable_works(self):
114
init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
115
model = self.model_class(**init_dict)
116
117
model.enable_xformers_memory_efficient_attention()
118
119
assert (
120
model.mid_block.attentions[0].transformer_blocks[0].attn1.processor.__class__.__name__
121
== "XFormersAttnProcessor"
122
), "xformers is not enabled"
123
124
# Overriding because `block_out_channels` needs to be different for this model.
125
def test_forward_with_norm_groups(self):
126
init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
127
128
init_dict["norm_num_groups"] = 32
129
init_dict["block_out_channels"] = (32, 64, 64, 64)
130
131
model = self.model_class(**init_dict)
132
model.to(torch_device)
133
model.eval()
134
135
with torch.no_grad():
136
output = model(**inputs_dict)
137
138
if isinstance(output, dict):
139
output = output.sample
140
141
self.assertIsNotNone(output)
142
expected_shape = inputs_dict["sample"].shape
143
self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match")
144
145
# Overriding since the UNet3D outputs a different structure.
146
def test_determinism(self):
147
init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
148
model = self.model_class(**init_dict)
149
model.to(torch_device)
150
model.eval()
151
152
with torch.no_grad():
153
# Warmup pass when using mps (see #372)
154
if torch_device == "mps" and isinstance(model, ModelMixin):
155
model(**self.dummy_input)
156
157
first = model(**inputs_dict)
158
if isinstance(first, dict):
159
first = first.sample
160
161
second = model(**inputs_dict)
162
if isinstance(second, dict):
163
second = second.sample
164
165
out_1 = first.cpu().numpy()
166
out_2 = second.cpu().numpy()
167
out_1 = out_1[~np.isnan(out_1)]
168
out_2 = out_2[~np.isnan(out_2)]
169
max_diff = np.amax(np.abs(out_1 - out_2))
170
self.assertLessEqual(max_diff, 1e-5)
171
172
def test_model_attention_slicing(self):
173
init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
174
175
init_dict["attention_head_dim"] = 8
176
177
model = self.model_class(**init_dict)
178
model.to(torch_device)
179
model.eval()
180
181
model.set_attention_slice("auto")
182
with torch.no_grad():
183
output = model(**inputs_dict)
184
assert output is not None
185
186
model.set_attention_slice("max")
187
with torch.no_grad():
188
output = model(**inputs_dict)
189
assert output is not None
190
191
model.set_attention_slice(2)
192
with torch.no_grad():
193
output = model(**inputs_dict)
194
assert output is not None
195
196
# (`attn_processors`) needs to be implemented in this model for this test.
197
# def test_lora_processors(self):
198
199
# (`attn_processors`) needs to be implemented in this model for this test.
200
# def test_lora_save_load(self):
201
202
# (`attn_processors`) needs to be implemented for this test in the model.
203
# def test_lora_save_load_safetensors(self):
204
205
# (`attn_processors`) needs to be implemented for this test in the model.
206
# def test_lora_save_safetensors_load_torch(self):
207
208
# (`attn_processors`) needs to be implemented for this test.
209
# def test_lora_save_torch_force_load_safetensors_error(self):
210
211
# (`attn_processors`) needs to be added for this test.
212
# def test_lora_on_off(self):
213
214
@unittest.skipIf(
215
torch_device != "cuda" or not is_xformers_available(),
216
reason="XFormers attention is only available with CUDA and `xformers` installed",
217
)
218
def test_lora_xformers_on_off(self):
219
# enable deterministic behavior for gradient checkpointing
220
init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
221
222
init_dict["attention_head_dim"] = 4
223
224
torch.manual_seed(0)
225
model = self.model_class(**init_dict)
226
model.to(torch_device)
227
lora_attn_procs = create_lora_layers(model)
228
model.set_attn_processor(lora_attn_procs)
229
230
# default
231
with torch.no_grad():
232
sample = model(**inputs_dict).sample
233
234
model.enable_xformers_memory_efficient_attention()
235
on_sample = model(**inputs_dict).sample
236
237
model.disable_xformers_memory_efficient_attention()
238
off_sample = model(**inputs_dict).sample
239
240
assert (sample - on_sample).abs().max() < 1e-4
241
assert (sample - off_sample).abs().max() < 1e-4
242
243
244
# (todo: sayakpaul) implement SLOW tests.
245
246