import_utils.py 32.6 KB
Newer Older
1
# Copyright 2024 The HuggingFace Team. All rights reserved.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#
# 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 utilities: Utilities related to imports and our lazy inits.
"""
Mengqing Cao's avatar
Mengqing Cao committed
17

18
import importlib.util
19
import operator as op
20
21
22
import os
import sys
from collections import OrderedDict
Dhruv Nair's avatar
Dhruv Nair committed
23
24
25
from itertools import chain
from types import ModuleType
from typing import Any, Union
26

Lucain's avatar
Lucain committed
27
from huggingface_hub.utils import is_jinja_available  # noqa: F401
28
from packaging import version
29
from packaging.version import Version, parse
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

from . import logging


# The package importlib_metadata is in a different place, depending on the python version.
if sys.version_info < (3, 8):
    import importlib_metadata
else:
    import importlib.metadata as importlib_metadata


logger = logging.get_logger(__name__)  # pylint: disable=invalid-name

ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}
ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})

USE_TF = os.environ.get("USE_TF", "AUTO").upper()
USE_TORCH = os.environ.get("USE_TORCH", "AUTO").upper()
USE_JAX = os.environ.get("USE_FLAX", "AUTO").upper()
49
USE_SAFETENSORS = os.environ.get("USE_SAFETENSORS", "AUTO").upper()
50
51
DIFFUSERS_SLOW_IMPORT = os.environ.get("DIFFUSERS_SLOW_IMPORT", "FALSE").upper()
DIFFUSERS_SLOW_IMPORT = DIFFUSERS_SLOW_IMPORT in ENV_VARS_TRUE_VALUES
52

53
54
STR_OPERATION_TO_FUNC = {">": op.gt, ">=": op.ge, "==": op.eq, "!=": op.ne, "<=": op.le, "<": op.lt}

55
56
57
58
59
60
61
62
63
64
_torch_version = "N/A"
if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
    _torch_available = importlib.util.find_spec("torch") is not None
    if _torch_available:
        try:
            _torch_version = importlib_metadata.version("torch")
            logger.info(f"PyTorch version {_torch_version} available.")
        except importlib_metadata.PackageNotFoundError:
            _torch_available = False
else:
65
    logger.info("Disabling PyTorch because USE_TORCH is set")
66
67
    _torch_available = False

68
69
70
71
72
73
74
75
_torch_xla_available = importlib.util.find_spec("torch_xla") is not None
if _torch_xla_available:
    try:
        _torch_xla_version = importlib_metadata.version("torch_xla")
        logger.info(f"PyTorch XLA version {_torch_xla_version} available.")
    except ImportError:
        _torch_xla_available = False

Mengqing Cao's avatar
Mengqing Cao committed
76
77
78
79
80
81
82
83
84
# check whether torch_npu is available
_torch_npu_available = importlib.util.find_spec("torch_npu") is not None
if _torch_npu_available:
    try:
        _torch_npu_version = importlib_metadata.version("torch_npu")
        logger.info(f"torch_npu version {_torch_npu_version} available.")
    except ImportError:
        _torch_npu_available = False

85
86
_jax_version = "N/A"
_flax_version = "N/A"
87
88
89
90
91
92
93
94
95
96
97
98
if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
    _flax_available = importlib.util.find_spec("jax") is not None and importlib.util.find_spec("flax") is not None
    if _flax_available:
        try:
            _jax_version = importlib_metadata.version("jax")
            _flax_version = importlib_metadata.version("flax")
            logger.info(f"JAX version {_jax_version}, Flax version {_flax_version} available.")
        except importlib_metadata.PackageNotFoundError:
            _flax_available = False
else:
    _flax_available = False

99
100
101
102
103
104
105
106
107
108
109
if USE_SAFETENSORS in ENV_VARS_TRUE_AND_AUTO_VALUES:
    _safetensors_available = importlib.util.find_spec("safetensors") is not None
    if _safetensors_available:
        try:
            _safetensors_version = importlib_metadata.version("safetensors")
            logger.info(f"Safetensors version {_safetensors_version} available.")
        except importlib_metadata.PackageNotFoundError:
            _safetensors_available = False
else:
    logger.info("Disabling Safetensors because USE_TF is set")
    _safetensors_available = False
110
111
112
113
114
115
116
117

_transformers_available = importlib.util.find_spec("transformers") is not None
try:
    _transformers_version = importlib_metadata.version("transformers")
    logger.debug(f"Successfully imported transformers version {_transformers_version}")
except importlib_metadata.PackageNotFoundError:
    _transformers_available = False

Marc Sun's avatar
Marc Sun committed
118
119
120
121
122
123
124
_hf_hub_available = importlib.util.find_spec("huggingface_hub") is not None
try:
    _hf_hub_version = importlib_metadata.version("huggingface_hub")
    logger.debug(f"Successfully imported huggingface_hub version {_hf_hub_version}")
except importlib_metadata.PackageNotFoundError:
    _hf_hub_available = False

125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140

_inflect_available = importlib.util.find_spec("inflect") is not None
try:
    _inflect_version = importlib_metadata.version("inflect")
    logger.debug(f"Successfully imported inflect version {_inflect_version}")
except importlib_metadata.PackageNotFoundError:
    _inflect_available = False


_unidecode_available = importlib.util.find_spec("unidecode") is not None
try:
    _unidecode_version = importlib_metadata.version("unidecode")
    logger.debug(f"Successfully imported unidecode version {_unidecode_version}")
except importlib_metadata.PackageNotFoundError:
    _unidecode_available = False

141
_onnxruntime_version = "N/A"
142
_onnx_available = importlib.util.find_spec("onnxruntime") is not None
SkyTNT's avatar
SkyTNT committed
143
if _onnx_available:
144
145
146
    candidates = (
        "onnxruntime",
        "onnxruntime-gpu",
147
        "ort_nightly_gpu",
148
149
150
        "onnxruntime-directml",
        "onnxruntime-openvino",
        "ort_nightly_directml",
151
152
        "onnxruntime-rocm",
        "onnxruntime-training",
153
    )
SkyTNT's avatar
SkyTNT committed
154
155
156
157
158
159
160
161
162
163
164
    _onnxruntime_version = None
    # For the metadata, we have to look for both onnxruntime and onnxruntime-gpu
    for pkg in candidates:
        try:
            _onnxruntime_version = importlib_metadata.version(pkg)
            break
        except importlib_metadata.PackageNotFoundError:
            pass
    _onnx_available = _onnxruntime_version is not None
    if _onnx_available:
        logger.debug(f"Successfully imported onnxruntime version {_onnxruntime_version}")
165

166
167
168
# (sayakpaul): importlib.util.find_spec("opencv-python") returns None even when it's installed.
# _opencv_available = importlib.util.find_spec("opencv-python") is not None
try:
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
    candidates = (
        "opencv-python",
        "opencv-contrib-python",
        "opencv-python-headless",
        "opencv-contrib-python-headless",
    )
    _opencv_version = None
    for pkg in candidates:
        try:
            _opencv_version = importlib_metadata.version(pkg)
            break
        except importlib_metadata.PackageNotFoundError:
            pass
    _opencv_available = _opencv_version is not None
    if _opencv_available:
        logger.debug(f"Successfully imported cv2 version {_opencv_version}")
185
186
except importlib_metadata.PackageNotFoundError:
    _opencv_available = False
187

188
189
190
_scipy_available = importlib.util.find_spec("scipy") is not None
try:
    _scipy_version = importlib_metadata.version("scipy")
191
    logger.debug(f"Successfully imported scipy version {_scipy_version}")
192
193
194
except importlib_metadata.PackageNotFoundError:
    _scipy_available = False

195
196
197
198
199
200
201
_librosa_available = importlib.util.find_spec("librosa") is not None
try:
    _librosa_version = importlib_metadata.version("librosa")
    logger.debug(f"Successfully imported librosa version {_librosa_version}")
except importlib_metadata.PackageNotFoundError:
    _librosa_available = False

202
203
204
205
206
207
208
_accelerate_available = importlib.util.find_spec("accelerate") is not None
try:
    _accelerate_version = importlib_metadata.version("accelerate")
    logger.debug(f"Successfully imported accelerate version {_accelerate_version}")
except importlib_metadata.PackageNotFoundError:
    _accelerate_available = False

209
210
211
212
_xformers_available = importlib.util.find_spec("xformers") is not None
try:
    _xformers_version = importlib_metadata.version("xformers")
    if _torch_available:
Dhruv Nair's avatar
Dhruv Nair committed
213
214
215
        _torch_version = importlib_metadata.version("torch")
        if version.Version(_torch_version) < version.Version("1.12"):
            raise ValueError("xformers is installed in your environment and requires PyTorch >= 1.12")
216
217
218
219
220

    logger.debug(f"Successfully imported xformers version {_xformers_version}")
except importlib_metadata.PackageNotFoundError:
    _xformers_available = False

221
222
223
224
225
226
227
_k_diffusion_available = importlib.util.find_spec("k_diffusion") is not None
try:
    _k_diffusion_version = importlib_metadata.version("k_diffusion")
    logger.debug(f"Successfully imported k-diffusion version {_k_diffusion_version}")
except importlib_metadata.PackageNotFoundError:
    _k_diffusion_available = False

228
229
230
231
232
233
234
_note_seq_available = importlib.util.find_spec("note_seq") is not None
try:
    _note_seq_version = importlib_metadata.version("note_seq")
    logger.debug(f"Successfully imported note-seq version {_note_seq_version}")
except importlib_metadata.PackageNotFoundError:
    _note_seq_available = False

235
236
237
_wandb_available = importlib.util.find_spec("wandb") is not None
try:
    _wandb_version = importlib_metadata.version("wandb")
238
    logger.debug(f"Successfully imported wandb version {_wandb_version }")
239
240
241
except importlib_metadata.PackageNotFoundError:
    _wandb_available = False

242

243
244
245
246
247
248
249
_tensorboard_available = importlib.util.find_spec("tensorboard")
try:
    _tensorboard_version = importlib_metadata.version("tensorboard")
    logger.debug(f"Successfully imported tensorboard version {_tensorboard_version}")
except importlib_metadata.PackageNotFoundError:
    _tensorboard_available = False

250

251
252
253
254
255
256
257
258
_compel_available = importlib.util.find_spec("compel")
try:
    _compel_version = importlib_metadata.version("compel")
    logger.debug(f"Successfully imported compel version {_compel_version}")
except importlib_metadata.PackageNotFoundError:
    _compel_available = False


Patrick von Platen's avatar
Patrick von Platen committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
_ftfy_available = importlib.util.find_spec("ftfy") is not None
try:
    _ftfy_version = importlib_metadata.version("ftfy")
    logger.debug(f"Successfully imported ftfy version {_ftfy_version}")
except importlib_metadata.PackageNotFoundError:
    _ftfy_available = False


_bs4_available = importlib.util.find_spec("bs4") is not None
try:
    # importlib metadata under different name
    _bs4_version = importlib_metadata.version("beautifulsoup4")
    logger.debug(f"Successfully imported ftfy version {_bs4_version}")
except importlib_metadata.PackageNotFoundError:
    _bs4_available = False

275
276
277
278
279
280
281
_torchsde_available = importlib.util.find_spec("torchsde") is not None
try:
    _torchsde_version = importlib_metadata.version("torchsde")
    logger.debug(f"Successfully imported torchsde version {_torchsde_version}")
except importlib_metadata.PackageNotFoundError:
    _torchsde_available = False

282
283
284
285
286
287
288
_invisible_watermark_available = importlib.util.find_spec("imwatermark") is not None
try:
    _invisible_watermark_version = importlib_metadata.version("invisible-watermark")
    logger.debug(f"Successfully imported invisible-watermark version {_invisible_watermark_version}")
except importlib_metadata.PackageNotFoundError:
    _invisible_watermark_available = False

Patrick von Platen's avatar
Patrick von Platen committed
289

290
291
292
293
294
295
296
_peft_available = importlib.util.find_spec("peft") is not None
try:
    _peft_version = importlib_metadata.version("peft")
    logger.debug(f"Successfully imported peft version {_peft_version}")
except importlib_metadata.PackageNotFoundError:
    _peft_available = False

YiYi Xu's avatar
YiYi Xu committed
297
298
299
300
301
302
303
_torchvision_available = importlib.util.find_spec("torchvision") is not None
try:
    _torchvision_version = importlib_metadata.version("torchvision")
    logger.debug(f"Successfully imported torchvision version {_torchvision_version}")
except importlib_metadata.PackageNotFoundError:
    _torchvision_available = False

304
305
306
307
308
309
310
_sentencepiece_available = importlib.util.find_spec("sentencepiece") is not None
try:
    _sentencepiece_version = importlib_metadata.version("sentencepiece")
    logger.info(f"Successfully imported sentencepiece version {_sentencepiece_version}")
except importlib_metadata.PackageNotFoundError:
    _sentencepiece_available = False

311
312
313
314
315
316
317
_matplotlib_available = importlib.util.find_spec("matplotlib") is not None
try:
    _matplotlib_version = importlib_metadata.version("matplotlib")
    logger.debug(f"Successfully imported matplotlib version {_matplotlib_version}")
except importlib_metadata.PackageNotFoundError:
    _matplotlib_available = False

318
319
320
321
322
323
324
325
326
327
328
329
330
_timm_available = importlib.util.find_spec("timm") is not None
if _timm_available:
    try:
        _timm_version = importlib_metadata.version("timm")
        logger.info(f"Timm version {_timm_version} available.")
    except importlib_metadata.PackageNotFoundError:
        _timm_available = False


def is_timm_available():
    return _timm_available


331
332
333
334
335
336
337
_bitsandbytes_available = importlib.util.find_spec("bitsandbytes") is not None
try:
    _bitsandbytes_version = importlib_metadata.version("bitsandbytes")
    logger.debug(f"Successfully imported bitsandbytes version {_bitsandbytes_version}")
except importlib_metadata.PackageNotFoundError:
    _bitsandbytes_available = False

338
_is_google_colab = "google.colab" in sys.modules or any(k.startswith("COLAB_") for k in os.environ)
339

340
341
342
343
344
345
346
347
348
_imageio_available = importlib.util.find_spec("imageio") is not None
if _imageio_available:
    try:
        _imageio_version = importlib_metadata.version("imageio")
        logger.debug(f"Successfully imported imageio version {_imageio_version}")

    except importlib_metadata.PackageNotFoundError:
        _imageio_available = False

349
350
351
352
353
354
355
356
_is_gguf_available = importlib.util.find_spec("gguf") is not None
if _is_gguf_available:
    try:
        _gguf_version = importlib_metadata.version("gguf")
        logger.debug(f"Successfully import gguf version {_gguf_version}")
    except importlib_metadata.PackageNotFoundError:
        _is_gguf_available = False

357

Aryan's avatar
Aryan committed
358
359
360
361
362
363
364
365
366
_is_torchao_available = importlib.util.find_spec("torchao") is not None
if _is_torchao_available:
    try:
        _torchao_version = importlib_metadata.version("torchao")
        logger.debug(f"Successfully import torchao version {_torchao_version}")
    except importlib_metadata.PackageNotFoundError:
        _is_torchao_available = False


367
368
369
370
def is_torch_available():
    return _torch_available


371
372
373
374
def is_torch_xla_available():
    return _torch_xla_available


Mengqing Cao's avatar
Mengqing Cao committed
375
376
377
378
def is_torch_npu_available():
    return _torch_npu_available


379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def is_flax_available():
    return _flax_available


def is_transformers_available():
    return _transformers_available


def is_inflect_available():
    return _inflect_available


def is_unidecode_available():
    return _unidecode_available


395
396
397
398
def is_onnx_available():
    return _onnx_available


399
400
401
402
def is_opencv_available():
    return _opencv_available


403
404
405
406
def is_scipy_available():
    return _scipy_available


407
408
409
410
def is_librosa_available():
    return _librosa_available


411
412
413
414
def is_xformers_available():
    return _xformers_available


415
416
417
418
def is_accelerate_available():
    return _accelerate_available


419
420
421
422
def is_k_diffusion_available():
    return _k_diffusion_available


423
424
425
426
def is_note_seq_available():
    return _note_seq_available


427
428
429
430
def is_wandb_available():
    return _wandb_available


431
432
433
434
def is_tensorboard_available():
    return _tensorboard_available


435
436
437
438
def is_compel_available():
    return _compel_available


Patrick von Platen's avatar
Patrick von Platen committed
439
440
441
442
443
444
445
446
def is_ftfy_available():
    return _ftfy_available


def is_bs4_available():
    return _bs4_available


447
448
449
450
def is_torchsde_available():
    return _torchsde_available


451
452
453
454
def is_invisible_watermark_available():
    return _invisible_watermark_available


455
456
457
458
def is_peft_available():
    return _peft_available


YiYi Xu's avatar
YiYi Xu committed
459
460
461
462
def is_torchvision_available():
    return _torchvision_available


463
464
465
466
def is_matplotlib_available():
    return _matplotlib_available


467
468
469
470
471
472
473
474
475
476
477
478
def is_safetensors_available():
    return _safetensors_available


def is_bitsandbytes_available():
    return _bitsandbytes_available


def is_google_colab():
    return _is_google_colab


479
480
481
482
def is_sentencepiece_available():
    return _sentencepiece_available


483
484
485
486
def is_imageio_available():
    return _imageio_available


487
488
489
490
def is_gguf_available():
    return _is_gguf_available


Aryan's avatar
Aryan committed
491
492
493
494
def is_torchao_available():
    return _is_torchao_available


495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# docstyle-ignore
FLAX_IMPORT_ERROR = """
{0} requires the FLAX library but it was not found in your environment. Checkout the instructions on the
installation page: https://github.com/google/flax and follow the ones that match your environment.
"""

# docstyle-ignore
INFLECT_IMPORT_ERROR = """
{0} requires the inflect library but it was not found in your environment. You can install it with pip: `pip install
inflect`
"""

# docstyle-ignore
PYTORCH_IMPORT_ERROR = """
{0} requires the PyTorch library but it was not found in your environment. Checkout the instructions on the
installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment.
"""

513
514
515
516
517
518
# docstyle-ignore
ONNX_IMPORT_ERROR = """
{0} requires the onnxruntime library but it was not found in your environment. You can install it with pip: `pip
install onnxruntime`
"""

519
520
521
522
523
524
# docstyle-ignore
OPENCV_IMPORT_ERROR = """
{0} requires the OpenCV library but it was not found in your environment. You can install it with pip: `pip
install opencv-python`
"""

525
526
527
528
529
530
# docstyle-ignore
SCIPY_IMPORT_ERROR = """
{0} requires the scipy library but it was not found in your environment. You can install it with pip: `pip install
scipy`
"""

531
532
533
534
535
536
# docstyle-ignore
LIBROSA_IMPORT_ERROR = """
{0} requires the librosa library but it was not found in your environment.  Checkout the instructions on the
installation page: https://librosa.org/doc/latest/install.html and follow the ones that match your environment.
"""

537
538
539
540
541
542
543
544
545
546
547
548
# docstyle-ignore
TRANSFORMERS_IMPORT_ERROR = """
{0} requires the transformers library but it was not found in your environment. You can install it with pip: `pip
install transformers`
"""

# docstyle-ignore
UNIDECODE_IMPORT_ERROR = """
{0} requires the unidecode library but it was not found in your environment. You can install it with pip: `pip install
Unidecode`
"""

549
550
551
552
553
554
# docstyle-ignore
K_DIFFUSION_IMPORT_ERROR = """
{0} requires the k-diffusion library but it was not found in your environment. You can install it with pip: `pip
install k-diffusion`
"""

555
556
557
558
559
560
# docstyle-ignore
NOTE_SEQ_IMPORT_ERROR = """
{0} requires the note-seq library but it was not found in your environment. You can install it with pip: `pip
install note-seq`
"""

561
562
563
564
565
566
# docstyle-ignore
WANDB_IMPORT_ERROR = """
{0} requires the wandb library but it was not found in your environment. You can install it with pip: `pip
install wandb`
"""

567
568
569
570
571
572
# docstyle-ignore
TENSORBOARD_IMPORT_ERROR = """
{0} requires the tensorboard library but it was not found in your environment. You can install it with pip: `pip
install tensorboard`
"""

573
574
575
576
577
578

# docstyle-ignore
COMPEL_IMPORT_ERROR = """
{0} requires the compel library but it was not found in your environment. You can install it with pip: `pip install compel`
"""

Patrick von Platen's avatar
Patrick von Platen committed
579
580
581
582
583
584
585
586
587
588
589
590
591
# docstyle-ignore
BS4_IMPORT_ERROR = """
{0} requires the Beautiful Soup library but it was not found in your environment. You can install it with pip:
`pip install beautifulsoup4`. Please note that you may need to restart your runtime after installation.
"""

# docstyle-ignore
FTFY_IMPORT_ERROR = """
{0} requires the ftfy library but it was not found in your environment. Checkout the instructions on the
installation section: https://github.com/rspeer/python-ftfy/tree/master#installing and follow the ones
that match your environment. Please note that you may need to restart your runtime after installation.
"""

592
593
594
595
596
# docstyle-ignore
TORCHSDE_IMPORT_ERROR = """
{0} requires the torchsde library but it was not found in your environment. You can install it with pip: `pip install torchsde`
"""

597
598
# docstyle-ignore
INVISIBLE_WATERMARK_IMPORT_ERROR = """
599
{0} requires the invisible-watermark library but it was not found in your environment. You can install it with pip: `pip install invisible-watermark>=0.2.0`
600
601
"""

602
603
604
605
606
607
608
609
610
611
# docstyle-ignore
PEFT_IMPORT_ERROR = """
{0} requires the peft library but it was not found in your environment. You can install it with pip: `pip install peft`
"""

# docstyle-ignore
SAFETENSORS_IMPORT_ERROR = """
{0} requires the safetensors library but it was not found in your environment. You can install it with pip: `pip install safetensors`
"""

612
613
614
615
616
617
# docstyle-ignore
SENTENCEPIECE_IMPORT_ERROR = """
{0} requires the sentencepiece library but it was not found in your environment. You can install it with pip: `pip install sentencepiece`
"""


618
619
620
621
# docstyle-ignore
BITSANDBYTES_IMPORT_ERROR = """
{0} requires the bitsandbytes library but it was not found in your environment. You can install it with pip: `pip install bitsandbytes`
"""
Patrick von Platen's avatar
Patrick von Platen committed
622

623
624
625
626
627
# docstyle-ignore
IMAGEIO_IMPORT_ERROR = """
{0} requires the imageio library and ffmpeg but it was not found in your environment. You can install it with pip: `pip install imageio imageio-ffmpeg`
"""

Aryan's avatar
Aryan committed
628
# docstyle-ignore
629
630
631
632
GGUF_IMPORT_ERROR = """
{0} requires the gguf library but it was not found in your environment. You can install it with pip: `pip install gguf`
"""

Aryan's avatar
Aryan committed
633
TORCHAO_IMPORT_ERROR = """
634
635
{0} requires the torchao library but it was not found in your environment. You can install it with pip: `pip install
torchao`
Aryan's avatar
Aryan committed
636
637
"""

638
639
BACKENDS_MAPPING = OrderedDict(
    [
Patrick von Platen's avatar
Patrick von Platen committed
640
        ("bs4", (is_bs4_available, BS4_IMPORT_ERROR)),
641
642
        ("flax", (is_flax_available, FLAX_IMPORT_ERROR)),
        ("inflect", (is_inflect_available, INFLECT_IMPORT_ERROR)),
643
        ("onnx", (is_onnx_available, ONNX_IMPORT_ERROR)),
644
        ("opencv", (is_opencv_available, OPENCV_IMPORT_ERROR)),
645
646
647
648
        ("scipy", (is_scipy_available, SCIPY_IMPORT_ERROR)),
        ("torch", (is_torch_available, PYTORCH_IMPORT_ERROR)),
        ("transformers", (is_transformers_available, TRANSFORMERS_IMPORT_ERROR)),
        ("unidecode", (is_unidecode_available, UNIDECODE_IMPORT_ERROR)),
649
        ("librosa", (is_librosa_available, LIBROSA_IMPORT_ERROR)),
650
        ("k_diffusion", (is_k_diffusion_available, K_DIFFUSION_IMPORT_ERROR)),
651
        ("note_seq", (is_note_seq_available, NOTE_SEQ_IMPORT_ERROR)),
652
        ("wandb", (is_wandb_available, WANDB_IMPORT_ERROR)),
653
654
        ("tensorboard", (is_tensorboard_available, TENSORBOARD_IMPORT_ERROR)),
        ("compel", (is_compel_available, COMPEL_IMPORT_ERROR)),
Patrick von Platen's avatar
Patrick von Platen committed
655
        ("ftfy", (is_ftfy_available, FTFY_IMPORT_ERROR)),
656
657
        ("torchsde", (is_torchsde_available, TORCHSDE_IMPORT_ERROR)),
        ("invisible_watermark", (is_invisible_watermark_available, INVISIBLE_WATERMARK_IMPORT_ERROR)),
658
659
660
        ("peft", (is_peft_available, PEFT_IMPORT_ERROR)),
        ("safetensors", (is_safetensors_available, SAFETENSORS_IMPORT_ERROR)),
        ("bitsandbytes", (is_bitsandbytes_available, BITSANDBYTES_IMPORT_ERROR)),
661
        ("sentencepiece", (is_sentencepiece_available, SENTENCEPIECE_IMPORT_ERROR)),
662
        ("imageio", (is_imageio_available, IMAGEIO_IMPORT_ERROR)),
663
        ("gguf", (is_gguf_available, GGUF_IMPORT_ERROR)),
Aryan's avatar
Aryan committed
664
        ("torchao", (is_torchao_available, TORCHAO_IMPORT_ERROR)),
665
666
667
668
669
670
671
672
673
674
675
676
677
678
    ]
)


def requires_backends(obj, backends):
    if not isinstance(backends, (list, tuple)):
        backends = [backends]

    name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
    checks = (BACKENDS_MAPPING[backend] for backend in backends)
    failed = [msg.format(name) for available, msg in checks if not available()]
    if failed:
        raise ImportError("".join(failed))

679
680
681
682
683
    if name in [
        "VersatileDiffusionTextToImagePipeline",
        "VersatileDiffusionPipeline",
        "VersatileDiffusionDualGuidedPipeline",
        "StableDiffusionImageVariationPipeline",
684
        "UnCLIPPipeline",
685
686
687
688
689
690
    ] and is_transformers_version("<", "4.25.0"):
        raise ImportError(
            f"You need to install `transformers>=4.25` in order to use {name}: \n```\n pip install"
            " --upgrade transformers \n```"
        )

691
692
693
    if name in ["StableDiffusionDepth2ImgPipeline", "StableDiffusionPix2PixZeroPipeline"] and is_transformers_version(
        "<", "4.26.0"
    ):
694
        raise ImportError(
695
696
            f"You need to install `transformers>=4.26` in order to use {name}: \n```\n pip install"
            " --upgrade transformers \n```"
697
698
        )

699
700
701
702
703
704
705
706

class DummyObject(type):
    """
    Metaclass for the dummy objects. Any class inheriting from it will return the ImportError generated by
    `requires_backend` each time a user tries to access any method of that class.
    """

    def __getattr__(cls, key):
707
        if key.startswith("_") and key not in ["_load_connected_pipes", "_is_onnx"]:
708
709
            return super().__getattr__(cls, key)
        requires_backends(cls, cls._backends)
710
711
712
713
714
715


# This function was copied from: https://github.com/huggingface/accelerate/blob/874c4967d94badd24f893064cc3bef45f57cadf7/src/accelerate/utils/versions.py#L319
def compare_versions(library_or_version: Union[str, Version], operation: str, requirement_version: str):
    """
    Compares a library version to some requirement using a given operation.
