import_utils.py 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899
  1. # Copyright 2022 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. Import utilities: Utilities related to imports and our lazy inits.
  16. """
  17. import importlib.machinery
  18. import importlib.metadata
  19. import importlib.util
  20. import json
  21. import operator
  22. import os
  23. import re
  24. import shutil
  25. import subprocess
  26. import sys
  27. import warnings
  28. from collections import OrderedDict
  29. from enum import Enum
  30. from functools import lru_cache
  31. from itertools import chain
  32. from types import ModuleType
  33. from typing import Any, Callable, Optional, Union
  34. from packaging import version
  35. from . import logging
  36. logger = logging.get_logger(__name__) # pylint: disable=invalid-name
  37. # TODO: This doesn't work for all packages (`bs4`, `faiss`, etc.) Talk to Sylvain to see how to do with it better.
  38. def _is_package_available(pkg_name: str, return_version: bool = False) -> Union[tuple[bool, str], bool]:
  39. # Check if the package spec exists and grab its version to avoid importing a local directory
  40. package_exists = importlib.util.find_spec(pkg_name) is not None
  41. package_version = "N/A"
  42. if package_exists:
  43. try:
  44. # TODO: Once python 3.9 support is dropped, `importlib.metadata.packages_distributions()`
  45. # should be used here to map from package name to distribution names
  46. # e.g. PIL -> Pillow, Pillow-SIMD; quark -> amd-quark; onnxruntime -> onnxruntime-gpu.
  47. # `importlib.metadata.packages_distributions()` is not available in Python 3.9.
  48. # Primary method to get the package version
  49. package_version = importlib.metadata.version(pkg_name)
  50. except importlib.metadata.PackageNotFoundError:
  51. # Fallback method: Only for "torch" and versions containing "dev"
  52. if pkg_name == "torch":
  53. try:
  54. package = importlib.import_module(pkg_name)
  55. temp_version = getattr(package, "__version__", "N/A")
  56. # Check if the version contains "dev"
  57. if "dev" in temp_version:
  58. package_version = temp_version
  59. package_exists = True
  60. else:
  61. package_exists = False
  62. except ImportError:
  63. # If the package can't be imported, it's not available
  64. package_exists = False
  65. elif pkg_name == "quark":
  66. # TODO: remove once `importlib.metadata.packages_distributions()` is supported.
  67. try:
  68. package_version = importlib.metadata.version("amd-quark")
  69. except Exception:
  70. package_exists = False
  71. elif pkg_name == "triton":
  72. try:
  73. # import triton works for both linux and windows
  74. package = importlib.import_module(pkg_name)
  75. package_version = getattr(package, "__version__", "N/A")
  76. except Exception:
  77. try:
  78. package_version = importlib.metadata.version("pytorch-triton") # pytorch-triton
  79. except Exception:
  80. package_exists = False
  81. else:
  82. # For packages other than "torch", don't attempt the fallback and set as not available
  83. package_exists = False
  84. logger.debug(f"Detected {pkg_name} version: {package_version}")
  85. if return_version:
  86. return package_exists, package_version
  87. else:
  88. return package_exists
  89. ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}
  90. ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})
  91. USE_TF = os.environ.get("USE_TF", "AUTO").upper()
  92. USE_TORCH = os.environ.get("USE_TORCH", "AUTO").upper()
  93. USE_JAX = os.environ.get("USE_FLAX", "AUTO").upper()
  94. # Try to run a native pytorch job in an environment with TorchXLA installed by setting this value to 0.
  95. USE_TORCH_XLA = os.environ.get("USE_TORCH_XLA", "1").upper()
  96. FORCE_TF_AVAILABLE = os.environ.get("FORCE_TF_AVAILABLE", "AUTO").upper()
  97. # `transformers` requires `torch>=1.11` but this variable is exposed publicly, and we can't simply remove it.
  98. # This is the version of torch required to run torch.fx features and torch.onnx with dictionary inputs.
  99. TORCH_FX_REQUIRED_VERSION = version.parse("1.10")
  100. ACCELERATE_MIN_VERSION = "0.26.0"
  101. SCHEDULEFREE_MIN_VERSION = "1.2.6"
  102. FSDP_MIN_VERSION = "1.12.0"
  103. GGUF_MIN_VERSION = "0.10.0"
  104. XLA_FSDPV2_MIN_VERSION = "2.2.0"
  105. HQQ_MIN_VERSION = "0.2.1"
  106. VPTQ_MIN_VERSION = "0.0.4"
  107. TORCHAO_MIN_VERSION = "0.4.0"
  108. AUTOROUND_MIN_VERSION = "0.5.0"
  109. TRITON_MIN_VERSION = "1.0.0"
  110. _accelerate_available, _accelerate_version = _is_package_available("accelerate", return_version=True)
  111. _apex_available = _is_package_available("apex")
  112. _apollo_torch_available = _is_package_available("apollo_torch")
  113. _aqlm_available = _is_package_available("aqlm")
  114. _vptq_available, _vptq_version = _is_package_available("vptq", return_version=True)
  115. _av_available = importlib.util.find_spec("av") is not None
  116. _decord_available = importlib.util.find_spec("decord") is not None
  117. _torchcodec_available = importlib.util.find_spec("torchcodec") is not None
  118. _libcst_available = _is_package_available("libcst")
  119. _bitsandbytes_available = _is_package_available("bitsandbytes")
  120. _eetq_available = _is_package_available("eetq")
  121. _fbgemm_gpu_available = _is_package_available("fbgemm_gpu")
  122. _galore_torch_available = _is_package_available("galore_torch")
  123. _lomo_available = _is_package_available("lomo_optim")
  124. _grokadamw_available = _is_package_available("grokadamw")
  125. _schedulefree_available, _schedulefree_version = _is_package_available("schedulefree", return_version=True)
  126. _torch_optimi_available = importlib.util.find_spec("optimi") is not None
  127. # `importlib.metadata.version` doesn't work with `bs4` but `beautifulsoup4`. For `importlib.util.find_spec`, reversed.
  128. _bs4_available = importlib.util.find_spec("bs4") is not None
  129. _coloredlogs_available = _is_package_available("coloredlogs")
  130. # `importlib.metadata.util` doesn't work with `opencv-python-headless`.
  131. _cv2_available = importlib.util.find_spec("cv2") is not None
  132. _yt_dlp_available = importlib.util.find_spec("yt_dlp") is not None
  133. _datasets_available = _is_package_available("datasets")
  134. _detectron2_available = _is_package_available("detectron2")
  135. # We need to check `faiss`, `faiss-cpu` and `faiss-gpu`.
  136. _faiss_available = importlib.util.find_spec("faiss") is not None
  137. try:
  138. _faiss_version = importlib.metadata.version("faiss")
  139. logger.debug(f"Successfully imported faiss version {_faiss_version}")
  140. except importlib.metadata.PackageNotFoundError:
  141. try:
  142. _faiss_version = importlib.metadata.version("faiss-cpu")
  143. logger.debug(f"Successfully imported faiss version {_faiss_version}")
  144. except importlib.metadata.PackageNotFoundError:
  145. try:
  146. _faiss_version = importlib.metadata.version("faiss-gpu")
  147. logger.debug(f"Successfully imported faiss version {_faiss_version}")
  148. except importlib.metadata.PackageNotFoundError:
  149. _faiss_available = False
  150. _ftfy_available = _is_package_available("ftfy")
  151. _g2p_en_available = _is_package_available("g2p_en")
  152. _hadamard_available = _is_package_available("fast_hadamard_transform")
  153. _ipex_available, _ipex_version = _is_package_available("intel_extension_for_pytorch", return_version=True)
  154. _jinja_available = _is_package_available("jinja2")
  155. _kenlm_available = _is_package_available("kenlm")
  156. _keras_nlp_available = _is_package_available("keras_nlp")
  157. _levenshtein_available = _is_package_available("Levenshtein")
  158. _librosa_available = _is_package_available("librosa")
  159. _natten_available = _is_package_available("natten")
  160. _nltk_available = _is_package_available("nltk")
  161. _onnx_available = _is_package_available("onnx")
  162. _openai_available = _is_package_available("openai")
  163. _optimum_available = _is_package_available("optimum")
  164. _auto_gptq_available = _is_package_available("auto_gptq")
  165. _gptqmodel_available = _is_package_available("gptqmodel")
  166. _auto_round_available, _auto_round_version = _is_package_available("auto_round", return_version=True)
  167. # `importlib.metadata.version` doesn't work with `awq`
  168. _auto_awq_available = importlib.util.find_spec("awq") is not None
  169. _quark_available = _is_package_available("quark")
  170. _fp_quant_available, _fp_quant_version = _is_package_available("fp_quant", return_version=True)
  171. _qutlass_available, _qutlass_version = _is_package_available("qutlass", return_version=True)
  172. _is_optimum_quanto_available = False
  173. try:
  174. importlib.metadata.version("optimum_quanto")
  175. _is_optimum_quanto_available = True
  176. except importlib.metadata.PackageNotFoundError:
  177. _is_optimum_quanto_available = False
  178. # For compressed_tensors, only check spec to allow compressed_tensors-nightly package
  179. _compressed_tensors_available = importlib.util.find_spec("compressed_tensors") is not None
  180. _pandas_available = _is_package_available("pandas")
  181. _peft_available = _is_package_available("peft")
  182. _phonemizer_available = _is_package_available("phonemizer")
  183. _uroman_available = _is_package_available("uroman")
  184. _psutil_available = _is_package_available("psutil")
  185. _py3nvml_available = _is_package_available("py3nvml")
  186. _pyctcdecode_available = _is_package_available("pyctcdecode")
  187. _pygments_available = _is_package_available("pygments")
  188. _pytesseract_available = _is_package_available("pytesseract")
  189. _pytest_available = _is_package_available("pytest")
  190. _pytorch_quantization_available = _is_package_available("pytorch_quantization")
  191. _rjieba_available = _is_package_available("rjieba")
  192. _sacremoses_available = _is_package_available("sacremoses")
  193. _safetensors_available = _is_package_available("safetensors")
  194. _scipy_available = _is_package_available("scipy")
  195. _sentencepiece_available = _is_package_available("sentencepiece")
  196. _is_seqio_available = _is_package_available("seqio")
  197. _is_gguf_available, _gguf_version = _is_package_available("gguf", return_version=True)
  198. _sklearn_available = importlib.util.find_spec("sklearn") is not None
  199. if _sklearn_available:
  200. try:
  201. importlib.metadata.version("scikit-learn")
  202. except importlib.metadata.PackageNotFoundError:
  203. _sklearn_available = False
  204. _smdistributed_available = importlib.util.find_spec("smdistributed") is not None
  205. _soundfile_available = _is_package_available("soundfile")
  206. _spacy_available = _is_package_available("spacy")
  207. _sudachipy_available, _sudachipy_version = _is_package_available("sudachipy", return_version=True)
  208. _tensorflow_probability_available = _is_package_available("tensorflow_probability")
  209. _tensorflow_text_available = _is_package_available("tensorflow_text")
  210. _tf2onnx_available = _is_package_available("tf2onnx")
  211. _timm_available = _is_package_available("timm")
  212. _tokenizers_available = _is_package_available("tokenizers")
  213. _torchaudio_available = _is_package_available("torchaudio")
  214. _torchao_available, _torchao_version = _is_package_available("torchao", return_version=True)
  215. _torchdistx_available = _is_package_available("torchdistx")
  216. _torchvision_available, _torchvision_version = _is_package_available("torchvision", return_version=True)
  217. _mlx_available = _is_package_available("mlx")
  218. _num2words_available = _is_package_available("num2words")
  219. _hqq_available, _hqq_version = _is_package_available("hqq", return_version=True)
  220. _tiktoken_available = _is_package_available("tiktoken")
  221. _blobfile_available = _is_package_available("blobfile")
  222. _liger_kernel_available = _is_package_available("liger_kernel")
  223. _spqr_available = _is_package_available("spqr_quant")
  224. _rich_available = _is_package_available("rich")
  225. _kernels_available = _is_package_available("kernels")
  226. _matplotlib_available = _is_package_available("matplotlib")
  227. _mistral_common_available = _is_package_available("mistral_common")
  228. _triton_available, _triton_version = _is_package_available("triton", return_version=True)
  229. _torch_version = "N/A"
  230. _torch_available = False
  231. if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
  232. _torch_available, _torch_version = _is_package_available("torch", return_version=True)
  233. if _torch_available:
  234. _torch_available = version.parse(_torch_version) >= version.parse("2.1.0")
  235. if not _torch_available:
  236. logger.warning(f"Disabling PyTorch because PyTorch >= 2.1 is required but found {_torch_version}")
  237. else:
  238. logger.info("Disabling PyTorch because USE_TF is set")
  239. _torch_available = False
  240. _tf_version = "N/A"
  241. _tf_available = False
  242. if FORCE_TF_AVAILABLE in ENV_VARS_TRUE_VALUES:
  243. _tf_available = True
  244. else:
  245. if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
  246. # Note: _is_package_available("tensorflow") fails for tensorflow-cpu. Please test any changes to the line below
  247. # with tensorflow-cpu to make sure it still works!
  248. _tf_available = importlib.util.find_spec("tensorflow") is not None
  249. if _tf_available:
  250. candidates = (
  251. "tensorflow",
  252. "tensorflow-cpu",
  253. "tensorflow-gpu",
  254. "tf-nightly",
  255. "tf-nightly-cpu",
  256. "tf-nightly-gpu",
  257. "tf-nightly-rocm",
  258. "intel-tensorflow",
  259. "intel-tensorflow-avx512",
  260. "tensorflow-rocm",
  261. "tensorflow-macos",
  262. "tensorflow-aarch64",
  263. )
  264. _tf_version = None
  265. # For the metadata, we have to look for both tensorflow and tensorflow-cpu
  266. for pkg in candidates:
  267. try:
  268. _tf_version = importlib.metadata.version(pkg)
  269. break
  270. except importlib.metadata.PackageNotFoundError:
  271. pass
  272. _tf_available = _tf_version is not None
  273. if _tf_available:
  274. if version.parse(_tf_version) < version.parse("2"):
  275. logger.info(
  276. f"TensorFlow found but with version {_tf_version}. Transformers requires version 2 minimum."
  277. )
  278. _tf_available = False
  279. else:
  280. logger.info("Disabling Tensorflow because USE_TORCH is set")
  281. _essentia_available = importlib.util.find_spec("essentia") is not None
  282. try:
  283. _essentia_version = importlib.metadata.version("essentia")
  284. logger.debug(f"Successfully imported essentia version {_essentia_version}")
  285. except importlib.metadata.PackageNotFoundError:
  286. _essentia_version = False
  287. _pydantic_available = importlib.util.find_spec("pydantic") is not None
  288. try:
  289. _pydantic_version = importlib.metadata.version("pydantic")
  290. logger.debug(f"Successfully imported pydantic version {_pydantic_version}")
  291. except importlib.metadata.PackageNotFoundError:
  292. _pydantic_available = False
  293. _fastapi_available = importlib.util.find_spec("fastapi") is not None
  294. try:
  295. _fastapi_version = importlib.metadata.version("fastapi")
  296. logger.debug(f"Successfully imported pydantic version {_fastapi_version}")
  297. except importlib.metadata.PackageNotFoundError:
  298. _fastapi_available = False
  299. _uvicorn_available = importlib.util.find_spec("uvicorn") is not None
  300. try:
  301. _uvicorn_version = importlib.metadata.version("uvicorn")
  302. logger.debug(f"Successfully imported pydantic version {_uvicorn_version}")
  303. except importlib.metadata.PackageNotFoundError:
  304. _uvicorn_available = False
  305. _pretty_midi_available = importlib.util.find_spec("pretty_midi") is not None
  306. try:
  307. _pretty_midi_version = importlib.metadata.version("pretty_midi")
  308. logger.debug(f"Successfully imported pretty_midi version {_pretty_midi_version}")
  309. except importlib.metadata.PackageNotFoundError:
  310. _pretty_midi_available = False
  311. ccl_version = "N/A"
  312. _is_ccl_available = (
  313. importlib.util.find_spec("torch_ccl") is not None
  314. or importlib.util.find_spec("oneccl_bindings_for_pytorch") is not None
  315. )
  316. try:
  317. ccl_version = importlib.metadata.version("oneccl_bind_pt")
  318. logger.debug(f"Detected oneccl_bind_pt version {ccl_version}")
  319. except importlib.metadata.PackageNotFoundError:
  320. _is_ccl_available = False
  321. _flax_available = False
  322. if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
  323. _flax_available, _flax_version = _is_package_available("flax", return_version=True)
  324. if _flax_available:
  325. _jax_available, _jax_version = _is_package_available("jax", return_version=True)
  326. if _jax_available:
  327. logger.info(f"JAX version {_jax_version}, Flax version {_flax_version} available.")
  328. else:
  329. _flax_available = _jax_available = False
  330. _jax_version = _flax_version = "N/A"
  331. _torch_xla_available = False
  332. if USE_TORCH_XLA in ENV_VARS_TRUE_VALUES:
  333. _torch_xla_available, _torch_xla_version = _is_package_available("torch_xla", return_version=True)
  334. if _torch_xla_available:
  335. logger.info(f"Torch XLA version {_torch_xla_version} available.")
  336. def is_kenlm_available() -> Union[tuple[bool, str], bool]:
  337. return _kenlm_available
  338. def is_kernels_available() -> Union[tuple[bool, str], bool]:
  339. return _kernels_available
  340. def is_cv2_available() -> Union[tuple[bool, str], bool]:
  341. return _cv2_available
  342. def is_yt_dlp_available() -> Union[tuple[bool, str], bool]:
  343. return _yt_dlp_available
  344. def is_torch_available() -> Union[tuple[bool, str], bool]:
  345. return _torch_available
  346. def is_libcst_available() -> Union[tuple[bool, str], bool]:
  347. return _libcst_available
  348. def is_accelerate_available(min_version: str = ACCELERATE_MIN_VERSION) -> bool:
  349. return _accelerate_available and version.parse(_accelerate_version) >= version.parse(min_version)
  350. def is_torch_accelerator_available() -> bool:
  351. if is_torch_available():
  352. import torch
  353. return hasattr(torch, "accelerator")
  354. return False
  355. def is_torch_deterministic() -> bool:
  356. """
  357. Check whether pytorch uses deterministic algorithms by looking if torch.set_deterministic_debug_mode() is set to 1 or 2"
  358. """
  359. if is_torch_available():
  360. import torch
  361. if torch.get_deterministic_debug_mode() == 0:
  362. return False
  363. else:
  364. return True
  365. return False
  366. def is_triton_available(min_version: str = TRITON_MIN_VERSION) -> bool:
  367. return _triton_available and version.parse(_triton_version) >= version.parse(min_version)
  368. def is_hadamard_available() -> Union[tuple[bool, str], bool]:
  369. return _hadamard_available
  370. def is_hqq_available(min_version: str = HQQ_MIN_VERSION) -> bool:
  371. return _hqq_available and version.parse(_hqq_version) >= version.parse(min_version)
  372. def is_pygments_available() -> Union[tuple[bool, str], bool]:
  373. return _pygments_available
  374. def get_torch_version() -> str:
  375. return _torch_version
  376. def get_torch_major_and_minor_version() -> str:
  377. if _torch_version == "N/A":
  378. return "N/A"
  379. parsed_version = version.parse(_torch_version)
  380. return str(parsed_version.major) + "." + str(parsed_version.minor)
  381. def is_torch_sdpa_available():
  382. # Mostly retained for backward compatibility in remote code, since sdpa works correctly on all torch versions >= 2.2
  383. if not is_torch_available() or _torch_version == "N/A":
  384. return False
  385. return True
  386. def is_torch_flex_attn_available() -> bool:
  387. if not is_torch_available() or _torch_version == "N/A":
  388. return False
  389. # TODO check if some bugs cause push backs on the exact version
  390. # NOTE: We require torch>=2.5.0 as it is the first release
  391. return version.parse(_torch_version) >= version.parse("2.5.0")
  392. def is_torchvision_available() -> bool:
  393. return _torchvision_available
  394. def is_torchvision_v2_available() -> bool:
  395. return is_torchvision_available()
  396. def is_galore_torch_available() -> Union[tuple[bool, str], bool]:
  397. return _galore_torch_available
  398. def is_apollo_torch_available() -> Union[tuple[bool, str], bool]:
  399. return _apollo_torch_available
  400. def is_torch_optimi_available() -> Union[tuple[bool, str], bool]:
  401. return _torch_optimi_available
  402. def is_lomo_available() -> Union[tuple[bool, str], bool]:
  403. return _lomo_available
  404. def is_grokadamw_available() -> Union[tuple[bool, str], bool]:
  405. return _grokadamw_available
  406. def is_schedulefree_available(min_version: str = SCHEDULEFREE_MIN_VERSION) -> bool:
  407. return _schedulefree_available and version.parse(_schedulefree_version) >= version.parse(min_version)
  408. def is_pyctcdecode_available() -> Union[tuple[bool, str], bool]:
  409. return _pyctcdecode_available
  410. def is_librosa_available() -> Union[tuple[bool, str], bool]:
  411. return _librosa_available
  412. def is_essentia_available() -> Union[tuple[bool, str], bool]:
  413. return _essentia_available
  414. def is_pydantic_available() -> Union[tuple[bool, str], bool]:
  415. return _pydantic_available
  416. def is_fastapi_available() -> Union[tuple[bool, str], bool]:
  417. return _fastapi_available
  418. def is_uvicorn_available() -> Union[tuple[bool, str], bool]:
  419. return _uvicorn_available
  420. def is_openai_available() -> Union[tuple[bool, str], bool]:
  421. return _openai_available
  422. def is_pretty_midi_available() -> Union[tuple[bool, str], bool]:
  423. return _pretty_midi_available
  424. def is_torch_cuda_available() -> bool:
  425. if is_torch_available():
  426. import torch
  427. return torch.cuda.is_available()
  428. else:
  429. return False
  430. def is_cuda_platform() -> bool:
  431. if is_torch_available():
  432. import torch
  433. return torch.version.cuda is not None
  434. else:
  435. return False
  436. def is_rocm_platform() -> bool:
  437. if is_torch_available():
  438. import torch
  439. return torch.version.hip is not None
  440. else:
  441. return False
  442. def is_mamba_ssm_available() -> Union[tuple[bool, str], bool]:
  443. if is_torch_available():
  444. import torch
  445. if not torch.cuda.is_available():
  446. return False
  447. else:
  448. return _is_package_available("mamba_ssm")
  449. return False
  450. def is_mamba_2_ssm_available() -> bool:
  451. if is_torch_available():
  452. import torch
  453. if not torch.cuda.is_available():
  454. return False
  455. else:
  456. if _is_package_available("mamba_ssm"):
  457. import mamba_ssm
  458. if version.parse(mamba_ssm.__version__) >= version.parse("2.0.4"):
  459. return True
  460. return False
  461. def is_flash_linear_attention_available():
  462. if is_torch_available():
  463. import torch
  464. if not torch.cuda.is_available():
  465. return False
  466. try:
  467. import fla
  468. if version.parse(fla.__version__) >= version.parse("0.2.2"):
  469. return True
  470. except Exception:
  471. pass
  472. return False
  473. def is_causal_conv1d_available() -> Union[tuple[bool, str], bool]:
  474. if is_torch_available():
  475. import torch
  476. if not torch.cuda.is_available():
  477. return False
  478. return _is_package_available("causal_conv1d")
  479. return False
  480. def is_xlstm_available() -> Union[tuple[bool, str], bool]:
  481. if is_torch_available():
  482. return _is_package_available("xlstm")
  483. return False
  484. def is_mambapy_available() -> Union[tuple[bool, str], bool]:
  485. if is_torch_available():
  486. return _is_package_available("mambapy")
  487. return False
  488. def is_torch_mps_available(min_version: Optional[str] = None) -> bool:
  489. if is_torch_available():
  490. import torch
  491. if hasattr(torch.backends, "mps"):
  492. backend_available = torch.backends.mps.is_available() and torch.backends.mps.is_built()
  493. if min_version is not None:
  494. flag = version.parse(_torch_version) >= version.parse(min_version)
  495. backend_available = backend_available and flag
  496. return backend_available
  497. return False
  498. def is_torch_bf16_gpu_available() -> bool:
  499. if not is_torch_available():
  500. return False
  501. import torch
  502. if torch.cuda.is_available():
  503. return torch.cuda.is_bf16_supported()
  504. if is_torch_xpu_available():
  505. return torch.xpu.is_bf16_supported()
  506. if is_torch_hpu_available():
  507. return True
  508. if is_torch_npu_available():
  509. return torch.npu.is_bf16_supported()
  510. if is_torch_mps_available():
  511. # Note: Emulated in software by Metal using fp32 for hardware without native support (like M1/M2)
  512. return torch.backends.mps.is_macos_or_newer(14, 0)
  513. if is_torch_musa_available():
  514. return torch.musa.is_bf16_supported()
  515. return False
  516. def is_torch_bf16_cpu_available() -> Union[tuple[bool, str], bool]:
  517. return is_torch_available()
  518. def is_torch_bf16_available() -> bool:
  519. # the original bf16 check was for gpu only, but later a cpu/bf16 combo has emerged so this util
  520. # has become ambiguous and therefore deprecated
  521. warnings.warn(
  522. "The util is_torch_bf16_available is deprecated, please use is_torch_bf16_gpu_available "
  523. "or is_torch_bf16_cpu_available instead according to whether it's used with cpu or gpu",
  524. FutureWarning,
  525. )
  526. return is_torch_bf16_gpu_available()
  527. @lru_cache
  528. def is_torch_fp16_available_on_device(device: str) -> bool:
  529. if not is_torch_available():
  530. return False
  531. if is_torch_hpu_available():
  532. if is_habana_gaudi1():
  533. return False
  534. else:
  535. return True
  536. import torch
  537. try:
  538. x = torch.zeros(2, 2, dtype=torch.float16, device=device)
  539. _ = x @ x
  540. # At this moment, let's be strict of the check: check if `LayerNorm` is also supported on device, because many
  541. # models use this layer.
  542. batch, sentence_length, embedding_dim = 3, 4, 5
  543. embedding = torch.randn(batch, sentence_length, embedding_dim, dtype=torch.float16, device=device)
  544. layer_norm = torch.nn.LayerNorm(embedding_dim, dtype=torch.float16, device=device)
  545. _ = layer_norm(embedding)
  546. except: # noqa: E722
  547. # TODO: more precise exception matching, if possible.
  548. # most backends should return `RuntimeError` however this is not guaranteed.
  549. return False
  550. return True
  551. @lru_cache
  552. def is_torch_bf16_available_on_device(device: str) -> bool:
  553. if not is_torch_available():
  554. return False
  555. import torch
  556. if device == "cuda":
  557. return is_torch_bf16_gpu_available()
  558. if device == "hpu":
  559. return True
  560. try:
  561. x = torch.zeros(2, 2, dtype=torch.bfloat16, device=device)
  562. _ = x @ x
  563. except: # noqa: E722
  564. # TODO: more precise exception matching, if possible.
  565. # most backends should return `RuntimeError` however this is not guaranteed.
  566. return False
  567. return True
  568. def is_torch_tf32_available() -> bool:
  569. if not is_torch_available():
  570. return False
  571. import torch
  572. if is_torch_musa_available():
  573. device_info = torch.musa.get_device_properties(torch.musa.current_device())
  574. if f"{device_info.major}{device_info.minor}" >= "22":
  575. return True
  576. return False
  577. if not torch.cuda.is_available() or torch.version.cuda is None:
  578. return False
  579. if torch.cuda.get_device_properties(torch.cuda.current_device()).major < 8:
  580. return False
  581. return True
  582. def is_torch_fx_available() -> Union[tuple[bool, str], bool]:
  583. return is_torch_available()
  584. def is_peft_available() -> Union[tuple[bool, str], bool]:
  585. return _peft_available
  586. def is_bs4_available() -> Union[tuple[bool, str], bool]:
  587. return _bs4_available
  588. def is_tf_available() -> bool:
  589. return _tf_available
  590. def is_coloredlogs_available() -> Union[tuple[bool, str], bool]:
  591. return _coloredlogs_available
  592. def is_tf2onnx_available() -> Union[tuple[bool, str], bool]:
  593. return _tf2onnx_available
  594. def is_onnx_available() -> Union[tuple[bool, str], bool]:
  595. return _onnx_available
  596. def is_flax_available() -> bool:
  597. return _flax_available
  598. def is_flute_available() -> bool:
  599. try:
  600. return importlib.util.find_spec("flute") is not None and importlib.metadata.version("flute-kernel") >= "0.4.1"
  601. except importlib.metadata.PackageNotFoundError:
  602. return False
  603. def is_ftfy_available() -> Union[tuple[bool, str], bool]:
  604. return _ftfy_available
  605. def is_g2p_en_available() -> Union[tuple[bool, str], bool]:
  606. return _g2p_en_available
  607. @lru_cache
  608. def is_torch_xla_available(check_is_tpu=False, check_is_gpu=False) -> bool:
  609. """
  610. Check if `torch_xla` is available. To train a native pytorch job in an environment with torch xla installed, set
  611. the USE_TORCH_XLA to false.
  612. """
  613. assert not (check_is_tpu and check_is_gpu), "The check_is_tpu and check_is_gpu cannot both be true."
  614. if not _torch_xla_available:
  615. return False
  616. import torch_xla
  617. if check_is_gpu:
  618. return torch_xla.runtime.device_type() in ["GPU", "CUDA"]
  619. elif check_is_tpu:
  620. return torch_xla.runtime.device_type() == "TPU"
  621. return True
  622. @lru_cache
  623. def is_torch_neuroncore_available(check_device=True) -> bool:
  624. if importlib.util.find_spec("torch_neuronx") is not None:
  625. return is_torch_xla_available()
  626. return False
  627. @lru_cache
  628. def is_torch_npu_available(check_device=False) -> bool:
  629. "Checks if `torch_npu` is installed and potentially if a NPU is in the environment"
  630. if not _torch_available or importlib.util.find_spec("torch_npu") is None:
  631. return False
  632. import torch
  633. import torch_npu # noqa: F401
  634. if check_device:
  635. try:
  636. # Will raise a RuntimeError if no NPU is found
  637. _ = torch.npu.device_count()
  638. return torch.npu.is_available()
  639. except RuntimeError:
  640. return False
  641. return hasattr(torch, "npu") and torch.npu.is_available()
  642. @lru_cache
  643. def is_torch_mlu_available() -> bool:
  644. """
  645. Checks if `mlu` is available via an `cndev-based` check which won't trigger the drivers and leave mlu
  646. uninitialized.
  647. """
  648. if not _torch_available or importlib.util.find_spec("torch_mlu") is None:
  649. return False
  650. import torch
  651. import torch_mlu # noqa: F401
  652. pytorch_cndev_based_mlu_check_previous_value = os.environ.get("PYTORCH_CNDEV_BASED_MLU_CHECK")
  653. try:
  654. os.environ["PYTORCH_CNDEV_BASED_MLU_CHECK"] = str(1)
  655. available = torch.mlu.is_available()
  656. finally:
  657. if pytorch_cndev_based_mlu_check_previous_value:
  658. os.environ["PYTORCH_CNDEV_BASED_MLU_CHECK"] = pytorch_cndev_based_mlu_check_previous_value
  659. else:
  660. os.environ.pop("PYTORCH_CNDEV_BASED_MLU_CHECK", None)
  661. return available
  662. @lru_cache
  663. def is_torch_musa_available(check_device=False) -> bool:
  664. "Checks if `torch_musa` is installed and potentially if a MUSA is in the environment"
  665. if not _torch_available or importlib.util.find_spec("torch_musa") is None:
  666. return False
  667. import torch
  668. import torch_musa # noqa: F401
  669. torch_musa_min_version = "0.33.0"
  670. if _accelerate_available and version.parse(_accelerate_version) < version.parse(torch_musa_min_version):
  671. return False
  672. if check_device:
  673. try:
  674. # Will raise a RuntimeError if no MUSA is found
  675. _ = torch.musa.device_count()
  676. return torch.musa.is_available()
  677. except RuntimeError:
  678. return False
  679. return hasattr(torch, "musa") and torch.musa.is_available()
  680. @lru_cache
  681. def is_torch_hpu_available() -> bool:
  682. "Checks if `torch.hpu` is available and potentially if a HPU is in the environment"
  683. if (
  684. not _torch_available
  685. or importlib.util.find_spec("habana_frameworks") is None
  686. or importlib.util.find_spec("habana_frameworks.torch") is None
  687. ):
  688. return False
  689. torch_hpu_min_accelerate_version = "1.5.0"
  690. if _accelerate_available and version.parse(_accelerate_version) < version.parse(torch_hpu_min_accelerate_version):
  691. return False
  692. import torch
  693. if os.environ.get("PT_HPU_LAZY_MODE", "1") == "1":
  694. # import habana_frameworks.torch in case of lazy mode to patch torch with torch.hpu
  695. import habana_frameworks.torch # noqa: F401
  696. if not hasattr(torch, "hpu") or not torch.hpu.is_available():
  697. return False
  698. # We patch torch.gather for int64 tensors to avoid a bug on Gaudi
  699. # Graph compile failed with synStatus 26 [Generic failure]
  700. # This can be removed once bug is fixed but for now we need it.
  701. original_gather = torch.gather
  702. def patched_gather(input: torch.Tensor, dim: int, index: torch.LongTensor) -> torch.Tensor:
  703. if input.dtype == torch.int64 and input.device.type == "hpu":
  704. return original_gather(input.to(torch.int32), dim, index).to(torch.int64)
  705. else:
  706. return original_gather(input, dim, index)
  707. torch.gather = patched_gather
  708. torch.Tensor.gather = patched_gather
  709. original_take_along_dim = torch.take_along_dim
  710. def patched_take_along_dim(
  711. input: torch.Tensor, indices: torch.LongTensor, dim: Optional[int] = None
  712. ) -> torch.Tensor:
  713. if input.dtype == torch.int64 and input.device.type == "hpu":
  714. return original_take_along_dim(input.to(torch.int32), indices, dim).to(torch.int64)
  715. else:
  716. return original_take_along_dim(input, indices, dim)
  717. torch.take_along_dim = patched_take_along_dim
  718. original_cholesky = torch.linalg.cholesky
  719. def safe_cholesky(A, *args, **kwargs):
  720. output = original_cholesky(A, *args, **kwargs)
  721. if torch.isnan(output).any():
  722. jitter_value = 1e-9
  723. diag_jitter = torch.eye(A.size(-1), dtype=A.dtype, device=A.device) * jitter_value
  724. output = original_cholesky(A + diag_jitter, *args, **kwargs)
  725. return output
  726. torch.linalg.cholesky = safe_cholesky
  727. original_scatter = torch.scatter
  728. def patched_scatter(
  729. input: torch.Tensor, dim: int, index: torch.Tensor, src: torch.Tensor, *args, **kwargs
  730. ) -> torch.Tensor:
  731. if input.device.type == "hpu" and input is src:
  732. return original_scatter(input, dim, index, src.clone(), *args, **kwargs)
  733. else:
  734. return original_scatter(input, dim, index, src, *args, **kwargs)
  735. torch.scatter = patched_scatter
  736. torch.Tensor.scatter = patched_scatter
  737. # IlyasMoutawwakil: we patch torch.compile to use the HPU backend by default
  738. # https://github.com/huggingface/transformers/pull/38790#discussion_r2157043944
  739. # This is necessary for cases where torch.compile is used as a decorator (defaulting to inductor)
  740. # https://github.com/huggingface/transformers/blob/af6120b3eb2470b994c21421bb6eaa76576128b0/src/transformers/models/modernbert/modeling_modernbert.py#L204
  741. original_compile = torch.compile
  742. def hpu_backend_compile(*args, **kwargs):
  743. if kwargs.get("backend") not in ["hpu_backend", "eager"]:
  744. logger.warning(
  745. f"Calling torch.compile with backend={kwargs.get('backend')} on a Gaudi device is not supported. "
  746. "We will override the backend with 'hpu_backend' to avoid errors."
  747. )
  748. kwargs["backend"] = "hpu_backend"
  749. return original_compile(*args, **kwargs)
  750. torch.compile = hpu_backend_compile
  751. return True
  752. @lru_cache
  753. def is_habana_gaudi1() -> bool:
  754. if not is_torch_hpu_available():
  755. return False
  756. import habana_frameworks.torch.utils.experimental as htexp
  757. # Check if the device is Gaudi1 (vs Gaudi2, Gaudi3)
  758. return htexp._get_device_type() == htexp.synDeviceType.synDeviceGaudi
  759. def is_torchdynamo_available() -> Union[tuple[bool, str], bool]:
  760. return is_torch_available()
  761. def is_torch_compile_available() -> Union[tuple[bool, str], bool]:
  762. return is_torch_available()
  763. def is_torchdynamo_compiling() -> Union[tuple[bool, str], bool]:
  764. if not is_torch_available():
  765. return False
  766. # Importing torch._dynamo causes issues with PyTorch profiler (https://github.com/pytorch/pytorch/issues/130622)
  767. # hence rather relying on `torch.compiler.is_compiling()` when possible (torch>=2.3)
  768. try:
  769. import torch
  770. return torch.compiler.is_compiling()
  771. except Exception:
  772. try:
  773. import torch._dynamo as dynamo
  774. return dynamo.is_compiling()
  775. except Exception:
  776. return False
  777. def is_torchdynamo_exporting() -> bool:
  778. if not is_torch_available():
  779. return False
  780. try:
  781. import torch
  782. return torch.compiler.is_exporting()
  783. except Exception:
  784. try:
  785. import torch._dynamo as dynamo
  786. return dynamo.is_exporting()
  787. except Exception:
  788. return False
  789. def is_torch_tensorrt_fx_available() -> bool:
  790. if importlib.util.find_spec("torch_tensorrt") is None:
  791. return False
  792. return importlib.util.find_spec("torch_tensorrt.fx") is not None
  793. def is_datasets_available() -> Union[tuple[bool, str], bool]:
  794. return _datasets_available
  795. def is_detectron2_available() -> Union[tuple[bool, str], bool]:
  796. return _detectron2_available
  797. def is_rjieba_available() -> Union[tuple[bool, str], bool]:
  798. return _rjieba_available
  799. def is_psutil_available() -> Union[tuple[bool, str], bool]:
  800. return _psutil_available
  801. def is_py3nvml_available() -> Union[tuple[bool, str], bool]:
  802. return _py3nvml_available
  803. def is_sacremoses_available() -> Union[tuple[bool, str], bool]:
  804. return _sacremoses_available
  805. def is_apex_available() -> Union[tuple[bool, str], bool]:
  806. return _apex_available
  807. def is_aqlm_available() -> Union[tuple[bool, str], bool]:
  808. return _aqlm_available
  809. def is_vptq_available(min_version: str = VPTQ_MIN_VERSION) -> bool:
  810. return _vptq_available and version.parse(_vptq_version) >= version.parse(min_version)
  811. def is_av_available() -> bool:
  812. return _av_available
  813. def is_decord_available() -> bool:
  814. return _decord_available
  815. def is_torchcodec_available() -> bool:
  816. return _torchcodec_available
  817. def is_ninja_available() -> bool:
  818. r"""
  819. Code comes from *torch.utils.cpp_extension.is_ninja_available()*. Returns `True` if the
  820. [ninja](https://ninja-build.org/) build system is available on the system, `False` otherwise.
  821. """
  822. try:
  823. subprocess.check_output(["ninja", "--version"])
  824. except Exception:
  825. return False
  826. else:
  827. return True
  828. def is_ipex_available(min_version: str = "") -> bool:
  829. def get_major_and_minor_from_version(full_version):
  830. return str(version.parse(full_version).major) + "." + str(version.parse(full_version).minor)
  831. if not is_torch_available() or not _ipex_available:
  832. return False
  833. torch_major_and_minor = get_major_and_minor_from_version(_torch_version)
  834. ipex_major_and_minor = get_major_and_minor_from_version(_ipex_version)
  835. if torch_major_and_minor != ipex_major_and_minor:
  836. logger.warning(
  837. f"Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*,"
  838. f" but PyTorch {_torch_version} is found. Please switch to the matching version and run again."
  839. )
  840. return False
  841. if min_version:
  842. return version.parse(_ipex_version) >= version.parse(min_version)
  843. return True
  844. @lru_cache
  845. def is_torch_xpu_available(check_device: bool = False) -> bool:
  846. """
  847. Checks if XPU acceleration is available either via native PyTorch (>=2.6),
  848. `intel_extension_for_pytorch` or via stock PyTorch (>=2.4) and potentially
  849. if a XPU is in the environment.
  850. """
  851. if not is_torch_available():
  852. return False
  853. torch_version = version.parse(_torch_version)
  854. if torch_version.major == 2 and torch_version.minor < 6:
  855. if is_ipex_available():
  856. import intel_extension_for_pytorch # noqa: F401
  857. elif torch_version.major == 2 and torch_version.minor < 4:
  858. return False
  859. import torch
  860. if check_device:
  861. try:
  862. # Will raise a RuntimeError if no XPU is found
  863. _ = torch.xpu.device_count()
  864. return torch.xpu.is_available()
  865. except RuntimeError:
  866. return False
  867. return hasattr(torch, "xpu") and torch.xpu.is_available()
  868. @lru_cache
  869. def is_bitsandbytes_available(check_library_only: bool = False) -> bool:
  870. if not _bitsandbytes_available:
  871. return False
  872. if check_library_only:
  873. return True
  874. if not is_torch_available():
  875. return False
  876. import torch
  877. # `bitsandbytes` versions older than 0.43.1 eagerly require CUDA at import time,
  878. # so those versions of the library are practically only available when CUDA is too.
  879. if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.43.1"):
  880. return torch.cuda.is_available()
  881. # Newer versions of `bitsandbytes` can be imported on systems without CUDA.
  882. return True
  883. def is_bitsandbytes_multi_backend_available() -> bool:
  884. if not is_bitsandbytes_available():
  885. return False
  886. import bitsandbytes as bnb
  887. return "multi_backend" in getattr(bnb, "features", set())
  888. def is_flash_attn_2_available() -> bool:
  889. if not is_torch_available():
  890. return False
  891. if not _is_package_available("flash_attn"):
  892. return False
  893. # Let's add an extra check to see if cuda is available
  894. import torch
  895. if not (torch.cuda.is_available() or is_torch_mlu_available()):
  896. return False
  897. if torch.version.cuda:
  898. return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.1.0")
  899. elif torch.version.hip:
  900. # TODO: Bump the requirement to 2.1.0 once released in https://github.com/ROCmSoftwarePlatform/flash-attention
  901. return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.0.4")
  902. elif is_torch_mlu_available():
  903. return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.3.3")
  904. else:
  905. return False
  906. @lru_cache
  907. def is_flash_attn_3_available() -> bool:
  908. if not is_torch_available():
  909. return False
  910. if not _is_package_available("flash_attn_3"):
  911. return False
  912. import torch
  913. if not torch.cuda.is_available():
  914. return False
  915. # TODO: Check for a minimum version when FA3 is stable
  916. # return version.parse(importlib.metadata.version("flash_attn_3")) >= version.parse("3.0.0")
  917. return True
  918. @lru_cache
  919. def is_flash_attn_greater_or_equal_2_10() -> bool:
  920. if not _is_package_available("flash_attn"):
  921. return False
  922. return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.1.0")
  923. @lru_cache
  924. def is_flash_attn_greater_or_equal(library_version: str) -> bool:
  925. if not _is_package_available("flash_attn"):
  926. return False
  927. return version.parse(importlib.metadata.version("flash_attn")) >= version.parse(library_version)
  928. @lru_cache
  929. def is_torch_greater_or_equal(library_version: str, accept_dev: bool = False) -> bool:
  930. """
  931. Accepts a library version and returns True if the current version of the library is greater than or equal to the
  932. given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches
  933. 2.7.0).
  934. """
  935. if not _is_package_available("torch"):
  936. return False
  937. if accept_dev:
  938. return version.parse(version.parse(importlib.metadata.version("torch")).base_version) >= version.parse(
  939. library_version
  940. )
  941. else:
  942. return version.parse(importlib.metadata.version("torch")) >= version.parse(library_version)
  943. @lru_cache
  944. def is_torch_less_or_equal(library_version: str, accept_dev: bool = False) -> bool:
  945. """
  946. Accepts a library version and returns True if the current version of the library is less than or equal to the
  947. given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches
  948. 2.7.0).
  949. """
  950. if not _is_package_available("torch"):
  951. return False
  952. if accept_dev:
  953. return version.parse(version.parse(importlib.metadata.version("torch")).base_version) <= version.parse(
  954. library_version
  955. )
  956. else:
  957. return version.parse(importlib.metadata.version("torch")) <= version.parse(library_version)
  958. @lru_cache
  959. def is_huggingface_hub_greater_or_equal(library_version: str, accept_dev: bool = False) -> bool:
  960. if not _is_package_available("huggingface_hub"):
  961. return False
  962. if accept_dev:
  963. return version.parse(
  964. version.parse(importlib.metadata.version("huggingface_hub")).base_version
  965. ) >= version.parse(library_version)
  966. else:
  967. return version.parse(importlib.metadata.version("huggingface_hub")) >= version.parse(library_version)
  968. @lru_cache
  969. def is_quanto_greater(library_version: str, accept_dev: bool = False) -> bool:
  970. """
  971. Accepts a library version and returns True if the current version of the library is greater than or equal to the
  972. given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches
  973. 2.7.0).
  974. """
  975. if not _is_package_available("optimum.quanto"):
  976. return False
  977. if accept_dev:
  978. return version.parse(version.parse(importlib.metadata.version("optimum-quanto")).base_version) > version.parse(
  979. library_version
  980. )
  981. else:
  982. return version.parse(importlib.metadata.version("optimum-quanto")) > version.parse(library_version)
  983. def is_torchdistx_available():
  984. return _torchdistx_available
  985. def is_faiss_available() -> bool:
  986. return _faiss_available
  987. def is_scipy_available() -> Union[tuple[bool, str], bool]:
  988. return _scipy_available
  989. def is_sklearn_available() -> Union[tuple[bool, str], bool]:
  990. return _sklearn_available
  991. def is_sentencepiece_available() -> Union[tuple[bool, str], bool]:
  992. return _sentencepiece_available
  993. def is_seqio_available() -> Union[tuple[bool, str], bool]:
  994. return _is_seqio_available
  995. def is_gguf_available(min_version: str = GGUF_MIN_VERSION) -> bool:
  996. return _is_gguf_available and version.parse(_gguf_version) >= version.parse(min_version)
  997. def is_protobuf_available() -> bool:
  998. if importlib.util.find_spec("google") is None:
  999. return False
  1000. return importlib.util.find_spec("google.protobuf") is not None
  1001. def is_fsdp_available(min_version: str = FSDP_MIN_VERSION) -> bool:
  1002. return is_torch_available() and version.parse(_torch_version) >= version.parse(min_version)
  1003. def is_optimum_available() -> Union[tuple[bool, str], bool]:
  1004. return _optimum_available
  1005. def is_auto_awq_available() -> bool:
  1006. return _auto_awq_available
  1007. def is_auto_round_available(min_version: str = AUTOROUND_MIN_VERSION) -> bool:
  1008. return _auto_round_available and version.parse(_auto_round_version) >= version.parse(min_version)
  1009. def is_optimum_quanto_available():
  1010. # `importlib.metadata.version` doesn't work with `optimum.quanto`, need to put `optimum_quanto`
  1011. return _is_optimum_quanto_available
  1012. def is_quark_available() -> Union[tuple[bool, str], bool]:
  1013. return _quark_available
  1014. def is_fp_quant_available():
  1015. return _fp_quant_available and version.parse(_fp_quant_version) >= version.parse("0.2.0")
  1016. def is_qutlass_available():
  1017. return _qutlass_available and version.parse(_qutlass_version) >= version.parse("0.1.0")
  1018. def is_compressed_tensors_available() -> bool:
  1019. return _compressed_tensors_available
  1020. def is_auto_gptq_available() -> Union[tuple[bool, str], bool]:
  1021. return _auto_gptq_available
  1022. def is_gptqmodel_available() -> Union[tuple[bool, str], bool]:
  1023. return _gptqmodel_available
  1024. def is_eetq_available() -> Union[tuple[bool, str], bool]:
  1025. return _eetq_available
  1026. def is_fbgemm_gpu_available() -> Union[tuple[bool, str], bool]:
  1027. return _fbgemm_gpu_available
  1028. def is_levenshtein_available() -> Union[tuple[bool, str], bool]:
  1029. return _levenshtein_available
  1030. def is_optimum_neuron_available() -> Union[tuple[bool, str], bool]:
  1031. return _optimum_available and _is_package_available("optimum.neuron")
  1032. def is_safetensors_available() -> Union[tuple[bool, str], bool]:
  1033. return _safetensors_available
  1034. def is_tokenizers_available() -> Union[tuple[bool, str], bool]:
  1035. return _tokenizers_available
  1036. @lru_cache
  1037. def is_vision_available() -> bool:
  1038. _pil_available = importlib.util.find_spec("PIL") is not None
  1039. if _pil_available:
  1040. try:
  1041. package_version = importlib.metadata.version("Pillow")
  1042. except importlib.metadata.PackageNotFoundError:
  1043. try:
  1044. package_version = importlib.metadata.version("Pillow-SIMD")
  1045. except importlib.metadata.PackageNotFoundError:
  1046. return False
  1047. logger.debug(f"Detected PIL version {package_version}")
  1048. return _pil_available
  1049. def is_pytesseract_available() -> Union[tuple[bool, str], bool]:
  1050. return _pytesseract_available
  1051. def is_pytest_available() -> Union[tuple[bool, str], bool]:
  1052. return _pytest_available
  1053. def is_spacy_available() -> Union[tuple[bool, str], bool]:
  1054. return _spacy_available
  1055. def is_tensorflow_text_available() -> Union[tuple[bool, str], bool]:
  1056. return is_tf_available() and _tensorflow_text_available
  1057. def is_keras_nlp_available() -> Union[tuple[bool, str], bool]:
  1058. return is_tensorflow_text_available() and _keras_nlp_available
  1059. def is_in_notebook() -> bool:
  1060. try:
  1061. # Check if we are running inside Marimo
  1062. if "marimo" in sys.modules:
  1063. return True
  1064. # Test adapted from tqdm.autonotebook: https://github.com/tqdm/tqdm/blob/master/tqdm/autonotebook.py
  1065. get_ipython = sys.modules["IPython"].get_ipython
  1066. if "IPKernelApp" not in get_ipython().config:
  1067. raise ImportError("console")
  1068. # Removed the lines to include VSCode
  1069. if "DATABRICKS_RUNTIME_VERSION" in os.environ and os.environ["DATABRICKS_RUNTIME_VERSION"] < "11.0":
  1070. # Databricks Runtime 11.0 and above uses IPython kernel by default so it should be compatible with Jupyter notebook
  1071. # https://docs.microsoft.com/en-us/azure/databricks/notebooks/ipython-kernel
  1072. raise ImportError("databricks")
  1073. return importlib.util.find_spec("IPython") is not None
  1074. except (AttributeError, ImportError, KeyError):
  1075. return False
  1076. def is_pytorch_quantization_available() -> Union[tuple[bool, str], bool]:
  1077. return _pytorch_quantization_available
  1078. def is_tensorflow_probability_available() -> Union[tuple[bool, str], bool]:
  1079. return _tensorflow_probability_available
  1080. def is_pandas_available() -> Union[tuple[bool, str], bool]:
  1081. return _pandas_available
  1082. def is_sagemaker_dp_enabled() -> bool:
  1083. # Get the sagemaker specific env variable.
  1084. sagemaker_params = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
  1085. try:
  1086. # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
  1087. sagemaker_params = json.loads(sagemaker_params)
  1088. if not sagemaker_params.get("sagemaker_distributed_dataparallel_enabled", False):
  1089. return False
  1090. except json.JSONDecodeError:
  1091. return False
  1092. # Lastly, check if the `smdistributed` module is present.
  1093. return _smdistributed_available
  1094. def is_sagemaker_mp_enabled() -> bool:
  1095. # Get the sagemaker specific mp parameters from smp_options variable.
  1096. smp_options = os.getenv("SM_HP_MP_PARAMETERS", "{}")
  1097. try:
  1098. # Parse it and check the field "partitions" is included, it is required for model parallel.
  1099. smp_options = json.loads(smp_options)
  1100. if "partitions" not in smp_options:
  1101. return False
  1102. except json.JSONDecodeError:
  1103. return False
  1104. # Get the sagemaker specific framework parameters from mpi_options variable.
  1105. mpi_options = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
  1106. try:
  1107. # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
  1108. mpi_options = json.loads(mpi_options)
  1109. if not mpi_options.get("sagemaker_mpi_enabled", False):
  1110. return False
  1111. except json.JSONDecodeError:
  1112. return False
  1113. # Lastly, check if the `smdistributed` module is present.
  1114. return _smdistributed_available
  1115. def is_training_run_on_sagemaker() -> bool:
  1116. return "SAGEMAKER_JOB_NAME" in os.environ
  1117. def is_soundfile_available() -> Union[tuple[bool, str], bool]:
  1118. return _soundfile_available
  1119. def is_timm_available() -> Union[tuple[bool, str], bool]:
  1120. return _timm_available
  1121. def is_natten_available() -> Union[tuple[bool, str], bool]:
  1122. return _natten_available
  1123. def is_nltk_available() -> Union[tuple[bool, str], bool]:
  1124. return _nltk_available
  1125. def is_torchaudio_available() -> Union[tuple[bool, str], bool]:
  1126. return _torchaudio_available
  1127. def is_torchao_available(min_version: str = TORCHAO_MIN_VERSION) -> bool:
  1128. return _torchao_available and version.parse(_torchao_version) >= version.parse(min_version)
  1129. def is_speech_available() -> Union[tuple[bool, str], bool]:
  1130. # For now this depends on torchaudio but the exact dependency might evolve in the future.
  1131. return _torchaudio_available
  1132. def is_spqr_available() -> Union[tuple[bool, str], bool]:
  1133. return _spqr_available
  1134. def is_phonemizer_available() -> Union[tuple[bool, str], bool]:
  1135. return _phonemizer_available
  1136. def is_uroman_available() -> Union[tuple[bool, str], bool]:
  1137. return _uroman_available
  1138. def torch_only_method(fn: Callable) -> Callable:
  1139. def wrapper(*args, **kwargs):
  1140. if not _torch_available:
  1141. raise ImportError(
  1142. "You need to install pytorch to use this method or class, "
  1143. "or activate it with environment variables USE_TORCH=1 and USE_TF=0."
  1144. )
  1145. else:
  1146. return fn(*args, **kwargs)
  1147. return wrapper
  1148. def is_ccl_available() -> bool:
  1149. return _is_ccl_available
  1150. def is_sudachi_available() -> bool:
  1151. return _sudachipy_available
  1152. def get_sudachi_version() -> bool:
  1153. return _sudachipy_version
  1154. def is_sudachi_projection_available() -> bool:
  1155. if not is_sudachi_available():
  1156. return False
  1157. # NOTE: We require sudachipy>=0.6.8 to use projection option in sudachi_kwargs for the constructor of BertJapaneseTokenizer.
  1158. # - `projection` option is not supported in sudachipy<0.6.8, see https://github.com/WorksApplications/sudachi.rs/issues/230
  1159. return version.parse(_sudachipy_version) >= version.parse("0.6.8")
  1160. def is_jumanpp_available() -> bool:
  1161. return (importlib.util.find_spec("rhoknp") is not None) and (shutil.which("jumanpp") is not None)
  1162. def is_cython_available() -> bool:
  1163. return importlib.util.find_spec("pyximport") is not None
  1164. def is_jinja_available() -> Union[tuple[bool, str], bool]:
  1165. return _jinja_available
  1166. def is_mlx_available() -> Union[tuple[bool, str], bool]:
  1167. return _mlx_available
  1168. def is_num2words_available() -> Union[tuple[bool, str], bool]:
  1169. return _num2words_available
  1170. def is_tiktoken_available() -> Union[tuple[bool, str], bool]:
  1171. return _tiktoken_available and _blobfile_available
  1172. def is_liger_kernel_available() -> bool:
  1173. if not _liger_kernel_available:
  1174. return False
  1175. return version.parse(importlib.metadata.version("liger_kernel")) >= version.parse("0.3.0")
  1176. def is_rich_available() -> Union[tuple[bool, str], bool]:
  1177. return _rich_available
  1178. def is_matplotlib_available() -> Union[tuple[bool, str], bool]:
  1179. return _matplotlib_available
  1180. def is_mistral_common_available() -> Union[tuple[bool, str], bool]:
  1181. return _mistral_common_available
  1182. def check_torch_load_is_safe() -> None:
  1183. if not is_torch_greater_or_equal("2.6"):
  1184. raise ValueError(
  1185. "Due to a serious vulnerability issue in `torch.load`, even with `weights_only=True`, we now require users "
  1186. "to upgrade torch to at least v2.6 in order to use the function. This version restriction does not apply "
  1187. "when loading files with safetensors."
  1188. "\nSee the vulnerability report here https://nvd.nist.gov/vuln/detail/CVE-2025-32434"
  1189. )
  1190. # docstyle-ignore
  1191. AV_IMPORT_ERROR = """
  1192. {0} requires the PyAv library but it was not found in your environment. You can install it with:
  1193. ```
  1194. pip install av
  1195. ```
  1196. Please note that you may need to restart your runtime after installation.
  1197. """
  1198. # docstyle-ignore
  1199. YT_DLP_IMPORT_ERROR = """
  1200. {0} requires the YT-DLP library but it was not found in your environment. You can install it with:
  1201. ```
  1202. pip install yt-dlp
  1203. ```
  1204. Please note that you may need to restart your runtime after installation.
  1205. """
  1206. DECORD_IMPORT_ERROR = """
  1207. {0} requires the PyAv library but it was not found in your environment. You can install it with:
  1208. ```
  1209. pip install decord
  1210. ```
  1211. Please note that you may need to restart your runtime after installation.
  1212. """
  1213. TORCHCODEC_IMPORT_ERROR = """
  1214. {0} requires the TorchCodec (https://github.com/pytorch/torchcodec) library, but it was not found in your environment. You can install it with:
  1215. ```
  1216. pip install torchcodec
  1217. ```
  1218. Please note that you may need to restart your runtime after installation.
  1219. """
  1220. # docstyle-ignore
  1221. CV2_IMPORT_ERROR = """
  1222. {0} requires the OpenCV library but it was not found in your environment. You can install it with:
  1223. ```
  1224. pip install opencv-python
  1225. ```
  1226. Please note that you may need to restart your runtime after installation.
  1227. """
  1228. # docstyle-ignore
  1229. DATASETS_IMPORT_ERROR = """
  1230. {0} requires the 🤗 Datasets library but it was not found in your environment. You can install it with:
  1231. ```
  1232. pip install datasets
  1233. ```
  1234. In a notebook or a colab, you can install it by executing a cell with
  1235. ```
  1236. !pip install datasets
  1237. ```
  1238. then restarting your kernel.
  1239. Note that if you have a local folder named `datasets` or a local python file named `datasets.py` in your current
  1240. working directory, python may try to import this instead of the 🤗 Datasets library. You should rename this folder or
  1241. that python file if that's the case. Please note that you may need to restart your runtime after installation.
  1242. """
  1243. # docstyle-ignore
  1244. TOKENIZERS_IMPORT_ERROR = """
  1245. {0} requires the 🤗 Tokenizers library but it was not found in your environment. You can install it with:
  1246. ```
  1247. pip install tokenizers
  1248. ```
  1249. In a notebook or a colab, you can install it by executing a cell with
  1250. ```
  1251. !pip install tokenizers
  1252. ```
  1253. Please note that you may need to restart your runtime after installation.
  1254. """
  1255. # docstyle-ignore
  1256. SENTENCEPIECE_IMPORT_ERROR = """
  1257. {0} requires the SentencePiece library but it was not found in your environment. Check out the instructions on the
  1258. installation page of its repo: https://github.com/google/sentencepiece#installation and follow the ones
  1259. that match your environment. Please note that you may need to restart your runtime after installation.
  1260. """
  1261. # docstyle-ignore
  1262. PROTOBUF_IMPORT_ERROR = """
  1263. {0} requires the protobuf library but it was not found in your environment. Check out the instructions on the
  1264. installation page of its repo: https://github.com/protocolbuffers/protobuf/tree/master/python#installation and follow the ones
  1265. that match your environment. Please note that you may need to restart your runtime after installation.
  1266. """
  1267. # docstyle-ignore
  1268. FAISS_IMPORT_ERROR = """
  1269. {0} requires the faiss library but it was not found in your environment. Check out the instructions on the
  1270. installation page of its repo: https://github.com/facebookresearch/faiss/blob/master/INSTALL.md and follow the ones
  1271. that match your environment. Please note that you may need to restart your runtime after installation.
  1272. """
  1273. # docstyle-ignore
  1274. PYTORCH_IMPORT_ERROR = """
  1275. {0} requires the PyTorch library but it was not found in your environment. Check out the instructions on the
  1276. installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment.
  1277. Please note that you may need to restart your runtime after installation.
  1278. """
  1279. # docstyle-ignore
  1280. TORCHVISION_IMPORT_ERROR = """
  1281. {0} requires the Torchvision library but it was not found in your environment. Check out the instructions on the
  1282. installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment.
  1283. Please note that you may need to restart your runtime after installation.
  1284. """
  1285. # docstyle-ignore
  1286. PYTORCH_IMPORT_ERROR_WITH_TF = """
  1287. {0} requires the PyTorch library but it was not found in your environment.
  1288. However, we were able to find a TensorFlow installation. TensorFlow classes begin
  1289. with "TF", but are otherwise identically named to our PyTorch classes. This
  1290. means that the TF equivalent of the class you tried to import would be "TF{0}".
  1291. If you want to use TensorFlow, please use TF classes instead!
  1292. If you really do want to use PyTorch please go to
  1293. https://pytorch.org/get-started/locally/ and follow the instructions that
  1294. match your environment.
  1295. """
  1296. # docstyle-ignore
  1297. TF_IMPORT_ERROR_WITH_PYTORCH = """
  1298. {0} requires the TensorFlow library but it was not found in your environment.
  1299. However, we were able to find a PyTorch installation. PyTorch classes do not begin
  1300. with "TF", but are otherwise identically named to our TF classes.
  1301. If you want to use PyTorch, please use those classes instead!
  1302. If you really do want to use TensorFlow, please follow the instructions on the
  1303. installation page https://www.tensorflow.org/install that match your environment.
  1304. """
  1305. # docstyle-ignore
  1306. BS4_IMPORT_ERROR = """
  1307. {0} requires the Beautiful Soup library but it was not found in your environment. You can install it with pip:
  1308. `pip install beautifulsoup4`. Please note that you may need to restart your runtime after installation.
  1309. """
  1310. # docstyle-ignore
  1311. SKLEARN_IMPORT_ERROR = """
  1312. {0} requires the scikit-learn library but it was not found in your environment. You can install it with:
  1313. ```
  1314. pip install -U scikit-learn
  1315. ```
  1316. In a notebook or a colab, you can install it by executing a cell with
  1317. ```
  1318. !pip install -U scikit-learn
  1319. ```
  1320. Please note that you may need to restart your runtime after installation.
  1321. """
  1322. # docstyle-ignore
  1323. TENSORFLOW_IMPORT_ERROR = """
  1324. {0} requires the TensorFlow library but it was not found in your environment. Check out the instructions on the
  1325. installation page: https://www.tensorflow.org/install and follow the ones that match your environment.
  1326. Please note that you may need to restart your runtime after installation.
  1327. """
  1328. # docstyle-ignore
  1329. DETECTRON2_IMPORT_ERROR = """
  1330. {0} requires the detectron2 library but it was not found in your environment. Check out the instructions on the
  1331. installation page: https://github.com/facebookresearch/detectron2/blob/master/INSTALL.md and follow the ones
  1332. that match your environment. Please note that you may need to restart your runtime after installation.
  1333. """
  1334. # docstyle-ignore
  1335. FLAX_IMPORT_ERROR = """
  1336. {0} requires the FLAX library but it was not found in your environment. Check out the instructions on the
  1337. installation page: https://github.com/google/flax and follow the ones that match your environment.
  1338. Please note that you may need to restart your runtime after installation.
  1339. """
  1340. # docstyle-ignore
  1341. FTFY_IMPORT_ERROR = """
  1342. {0} requires the ftfy library but it was not found in your environment. Check out the instructions on the
  1343. installation section: https://github.com/rspeer/python-ftfy/tree/master#installing and follow the ones
  1344. that match your environment. Please note that you may need to restart your runtime after installation.
  1345. """
  1346. LEVENSHTEIN_IMPORT_ERROR = """
  1347. {0} requires the python-Levenshtein library but it was not found in your environment. You can install it with pip: `pip
  1348. install python-Levenshtein`. Please note that you may need to restart your runtime after installation.
  1349. """
  1350. # docstyle-ignore
  1351. G2P_EN_IMPORT_ERROR = """
  1352. {0} requires the g2p-en library but it was not found in your environment. You can install it with pip:
  1353. `pip install g2p-en`. Please note that you may need to restart your runtime after installation.
  1354. """
  1355. # docstyle-ignore
  1356. PYTORCH_QUANTIZATION_IMPORT_ERROR = """
  1357. {0} requires the pytorch-quantization library but it was not found in your environment. You can install it with pip:
  1358. `pip install pytorch-quantization --extra-index-url https://pypi.ngc.nvidia.com`
  1359. Please note that you may need to restart your runtime after installation.
  1360. """
  1361. # docstyle-ignore
  1362. TENSORFLOW_PROBABILITY_IMPORT_ERROR = """
  1363. {0} requires the tensorflow_probability library but it was not found in your environment. You can install it with pip as
  1364. explained here: https://github.com/tensorflow/probability. Please note that you may need to restart your runtime after installation.
  1365. """
  1366. # docstyle-ignore
  1367. TENSORFLOW_TEXT_IMPORT_ERROR = """
  1368. {0} requires the tensorflow_text library but it was not found in your environment. You can install it with pip as
  1369. explained here: https://www.tensorflow.org/text/guide/tf_text_intro.
  1370. Please note that you may need to restart your runtime after installation.
  1371. """
  1372. # docstyle-ignore
  1373. TORCHAUDIO_IMPORT_ERROR = """
  1374. {0} requires the torchaudio library but it was not found in your environment. Please install it and restart your
  1375. runtime.
  1376. """
  1377. # docstyle-ignore
  1378. PANDAS_IMPORT_ERROR = """
  1379. {0} requires the pandas library but it was not found in your environment. You can install it with pip as
  1380. explained here: https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html.
  1381. Please note that you may need to restart your runtime after installation.
  1382. """
  1383. # docstyle-ignore
  1384. PHONEMIZER_IMPORT_ERROR = """
  1385. {0} requires the phonemizer library but it was not found in your environment. You can install it with pip:
  1386. `pip install phonemizer`. Please note that you may need to restart your runtime after installation.
  1387. """
  1388. # docstyle-ignore
  1389. UROMAN_IMPORT_ERROR = """
  1390. {0} requires the uroman library but it was not found in your environment. You can install it with pip:
  1391. `pip install uroman`. Please note that you may need to restart your runtime after installation.
  1392. """
  1393. # docstyle-ignore
  1394. SACREMOSES_IMPORT_ERROR = """
  1395. {0} requires the sacremoses library but it was not found in your environment. You can install it with pip:
  1396. `pip install sacremoses`. Please note that you may need to restart your runtime after installation.
  1397. """
  1398. # docstyle-ignore
  1399. SCIPY_IMPORT_ERROR = """
  1400. {0} requires the scipy library but it was not found in your environment. You can install it with pip:
  1401. `pip install scipy`. Please note that you may need to restart your runtime after installation.
  1402. """
  1403. # docstyle-ignore
  1404. KERAS_NLP_IMPORT_ERROR = """
  1405. {0} requires the keras_nlp library but it was not found in your environment. You can install it with pip.
  1406. Please note that you may need to restart your runtime after installation.
  1407. """
  1408. # docstyle-ignore
  1409. SPEECH_IMPORT_ERROR = """
  1410. {0} requires the torchaudio library but it was not found in your environment. You can install it with pip:
  1411. `pip install torchaudio`. Please note that you may need to restart your runtime after installation.
  1412. """
  1413. # docstyle-ignore
  1414. TIMM_IMPORT_ERROR = """
  1415. {0} requires the timm library but it was not found in your environment. You can install it with pip:
  1416. `pip install timm`. Please note that you may need to restart your runtime after installation.
  1417. """
  1418. # docstyle-ignore
  1419. NATTEN_IMPORT_ERROR = """
  1420. {0} requires the natten library but it was not found in your environment. You can install it by referring to:
  1421. shi-labs.com/natten . You can also install it with pip (may take longer to build):
  1422. `pip install natten`. Please note that you may need to restart your runtime after installation.
  1423. """
  1424. NUMEXPR_IMPORT_ERROR = """
  1425. {0} requires the numexpr library but it was not found in your environment. You can install it by referring to:
  1426. https://numexpr.readthedocs.io/en/latest/index.html.
  1427. """
  1428. # docstyle-ignore
  1429. NLTK_IMPORT_ERROR = """
  1430. {0} requires the NLTK library but it was not found in your environment. You can install it by referring to:
  1431. https://www.nltk.org/install.html. Please note that you may need to restart your runtime after installation.
  1432. """
  1433. # docstyle-ignore
  1434. VISION_IMPORT_ERROR = """
  1435. {0} requires the PIL library but it was not found in your environment. You can install it with pip:
  1436. `pip install pillow`. Please note that you may need to restart your runtime after installation.
  1437. """
  1438. # docstyle-ignore
  1439. PYDANTIC_IMPORT_ERROR = """
  1440. {0} requires the pydantic library but it was not found in your environment. You can install it with pip:
  1441. `pip install pydantic`. Please note that you may need to restart your runtime after installation.
  1442. """
  1443. # docstyle-ignore
  1444. FASTAPI_IMPORT_ERROR = """
  1445. {0} requires the fastapi library but it was not found in your environment. You can install it with pip:
  1446. `pip install fastapi`. Please note that you may need to restart your runtime after installation.
  1447. """
  1448. # docstyle-ignore
  1449. UVICORN_IMPORT_ERROR = """
  1450. {0} requires the uvicorn library but it was not found in your environment. You can install it with pip:
  1451. `pip install uvicorn`. Please note that you may need to restart your runtime after installation.
  1452. """
  1453. # docstyle-ignore
  1454. OPENAI_IMPORT_ERROR = """
  1455. {0} requires the openai library but it was not found in your environment. You can install it with pip:
  1456. `pip install openai`. Please note that you may need to restart your runtime after installation.
  1457. """
  1458. # docstyle-ignore
  1459. PYTESSERACT_IMPORT_ERROR = """
  1460. {0} requires the PyTesseract library but it was not found in your environment. You can install it with pip:
  1461. `pip install pytesseract`. Please note that you may need to restart your runtime after installation.
  1462. """
  1463. # docstyle-ignore
  1464. PYCTCDECODE_IMPORT_ERROR = """
  1465. {0} requires the pyctcdecode library but it was not found in your environment. You can install it with pip:
  1466. `pip install pyctcdecode`. Please note that you may need to restart your runtime after installation.
  1467. """
  1468. # docstyle-ignore
  1469. ACCELERATE_IMPORT_ERROR = """
  1470. {0} requires the accelerate library >= {ACCELERATE_MIN_VERSION} it was not found in your environment.
  1471. You can install or update it with pip: `pip install --upgrade accelerate`. Please note that you may need to restart your
  1472. runtime after installation.
  1473. """
  1474. # docstyle-ignore
  1475. CCL_IMPORT_ERROR = """
  1476. {0} requires the torch ccl library but it was not found in your environment. You can install it with pip:
  1477. `pip install oneccl_bind_pt -f https://developer.intel.com/ipex-whl-stable`
  1478. Please note that you may need to restart your runtime after installation.
  1479. """
  1480. # docstyle-ignore
  1481. ESSENTIA_IMPORT_ERROR = """
  1482. {0} requires essentia library. But that was not found in your environment. You can install them with pip:
  1483. `pip install essentia==2.1b6.dev1034`
  1484. Please note that you may need to restart your runtime after installation.
  1485. """
  1486. # docstyle-ignore
  1487. LIBROSA_IMPORT_ERROR = """
  1488. {0} requires the librosa library. But that was not found in your environment. You can install them with pip:
  1489. `pip install librosa`
  1490. Please note that you may need to restart your runtime after installation.
  1491. """
  1492. # docstyle-ignore
  1493. PRETTY_MIDI_IMPORT_ERROR = """
  1494. {0} requires the pretty_midi library. But that was not found in your environment. You can install them with pip:
  1495. `pip install pretty_midi`
  1496. Please note that you may need to restart your runtime after installation.
  1497. """
  1498. CYTHON_IMPORT_ERROR = """
  1499. {0} requires the Cython library but it was not found in your environment. You can install it with pip: `pip install
  1500. Cython`. Please note that you may need to restart your runtime after installation.
  1501. """
  1502. RJIEBA_IMPORT_ERROR = """
  1503. {0} requires the rjieba library but it was not found in your environment. You can install it with pip: `pip install
  1504. rjieba`. Please note that you may need to restart your runtime after installation.
  1505. """
  1506. PEFT_IMPORT_ERROR = """
  1507. {0} requires the peft library but it was not found in your environment. You can install it with pip: `pip install
  1508. peft`. Please note that you may need to restart your runtime after installation.
  1509. """
  1510. JINJA_IMPORT_ERROR = """
  1511. {0} requires the jinja library but it was not found in your environment. You can install it with pip: `pip install
  1512. jinja2`. Please note that you may need to restart your runtime after installation.
  1513. """
  1514. RICH_IMPORT_ERROR = """
  1515. {0} requires the rich library but it was not found in your environment. You can install it with pip: `pip install
  1516. rich`. Please note that you may need to restart your runtime after installation.
  1517. """
  1518. MISTRAL_COMMON_IMPORT_ERROR = """
  1519. {0} requires the mistral-common library but it was not found in your environment. You can install it with pip: `pip install mistral-common`. Please note that you may need to restart your runtime after installation.
  1520. """
  1521. BACKENDS_MAPPING = OrderedDict(
  1522. [
  1523. ("av", (is_av_available, AV_IMPORT_ERROR)),
  1524. ("bs4", (is_bs4_available, BS4_IMPORT_ERROR)),
  1525. ("cv2", (is_cv2_available, CV2_IMPORT_ERROR)),
  1526. ("datasets", (is_datasets_available, DATASETS_IMPORT_ERROR)),
  1527. ("decord", (is_decord_available, DECORD_IMPORT_ERROR)),
  1528. ("detectron2", (is_detectron2_available, DETECTRON2_IMPORT_ERROR)),
  1529. ("essentia", (is_essentia_available, ESSENTIA_IMPORT_ERROR)),
  1530. ("faiss", (is_faiss_available, FAISS_IMPORT_ERROR)),
  1531. ("flax", (is_flax_available, FLAX_IMPORT_ERROR)),
  1532. ("ftfy", (is_ftfy_available, FTFY_IMPORT_ERROR)),
  1533. ("g2p_en", (is_g2p_en_available, G2P_EN_IMPORT_ERROR)),
  1534. ("pandas", (is_pandas_available, PANDAS_IMPORT_ERROR)),
  1535. ("phonemizer", (is_phonemizer_available, PHONEMIZER_IMPORT_ERROR)),
  1536. ("uroman", (is_uroman_available, UROMAN_IMPORT_ERROR)),
  1537. ("pretty_midi", (is_pretty_midi_available, PRETTY_MIDI_IMPORT_ERROR)),
  1538. ("levenshtein", (is_levenshtein_available, LEVENSHTEIN_IMPORT_ERROR)),
  1539. ("librosa", (is_librosa_available, LIBROSA_IMPORT_ERROR)),
  1540. ("protobuf", (is_protobuf_available, PROTOBUF_IMPORT_ERROR)),
  1541. ("pyctcdecode", (is_pyctcdecode_available, PYCTCDECODE_IMPORT_ERROR)),
  1542. ("pytesseract", (is_pytesseract_available, PYTESSERACT_IMPORT_ERROR)),
  1543. ("sacremoses", (is_sacremoses_available, SACREMOSES_IMPORT_ERROR)),
  1544. ("pytorch_quantization", (is_pytorch_quantization_available, PYTORCH_QUANTIZATION_IMPORT_ERROR)),
  1545. ("sentencepiece", (is_sentencepiece_available, SENTENCEPIECE_IMPORT_ERROR)),
  1546. ("sklearn", (is_sklearn_available, SKLEARN_IMPORT_ERROR)),
  1547. ("speech", (is_speech_available, SPEECH_IMPORT_ERROR)),
  1548. ("tensorflow_probability", (is_tensorflow_probability_available, TENSORFLOW_PROBABILITY_IMPORT_ERROR)),
  1549. ("tf", (is_tf_available, TENSORFLOW_IMPORT_ERROR)),
  1550. ("tensorflow_text", (is_tensorflow_text_available, TENSORFLOW_TEXT_IMPORT_ERROR)),
  1551. ("timm", (is_timm_available, TIMM_IMPORT_ERROR)),
  1552. ("torchaudio", (is_torchaudio_available, TORCHAUDIO_IMPORT_ERROR)),
  1553. ("natten", (is_natten_available, NATTEN_IMPORT_ERROR)),
  1554. ("nltk", (is_nltk_available, NLTK_IMPORT_ERROR)),
  1555. ("tokenizers", (is_tokenizers_available, TOKENIZERS_IMPORT_ERROR)),
  1556. ("torch", (is_torch_available, PYTORCH_IMPORT_ERROR)),
  1557. ("torchvision", (is_torchvision_available, TORCHVISION_IMPORT_ERROR)),
  1558. ("torchcodec", (is_torchcodec_available, TORCHCODEC_IMPORT_ERROR)),
  1559. ("vision", (is_vision_available, VISION_IMPORT_ERROR)),
  1560. ("scipy", (is_scipy_available, SCIPY_IMPORT_ERROR)),
  1561. ("accelerate", (is_accelerate_available, ACCELERATE_IMPORT_ERROR)),
  1562. ("oneccl_bind_pt", (is_ccl_available, CCL_IMPORT_ERROR)),
  1563. ("cython", (is_cython_available, CYTHON_IMPORT_ERROR)),
  1564. ("rjieba", (is_rjieba_available, RJIEBA_IMPORT_ERROR)),
  1565. ("peft", (is_peft_available, PEFT_IMPORT_ERROR)),
  1566. ("jinja", (is_jinja_available, JINJA_IMPORT_ERROR)),
  1567. ("yt_dlp", (is_yt_dlp_available, YT_DLP_IMPORT_ERROR)),
  1568. ("rich", (is_rich_available, RICH_IMPORT_ERROR)),
  1569. ("keras_nlp", (is_keras_nlp_available, KERAS_NLP_IMPORT_ERROR)),
  1570. ("pydantic", (is_pydantic_available, PYDANTIC_IMPORT_ERROR)),
  1571. ("fastapi", (is_fastapi_available, FASTAPI_IMPORT_ERROR)),
  1572. ("uvicorn", (is_uvicorn_available, UVICORN_IMPORT_ERROR)),
  1573. ("openai", (is_openai_available, OPENAI_IMPORT_ERROR)),
  1574. ("mistral-common", (is_mistral_common_available, MISTRAL_COMMON_IMPORT_ERROR)),
  1575. ]
  1576. )
  1577. def requires_backends(obj, backends):
  1578. if not isinstance(backends, (list, tuple)):
  1579. backends = [backends]
  1580. name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
  1581. # Raise an error for users who might not realize that classes without "TF" are torch-only
  1582. if "torch" in backends and "tf" not in backends and not is_torch_available() and is_tf_available():
  1583. raise ImportError(PYTORCH_IMPORT_ERROR_WITH_TF.format(name))
  1584. # Raise the inverse error for PyTorch users trying to load TF classes
  1585. if "tf" in backends and "torch" not in backends and is_torch_available() and not is_tf_available():
  1586. raise ImportError(TF_IMPORT_ERROR_WITH_PYTORCH.format(name))
  1587. failed = []
  1588. for backend in backends:
  1589. if isinstance(backend, Backend):
  1590. available, msg = backend.is_satisfied, backend.error_message
  1591. else:
  1592. available, msg = BACKENDS_MAPPING[backend]
  1593. if not available():
  1594. failed.append(msg.format(name))
  1595. if failed:
  1596. raise ImportError("".join(failed))
  1597. class DummyObject(type):
  1598. """
  1599. Metaclass for the dummy objects. Any class inheriting from it will return the ImportError generated by
  1600. `requires_backend` each time a user tries to access any method of that class.
  1601. """
  1602. is_dummy = True
  1603. def __getattribute__(cls, key):
  1604. if (key.startswith("_") and key != "_from_config") or key == "is_dummy" or key == "mro" or key == "call":
  1605. return super().__getattribute__(key)
  1606. requires_backends(cls, cls._backends)
  1607. def is_torch_fx_proxy(x):
  1608. if is_torch_fx_available():
  1609. import torch.fx
  1610. return isinstance(x, torch.fx.Proxy)
  1611. return False
  1612. BACKENDS_T = frozenset[str]
  1613. IMPORT_STRUCTURE_T = dict[BACKENDS_T, dict[str, set[str]]]
  1614. class _LazyModule(ModuleType):
  1615. """
  1616. Module class that surfaces all objects but only performs associated imports when the objects are requested.
  1617. """
  1618. # Very heavily inspired by optuna.integration._IntegrationModule
  1619. # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py
  1620. def __init__(
  1621. self,
  1622. name: str,
  1623. module_file: str,
  1624. import_structure: IMPORT_STRUCTURE_T,
  1625. module_spec: Optional[importlib.machinery.ModuleSpec] = None,
  1626. extra_objects: Optional[dict[str, object]] = None,
  1627. explicit_import_shortcut: Optional[dict[str, list[str]]] = None,
  1628. ):
  1629. super().__init__(name)
  1630. self._object_missing_backend = {}
  1631. self._explicit_import_shortcut = explicit_import_shortcut if explicit_import_shortcut else {}
  1632. if any(isinstance(key, frozenset) for key in import_structure):
  1633. self._modules = set()
  1634. self._class_to_module = {}
  1635. self.__all__ = []
  1636. _import_structure = {}
  1637. for backends, module in import_structure.items():
  1638. missing_backends = []
  1639. # This ensures that if a module is importable, then all other keys of the module are importable.
  1640. # As an example, in module.keys() we might have the following:
  1641. #
  1642. # dict_keys(['models.nllb_moe.configuration_nllb_moe', 'models.sew_d.configuration_sew_d'])
  1643. #
  1644. # with this, we don't only want to be able to import these explicitly, we want to be able to import
  1645. # every intermediate module as well. Therefore, this is what is returned:
  1646. #
  1647. # {
  1648. # 'models.nllb_moe.configuration_nllb_moe',
  1649. # 'models.sew_d.configuration_sew_d',
  1650. # 'models',
  1651. # 'models.sew_d', 'models.nllb_moe'
  1652. # }
  1653. module_keys = set(
  1654. chain(*[[k.rsplit(".", i)[0] for i in range(k.count(".") + 1)] for k in list(module.keys())])
  1655. )
  1656. for backend in backends:
  1657. if backend in BACKENDS_MAPPING:
  1658. callable, _ = BACKENDS_MAPPING[backend]
  1659. else:
  1660. if any(key in backend for key in ["=", "<", ">"]):
  1661. backend = Backend(backend)
  1662. callable = backend.is_satisfied
  1663. else:
  1664. raise ValueError(
  1665. f"Backend should be defined in the BACKENDS_MAPPING. Offending backend: {backend}"
  1666. )
  1667. try:
  1668. if not callable():
  1669. missing_backends.append(backend)
  1670. except (importlib.metadata.PackageNotFoundError, ModuleNotFoundError, RuntimeError):
  1671. missing_backends.append(backend)
  1672. self._modules = self._modules.union(module_keys)
  1673. for key, values in module.items():
  1674. if missing_backends:
  1675. self._object_missing_backend[key] = missing_backends
  1676. for value in values:
  1677. self._class_to_module[value] = key
  1678. if missing_backends:
  1679. self._object_missing_backend[value] = missing_backends
  1680. _import_structure.setdefault(key, []).extend(values)
  1681. # Needed for autocompletion in an IDE
  1682. self.__all__.extend(module_keys | set(chain(*module.values())))
  1683. self.__file__ = module_file
  1684. self.__spec__ = module_spec
  1685. self.__path__ = [os.path.dirname(module_file)]
  1686. self._objects = {} if extra_objects is None else extra_objects
  1687. self._name = name
  1688. self._import_structure = _import_structure
  1689. # This can be removed once every exportable object has a `require()` require.
  1690. else:
  1691. self._modules = set(import_structure.keys())
  1692. self._class_to_module = {}
  1693. for key, values in import_structure.items():
  1694. for value in values:
  1695. self._class_to_module[value] = key
  1696. # Needed for autocompletion in an IDE
  1697. self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values()))
  1698. self.__file__ = module_file
  1699. self.__spec__ = module_spec
  1700. self.__path__ = [os.path.dirname(module_file)]
  1701. self._objects = {} if extra_objects is None else extra_objects
  1702. self._name = name
  1703. self._import_structure = import_structure
  1704. # Needed for autocompletion in an IDE
  1705. def __dir__(self):
  1706. result = super().__dir__()
  1707. # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether
  1708. # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir.
  1709. for attr in self.__all__:
  1710. if attr not in result:
  1711. result.append(attr)
  1712. return result
  1713. def __getattr__(self, name: str) -> Any:
  1714. if name in self._objects:
  1715. return self._objects[name]
  1716. if name in self._object_missing_backend:
  1717. missing_backends = self._object_missing_backend[name]
  1718. class Placeholder(metaclass=DummyObject):
  1719. _backends = missing_backends
  1720. def __init__(self, *args, **kwargs):
  1721. requires_backends(self, missing_backends)
  1722. def call(self, *args, **kwargs):
  1723. pass
  1724. Placeholder.__name__ = name
  1725. if name not in self._class_to_module:
  1726. module_name = f"transformers.{name}"
  1727. else:
  1728. module_name = self._class_to_module[name]
  1729. if not module_name.startswith("transformers."):
  1730. module_name = f"transformers.{module_name}"
  1731. Placeholder.__module__ = module_name
  1732. value = Placeholder
  1733. elif name in self._class_to_module:
  1734. try:
  1735. module = self._get_module(self._class_to_module[name])
  1736. value = getattr(module, name)
  1737. except (ModuleNotFoundError, RuntimeError) as e:
  1738. raise ModuleNotFoundError(
  1739. f"Could not import module '{name}'. Are this object's requirements defined correctly?"
  1740. ) from e
  1741. elif name in self._modules:
  1742. try:
  1743. value = self._get_module(name)
  1744. except (ModuleNotFoundError, RuntimeError) as e:
  1745. raise ModuleNotFoundError(
  1746. f"Could not import module '{name}'. Are this object's requirements defined correctly?"
  1747. ) from e
  1748. else:
  1749. value = None
  1750. for key, values in self._explicit_import_shortcut.items():
  1751. if name in values:
  1752. value = self._get_module(key)
  1753. if value is None:
  1754. raise AttributeError(f"module {self.__name__} has no attribute {name}")
  1755. setattr(self, name, value)
  1756. return value
  1757. def _get_module(self, module_name: str):
  1758. try:
  1759. return importlib.import_module("." + module_name, self.__name__)
  1760. except Exception as e:
  1761. raise e
  1762. def __reduce__(self):
  1763. return (self.__class__, (self._name, self.__file__, self._import_structure))
  1764. class OptionalDependencyNotAvailable(BaseException):
  1765. """Internally used error class for signalling an optional dependency was not found."""
  1766. def direct_transformers_import(path: str, file="__init__.py") -> ModuleType:
  1767. """Imports transformers directly
  1768. Args:
  1769. path (`str`): The path to the source file
  1770. file (`str`, *optional*): The file to join with the path. Defaults to "__init__.py".
  1771. Returns:
  1772. `ModuleType`: The resulting imported module
  1773. """
  1774. name = "transformers"
  1775. location = os.path.join(path, file)
  1776. spec = importlib.util.spec_from_file_location(name, location, submodule_search_locations=[path])
  1777. module = importlib.util.module_from_spec(spec)
  1778. spec.loader.exec_module(module)
  1779. module = sys.modules[name]
  1780. return module
  1781. class VersionComparison(Enum):
  1782. EQUAL = operator.eq
  1783. NOT_EQUAL = operator.ne
  1784. GREATER_THAN = operator.gt
  1785. LESS_THAN = operator.lt
  1786. GREATER_THAN_OR_EQUAL = operator.ge
  1787. LESS_THAN_OR_EQUAL = operator.le
  1788. @staticmethod
  1789. def from_string(version_string: str) -> "VersionComparison":
  1790. string_to_operator = {
  1791. "=": VersionComparison.EQUAL.value,
  1792. "==": VersionComparison.EQUAL.value,
  1793. "!=": VersionComparison.NOT_EQUAL.value,
  1794. ">": VersionComparison.GREATER_THAN.value,
  1795. "<": VersionComparison.LESS_THAN.value,
  1796. ">=": VersionComparison.GREATER_THAN_OR_EQUAL.value,
  1797. "<=": VersionComparison.LESS_THAN_OR_EQUAL.value,
  1798. }
  1799. return string_to_operator[version_string]
  1800. @lru_cache
  1801. def split_package_version(package_version_str) -> tuple[str, str, str]:
  1802. pattern = r"([a-zA-Z0-9_-]+)([!<>=~]+)([0-9.]+)"
  1803. match = re.match(pattern, package_version_str)
  1804. if match:
  1805. return (match.group(1), match.group(2), match.group(3))
  1806. else:
  1807. raise ValueError(f"Invalid package version string: {package_version_str}")
  1808. class Backend:
  1809. def __init__(self, backend_requirement: str):
  1810. self.package_name, self.version_comparison, self.version = split_package_version(backend_requirement)
  1811. if self.package_name not in BACKENDS_MAPPING:
  1812. raise ValueError(
  1813. f"Backends should be defined in the BACKENDS_MAPPING. Offending backend: {self.package_name}"
  1814. )
  1815. def is_satisfied(self) -> bool:
  1816. return VersionComparison.from_string(self.version_comparison)(
  1817. version.parse(importlib.metadata.version(self.package_name)), version.parse(self.version)
  1818. )
  1819. def __repr__(self) -> str:
  1820. return f'Backend("{self.package_name}", {VersionComparison[self.version_comparison]}, "{self.version}")'
  1821. @property
  1822. def error_message(self):
  1823. return (
  1824. f"{{0}} requires the {self.package_name} library version {self.version_comparison}{self.version}. That"
  1825. f" library was not found with this version in your environment."
  1826. )
  1827. def requires(*, backends=()):
  1828. """
  1829. This decorator enables two things:
  1830. - Attaching a `__backends` tuple to an object to see what are the necessary backends for it
  1831. to execute correctly without instantiating it
  1832. - The '@requires' string is used to dynamically import objects
  1833. """
  1834. if not isinstance(backends, tuple):
  1835. raise TypeError("Backends should be a tuple.")
  1836. applied_backends = []
  1837. for backend in backends:
  1838. if backend in BACKENDS_MAPPING:
  1839. applied_backends.append(backend)
  1840. else:
  1841. if any(key in backend for key in ["=", "<", ">"]):
  1842. applied_backends.append(Backend(backend))
  1843. else:
  1844. raise ValueError(f"Backend should be defined in the BACKENDS_MAPPING. Offending backend: {backend}")
  1845. def inner_fn(fun):
  1846. fun.__backends = applied_backends
  1847. return fun
  1848. return inner_fn
  1849. BASE_FILE_REQUIREMENTS = {
  1850. lambda e: "modeling_tf_" in e: ("tf",),
  1851. lambda e: "modeling_flax_" in e: ("flax",),
  1852. lambda e: "modeling_" in e: ("torch",),
  1853. lambda e: e.startswith("tokenization_") and e.endswith("_fast"): ("tokenizers",),
  1854. lambda e: e.startswith("image_processing_") and e.endswith("_fast"): ("vision", "torch", "torchvision"),
  1855. lambda e: e.startswith("image_processing_"): ("vision",),
  1856. lambda e: e.startswith("video_processing_"): ("vision", "torch", "torchvision"),
  1857. }
  1858. def fetch__all__(file_content) -> list[str]:
  1859. """
  1860. Returns the content of the __all__ variable in the file content.
  1861. Returns None if not defined, otherwise returns a list of strings.
  1862. """
  1863. if "__all__" not in file_content:
  1864. return []
  1865. start_index = None
  1866. lines = file_content.splitlines()
  1867. for index, line in enumerate(lines):
  1868. if line.startswith("__all__"):
  1869. start_index = index
  1870. # There is no line starting with `__all__`
  1871. if start_index is None:
  1872. return []
  1873. lines = lines[start_index:]
  1874. if not lines[0].startswith("__all__"):
  1875. raise ValueError(
  1876. "fetch__all__ accepts a list of lines, with the first line being the __all__ variable declaration"
  1877. )
  1878. # __all__ is defined on a single line
  1879. if lines[0].endswith("]"):
  1880. return [obj.strip("\"' ") for obj in lines[0].split("=")[1].strip(" []").split(",")]
  1881. # __all__ is defined on multiple lines
  1882. else:
  1883. _all: list[str] = []
  1884. for __all__line_index in range(1, len(lines)):
  1885. if lines[__all__line_index].strip() == "]":
  1886. return _all
  1887. else:
  1888. _all.append(lines[__all__line_index].strip("\"', "))
  1889. return _all
  1890. @lru_cache
  1891. def create_import_structure_from_path(module_path):
  1892. """
  1893. This method takes the path to a file/a folder and returns the import structure.
  1894. If a file is given, it will return the import structure of the parent folder.
  1895. Import structures are designed to be digestible by `_LazyModule` objects. They are
  1896. created from the __all__ definitions in each files as well as the `@require` decorators
  1897. above methods and objects.
  1898. The import structure allows explicit display of the required backends for a given object.
  1899. These backends are specified in two ways:
  1900. 1. Through their `@require`, if they are exported with that decorator. This `@require` decorator
  1901. accepts a `backend` tuple kwarg mentioning which backends are required to run this object.
  1902. 2. If an object is defined in a file with "default" backends, it will have, at a minimum, this
  1903. backend specified. The default backends are defined according to the filename:
  1904. - If a file is named like `modeling_*.py`, it will have a `torch` backend
  1905. - If a file is named like `modeling_tf_*.py`, it will have a `tf` backend
  1906. - If a file is named like `modeling_flax_*.py`, it will have a `flax` backend
  1907. - If a file is named like `tokenization_*_fast.py`, it will have a `tokenizers` backend
  1908. - If a file is named like `image_processing*_fast.py`, it will have a `torchvision` + `torch` backend
  1909. Backends serve the purpose of displaying a clear error message to the user in case the backends are not installed.
  1910. Should an object be imported without its required backends being in the environment, any attempt to use the
  1911. object will raise an error mentioning which backend(s) should be added to the environment in order to use
  1912. that object.
  1913. Here's an example of an input import structure at the src.transformers.models level:
  1914. {
  1915. 'albert': {
  1916. frozenset(): {
  1917. 'configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'}
  1918. },
  1919. frozenset({'tokenizers'}): {
  1920. 'tokenization_albert_fast': {'AlbertTokenizerFast'}
  1921. },
  1922. },
  1923. 'align': {
  1924. frozenset(): {
  1925. 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
  1926. 'processing_align': {'AlignProcessor'}
  1927. },
  1928. },
  1929. 'altclip': {
  1930. frozenset(): {
  1931. 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
  1932. 'processing_altclip': {'AltCLIPProcessor'},
  1933. }
  1934. }
  1935. }
  1936. """
  1937. import_structure = {}
  1938. if os.path.isfile(module_path):
  1939. module_path = os.path.dirname(module_path)
  1940. directory = module_path
  1941. adjacent_modules = []
  1942. for f in os.listdir(module_path):
  1943. if f != "__pycache__" and os.path.isdir(os.path.join(module_path, f)):
  1944. import_structure[f] = create_import_structure_from_path(os.path.join(module_path, f))
  1945. elif not os.path.isdir(os.path.join(directory, f)):
  1946. adjacent_modules.append(f)
  1947. # We're only taking a look at files different from __init__.py
  1948. # We could theoretically require things directly from the __init__.py
  1949. # files, but this is not supported at this time.
  1950. if "__init__.py" in adjacent_modules:
  1951. adjacent_modules.remove("__init__.py")
  1952. # Modular files should not be imported
  1953. def find_substring(substring, list_):
  1954. return any(substring in x for x in list_)
  1955. if find_substring("modular_", adjacent_modules) and find_substring("modeling_", adjacent_modules):
  1956. adjacent_modules = [module for module in adjacent_modules if "modular_" not in module]
  1957. module_requirements = {}
  1958. for module_name in adjacent_modules:
  1959. # Only modules ending in `.py` are accepted here.
  1960. if not module_name.endswith(".py"):
  1961. continue
  1962. with open(os.path.join(directory, module_name), encoding="utf-8") as f:
  1963. file_content = f.read()
  1964. # Remove the .py suffix
  1965. module_name = module_name[:-3]
  1966. previous_line = ""
  1967. previous_index = 0
  1968. # Some files have some requirements by default.
  1969. # For example, any file named `modeling_tf_xxx.py`
  1970. # should have TensorFlow as a required backend.
  1971. base_requirements = ()
  1972. for string_check, requirements in BASE_FILE_REQUIREMENTS.items():
  1973. if string_check(module_name):
  1974. base_requirements = requirements
  1975. break
  1976. # Objects that have a `@require` assigned to them will get exported
  1977. # with the backends specified in the decorator as well as the file backends.
  1978. exported_objects = set()
  1979. if "@requires" in file_content:
  1980. lines = file_content.split("\n")
  1981. for index, line in enumerate(lines):
  1982. # This allows exporting items with other decorators. We'll take a look
  1983. # at the line that follows at the same indentation level.
  1984. if line.startswith((" ", "\t", "@", ")")) and not line.startswith("@requires"):
  1985. continue
  1986. # Skipping line enables putting whatever we want between the
  1987. # export() call and the actual class/method definition.
  1988. # This is what enables having # Copied from statements, docs, etc.
  1989. skip_line = False
  1990. if "@requires" in previous_line:
  1991. skip_line = False
  1992. # Backends are defined on the same line as export
  1993. if "backends" in previous_line:
  1994. backends_string = previous_line.split("backends=")[1].split("(")[1].split(")")[0]
  1995. backends = tuple(sorted([b.strip("'\",") for b in backends_string.split(", ") if b]))
  1996. # Backends are defined in the lines following export, for example such as:
  1997. # @export(
  1998. # backends=(
  1999. # "sentencepiece",
  2000. # "torch",
  2001. # "tf",
  2002. # )
  2003. # )
  2004. #
  2005. # or
  2006. #
  2007. # @export(
  2008. # backends=(
  2009. # "sentencepiece", "tf"
  2010. # )
  2011. # )
  2012. elif "backends" in lines[previous_index + 1]:
  2013. backends = []
  2014. for backend_line in lines[previous_index:index]:
  2015. if "backends" in backend_line:
  2016. backend_line = backend_line.split("=")[1]
  2017. if '"' in backend_line or "'" in backend_line:
  2018. if ", " in backend_line:
  2019. backends.extend(backend.strip("()\"', ") for backend in backend_line.split(", "))
  2020. else:
  2021. backends.append(backend_line.strip("()\"', "))
  2022. # If the line is only a ')', then we reached the end of the backends and we break.
  2023. if backend_line.strip() == ")":
  2024. break
  2025. backends = tuple(backends)
  2026. # No backends are registered for export
  2027. else:
  2028. backends = ()
  2029. backends = frozenset(backends + base_requirements)
  2030. if backends not in module_requirements:
  2031. module_requirements[backends] = {}
  2032. if module_name not in module_requirements[backends]:
  2033. module_requirements[backends][module_name] = set()
  2034. if not line.startswith("class") and not line.startswith("def"):
  2035. skip_line = True
  2036. else:
  2037. start_index = 6 if line.startswith("class") else 4
  2038. object_name = line[start_index:].split("(")[0].strip(":")
  2039. module_requirements[backends][module_name].add(object_name)
  2040. exported_objects.add(object_name)
  2041. if not skip_line:
  2042. previous_line = line
  2043. previous_index = index
  2044. # All objects that are in __all__ should be exported by default.
  2045. # These objects are exported with the file backends.
  2046. if "__all__" in file_content:
  2047. for _all_object in fetch__all__(file_content):
  2048. if _all_object not in exported_objects:
  2049. backends = frozenset(base_requirements)
  2050. if backends not in module_requirements:
  2051. module_requirements[backends] = {}
  2052. if module_name not in module_requirements[backends]:
  2053. module_requirements[backends][module_name] = set()
  2054. module_requirements[backends][module_name].add(_all_object)
  2055. import_structure = {**module_requirements, **import_structure}
  2056. return import_structure
  2057. def spread_import_structure(nested_import_structure):
  2058. """
  2059. This method takes as input an unordered import structure and brings the required backends at the top-level,
  2060. aggregating modules and objects under their required backends.
  2061. Here's an example of an input import structure at the src.transformers.models level:
  2062. {
  2063. 'albert': {
  2064. frozenset(): {
  2065. 'configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'}
  2066. },
  2067. frozenset({'tokenizers'}): {
  2068. 'tokenization_albert_fast': {'AlbertTokenizerFast'}
  2069. },
  2070. },
  2071. 'align': {
  2072. frozenset(): {
  2073. 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
  2074. 'processing_align': {'AlignProcessor'}
  2075. },
  2076. },
  2077. 'altclip': {
  2078. frozenset(): {
  2079. 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
  2080. 'processing_altclip': {'AltCLIPProcessor'},
  2081. }
  2082. }
  2083. }
  2084. Here's an example of an output import structure at the src.transformers.models level:
  2085. {
  2086. frozenset({'tokenizers'}): {
  2087. 'albert.tokenization_albert_fast': {'AlbertTokenizerFast'}
  2088. },
  2089. frozenset(): {
  2090. 'albert.configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'},
  2091. 'align.processing_align': {'AlignProcessor'},
  2092. 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
  2093. 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
  2094. 'altclip.processing_altclip': {'AltCLIPProcessor'}
  2095. }
  2096. }
  2097. """
  2098. def propagate_frozenset(unordered_import_structure):
  2099. frozenset_first_import_structure = {}
  2100. for _key, _value in unordered_import_structure.items():
  2101. # If the value is not a dict but a string, no need for custom manipulation
  2102. if not isinstance(_value, dict):
  2103. frozenset_first_import_structure[_key] = _value
  2104. elif any(isinstance(v, frozenset) for v in _value):
  2105. for k, v in _value.items():
  2106. if isinstance(k, frozenset):
  2107. # Here we want to switch around _key and k to propagate k upstream if it is a frozenset
  2108. if k not in frozenset_first_import_structure:
  2109. frozenset_first_import_structure[k] = {}
  2110. if _key not in frozenset_first_import_structure[k]:
  2111. frozenset_first_import_structure[k][_key] = {}
  2112. frozenset_first_import_structure[k][_key].update(v)
  2113. else:
  2114. # If k is not a frozenset, it means that the dictionary is not "level": some keys (top-level)
  2115. # are frozensets, whereas some are not -> frozenset keys are at an unknown depth-level of the
  2116. # dictionary.
  2117. #
  2118. # We recursively propagate the frozenset for this specific dictionary so that the frozensets
  2119. # are at the top-level when we handle them.
  2120. propagated_frozenset = propagate_frozenset({k: v})
  2121. for r_k, r_v in propagated_frozenset.items():
  2122. if isinstance(_key, frozenset):
  2123. if r_k not in frozenset_first_import_structure:
  2124. frozenset_first_import_structure[r_k] = {}
  2125. if _key not in frozenset_first_import_structure[r_k]:
  2126. frozenset_first_import_structure[r_k][_key] = {}
  2127. # _key is a frozenset -> we switch around the r_k and _key
  2128. frozenset_first_import_structure[r_k][_key].update(r_v)
  2129. else:
  2130. if _key not in frozenset_first_import_structure:
  2131. frozenset_first_import_structure[_key] = {}
  2132. if r_k not in frozenset_first_import_structure[_key]:
  2133. frozenset_first_import_structure[_key][r_k] = {}
  2134. # _key is not a frozenset -> we keep the order of r_k and _key
  2135. frozenset_first_import_structure[_key][r_k].update(r_v)
  2136. else:
  2137. frozenset_first_import_structure[_key] = propagate_frozenset(_value)
  2138. return frozenset_first_import_structure
  2139. def flatten_dict(_dict, previous_key=None):
  2140. items = []
  2141. for _key, _value in _dict.items():
  2142. _key = f"{previous_key}.{_key}" if previous_key is not None else _key
  2143. if isinstance(_value, dict):
  2144. items.extend(flatten_dict(_value, _key).items())
  2145. else:
  2146. items.append((_key, _value))
  2147. return dict(items)
  2148. # The tuples contain the necessary backends. We want these first, so we propagate them up the
  2149. # import structure.
  2150. ordered_import_structure = nested_import_structure
  2151. # 6 is a number that gives us sufficient depth to go through all files and foreseeable folder depths
  2152. # while not taking too long to parse.
  2153. for i in range(6):
  2154. ordered_import_structure = propagate_frozenset(ordered_import_structure)
  2155. # We then flatten the dict so that it references a module path.
  2156. flattened_import_structure = {}
  2157. for key, value in ordered_import_structure.copy().items():
  2158. if isinstance(key, str):
  2159. del ordered_import_structure[key]
  2160. else:
  2161. flattened_import_structure[key] = flatten_dict(value)
  2162. return flattened_import_structure
  2163. @lru_cache
  2164. def define_import_structure(module_path: str, prefix: Optional[str] = None) -> IMPORT_STRUCTURE_T:
  2165. """
  2166. This method takes a module_path as input and creates an import structure digestible by a _LazyModule.
  2167. Here's an example of an output import structure at the src.transformers.models level:
  2168. {
  2169. frozenset({'tokenizers'}): {
  2170. 'albert.tokenization_albert_fast': {'AlbertTokenizerFast'}
  2171. },
  2172. frozenset(): {
  2173. 'albert.configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'},
  2174. 'align.processing_align': {'AlignProcessor'},
  2175. 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
  2176. 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
  2177. 'altclip.processing_altclip': {'AltCLIPProcessor'}
  2178. }
  2179. }
  2180. The import structure is a dict defined with frozensets as keys, and dicts of strings to sets of objects.
  2181. If `prefix` is not None, it will add that prefix to all keys in the returned dict.
  2182. """
  2183. import_structure = create_import_structure_from_path(module_path)
  2184. spread_dict = spread_import_structure(import_structure)
  2185. if prefix is None:
  2186. return spread_dict
  2187. else:
  2188. spread_dict = {k: {f"{prefix}.{kk}": vv for kk, vv in v.items()} for k, v in spread_dict.items()}
  2189. return spread_dict
  2190. def clear_import_cache() -> None:
  2191. """
  2192. Clear cached Transformers modules to allow reloading modified code.
  2193. This is useful when actively developing/modifying Transformers code.
  2194. """
  2195. # Get all transformers modules
  2196. transformers_modules = [mod_name for mod_name in sys.modules if mod_name.startswith("transformers.")]
  2197. # Remove them from sys.modules
  2198. for mod_name in transformers_modules:
  2199. module = sys.modules[mod_name]
  2200. # Clear _LazyModule caches if applicable
  2201. if isinstance(module, _LazyModule):
  2202. module._objects = {} # Clear cached objects
  2203. del sys.modules[mod_name]
  2204. # Force reload main transformers module
  2205. if "transformers" in sys.modules:
  2206. main_module = sys.modules["transformers"]
  2207. if isinstance(main_module, _LazyModule):
  2208. main_module._objects = {} # Clear cached objects
  2209. importlib.reload(main_module)