import_utils.py 48.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Copyright 2022 The HuggingFace Team. 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 utilities: Utilities related to imports and our lazy inits.
"""

18
import importlib.metadata
19
20
21
import importlib.util
import json
import os
22
import shutil
玩火's avatar
玩火 committed
23
import subprocess
24
import sys
25
import warnings
26
from collections import OrderedDict
Yih-Dar's avatar
Yih-Dar committed
27
from functools import lru_cache, wraps
28
29
from itertools import chain
from types import ModuleType
30
from typing import Any, Tuple, Union
31
32
33
34
35
36
37
38

from packaging import version

from . import logging


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

39

Yih-Dar's avatar
Yih-Dar committed
40
# TODO: This doesn't work for all packages (`bs4`, `faiss`, etc.) Talk to Sylvain to see how to do with it better.
41
42
43
44
45
46
def _is_package_available(pkg_name: str, return_version: bool = False) -> Union[Tuple[bool, str], bool]:
    # Check we're not importing a "pkg_name" directory somewhere but the actual library by trying to grab the version
    package_exists = importlib.util.find_spec(pkg_name) is not None
    package_version = "N/A"
    if package_exists:
        try:
47
            package_version = importlib.metadata.version(pkg_name)
48
            package_exists = True
49
        except importlib.metadata.PackageNotFoundError:
50
51
52
53
54
55
56
57
            package_exists = False
        logger.debug(f"Detected {pkg_name} version {package_version}")
    if return_version:
        return package_exists, package_version
    else:
        return package_exists


58
59
60
61
62
63
64
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()

65
66
FORCE_TF_AVAILABLE = os.environ.get("FORCE_TF_AVAILABLE", "AUTO").upper()

67
68
69
# This is the version of torch required to run torch.fx features and torch.onnx with dictionary inputs.
TORCH_FX_REQUIRED_VERSION = version.parse("1.10")

NielsRogge's avatar
NielsRogge committed
70
71
72
ACCELERATE_MIN_VERSION = "0.21.0"
FSDP_MIN_VERSION = "1.12.0"

73
74
75
76

_accelerate_available, _accelerate_version = _is_package_available("accelerate", return_version=True)
_apex_available = _is_package_available("apex")
_bitsandbytes_available = _is_package_available("bitsandbytes")
77
# `importlib.metadata.version` doesn't work with `bs4` but `beautifulsoup4`. For `importlib.util.find_spec`, reversed.
Yih-Dar's avatar
Yih-Dar committed
78
_bs4_available = importlib.util.find_spec("bs4") is not None
79
_coloredlogs_available = _is_package_available("coloredlogs")
NielsRogge's avatar
NielsRogge committed
80
81
# `importlib.metadata.util` doesn't work with `opencv-python-headless`.
_cv2_available = importlib.util.find_spec("cv2") is not None
82
83
84
_datasets_available = _is_package_available("datasets")
_decord_available = importlib.util.find_spec("decord") is not None
_detectron2_available = _is_package_available("detectron2")
Yih-Dar's avatar
Yih-Dar committed
85
86
87
# We need to check both `faiss` and `faiss-cpu`.
_faiss_available = importlib.util.find_spec("faiss") is not None
try:
88
    _faiss_version = importlib.metadata.version("faiss")
Yih-Dar's avatar
Yih-Dar committed
89
    logger.debug(f"Successfully imported faiss version {_faiss_version}")
90
except importlib.metadata.PackageNotFoundError:
Yih-Dar's avatar
Yih-Dar committed
91
    try:
92
        _faiss_version = importlib.metadata.version("faiss-cpu")
Yih-Dar's avatar
Yih-Dar committed
93
        logger.debug(f"Successfully imported faiss version {_faiss_version}")
94
    except importlib.metadata.PackageNotFoundError:
Yih-Dar's avatar
Yih-Dar committed
95
        _faiss_available = False
96
_ftfy_available = _is_package_available("ftfy")
97
_g2p_en_available = _is_package_available("g2p_en")
98
99
_ipex_available, _ipex_version = _is_package_available("intel_extension_for_pytorch", return_version=True)
_jieba_available = _is_package_available("jieba")
100
_jinja_available = _is_package_available("jinja2")
101
102
_kenlm_available = _is_package_available("kenlm")
_keras_nlp_available = _is_package_available("keras_nlp")
NielsRogge's avatar
NielsRogge committed
103
_levenshtein_available = _is_package_available("Levenshtein")
104
105
_librosa_available = _is_package_available("librosa")
_natten_available = _is_package_available("natten")
NielsRogge's avatar
NielsRogge committed
106
_nltk_available = _is_package_available("nltk")
107
108
109
_onnx_available = _is_package_available("onnx")
_openai_available = _is_package_available("openai")
_optimum_available = _is_package_available("optimum")
Marc Sun's avatar
Marc Sun committed
110
_auto_gptq_available = _is_package_available("auto_gptq")
111
112
# `importlib.metadata.version` doesn't work with `awq`
_auto_awq_available = importlib.util.find_spec("awq") is not None
113
114
115
116
117
118
119
_pandas_available = _is_package_available("pandas")
_peft_available = _is_package_available("peft")
_phonemizer_available = _is_package_available("phonemizer")
_psutil_available = _is_package_available("psutil")
_py3nvml_available = _is_package_available("py3nvml")
_pyctcdecode_available = _is_package_available("pyctcdecode")
_pytesseract_available = _is_package_available("pytesseract")
120
_pytest_available = _is_package_available("pytest")
121
122
123
124
125
126
_pytorch_quantization_available = _is_package_available("pytorch_quantization")
_rjieba_available = _is_package_available("rjieba")
_sacremoses_available = _is_package_available("sacremoses")
_safetensors_available = _is_package_available("safetensors")
_scipy_available = _is_package_available("scipy")
_sentencepiece_available = _is_package_available("sentencepiece")
127
_is_seqio_available = _is_package_available("seqio")
128
129
130
_sklearn_available = importlib.util.find_spec("sklearn") is not None
if _sklearn_available:
    try:
131
132
        importlib.metadata.version("scikit-learn")
    except importlib.metadata.PackageNotFoundError:
133
        _sklearn_available = False
134
_smdistributed_available = importlib.util.find_spec("smdistributed") is not None
135
136
137
138
139
140
141
142
143
144
145
146
147
_soundfile_available = _is_package_available("soundfile")
_spacy_available = _is_package_available("spacy")
_sudachipy_available = _is_package_available("sudachipy")
_tensorflow_probability_available = _is_package_available("tensorflow_probability")
_tensorflow_text_available = _is_package_available("tensorflow_text")
_tf2onnx_available = _is_package_available("tf2onnx")
_timm_available = _is_package_available("timm")
_tokenizers_available = _is_package_available("tokenizers")
_torchaudio_available = _is_package_available("torchaudio")
_torchdistx_available = _is_package_available("torchdistx")
_torchvision_available = _is_package_available("torchvision")


148
_torch_version = "N/A"
149
_torch_available = False
150
if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
151
    _torch_available, _torch_version = _is_package_available("torch", return_version=True)
152
153
154
155
156
157
else:
    logger.info("Disabling PyTorch because USE_TF is set")
    _torch_available = False


_tf_version = "N/A"
158
_tf_available = False
159
160
if FORCE_TF_AVAILABLE in ENV_VARS_TRUE_VALUES:
    _tf_available = True
161
else:
162
    if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
163
164
165
        # Note: _is_package_available("tensorflow") fails for tensorflow-cpu. Please test any changes to the line below
        # with tensorflow-cpu to make sure it still works!
        _tf_available = importlib.util.find_spec("tensorflow") is not None
166
167
168
169
170
171
172
173
        if _tf_available:
            candidates = (
                "tensorflow",
                "tensorflow-cpu",
                "tensorflow-gpu",
                "tf-nightly",
                "tf-nightly-cpu",
                "tf-nightly-gpu",
174
                "tf-nightly-rocm",
175
176
177
178
179
180
181
182
183
184
                "intel-tensorflow",
                "intel-tensorflow-avx512",
                "tensorflow-rocm",
                "tensorflow-macos",
                "tensorflow-aarch64",
            )
            _tf_version = None
            # For the metadata, we have to look for both tensorflow and tensorflow-cpu
            for pkg in candidates:
                try:
185
                    _tf_version = importlib.metadata.version(pkg)
186
                    break
187
                except importlib.metadata.PackageNotFoundError:
188
189
190
191
192
193
194
195
196
197
                    pass
            _tf_available = _tf_version is not None
        if _tf_available:
            if version.parse(_tf_version) < version.parse("2"):
                logger.info(
                    f"TensorFlow found but with version {_tf_version}. Transformers requires version 2 minimum."
                )
                _tf_available = False
    else:
        logger.info("Disabling Tensorflow because USE_TORCH is set")
198
199


Susnato Dhar's avatar
Susnato Dhar committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
_essentia_available = importlib.util.find_spec("essentia") is not None
try:
    _essentia_version = importlib.metadata.version("essentia")
    logger.debug(f"Successfully imported essentia version {_essentia_version}")
except importlib.metadata.PackageNotFoundError:
    _essentia_version = False


_pretty_midi_available = importlib.util.find_spec("pretty_midi") is not None
try:
    _pretty_midi_version = importlib.metadata.version("pretty_midi")
    logger.debug(f"Successfully imported pretty_midi version {_pretty_midi_version}")
except importlib.metadata.PackageNotFoundError:
    _pretty_midi_available = False


216
217
218
219
220
221
ccl_version = "N/A"
_is_ccl_available = (
    importlib.util.find_spec("torch_ccl") is not None
    or importlib.util.find_spec("oneccl_bindings_for_pytorch") is not None
)
try:
222
    ccl_version = importlib.metadata.version("oneccl_bind_pt")
223
    logger.debug(f"Detected oneccl_bind_pt version {ccl_version}")
224
except importlib.metadata.PackageNotFoundError:
225
    _is_ccl_available = False
226

227

228
229
230
231
232
233
234
235
236
237
_flax_available = False
if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
    _flax_available, _flax_version = _is_package_available("flax", return_version=True)
    if _flax_available:
        _jax_available, _jax_version = _is_package_available("jax", return_version=True)
        if _jax_available:
            logger.info(f"JAX version {_jax_version}, Flax version {_flax_version} available.")
        else:
            _flax_available = _jax_available = False
            _jax_version = _flax_version = "N/A"
238

239
240
241
242
243
244
245
246

_torch_fx_available = False
if _torch_available:
    torch_version = version.parse(_torch_version)
    _torch_fx_available = (torch_version.major, torch_version.minor) >= (
        TORCH_FX_REQUIRED_VERSION.major,
        TORCH_FX_REQUIRED_VERSION.minor,
    )
247
248


249
def is_kenlm_available():
250
    return _kenlm_available
251
252


NielsRogge's avatar
NielsRogge committed
253
254
255
256
def is_cv2_available():
    return _cv2_available


257
258
259
260
def is_torch_available():
    return _torch_available


261
262
263
264
def get_torch_version():
    return _torch_version


265
266
267
268
269
270
271
272
273
274
275
276
277
def is_torch_sdpa_available():
    if not is_torch_available():
        return False
    elif _torch_version == "N/A":
        return False

    # NOTE: We require torch>=2.1 (and not torch>=2.0) to use SDPA in Transformers for two reasons:
    # - Allow the global use of the `scale` argument introduced in https://github.com/pytorch/pytorch/pull/95259
    # - Memory-efficient attention supports arbitrary attention_mask: https://github.com/pytorch/pytorch/pull/104310
    # NOTE: We require torch>=2.1.1 to avoid a numerical issue in SDPA with non-contiguous inputs: https://github.com/pytorch/pytorch/issues/112577
    return version.parse(_torch_version) >= version.parse("2.1.1")


NielsRogge's avatar
NielsRogge committed
278
def is_torchvision_available():
279
    return _torchvision_available
NielsRogge's avatar
NielsRogge committed
280
281


282
283
284
285
286
287
288
289
def is_pyctcdecode_available():
    return _pyctcdecode_available


def is_librosa_available():
    return _librosa_available


Susnato Dhar's avatar
Susnato Dhar committed
290
291
292
293
294
295
296
297
def is_essentia_available():
    return _essentia_available


def is_pretty_midi_available():
    return _pretty_midi_available


298
299
300
301
302
303
304
305
306
def is_torch_cuda_available():
    if is_torch_available():
        import torch

        return torch.cuda.is_available()
    else:
        return False


307
308
309
310
311
312
313
314
315
def is_torch_mps_available():
    if is_torch_available():
        import torch

        if hasattr(torch.backends, "mps"):
            return torch.backends.mps.is_available()
    return False


316
def is_torch_bf16_gpu_available():
317
318
319
320
321
    if not is_torch_available():
        return False

    import torch

Roohollah Etemadi's avatar
Roohollah Etemadi committed
322
    return torch.cuda.is_available() and torch.cuda.is_bf16_supported()
323
324
325
326
327
328
329
330


def is_torch_bf16_cpu_available():
    if not is_torch_available():
        return False

    import torch

331
332
333
334
    try:
        # multiple levels of AttributeError depending on the pytorch version so do them all in one check
        _ = torch.cpu.amp.autocast
    except AttributeError:
335
        return False
336

337
338
339
340
    return True


def is_torch_bf16_available():
341
342
343
344
345
346
347
348
    # the original bf16 check was for gpu only, but later a cpu/bf16 combo has emerged so this util
    # has become ambiguous and therefore deprecated
    warnings.warn(
        "The util is_torch_bf16_available is deprecated, please use is_torch_bf16_gpu_available "
        "or is_torch_bf16_cpu_available instead according to whether it's used with cpu or gpu",
        FutureWarning,
    )
    return is_torch_bf16_gpu_available()
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
@lru_cache()
def is_torch_fp16_available_on_device(device):
    if not is_torch_available():
        return False

    import torch

    try:
        x = torch.zeros(2, 2, dtype=torch.float16).to(device)
        _ = x @ x
    except:  # noqa: E722
        # TODO: more precise exception matching, if possible.
        # most backends should return `RuntimeError` however this is not guaranteed.
        return False

    return True


@lru_cache()
def is_torch_bf16_available_on_device(device):
    if not is_torch_available():
        return False

    import torch

    if device == "cuda":
        return is_torch_bf16_gpu_available()

    try:
        x = torch.zeros(2, 2, dtype=torch.bfloat16).to(device)
        _ = x @ x
    except:  # noqa: E722
        # TODO: more precise exception matching, if possible.
        # most backends should return `RuntimeError` however this is not guaranteed.
        return False

    return True


390
391
392
393
394
395
396
397
398
399
400
401
def is_torch_tf32_available():
    if not is_torch_available():
        return False

    import torch

    if not torch.cuda.is_available() or torch.version.cuda is None:
        return False
    if torch.cuda.get_device_properties(torch.cuda.current_device()).major < 8:
        return False
    if int(torch.version.cuda.split(".")[0]) < 11:
        return False
402
    if version.parse(version.parse(torch.__version__).base_version) < version.parse("1.7"):
403
404
405
406
407
408
409
410
411
        return False

    return True


def is_torch_fx_available():
    return _torch_fx_available


412
def is_peft_available():
413
    return _peft_available
414
415


NielsRogge's avatar
NielsRogge committed
416
def is_bs4_available():
417
    return _bs4_available
NielsRogge's avatar
NielsRogge committed
418
419


420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
def is_tf_available():
    return _tf_available


def is_coloredlogs_available():
    return _coloredlogs_available


def is_tf2onnx_available():
    return _tf2onnx_available


def is_onnx_available():
    return _onnx_available


Sylvain Gugger's avatar
Sylvain Gugger committed
436
def is_openai_available():
437
    return _openai_available
Sylvain Gugger's avatar
Sylvain Gugger committed
438
439


440
441
442
443
444
445
446
447
def is_flax_available():
    return _flax_available


def is_ftfy_available():
    return _ftfy_available


448
449
450
451
def is_g2p_en_available():
    return _g2p_en_available


452
@lru_cache()
453
454
def is_torch_tpu_available(check_device=True):
    "Checks if `torch_xla` is installed and potentially if a TPU is in the environment"
455
456
    if not _torch_available:
        return False
457
458
459
460
461
    if importlib.util.find_spec("torch_xla") is not None:
        if check_device:
            # We need to check if `xla_device` can be found, will raise a RuntimeError if not
            try:
                import torch_xla.core.xla_model as xm
462

463
464
465
466
                _ = xm.xla_device()
                return True
            except RuntimeError:
                return False
467
        return True
468
    return False
469
470


471
472
473
474
475
476
477
@lru_cache()
def is_torch_neuroncore_available(check_device=True):
    if importlib.util.find_spec("torch_neuronx") is not None:
        return is_torch_tpu_available(check_device)
    return False


478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
@lru_cache()
def is_torch_npu_available(check_device=False):
    "Checks if `torch_npu` is installed and potentially if a NPU is in the environment"
    if not _torch_available or importlib.util.find_spec("torch_npu") is None:
        return False

    import torch
    import torch_npu  # noqa: F401

    if check_device:
        try:
            # Will raise a RuntimeError if no NPU is found
            _ = torch.npu.device_count()
            return torch.npu.is_available()
        except RuntimeError:
            return False
    return hasattr(torch, "npu") and torch.npu.is_available()


497
def is_torchdynamo_available():
498
499
500
501
502
503
504
505
    if not is_torch_available():
        return False
    try:
        import torch._dynamo as dynamo  # noqa: F401

        return True
    except Exception:
        return False
506
507


508
509
510
511
512
513
def is_torch_compile_available():
    if not is_torch_available():
        return False

    import torch

514
515
    # We don't do any version check here to support nighlies marked as 1.14. Ultimately needs to check version against
    # 2.0 but let's do it later.
516
517
518
    return hasattr(torch, "compile")


519
520
521
522
523
524
525
526
527
528
529
def is_torchdynamo_compiling():
    if not is_torch_available():
        return False
    try:
        import torch._dynamo as dynamo  # noqa: F401

        return dynamo.is_compiling()
    except Exception:
        return False


530
531
532
533
534
535
def is_torch_tensorrt_fx_available():
    if importlib.util.find_spec("torch_tensorrt") is None:
        return False
    return importlib.util.find_spec("torch_tensorrt.fx") is not None


536
537
538
539
540
541
542
543
544
def is_datasets_available():
    return _datasets_available


def is_detectron2_available():
    return _detectron2_available


def is_rjieba_available():
545
    return _rjieba_available
546
547
548


def is_psutil_available():
549
    return _psutil_available
550
551
552


def is_py3nvml_available():
553
    return _py3nvml_available
554
555


556
def is_sacremoses_available():
557
    return _sacremoses_available
558
559


560
def is_apex_available():
561
    return _apex_available
562
563


564
def is_ninja_available():
玩火's avatar
玩火 committed
565
566
567
568
569
570
571
572
573
574
    r"""
    Code comes from *torch.utils.cpp_extension.is_ninja_available()*. Returns `True` if the
    [ninja](https://ninja-build.org/) build system is available on the system, `False` otherwise.
    """
    try:
        subprocess.check_output("ninja --version".split())
    except Exception:
        return False
    else:
        return True
575
576


577
def is_ipex_available():
578
579
580
    def get_major_and_minor_from_version(full_version):
        return str(version.parse(full_version).major) + "." + str(version.parse(full_version).minor)

581
    if not is_torch_available() or not _ipex_available:
582
        return False
583

584
585
586
587
588
589
590
591
592
    torch_major_and_minor = get_major_and_minor_from_version(_torch_version)
    ipex_major_and_minor = get_major_and_minor_from_version(_ipex_version)
    if torch_major_and_minor != ipex_major_and_minor:
        logger.warning(
            f"Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*,"
            f" but PyTorch {_torch_version} is found. Please switch to the matching version and run again."
        )
        return False
    return True
593
594


595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
@lru_cache
def is_torch_xpu_available(check_device=False):
    "Checks if `intel_extension_for_pytorch` is installed and potentially if a XPU is in the environment"
    if not is_ipex_available():
        return False

    import intel_extension_for_pytorch  # noqa: F401
    import torch

    if check_device:
        try:
            # Will raise a RuntimeError if no XPU  is found
            _ = torch.xpu.device_count()
            return torch.xpu.is_available()
        except RuntimeError:
            return False
    return hasattr(torch, "xpu") and torch.xpu.is_available()


614
def is_bitsandbytes_available():
615
616
617
618
619
620
621
622
    if not is_torch_available():
        return False

    # bitsandbytes throws an error if cuda is not available
    # let's avoid that by adding a simple check
    import torch

    return _bitsandbytes_available and torch.cuda.is_available()
623
624


625
def is_flash_attn_2_available():
626
627
628
    if not is_torch_available():
        return False

629
630
631
    if not _is_package_available("flash_attn"):
        return False

632
633
634
    # Let's add an extra check to see if cuda is available
    import torch

635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
    if not torch.cuda.is_available():
        return False

    if torch.version.cuda:
        return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.1.0")
    elif torch.version.hip:
        # TODO: Bump the requirement to 2.1.0 once released in https://github.com/ROCmSoftwarePlatform/flash-attention
        return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.0.4")
    else:
        return False


def is_flash_attn_greater_or_equal_2_10():
    if not _is_package_available("flash_attn"):
        return False

    return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.1.0")
652
653


654
655
656
657
658
659
660
661
def is_flash_attn_available():
    logger.warning(
        "Using `is_flash_attn_available` is deprecated and will be removed in v4.38. "
        "Please use `is_flash_attn_2_available` instead."
    )
    return is_flash_attn_2_available()


662
def is_torchdistx_available():
663
    return _torchdistx_available
664
665


666
667
668
669
670
def is_faiss_available():
    return _faiss_available


def is_scipy_available():
671
    return _scipy_available
672
673
674


def is_sklearn_available():
675
    return _sklearn_available
676
677
678


def is_sentencepiece_available():
679
    return _sentencepiece_available
680
681


682
683
684
685
def is_seqio_available():
    return _is_seqio_available


686
687
688
689
690
691
def is_protobuf_available():
    if importlib.util.find_spec("google") is None:
        return False
    return importlib.util.find_spec("google.protobuf") is not None


NielsRogge's avatar
NielsRogge committed
692
def is_accelerate_available(min_version: str = ACCELERATE_MIN_VERSION):
693
694
    if min_version is not None:
        return _accelerate_available and version.parse(_accelerate_version) >= version.parse(min_version)
695
    return _accelerate_available
696
697


NielsRogge's avatar
NielsRogge committed
698
def is_fsdp_available(min_version: str = FSDP_MIN_VERSION):
699
    return is_torch_available() and version.parse(_torch_version) >= version.parse(min_version)
700
701


702
def is_optimum_available():
703
    return _optimum_available
704
705


706
707
708
709
def is_auto_awq_available():
    return _auto_awq_available


Marc Sun's avatar
Marc Sun committed
710
711
712
713
def is_auto_gptq_available():
    return _auto_gptq_available


NielsRogge's avatar
NielsRogge committed
714
715
716
717
def is_levenshtein_available():
    return _levenshtein_available


718
def is_optimum_neuron_available():
719
    return _optimum_available and _is_package_available("optimum.neuron")
720
721


722
def is_safetensors_available():
723
    return _safetensors_available
724
725


726
def is_tokenizers_available():
727
    return _tokenizers_available
728
729
730


def is_vision_available():
731
732
733
    _pil_available = importlib.util.find_spec("PIL") is not None
    if _pil_available:
        try:
734
735
            package_version = importlib.metadata.version("Pillow")
        except importlib.metadata.PackageNotFoundError:
Yih-Dar's avatar
Yih-Dar committed
736
737
738
739
            try:
                package_version = importlib.metadata.version("Pillow-SIMD")
            except importlib.metadata.PackageNotFoundError:
                return False
740
741
        logger.debug(f"Detected PIL version {package_version}")
    return _pil_available
742
743
744


def is_pytesseract_available():
745
    return _pytesseract_available
746
747


748
749
750
751
def is_pytest_available():
    return _pytest_available


752
def is_spacy_available():
753
    return _spacy_available
754
755


756
def is_tensorflow_text_available():
757
    return is_tf_available() and _tensorflow_text_available
758
759


760
def is_keras_nlp_available():
761
    return is_tensorflow_text_available() and _keras_nlp_available
762
763


764
765
766
767
768
769
770
771
def is_in_notebook():
    try:
        # Test adapted from tqdm.autonotebook: https://github.com/tqdm/tqdm/blob/master/tqdm/autonotebook.py
        get_ipython = sys.modules["IPython"].get_ipython
        if "IPKernelApp" not in get_ipython().config:
            raise ImportError("console")
        if "VSCODE_PID" in os.environ:
            raise ImportError("vscode")
772
773
774
        if "DATABRICKS_RUNTIME_VERSION" in os.environ and os.environ["DATABRICKS_RUNTIME_VERSION"] < "11.0":
            # Databricks Runtime 11.0 and above uses IPython kernel by default so it should be compatible with Jupyter notebook
            # https://docs.microsoft.com/en-us/azure/databricks/notebooks/ipython-kernel
775
            raise ImportError("databricks")
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790

        return importlib.util.find_spec("IPython") is not None
    except (AttributeError, ImportError, KeyError):
        return False


def is_pytorch_quantization_available():
    return _pytorch_quantization_available


def is_tensorflow_probability_available():
    return _tensorflow_probability_available


def is_pandas_available():
791
    return _pandas_available
792
793
794
795
796
797
798
799
800
801
802
803
804


def is_sagemaker_dp_enabled():
    # Get the sagemaker specific env variable.
    sagemaker_params = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
    try:
        # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
        sagemaker_params = json.loads(sagemaker_params)
        if not sagemaker_params.get("sagemaker_distributed_dataparallel_enabled", False):
            return False
    except json.JSONDecodeError:
        return False
    # Lastly, check if the `smdistributed` module is present.
805
    return _smdistributed_available
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828


def is_sagemaker_mp_enabled():
    # Get the sagemaker specific mp parameters from smp_options variable.
    smp_options = os.getenv("SM_HP_MP_PARAMETERS", "{}")
    try:
        # Parse it and check the field "partitions" is included, it is required for model parallel.
        smp_options = json.loads(smp_options)
        if "partitions" not in smp_options:
            return False
    except json.JSONDecodeError:
        return False

    # Get the sagemaker specific framework parameters from mpi_options variable.
    mpi_options = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
    try:
        # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
        mpi_options = json.loads(mpi_options)
        if not mpi_options.get("sagemaker_mpi_enabled", False):
            return False
    except json.JSONDecodeError:
        return False
    # Lastly, check if the `smdistributed` module is present.
829
    return _smdistributed_available
830
831
832
833
834
835
836
837
838
839
840
841
842
843


def is_training_run_on_sagemaker():
    return "SAGEMAKER_JOB_NAME" in os.environ


def is_soundfile_availble():
    return _soundfile_available


def is_timm_available():
    return _timm_available


844
845
846
847
def is_natten_available():
    return _natten_available


NielsRogge's avatar
NielsRogge committed
848
849
850
851
def is_nltk_available():
    return _nltk_available


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
def is_torchaudio_available():
    return _torchaudio_available


def is_speech_available():
    # For now this depends on torchaudio but the exact dependency might evolve in the future.
    return _torchaudio_available


def is_phonemizer_available():
    return _phonemizer_available


def torch_only_method(fn):
    def wrapper(*args, **kwargs):
        if not _torch_available:
            raise ImportError(
                "You need to install pytorch to use this method or class, "
                "or activate it with environment variables USE_TORCH=1 and USE_TF=0."
            )
        else:
            return fn(*args, **kwargs)

    return wrapper


878
879
880
881
def is_ccl_available():
    return _is_ccl_available


882
def is_decord_available():
883
    return _decord_available
884
885


886
def is_sudachi_available():
887
    return _sudachipy_available
888
889
890


def is_jumanpp_available():
Hao Wang's avatar
Hao Wang committed
891
    return (importlib.util.find_spec("rhoknp") is not None) and (shutil.which("jumanpp") is not None)
892
893


894
895
896
897
def is_cython_available():
    return importlib.util.find_spec("pyximport") is not None


898
899
900
901
def is_jieba_available():
    return _jieba_available


902
903
904
905
def is_jinja_available():
    return _jinja_available


NielsRogge's avatar
NielsRogge committed
906
907
908
909
910
911
912
913
914
915
# docstyle-ignore
CV2_IMPORT_ERROR = """
{0} requires the OpenCV library but it was not found in your environment. You can install it with:
```
pip install opencv-python
```
Please note that you may need to restart your runtime after installation.
"""


916
917
918
919
920
921
922
923
924
925
926
927
928
929
# docstyle-ignore
DATASETS_IMPORT_ERROR = """
{0} requires the 🤗 Datasets library but it was not found in your environment. You can install it with:
```
pip install datasets
```
In a notebook or a colab, you can install it by executing a cell with
```
!pip install datasets
```
then restarting your kernel.

Note that if you have a local folder named `datasets` or a local python file named `datasets.py` in your current
working directory, python may try to import this instead of the 🤗 Datasets library. You should rename this folder or
930
that python file if that's the case. Please note that you may need to restart your runtime after installation.
931
932
933
934
935
936
937
938
939
940
941
942
943
"""


# docstyle-ignore
TOKENIZERS_IMPORT_ERROR = """
{0} requires the 🤗 Tokenizers library but it was not found in your environment. You can install it with:
```
pip install tokenizers
```
In a notebook or a colab, you can install it by executing a cell with
```
!pip install tokenizers
```
944
Please note that you may need to restart your runtime after installation.
945
946
947
948
949
950
951
"""


# docstyle-ignore
SENTENCEPIECE_IMPORT_ERROR = """
{0} requires the SentencePiece library but it was not found in your environment. Checkout the instructions on the
installation page of its repo: https://github.com/google/sentencepiece#installation and follow the ones
952
that match your environment. Please note that you may need to restart your runtime after installation.
953
954
955
956
957
958
959
"""


# docstyle-ignore
PROTOBUF_IMPORT_ERROR = """
{0} requires the protobuf library but it was not found in your environment. Checkout the instructions on the
installation page of its repo: https://github.com/protocolbuffers/protobuf/tree/master/python#installation and follow the ones
960
that match your environment. Please note that you may need to restart your runtime after installation.
961
962
963
964
965
966
967
"""


# docstyle-ignore
FAISS_IMPORT_ERROR = """
{0} requires the faiss library but it was not found in your environment. Checkout the instructions on the
installation page of its repo: https://github.com/facebookresearch/faiss/blob/master/INSTALL.md and follow the ones
968
that match your environment. Please note that you may need to restart your runtime after installation.
969
970
971
972
973
974
975
"""


# 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.
976
Please note that you may need to restart your runtime after installation.
977
978
"""

NielsRogge's avatar
NielsRogge committed
979
980
981
982
983
984
985
986

# docstyle-ignore
TORCHVISION_IMPORT_ERROR = """
{0} requires the Torchvision 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.
Please note that you may need to restart your runtime after installation.
"""

987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
# docstyle-ignore
PYTORCH_IMPORT_ERROR_WITH_TF = """
{0} requires the PyTorch library but it was not found in your environment.
However, we were able to find a TensorFlow installation. TensorFlow classes begin
with "TF", but are otherwise identically named to our PyTorch classes. This
means that the TF equivalent of the class you tried to import would be "TF{0}".
If you want to use TensorFlow, please use TF classes instead!

If you really do want to use PyTorch please go to
https://pytorch.org/get-started/locally/ and follow the instructions that
match your environment.
"""

# docstyle-ignore
TF_IMPORT_ERROR_WITH_PYTORCH = """
{0} requires the TensorFlow library but it was not found in your environment.
However, we were able to find a PyTorch installation. PyTorch classes do not begin
with "TF", but are otherwise identically named to our TF classes.
If you want to use PyTorch, please use those classes instead!

If you really do want to use TensorFlow, please follow the instructions on the
installation page https://www.tensorflow.org/install that match your environment.
"""

NielsRogge's avatar
NielsRogge committed
1011
1012
1013
# 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:
1014
`pip install beautifulsoup4`. Please note that you may need to restart your runtime after installation.
NielsRogge's avatar
NielsRogge committed
1015
1016
"""

1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027

# docstyle-ignore
SKLEARN_IMPORT_ERROR = """
{0} requires the scikit-learn library but it was not found in your environment. You can install it with:
```
pip install -U scikit-learn
```
In a notebook or a colab, you can install it by executing a cell with
```
!pip install -U scikit-learn
```
1028
Please note that you may need to restart your runtime after installation.
1029
1030
1031
1032
1033
1034
1035
"""


# docstyle-ignore
TENSORFLOW_IMPORT_ERROR = """
{0} requires the TensorFlow library but it was not found in your environment. Checkout the instructions on the
installation page: https://www.tensorflow.org/install and follow the ones that match your environment.
1036
Please note that you may need to restart your runtime after installation.
1037
1038
1039
1040
1041
1042
1043
"""


# docstyle-ignore
DETECTRON2_IMPORT_ERROR = """
{0} requires the detectron2 library but it was not found in your environment. Checkout the instructions on the
installation page: https://github.com/facebookresearch/detectron2/blob/master/INSTALL.md and follow the ones
1044
that match your environment. Please note that you may need to restart your runtime after installation.
1045
1046
1047
1048
1049
1050
1051
"""


# 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.
1052
Please note that you may need to restart your runtime after installation.
1053
1054
1055
1056
1057
1058
"""

# 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
1059
that match your environment. Please note that you may need to restart your runtime after installation.
1060
1061
"""

NielsRogge's avatar
NielsRogge committed
1062
1063
1064
1065
1066
LEVENSHTEIN_IMPORT_ERROR = """
{0} requires the python-Levenshtein library but it was not found in your environment. You can install it with pip: `pip
install python-Levenshtein`. Please note that you may need to restart your runtime after installation.
"""

1067
1068
1069
1070
1071
1072
# docstyle-ignore
G2P_EN_IMPORT_ERROR = """
{0} requires the g2p-en library but it was not found in your environment. You can install it with pip:
`pip install g2p-en`. Please note that you may need to restart your runtime after installation.
"""

1073
1074
1075
1076
# docstyle-ignore
PYTORCH_QUANTIZATION_IMPORT_ERROR = """
{0} requires the pytorch-quantization library but it was not found in your environment. You can install it with pip:
`pip install pytorch-quantization --extra-index-url https://pypi.ngc.nvidia.com`
1077
Please note that you may need to restart your runtime after installation.
1078
1079
1080
1081
1082
"""

# docstyle-ignore
TENSORFLOW_PROBABILITY_IMPORT_ERROR = """
{0} requires the tensorflow_probability library but it was not found in your environment. You can install it with pip as
1083
explained here: https://github.com/tensorflow/probability. Please note that you may need to restart your runtime after installation.
1084
1085
"""

1086
1087
1088
1089
# docstyle-ignore
TENSORFLOW_TEXT_IMPORT_ERROR = """
{0} requires the tensorflow_text library but it was not found in your environment. You can install it with pip as
explained here: https://www.tensorflow.org/text/guide/tf_text_intro.
1090
Please note that you may need to restart your runtime after installation.
1091
1092
"""

1093
1094
1095
1096
1097

# docstyle-ignore
PANDAS_IMPORT_ERROR = """
{0} requires the pandas library but it was not found in your environment. You can install it with pip as
explained here: https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html.
1098
Please note that you may need to restart your runtime after installation.
1099
1100
1101
1102
1103
1104
"""


# docstyle-ignore
PHONEMIZER_IMPORT_ERROR = """
{0} requires the phonemizer library but it was not found in your environment. You can install it with pip:
1105
`pip install phonemizer`. Please note that you may need to restart your runtime after installation.
1106
1107
1108
"""


1109
1110
1111
# docstyle-ignore
SACREMOSES_IMPORT_ERROR = """
{0} requires the sacremoses library but it was not found in your environment. You can install it with pip:
1112
`pip install sacremoses`. Please note that you may need to restart your runtime after installation.
1113
1114
"""

1115
1116
1117
# docstyle-ignore
SCIPY_IMPORT_ERROR = """
{0} requires the scipy library but it was not found in your environment. You can install it with pip:
1118
`pip install scipy`. Please note that you may need to restart your runtime after installation.
1119
1120
1121
1122
1123
1124
"""


# docstyle-ignore
SPEECH_IMPORT_ERROR = """
{0} requires the torchaudio library but it was not found in your environment. You can install it with pip:
1125
`pip install torchaudio`. Please note that you may need to restart your runtime after installation.
1126
1127
1128
1129
1130
"""

# docstyle-ignore
TIMM_IMPORT_ERROR = """
{0} requires the timm library but it was not found in your environment. You can install it with pip:
1131
`pip install timm`. Please note that you may need to restart your runtime after installation.
1132
1133
"""

1134
1135
1136
1137
1138
1139
1140
# docstyle-ignore
NATTEN_IMPORT_ERROR = """
{0} requires the natten library but it was not found in your environment. You can install it by referring to:
shi-labs.com/natten . You can also install it with pip (may take longer to build):
`pip install natten`. Please note that you may need to restart your runtime after installation.
"""

NielsRogge's avatar
NielsRogge committed
1141
1142
1143
1144
1145
1146
1147
1148

# docstyle-ignore
NLTK_IMPORT_ERROR = """
{0} requires the NLTK library but it was not found in your environment. You can install it by referring to:
https://www.nltk.org/install.html. Please note that you may need to restart your runtime after installation.
"""


1149
1150
1151
# docstyle-ignore
VISION_IMPORT_ERROR = """
{0} requires the PIL library but it was not found in your environment. You can install it with pip:
1152
`pip install pillow`. Please note that you may need to restart your runtime after installation.
1153
1154
1155
1156
1157
1158
"""


# docstyle-ignore
PYTESSERACT_IMPORT_ERROR = """
{0} requires the PyTesseract library but it was not found in your environment. You can install it with pip:
1159
`pip install pytesseract`. Please note that you may need to restart your runtime after installation.
1160
1161
1162
1163
1164
"""

# docstyle-ignore
PYCTCDECODE_IMPORT_ERROR = """
{0} requires the pyctcdecode library but it was not found in your environment. You can install it with pip:
1165
`pip install pyctcdecode`. Please note that you may need to restart your runtime after installation.
1166
1167
"""

1168
1169
# docstyle-ignore
ACCELERATE_IMPORT_ERROR = """
NielsRogge's avatar
NielsRogge committed
1170
1171
1172
{0} requires the accelerate library >= {ACCELERATE_MIN_VERSION} it was not found in your environment.
You can install or update it with pip: `pip install --upgrade accelerate`. Please note that you may need to restart your
runtime after installation.
1173
1174
"""

1175
1176
1177
1178
# docstyle-ignore
CCL_IMPORT_ERROR = """
{0} requires the torch ccl library but it was not found in your environment. You can install it with pip:
`pip install oneccl_bind_pt -f https://developer.intel.com/ipex-whl-stable`
1179
Please note that you may need to restart your runtime after installation.
1180
"""
1181

Susnato Dhar's avatar
Susnato Dhar committed
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
# docstyle-ignore
ESSENTIA_IMPORT_ERROR = """
{0} requires essentia library. But that was not found in your environment. You can install them with pip:
`pip install essentia==2.1b6.dev1034`
Please note that you may need to restart your runtime after installation.
"""

# docstyle-ignore
LIBROSA_IMPORT_ERROR = """
{0} requires thes librosa library. But that was not found in your environment. You can install them with pip:
`pip install librosa`
Please note that you may need to restart your runtime after installation.
"""

# docstyle-ignore
PRETTY_MIDI_IMPORT_ERROR = """
{0} requires thes pretty_midi library. But that was not found in your environment. You can install them with pip:
`pip install pretty_midi`
Please note that you may need to restart your runtime after installation.
"""

1203
1204
1205
1206
1207
DECORD_IMPORT_ERROR = """
{0} requires the decord library but it was not found in your environment. You can install it with pip: `pip install
decord`. Please note that you may need to restart your runtime after installation.
"""

Clémentine Fourrier's avatar
Clémentine Fourrier committed
1208
1209
1210
1211
1212
CYTHON_IMPORT_ERROR = """
{0} requires the Cython library but it was not found in your environment. You can install it with pip: `pip install
Cython`. Please note that you may need to restart your runtime after installation.
"""

1213
1214
1215
1216
1217
JIEBA_IMPORT_ERROR = """
{0} requires the jieba library but it was not found in your environment. You can install it with pip: `pip install
jieba`. Please note that you may need to restart your runtime after installation.
"""

1218
1219
1220
1221
1222
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`. Please note that you may need to restart your runtime after installation.
"""

1223
1224
1225
1226
1227
JINJA_IMPORT_ERROR = """
{0} requires the jinja library but it was not found in your environment. You can install it with pip: `pip install
jinja2`. Please note that you may need to restart your runtime after installation.
"""

1228
1229
BACKENDS_MAPPING = OrderedDict(
    [
NielsRogge's avatar
NielsRogge committed
1230
        ("bs4", (is_bs4_available, BS4_IMPORT_ERROR)),
NielsRogge's avatar
NielsRogge committed
1231
        ("cv2", (is_cv2_available, CV2_IMPORT_ERROR)),
1232
1233
        ("datasets", (is_datasets_available, DATASETS_IMPORT_ERROR)),
        ("detectron2", (is_detectron2_available, DETECTRON2_IMPORT_ERROR)),
Susnato Dhar's avatar
Susnato Dhar committed
1234
        ("essentia", (is_essentia_available, ESSENTIA_IMPORT_ERROR)),
1235
1236
1237
        ("faiss", (is_faiss_available, FAISS_IMPORT_ERROR)),
        ("flax", (is_flax_available, FLAX_IMPORT_ERROR)),
        ("ftfy", (is_ftfy_available, FTFY_IMPORT_ERROR)),
1238
        ("g2p_en", (is_g2p_en_available, G2P_EN_IMPORT_ERROR)),
1239
1240
        ("pandas", (is_pandas_available, PANDAS_IMPORT_ERROR)),
        ("phonemizer", (is_phonemizer_available, PHONEMIZER_IMPORT_ERROR)),
Susnato Dhar's avatar
Susnato Dhar committed
1241
        ("pretty_midi", (is_pretty_midi_available, PRETTY_MIDI_IMPORT_ERROR)),
NielsRogge's avatar
NielsRogge committed
1242
        ("levenshtein", (is_levenshtein_available, LEVENSHTEIN_IMPORT_ERROR)),
Susnato Dhar's avatar
Susnato Dhar committed
1243
        ("librosa", (is_librosa_available, LIBROSA_IMPORT_ERROR)),
1244
1245
1246
        ("protobuf", (is_protobuf_available, PROTOBUF_IMPORT_ERROR)),
        ("pyctcdecode", (is_pyctcdecode_available, PYCTCDECODE_IMPORT_ERROR)),
        ("pytesseract", (is_pytesseract_available, PYTESSERACT_IMPORT_ERROR)),
1247
        ("sacremoses", (is_sacremoses_available, SACREMOSES_IMPORT_ERROR)),
1248
1249
1250
1251
1252
1253
        ("pytorch_quantization", (is_pytorch_quantization_available, PYTORCH_QUANTIZATION_IMPORT_ERROR)),
        ("sentencepiece", (is_sentencepiece_available, SENTENCEPIECE_IMPORT_ERROR)),
        ("sklearn", (is_sklearn_available, SKLEARN_IMPORT_ERROR)),
        ("speech", (is_speech_available, SPEECH_IMPORT_ERROR)),
        ("tensorflow_probability", (is_tensorflow_probability_available, TENSORFLOW_PROBABILITY_IMPORT_ERROR)),
        ("tf", (is_tf_available, TENSORFLOW_IMPORT_ERROR)),
1254
        ("tensorflow_text", (is_tensorflow_text_available, TENSORFLOW_TEXT_IMPORT_ERROR)),
1255
        ("timm", (is_timm_available, TIMM_IMPORT_ERROR)),
1256
        ("natten", (is_natten_available, NATTEN_IMPORT_ERROR)),
NielsRogge's avatar
NielsRogge committed
1257
        ("nltk", (is_nltk_available, NLTK_IMPORT_ERROR)),
1258
1259
        ("tokenizers", (is_tokenizers_available, TOKENIZERS_IMPORT_ERROR)),
        ("torch", (is_torch_available, PYTORCH_IMPORT_ERROR)),
NielsRogge's avatar
NielsRogge committed
1260
        ("torchvision", (is_torchvision_available, TORCHVISION_IMPORT_ERROR)),
1261
1262
        ("vision", (is_vision_available, VISION_IMPORT_ERROR)),
        ("scipy", (is_scipy_available, SCIPY_IMPORT_ERROR)),
1263
        ("accelerate", (is_accelerate_available, ACCELERATE_IMPORT_ERROR)),
1264
        ("oneccl_bind_pt", (is_ccl_available, CCL_IMPORT_ERROR)),
1265
        ("decord", (is_decord_available, DECORD_IMPORT_ERROR)),
Clémentine Fourrier's avatar
Clémentine Fourrier committed
1266
        ("cython", (is_cython_available, CYTHON_IMPORT_ERROR)),
1267
        ("jieba", (is_jieba_available, JIEBA_IMPORT_ERROR)),
1268
        ("peft", (is_peft_available, PEFT_IMPORT_ERROR)),
1269
        ("jinja", (is_jinja_available, JINJA_IMPORT_ERROR)),
1270
1271
1272
1273
1274
1275
1276
1277
1278
    ]
)


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

    name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
1279
1280
1281
1282
1283
1284
1285
1286
1287

    # Raise an error for users who might not realize that classes without "TF" are torch-only
    if "torch" in backends and "tf" not in backends and not is_torch_available() and is_tf_available():
        raise ImportError(PYTORCH_IMPORT_ERROR_WITH_TF.format(name))

    # Raise the inverse error for PyTorch users trying to load TF classes
    if "tf" in backends and "torch" not in backends and is_torch_available() and not is_tf_available():
        raise ImportError(TF_IMPORT_ERROR_WITH_PYTORCH.format(name))

1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
    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))


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.
    """

1300
    def __getattribute__(cls, key):
1301
        if key.startswith("_") and key != "_from_config":
1302
            return super().__getattribute__(key)
1303
1304
1305
        requires_backends(cls, cls._backends)


Yih-Dar's avatar
Yih-Dar committed
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
def torch_required(func):
    warnings.warn(
        "The method `torch_required` is deprecated and will be removed in v4.36. Use `requires_backends` instead.",
        FutureWarning,
    )

    # Chose a different decorator name than in tests so it's clear they are not the same.
    @wraps(func)
    def wrapper(*args, **kwargs):
        if is_torch_available():
            return func(*args, **kwargs)
        else:
            raise ImportError(f"Method `{func.__name__}` requires PyTorch.")

    return wrapper


def tf_required(func):
    warnings.warn(
        "The method `tf_required` is deprecated and will be removed in v4.36. Use `requires_backends` instead.",
        FutureWarning,
    )

    # Chose a different decorator name than in tests so it's clear they are not the same.
    @wraps(func)
    def wrapper(*args, **kwargs):
        if is_tf_available():
            return func(*args, **kwargs)
        else:
            raise ImportError(f"Method `{func.__name__}` requires TF.")

    return wrapper


1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
def is_torch_fx_proxy(x):
    if is_torch_fx_available():
        import torch.fx

        return isinstance(x, torch.fx.Proxy)
    return False


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(
Sylvain Gugger's avatar
Sylvain Gugger committed
1400
1401
                f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
                f" traceback):\n{e}"
1402
1403
1404
1405
            ) from e

    def __reduce__(self):
        return (self.__class__, (self._name, self.__file__, self._import_structure))
1406
1407
1408
1409


class OptionalDependencyNotAvailable(BaseException):
    """Internally used error class for signalling an optional dependency was not found."""
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428


def direct_transformers_import(path: str, file="__init__.py") -> ModuleType:
    """Imports transformers directly

    Args:
        path (`str`): The path to the source file
        file (`str`, optional): The file to join with the path. Defaults to "__init__.py".

    Returns:
        `ModuleType`: The resulting imported module
    """
    name = "transformers"
    location = os.path.join(path, file)
    spec = importlib.util.spec_from_file_location(name, location, submodule_search_locations=[path])
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    module = sys.modules[name]
    return module