716
717

    Args:
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
        library_or_version (`str` or `packaging.version.Version`):
            A library name or a version to check.
        operation (`str`):
            A string representation of an operator, such as `">"` or `"<="`.
        requirement_version (`str`):
            The version to compare the library version against
    """
    if operation not in STR_OPERATION_TO_FUNC.keys():
        raise ValueError(f"`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys())}, received {operation}")
    operation = STR_OPERATION_TO_FUNC[operation]
    if isinstance(library_or_version, str):
        library_or_version = parse(importlib_metadata.version(library_or_version))
    return operation(library_or_version, parse(requirement_version))


# This function was copied from: https://github.com/huggingface/accelerate/blob/874c4967d94badd24f893064cc3bef45f57cadf7/src/accelerate/utils/versions.py#L338
def is_torch_version(operation: str, version: str):
    """
    Compares the current PyTorch version to a given reference with an operation.
737
738

    Args:
739
740
741
742
743
744
        operation (`str`):
            A string representation of an operator, such as `">"` or `"<="`
        version (`str`):
            A string version of PyTorch
    """
    return compare_versions(parse(_torch_version), operation, version)
745
746


Juan Acevedo's avatar
Juan Acevedo committed
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
def is_torch_xla_version(operation: str, version: str):
    """
    Compares the current torch_xla version to a given reference with an operation.

    Args:
        operation (`str`):
            A string representation of an operator, such as `">"` or `"<="`
        version (`str`):
            A string version of torch_xla
    """
    if not is_torch_xla_available:
        return False
    return compare_versions(parse(_torch_xla_version), operation, version)


762
763
764
def is_transformers_version(operation: str, version: str):
    """
    Compares the current Transformers version to a given reference with an operation.
