-
Notifications
You must be signed in to change notification settings - Fork 236
/
Copy pathtest_diffusers.py
6392 lines (5420 loc) · 232 KB
/
test_diffusers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
# Copyright 2022 The HuggingFace Inc. team.
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# 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.
import contextlib
import copy
import gc
import inspect
import json
import os
import random
import re
import shutil
import subprocess
import tempfile
from io import BytesIO, StringIO
from pathlib import Path
from typing import Callable, Union
from unittest import TestCase, skipUnless
import diffusers
import numpy as np
import PIL
import pytest
import requests
import safetensors
import torch
from diffusers import (
AutoencoderKL,
AutoencoderKLTemporalDecoder,
AutoencoderTiny,
ControlNetModel,
DiffusionPipeline,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
FlowMatchEulerDiscreteScheduler,
FluxTransformer2DModel,
I2VGenXLUNet,
LCMScheduler,
PNDMScheduler,
SD3Transformer2DModel,
StableDiffusionXLPipeline,
StableVideoDiffusionPipeline,
UNet2DConditionModel,
UNet2DModel,
UNet3DConditionModel,
UNetSpatioTemporalConditionModel,
UniPCMultistepScheduler,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.controlnet.pipeline_controlnet import MultiControlNetModel
from diffusers.schedulers import KarrasDiffusionSchedulers
from diffusers.utils import logging
from diffusers.utils.testing_utils import (
enable_full_determinism,
floats_tensor,
load_image,
numpy_cosine_similarity_distance,
require_torch,
)
from diffusers.utils.torch_utils import randn_tensor
from huggingface_hub import HfApi, hf_hub_download, snapshot_download
from huggingface_hub.utils import HfHubHTTPError
from parameterized import parameterized
from PIL import Image
from transformers import (
AutoTokenizer,
CLIPImageProcessor,
CLIPTextConfig,
CLIPTextModel,
CLIPTextModelWithProjection,
CLIPTokenizer,
CLIPVisionConfig,
CLIPVisionModelWithProjection,
DPTConfig,
DPTFeatureExtractor,
DPTForDepthEstimation,
T5EncoderModel,
)
from transformers.testing_utils import parse_flag_from_env, slow
from optimum.habana import GaudiConfig
from optimum.habana.diffusers import (
GaudiDDIMScheduler,
GaudiDDPMPipeline,
GaudiDiffusionPipeline,
GaudiEulerAncestralDiscreteScheduler,
GaudiEulerDiscreteScheduler,
GaudiFluxImg2ImgPipeline,
GaudiFluxPipeline,
GaudiI2VGenXLPipeline,
GaudiStableDiffusion3Pipeline,
GaudiStableDiffusionControlNetPipeline,
GaudiStableDiffusionDepth2ImgPipeline,
GaudiStableDiffusionImageVariationPipeline,
GaudiStableDiffusionImg2ImgPipeline,
GaudiStableDiffusionInpaintPipeline,
GaudiStableDiffusionInstructPix2PixPipeline,
GaudiStableDiffusionLDM3DPipeline,
GaudiStableDiffusionPipeline,
GaudiStableDiffusionUpscalePipeline,
GaudiStableDiffusionXLImg2ImgPipeline,
GaudiStableDiffusionXLInpaintPipeline,
GaudiStableDiffusionXLPipeline,
GaudiStableVideoDiffusionControlNetPipeline,
GaudiStableVideoDiffusionPipeline,
GaudiTextToVideoSDPipeline,
)
from optimum.habana.diffusers.models import (
ControlNetSDVModel,
UNetSpatioTemporalConditionControlNetModel,
)
from optimum.habana.utils import set_seed
from .clip_coco_utils import calculate_clip_score, download_files
from .utils import OH_DEVICE_CONTEXT
IS_GAUDI1 = bool("gaudi1" == OH_DEVICE_CONTEXT)
if OH_DEVICE_CONTEXT in ["gaudi2"]:
THROUGHPUT_BASELINE_BF16 = 1.086
THROUGHPUT_BASELINE_AUTOCAST = 0.394
TEXTUAL_INVERSION_THROUGHPUT = 131.7606336456344
TEXTUAL_INVERSION_RUNTIME = 1.542460777796805
TEXTUAL_INVERSION_SDXL_THROUGHPUT = 2.6694
TEXTUAL_INVERSION_SDXL_RUNTIME = 74.92
CONTROLNET_THROUGHPUT = 120.123522340414
CONTROLNET_RUNTIME = 1.8647471838630736
INPAINT_THROUGHPUT_BASELINE_BF16 = 1.025
INPAINT_XL_THROUGHPUT_BASELINE_BF16 = 0.175
THROUGHPUT_UNCONDITIONAL_IMAGE_BASELINE_BF16 = 0.145
SDXL_THROUGHPUT = 0.301
SVD_THROUGHPUT = 0.012
SD3_THROUGHPUT = 0.006
FLUX_THROUGHPUT = 0.03
FLUX_DEV_I2I_THROUGHPUT = 0.12
I2V_THROUGHPUT = 0.017
else:
THROUGHPUT_BASELINE_BF16 = 0.275
THROUGHPUT_BASELINE_AUTOCAST = 0.114
TEXTUAL_INVERSION_THROUGHPUT = 122.7445217395719
TEXTUAL_INVERSION_RUNTIME = 1.8249286960053723
TEXTUAL_INVERSION_SDXL_THROUGHPUT = 2.695
TEXTUAL_INVERSION_SDXL_RUNTIME = 74.19
CONTROLNET_THROUGHPUT = 78.51566937458146
CONTROLNET_RUNTIME = 2.852933710993966
INPAINT_THROUGHPUT_BASELINE_BF16 = 0.272
INPAINT_XL_THROUGHPUT_BASELINE_BF16 = 0.042
THROUGHPUT_UNCONDITIONAL_IMAGE_BASELINE_BF16 = 0.045
SDXL_THROUGHPUT = 0.074
SVD_THROUGHPUT = 0.012
I2V_THROUGHPUT = 0.008
_run_custom_bf16_ops_test_ = parse_flag_from_env("CUSTOM_BF16_OPS", default=False)
def custom_bf16_ops(test_case):
"""
Decorator marking a test as needing custom bf16 ops.
Custom bf16 ops must be declared before `habana_frameworks.torch.core` is imported, which is not possible if some other tests are executed before.
Such tests are skipped by default. Set the CUSTOM_BF16_OPS environment variable to a truthy value to run them.
"""
return skipUnless(_run_custom_bf16_ops_test_, "test requires custom bf16 ops")(test_case)
def check_gated_model_access(model):
"""
Skip test for a gated model if access is not granted; this occurs when an account
with the required permissions is not logged into the HF Hub.
"""
try:
hf_hub_download(repo_id=model, filename=HfApi().model_info(model).siblings[0].rfilename)
gated = False
except HfHubHTTPError:
gated = True
return pytest.mark.skipif(gated, reason=f"{model} is gated, please log in with approved HF access token")
def check_8xhpu(test_case):
"""
Decorator marking a test as it requires 8xHPU on system
"""
from optimum.habana.utils import get_device_count
if get_device_count() != 8:
skip = True
else:
skip = False
return pytest.mark.skipif(skip, reason="test requires 8xHPU multi-card system")(test_case)
class GaudiPipelineUtilsTester(TestCase):
"""
Tests the features added on top of diffusers/pipeline_utils.py.
"""
def test_use_hpu_graphs_raise_error_without_habana(self):
with self.assertRaises(ValueError):
_ = GaudiDiffusionPipeline(
use_habana=False,
use_hpu_graphs=True,
)
def test_gaudi_config_raise_error_without_habana(self):
with self.assertRaises(ValueError):
_ = GaudiDiffusionPipeline(
use_habana=False,
gaudi_config=GaudiConfig(),
)
def test_device(self):
pipeline_1 = GaudiDiffusionPipeline(
use_habana=True,
gaudi_config=GaudiConfig(),
)
self.assertEqual(pipeline_1._device.type, "hpu")
pipeline_2 = GaudiDiffusionPipeline(
use_habana=False,
)
self.assertEqual(pipeline_2._device.type, "cpu")
def test_gaudi_config_types(self):
# gaudi_config is a string
_ = GaudiDiffusionPipeline(
use_habana=True,
gaudi_config="Habana/stable-diffusion",
)
# gaudi_config is instantiated beforehand
gaudi_config = GaudiConfig.from_pretrained("Habana/stable-diffusion")
_ = GaudiDiffusionPipeline(
use_habana=True,
gaudi_config=gaudi_config,
)
def test_default(self):
pipeline = GaudiDiffusionPipeline(
use_habana=True,
gaudi_config=GaudiConfig(),
)
self.assertTrue(hasattr(pipeline, "htcore"))
def test_use_hpu_graphs(self):
pipeline = GaudiDiffusionPipeline(
use_habana=True,
use_hpu_graphs=True,
gaudi_config=GaudiConfig(),
)
self.assertTrue(hasattr(pipeline, "ht"))
self.assertTrue(hasattr(pipeline, "hpu_stream"))
self.assertTrue(hasattr(pipeline, "cache"))
def test_save_pretrained(self):
model_name = "hf-internal-testing/tiny-stable-diffusion-torch"
scheduler = GaudiDDIMScheduler.from_pretrained(model_name, subfolder="scheduler")
pipeline = GaudiStableDiffusionPipeline.from_pretrained(
model_name,
scheduler=scheduler,
use_habana=True,
gaudi_config=GaudiConfig(),
)
with tempfile.TemporaryDirectory() as tmp_dir:
pipeline.save_pretrained(tmp_dir)
self.assertTrue(Path(tmp_dir, "gaudi_config.json").is_file())
class GaudiStableDiffusionPipelineTester(TestCase):
"""
Tests the StableDiffusionPipeline for Gaudi.
"""
def get_dummy_components(self, time_cond_proj_dim=None):
torch.manual_seed(0)
unet = UNet2DConditionModel(
block_out_channels=(4, 8),
layers_per_block=1,
sample_size=32,
time_cond_proj_dim=time_cond_proj_dim,
in_channels=4,
out_channels=4,
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
cross_attention_dim=32,
norm_num_groups=2,
)
scheduler = GaudiDDIMScheduler(
beta_start=0.00085,
beta_end=0.012,
beta_schedule="scaled_linear",
clip_sample=False,
set_alpha_to_one=False,
)
torch.manual_seed(0)
vae = AutoencoderKL(
block_out_channels=[4, 8],
in_channels=3,
out_channels=3,
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
latent_channels=4,
norm_num_groups=2,
)
torch.manual_seed(0)
text_encoder_config = CLIPTextConfig(
bos_token_id=0,
eos_token_id=2,
hidden_size=32,
intermediate_size=64,
layer_norm_eps=1e-05,
num_attention_heads=8,
num_hidden_layers=3,
pad_token_id=1,
vocab_size=1000,
)
text_encoder = CLIPTextModel(text_encoder_config)
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
components = {
"unet": unet,
"scheduler": scheduler,
"vae": vae,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"safety_checker": None,
"feature_extractor": None,
}
return components
def get_dummy_inputs(self, device, seed=0):
generator = torch.Generator(device=device).manual_seed(seed)
inputs = {
"prompt": "A painting of a squirrel eating a burger",
"generator": generator,
"num_inference_steps": 2,
"guidance_scale": 6.0,
"output_type": "numpy",
}
return inputs
def test_stable_diffusion_ddim(self):
device = "cpu"
components = self.get_dummy_components()
gaudi_config = GaudiConfig(use_torch_autocast=False)
sd_pipe = GaudiStableDiffusionPipeline(
use_habana=True,
gaudi_config=gaudi_config,
**components,
)
sd_pipe.set_progress_bar_config(disable=None)
inputs = self.get_dummy_inputs(device)
output = sd_pipe(**inputs)
image = output.images[0]
image_slice = image[-3:, -3:, -1]
self.assertEqual(image.shape, (64, 64, 3))
expected_slice = np.array([0.3203, 0.4555, 0.4711, 0.3505, 0.3973, 0.4650, 0.5137, 0.3392, 0.4045])
self.assertLess(np.abs(image_slice.flatten() - expected_slice).max(), 1e-2)
def test_stable_diffusion_no_safety_checker(self):
gaudi_config = GaudiConfig()
scheduler = GaudiDDIMScheduler(
beta_start=0.00085,
beta_end=0.012,
beta_schedule="scaled_linear",
clip_sample=False,
set_alpha_to_one=False,
)
pipe = GaudiStableDiffusionPipeline.from_pretrained(
"hf-internal-testing/tiny-stable-diffusion-pipe",
scheduler=scheduler,
safety_checker=None,
use_habana=True,
gaudi_config=gaudi_config,
)
self.assertIsInstance(pipe, GaudiStableDiffusionPipeline)
self.assertIsInstance(pipe.scheduler, GaudiDDIMScheduler)
self.assertIsNone(pipe.safety_checker)
image = pipe("example prompt", num_inference_steps=2).images[0]
self.assertIsNotNone(image)
# Check that there's no error when saving a pipeline with one of the models being None
with tempfile.TemporaryDirectory() as tmpdirname:
pipe.save_pretrained(tmpdirname)
pipe = GaudiStableDiffusionPipeline.from_pretrained(
tmpdirname,
use_habana=True,
gaudi_config=tmpdirname,
)
# Sanity check that the pipeline still works
self.assertIsNone(pipe.safety_checker)
image = pipe("example prompt", num_inference_steps=2).images[0]
self.assertIsNotNone(image)
@parameterized.expand(["pil", "np", "latent"])
def test_stable_diffusion_output_types(self, output_type):
components = self.get_dummy_components()
gaudi_config = GaudiConfig()
sd_pipe = GaudiStableDiffusionPipeline(
use_habana=True,
gaudi_config=gaudi_config,
**components,
)
sd_pipe.set_progress_bar_config(disable=None)
prompt = "A painting of a squirrel eating a burger"
num_prompts = 2
num_images_per_prompt = 3
outputs = sd_pipe(
num_prompts * [prompt],
num_images_per_prompt=num_images_per_prompt,
num_inference_steps=2,
output_type=output_type,
)
self.assertEqual(len(outputs.images), 2 * 3)
def test_stable_diffusion_num_images_per_prompt(self):
components = self.get_dummy_components()
gaudi_config = GaudiConfig()
sd_pipe = GaudiStableDiffusionPipeline(
use_habana=True,
gaudi_config=gaudi_config,
**components,
)
sd_pipe.set_progress_bar_config(disable=None)
prompt = "A painting of a squirrel eating a burger"
# Test num_images_per_prompt=1 (default)
images = sd_pipe(prompt, num_inference_steps=2, output_type="np").images
self.assertEqual(len(images), 1)
self.assertEqual(images[0].shape, (64, 64, 3))
# Test num_images_per_prompt=1 (default) for several prompts
num_prompts = 3
images = sd_pipe([prompt] * num_prompts, num_inference_steps=2, output_type="np").images
self.assertEqual(len(images), num_prompts)
self.assertEqual(images[-1].shape, (64, 64, 3))
# Test num_images_per_prompt for single prompt
num_images_per_prompt = 2
images = sd_pipe(
prompt, num_inference_steps=2, output_type="np", num_images_per_prompt=num_images_per_prompt
).images
self.assertEqual(len(images), num_images_per_prompt)
self.assertEqual(images[-1].shape, (64, 64, 3))
# Test num_images_per_prompt for several prompts
num_prompts = 2
images = sd_pipe(
[prompt] * num_prompts,
num_inference_steps=2,
output_type="np",
num_images_per_prompt=num_images_per_prompt,
).images
self.assertEqual(len(images), num_prompts * num_images_per_prompt)
self.assertEqual(images[-1].shape, (64, 64, 3))
def test_stable_diffusion_batch_sizes(self):
components = self.get_dummy_components()
gaudi_config = GaudiConfig()
sd_pipe = GaudiStableDiffusionPipeline(
use_habana=True,
gaudi_config=gaudi_config,
**components,
)
sd_pipe.set_progress_bar_config(disable=None)
prompt = "A painting of a squirrel eating a burger"
# Test num_images > 1 where num_images is a divider of the total number of generated images
batch_size = 3
num_images_per_prompt = batch_size**2
images = sd_pipe(
prompt,
num_inference_steps=2,
output_type="np",
batch_size=batch_size,
num_images_per_prompt=num_images_per_prompt,
).images
self.assertEqual(len(images), num_images_per_prompt)
self.assertEqual(images[-1].shape, (64, 64, 3))
# Same test for several prompts
num_prompts = 3
images = sd_pipe(
[prompt] * num_prompts,
num_inference_steps=2,
output_type="np",
batch_size=batch_size,
num_images_per_prompt=num_images_per_prompt,
).images
self.assertEqual(len(images), num_prompts * num_images_per_prompt)
self.assertEqual(images[-1].shape, (64, 64, 3))
# Test num_images when it is not a divider of the total number of generated images for a single prompt
num_images_per_prompt = 7
images = sd_pipe(
prompt,
num_inference_steps=2,
output_type="np",
batch_size=batch_size,
num_images_per_prompt=num_images_per_prompt,
).images
self.assertEqual(len(images), num_images_per_prompt)
self.assertEqual(images[-1].shape, (64, 64, 3))
# Same test for several prompts
num_prompts = 2
images = sd_pipe(
[prompt] * num_prompts,
num_inference_steps=2,
output_type="np",
batch_size=batch_size,
num_images_per_prompt=num_images_per_prompt,
).images
self.assertEqual(len(images), num_prompts * num_images_per_prompt)
self.assertEqual(images[-1].shape, (64, 64, 3))
def test_stable_diffusion_bf16(self):
"""Test that stable diffusion works with bf16"""
components = self.get_dummy_components()
gaudi_config = GaudiConfig()
sd_pipe = GaudiStableDiffusionPipeline(
use_habana=True,
gaudi_config=gaudi_config,
**components,
)
sd_pipe.set_progress_bar_config(disable=None)
prompt = "A painting of a squirrel eating a burger"
generator = torch.Generator(device="cpu").manual_seed(0)
image = sd_pipe([prompt], generator=generator, num_inference_steps=2, output_type="np").images[0]
self.assertEqual(image.shape, (64, 64, 3))
def test_stable_diffusion_default(self):
components = self.get_dummy_components()
sd_pipe = GaudiStableDiffusionPipeline(
use_habana=True,
gaudi_config="Habana/stable-diffusion",
**components,
)
sd_pipe.set_progress_bar_config(disable=None)
prompt = "A painting of a squirrel eating a burger"
generator = torch.Generator(device="cpu").manual_seed(0)
images = sd_pipe(
[prompt] * 2,
generator=generator,
num_inference_steps=2,
output_type="np",
batch_size=3,
num_images_per_prompt=5,
).images
self.assertEqual(len(images), 10)
self.assertEqual(images[-1].shape, (64, 64, 3))
def test_stable_diffusion_hpu_graphs(self):
components = self.get_dummy_components()
sd_pipe = GaudiStableDiffusionPipeline(
use_habana=True,
use_hpu_graphs=True,
gaudi_config="Habana/stable-diffusion",
**components,
)
sd_pipe.set_progress_bar_config(disable=None)
prompt = "A painting of a squirrel eating a burger"
generator = torch.Generator(device="cpu").manual_seed(0)
images = sd_pipe(
[prompt] * 2,
generator=generator,
num_inference_steps=2,
output_type="np",
batch_size=3,
num_images_per_prompt=5,
).images
self.assertEqual(len(images), 10)
self.assertEqual(images[-1].shape, (64, 64, 3))
@slow
def test_no_throughput_regression_bf16(self):
prompts = [
"An image of a squirrel in Picasso style",
]
num_images_per_prompt = 28
batch_size = 7
model_name = "CompVis/stable-diffusion-v1-4"
scheduler = GaudiDDIMScheduler.from_pretrained(model_name, subfolder="scheduler")
pipeline = GaudiStableDiffusionPipeline.from_pretrained(
model_name,
scheduler=scheduler,
use_habana=True,
use_hpu_graphs=True,
gaudi_config=GaudiConfig.from_pretrained("Habana/stable-diffusion"),
torch_dtype=torch.bfloat16,
sdp_on_bf16=True,
)
pipeline.unet.set_default_attn_processor(pipeline.unet)
set_seed(27)
outputs = pipeline(
prompt=prompts,
num_images_per_prompt=num_images_per_prompt,
batch_size=batch_size,
output_type="np",
)
# Check expected number of output images
self.assertEqual(len(outputs.images), num_images_per_prompt * len(prompts))
# Throughput regression test
self.assertGreaterEqual(outputs.throughput, 0.95 * THROUGHPUT_BASELINE_BF16)
n = 0
clip_score_avg = 0.0
for i in range(len(outputs.images)):
# Check expected shape for each output image
self.assertEqual(outputs.images[i].shape, (512, 512, 3))
if np.any(outputs.images[i] != 0):
clip_score = calculate_clip_score(np.expand_dims(outputs.images[i], axis=0), prompts)
clip_score_avg += clip_score
n += 1
# Quality test (check that the average CLIP score of valid output images is well in the 30s range)
clip_score_avg /= n
CLIP_SCORE_THRESHOLD = 30.0
self.assertGreaterEqual(clip_score_avg, CLIP_SCORE_THRESHOLD)
@custom_bf16_ops
@slow
def test_no_throughput_regression_autocast(self):
prompts = [
"An image of a squirrel in Picasso style",
]
num_images_per_prompt = 28
batch_size = 7
model_name = "stabilityai/stable-diffusion-2-1"
scheduler = GaudiDDIMScheduler.from_pretrained(model_name, subfolder="scheduler")
pipeline = GaudiStableDiffusionPipeline.from_pretrained(
model_name,
scheduler=scheduler,
use_habana=True,
use_hpu_graphs=True,
gaudi_config=GaudiConfig.from_pretrained("Habana/stable-diffusion-2"),
sdp_on_bf16=True,
)
set_seed(27)
outputs = pipeline(
prompt=prompts,
num_images_per_prompt=num_images_per_prompt,
batch_size=batch_size,
height=768,
width=768,
)
# Check expected number of output images
self.assertEqual(len(outputs.images), num_images_per_prompt * len(prompts))
# Throughput regression test
self.assertGreaterEqual(outputs.throughput, 0.95 * THROUGHPUT_BASELINE_AUTOCAST)
@custom_bf16_ops
@slow
def test_no_generation_regression_ldm3d(self):
prompts = [
"An image of a squirrel in Picasso style",
]
num_images_per_prompt = 28
batch_size = 7
model_name = "Intel/ldm3d-4c"
scheduler = GaudiDDIMScheduler.from_pretrained(model_name, subfolder="scheduler")
pipeline = GaudiStableDiffusionLDM3DPipeline.from_pretrained(
model_name,
scheduler=scheduler,
safety_checker=None,
use_habana=True,
use_hpu_graphs=True,
gaudi_config=GaudiConfig.from_pretrained("Habana/stable-diffusion-2"),
sdp_on_bf16=True,
)
set_seed(27)
outputs = pipeline(
prompt=prompts,
num_images_per_prompt=num_images_per_prompt,
batch_size=batch_size,
output_type="np",
)
# Check expected number of output images
self.assertEqual(len(outputs.rgb), num_images_per_prompt * len(prompts))
self.assertEqual(len(outputs.depth), num_images_per_prompt * len(prompts))
# Throughput regression test
self.assertGreaterEqual(outputs.throughput, 0.95 * THROUGHPUT_BASELINE_AUTOCAST)
n = 0
clip_score_avg = 0.0
for i in range(len(outputs.rgb)):
# Check expected shape for each output image
self.assertEqual(outputs.rgb[i].shape, (512, 512, 3))
self.assertEqual(outputs.depth[i].shape, (512, 512, 1))
if np.any(outputs.rgb[i] != 0):
clip_score = calculate_clip_score(np.expand_dims(outputs.rgb[i], axis=0), prompts)
clip_score_avg += clip_score
n += 1
# Quality test (check that the average CLIP score of valid output images is well in the 30s range)
clip_score_avg /= n
CLIP_SCORE_THRESHOLD = 30.0
self.assertGreaterEqual(clip_score_avg, CLIP_SCORE_THRESHOLD)
@slow
def test_no_generation_regression_upscale(self):
model_name = "stabilityai/stable-diffusion-x4-upscaler"
scheduler = GaudiDDIMScheduler.from_pretrained(model_name, subfolder="scheduler")
pipeline = GaudiStableDiffusionUpscalePipeline.from_pretrained(
model_name,
scheduler=scheduler,
use_habana=True,
use_hpu_graphs=True,
gaudi_config=GaudiConfig(use_torch_autocast=False),
sdp_on_bf16=True,
)
set_seed(27)
url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale/low_res_cat.png"
response = requests.get(url)
low_res_img = Image.open(BytesIO(response.content)).convert("RGB")
low_res_img = low_res_img.resize((128, 128))
prompt = "a white cat"
upscaled_image = pipeline(prompt=prompt, image=low_res_img, output_type="np").images[0]
# Check expected shape of the upscaled image
self.assertEqual(upscaled_image.shape, (512, 512, 3))
# Check expected upscaled values of a sample slice
expected_slice = np.array(
[
0.16528079,
0.16161581,
0.15665841,
0.16609294,
0.15943781,
0.14936810,
0.15782778,
0.15342544,
0.14590860,
]
)
self.assertLess(np.abs(expected_slice - upscaled_image[-3:, -3:, -1].flatten()).max(), 5e-3)
@slow
@check_8xhpu
def test_sd_textual_inversion(self):
path_to_script = (
Path(os.path.dirname(__file__)).parent
/ "examples"
/ "stable-diffusion"
/ "training"
/ "textual_inversion.py"
)
with tempfile.TemporaryDirectory() as data_dir:
snapshot_download(
"diffusers/cat_toy_example", local_dir=data_dir, repo_type="dataset", ignore_patterns=".gitattributes"
)
cache_dir = Path(data_dir, ".cache")
if cache_dir.is_dir():
shutil.rmtree(cache_dir)
with tempfile.TemporaryDirectory() as run_dir:
cmd_line = [
"python3",
f"{path_to_script.parent.parent.parent / 'gaudi_spawn.py'}",
"--use_mpi",
"--world_size 8",
f"{path_to_script}",
"--pretrained_model_name_or_path CompVis/stable-diffusion-v1-4",
f"--train_data_dir {data_dir}",
'--learnable_property "object"',
'--placeholder_token "<cat-toy>"',
'--initializer_token "toy"',
"--resolution 256",
"--train_batch_size 4",
"--max_train_steps 10",
"--learning_rate 5.0e-04",
"--scale_lr",
'--lr_scheduler "constant"',
"--lr_warmup_steps 0",
f"--output_dir {run_dir}",
"--save_as_full_pipeline",
"--gaudi_config_name Habana/stable-diffusion",
"--throughput_warmup_steps 3",
"--seed 27",
]
pattern = re.compile(r"([\"\'].+?[\"\'])|\s")
cmd_line = [x for y in cmd_line for x in re.split(pattern, y) if x]
# Run textual inversion
p = subprocess.Popen(cmd_line)
return_code = p.wait()
# Ensure the run finished without any issue
self.assertEqual(return_code, 0)
# Assess throughput
with open(Path(run_dir) / "speed_metrics.json") as fp:
results = json.load(fp)
self.assertGreaterEqual(results["train_samples_per_second"], 0.95 * TEXTUAL_INVERSION_THROUGHPUT)
self.assertLessEqual(results["train_runtime"], 1.05 * TEXTUAL_INVERSION_RUNTIME)
# Assess generated image
pipe = GaudiStableDiffusionPipeline.from_pretrained(
run_dir,
torch_dtype=torch.bfloat16,
use_habana=True,
use_hpu_graphs=True,
gaudi_config=GaudiConfig(use_habana_mixed_precision=False),
sdp_on_bf16=True,
)
prompt = "A <cat-toy> backpack"
set_seed(27)
image = pipe(prompt, num_inference_steps=50, guidance_scale=7.5, output_type="np").images[0]
self.assertEqual(image.shape, (512, 512, 3))
class GaudiStableDiffusionXLPipelineTester(TestCase):
"""
Tests the StableDiffusionXLPipeline for Gaudi.
"""
def get_dummy_components(self, time_cond_proj_dim=None, timestep_spacing="leading"):
torch.manual_seed(0)
unet = UNet2DConditionModel(
block_out_channels=(2, 4),
layers_per_block=2,
time_cond_proj_dim=time_cond_proj_dim,
sample_size=32,
in_channels=4,
out_channels=4,
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
# SD2-specific config below
attention_head_dim=(2, 4),
use_linear_projection=True,
addition_embed_type="text_time",
addition_time_embed_dim=8,
transformer_layers_per_block=(1, 2),
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
cross_attention_dim=64,
norm_num_groups=1,
)
scheduler = GaudiEulerDiscreteScheduler(
beta_start=0.00085,
beta_end=0.012,
steps_offset=1,
beta_schedule="scaled_linear",
timestep_spacing=timestep_spacing,
)
torch.manual_seed(0)
vae = AutoencoderKL(
block_out_channels=[32, 64],
in_channels=3,
out_channels=3,
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
latent_channels=4,
sample_size=128,
)
torch.manual_seed(0)
text_encoder_config = CLIPTextConfig(
bos_token_id=0,
eos_token_id=2,
hidden_size=32,
intermediate_size=37,
layer_norm_eps=1e-05,
num_attention_heads=4,
num_hidden_layers=5,
pad_token_id=1,
vocab_size=1000,
# SD2-specific config below
hidden_act="gelu",
projection_dim=32,
)
text_encoder = CLIPTextModel(text_encoder_config)
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
components = {
"unet": unet,
"scheduler": scheduler,
"vae": vae,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"text_encoder_2": text_encoder_2,
"tokenizer_2": tokenizer_2,
"image_encoder": None,
"feature_extractor": None,
}
return components
def get_dummy_inputs(self, device, seed=0):
generator = torch.Generator(device=device).manual_seed(seed)
inputs = {
"prompt": "A painting of a squirrel eating a burger",
"generator": generator,
"num_inference_steps": 2,
"guidance_scale": 5.0,
"output_type": "np",
}
return inputs
def test_stable_diffusion_xl_euler(self):
device = "cpu" # ensure determinism for the device-dependent torch.Generator
components = self.get_dummy_components()
gaudi_config = GaudiConfig(use_torch_autocast=False)
sd_pipe_oh = GaudiStableDiffusionXLPipeline(use_habana=True, gaudi_config=gaudi_config, **components)
sd_pipe_hf = StableDiffusionXLPipeline(**components)
def _get_image_from_pipeline(pipeline, device=device):
pipeline.set_progress_bar_config(disable=None)
inputs = self.get_dummy_inputs(device)
image = pipeline(**inputs).images[0]
self.assertEqual(image.shape, (64, 64, 3))
return image[-3:, -3:, -1]
image_slice_oh = _get_image_from_pipeline(sd_pipe_oh)
image_slice_hf = _get_image_from_pipeline(sd_pipe_hf)
self.assertLess((np.abs(image_slice_oh.flatten() - image_slice_hf.flatten()).max()), 1e-2)
def test_stable_diffusion_xl_euler_ancestral(self):
device = "cpu" # ensure determinism for the device-dependent torch.Generator
components = self.get_dummy_components()
gaudi_config = GaudiConfig(use_torch_autocast=False)
sd_pipe = GaudiStableDiffusionXLPipeline(use_habana=True, gaudi_config=gaudi_config, **components)
sd_pipe.scheduler = GaudiEulerAncestralDiscreteScheduler.from_config(sd_pipe.scheduler.config)
sd_pipe.set_progress_bar_config(disable=None)
inputs = self.get_dummy_inputs(device)
image = sd_pipe(**inputs).images[0]
image_slice = image[-3:, -3:, -1]
self.assertEqual(image.shape, (64, 64, 3))
expected_slice = np.array([0.4539, 0.5119, 0.4521, 0.4395, 0.5495, 0.49344, 0.5761, 0.5147, 0.4943])
self.assertLess(np.abs(image_slice.flatten() - expected_slice).max(), 1e-2)