765
766

    Args:
767
768
769
        operation (`str`):
            A string representation of an operator, such as `">"` or `"<="`
        version (`str`):
770
            A version string
771
772
773
774
    """
    if not _transformers_available:
        return False
    return compare_versions(parse(_transformers_version), operation, version)
775
776


Marc Sun's avatar
Marc Sun committed
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
def is_hf_hub_version(operation: str, version: str):
    """
    Compares the current Hugging Face Hub version to a given reference with an operation.

    Args:
        operation (`str`):
            A string representation of an operator, such as `">"` or `"<="`
        version (`str`):
            A version string
    """
    if not _hf_hub_available:
        return False
    return compare_versions(parse(_hf_hub_version), operation, version)


792
793
794
def is_accelerate_version(operation: str, version: str):
    """
    Compares the current Accelerate version to a given reference with an operation.
795
796

    Args:
797
798
799
800
801
802
803
804
805
806
        operation (`str`):
            A string representation of an operator, such as `">"` or `"<="`
        version (`str`):
            A version string
    """
    if not _accelerate_available:
        return False
    return compare_versions(parse(_accelerate_version), operation, version)


807
808
809
def is_peft_version(operation: str, version: str):
    """
    Compares the current PEFT version to a given reference with an operation.
810
811

    Args:
812
813
814
815
816
817
818
819
820
821
        operation (`str`):
            A string representation of an operator, such as `">"` or `"<="`
        version (`str`):
            A version string
    """
    if not _peft_version:
        return False
    return compare_versions(parse(_peft_version), operation, version)


822
823
824
825
826
827
828
829
830
831
832
833
834
835
def is_bitsandbytes_version(operation: str, version: str):
    """
    Args:
    Compares the current bitsandbytes version to a given reference with an operation.
        operation (`str`):
            A string representation of an operator, such as `">"` or `"<="`
        version (`str`):
            A version string
    """
    if not _bitsandbytes_version:
        return False
    return compare_versions(parse(_bitsandbytes_version), operation, version)


836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
def is_gguf_version(operation: str, version: str):
    """
    Compares the current Accelerate version to a given reference with an operation.

    Args:
        operation (`str`):
            A string representation of an operator, such as `">"` or `"<="`
        version (`str`):
            A version string
    """
    if not _is_gguf_available:
        return False
    return compare_versions(parse(_gguf_version), operation, version)


851
852
853
def is_k_diffusion_version(operation: str, version: str):
    """
    Compares the current k-diffusion version to a given reference with an operation.
854
855

    Args:
856
857
858
859
860
861
862
863
864
865
        operation (`str`):
            A string representation of an operator, such as `">"` or `"<="`
        version (`str`):
            A version string
    """
    if not _k_diffusion_available:
        return False
    return compare_versions(parse(_k_diffusion_version), operation, version)


Dhruv Nair's avatar
Dhruv Nair committed
866
867
868
def get_objects_from_module(module):
    """
    Returns a dict of object names and values in a module, while skipping private/internal objects
869
870

    Args:
Dhruv Nair's avatar
Dhruv Nair committed
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
        module (ModuleType):
            Module to extract the objects from.

    Returns:
        dict: Dictionary of object names and corresponding values
    """

    objects = {}
    for name in dir(module):
        if name.startswith("_"):
            continue
        objects[name] = getattr(module, name)

    return objects


887
class OptionalDependencyNotAvailable(BaseException):
888
889
890
    """
    An error indicating that an optional dependency of Diffusers was not found in the environment.
    """
Dhruv Nair's avatar
Dhruv Nair committed
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


class _LazyModule(ModuleType):
    """
    Module class that surfaces all objects but only performs associated imports when the objects are requested.
    """

    # Very heavily inspired by optuna.integration._IntegrationModule
    # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py
    def __init__(self, name, module_file, import_structure, module_spec=None, extra_objects=None):
        super().__init__(name)
        self._modules = set(import_structure.keys())
        self._class_to_module = {}
        for key, values in import_structure.items():
            for value in values:
                self._class_to_module[value] = key
        # Needed for autocompletion in an IDE
        self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values()))
        self.__file__ = module_file
        self.__spec__ = module_spec
        self.__path__ = [os.path.dirname(module_file)]
        self._objects = {} if extra_objects is None else extra_objects
        self._name = name
        self._import_structure = import_structure

    # Needed for autocompletion in an IDE
    def __dir__(self):
        result = super().__dir__()
        # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether
        # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir.
        for attr in self.__all__:
            if attr not in result:
                result.append(attr)
        return result

    def __getattr__(self, name: str) -> Any:
        if name in self._objects:
            return self._objects[name]
        if name in self._modules:
            value = self._get_module(name)
        elif name in self._class_to_module.keys():
            module = self._get_module(self._class_to_module[name])
            value = getattr(module, name)
        else:
            raise AttributeError(f"module {self.__name__} has no attribute {name}")

        setattr(self, name, value)
        return value

    def _get_module(self, module_name: str):
        try:
            return importlib.import_module("." + module_name, self.__name__)
        except Exception as e:
            raise RuntimeError(
                f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
                f" traceback):\n{e}"
            ) from e

    def __reduce__(self):
        return (self.__class__, (self._name, self.__file__, self._import_structure))