import_utils.py 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198
  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 os
  22. import shutil
  23. import subprocess
  24. import sys
  25. import warnings
  26. from collections import OrderedDict
  27. from functools import lru_cache
  28. from itertools import chain
  29. from types import ModuleType
  30. from typing import Any, Dict, FrozenSet, Optional, Set, Tuple, Union
  31. from packaging import version
  32. from . import logging
  33. logger = logging.get_logger(__name__) # pylint: disable=invalid-name
  34. # TODO: This doesn't work for all packages (`bs4`, `faiss`, etc.) Talk to Sylvain to see how to do with it better.
  35. def _is_package_available(pkg_name: str, return_version: bool = False) -> Union[Tuple[bool, str], bool]:
  36. # Check if the package spec exists and grab its version to avoid importing a local directory
  37. package_exists = importlib.util.find_spec(pkg_name) is not None
  38. package_version = "N/A"
  39. if package_exists:
  40. try:
  41. # Primary method to get the package version
  42. package_version = importlib.metadata.version(pkg_name)
  43. except importlib.metadata.PackageNotFoundError:
  44. # Fallback method: Only for "torch" and versions containing "dev"
  45. if pkg_name == "torch":
  46. try:
  47. package = importlib.import_module(pkg_name)
  48. temp_version = getattr(package, "__version__", "N/A")
  49. # Check if the version contains "dev"
  50. if "dev" in temp_version:
  51. package_version = temp_version
  52. package_exists = True
  53. else:
  54. package_exists = False
  55. except ImportError:
  56. # If the package can't be imported, it's not available
  57. package_exists = False
  58. else:
  59. # For packages other than "torch", don't attempt the fallback and set as not available
  60. package_exists = False
  61. logger.debug(f"Detected {pkg_name} version: {package_version}")
  62. if return_version:
  63. return package_exists, package_version
  64. else:
  65. return package_exists
  66. ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}
  67. ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})
  68. USE_TF = os.environ.get("USE_TF", "AUTO").upper()
  69. USE_TORCH = os.environ.get("USE_TORCH", "AUTO").upper()
  70. USE_JAX = os.environ.get("USE_FLAX", "AUTO").upper()
  71. # Try to run a native pytorch job in an environment with TorchXLA installed by setting this value to 0.
  72. USE_TORCH_XLA = os.environ.get("USE_TORCH_XLA", "1").upper()
  73. FORCE_TF_AVAILABLE = os.environ.get("FORCE_TF_AVAILABLE", "AUTO").upper()
  74. # `transformers` requires `torch>=1.11` but this variable is exposed publicly, and we can't simply remove it.
  75. # This is the version of torch required to run torch.fx features and torch.onnx with dictionary inputs.
  76. TORCH_FX_REQUIRED_VERSION = version.parse("1.10")
  77. ACCELERATE_MIN_VERSION = "0.26.0"
  78. FSDP_MIN_VERSION = "1.12.0"
  79. GGUF_MIN_VERSION = "0.10.0"
  80. XLA_FSDPV2_MIN_VERSION = "2.2.0"
  81. HQQ_MIN_VERSION = "0.2.1"
  82. _accelerate_available, _accelerate_version = _is_package_available("accelerate", return_version=True)
  83. _apex_available = _is_package_available("apex")
  84. _aqlm_available = _is_package_available("aqlm")
  85. _av_available = importlib.util.find_spec("av") is not None
  86. _bitsandbytes_available = _is_package_available("bitsandbytes")
  87. _eetq_available = _is_package_available("eetq")
  88. _fbgemm_gpu_available = _is_package_available("fbgemm_gpu")
  89. _galore_torch_available = _is_package_available("galore_torch")
  90. _lomo_available = _is_package_available("lomo_optim")
  91. _grokadamw_available = _is_package_available("grokadamw")
  92. _schedulefree_available = _is_package_available("schedulefree")
  93. # `importlib.metadata.version` doesn't work with `bs4` but `beautifulsoup4`. For `importlib.util.find_spec`, reversed.
  94. _bs4_available = importlib.util.find_spec("bs4") is not None
  95. _coloredlogs_available = _is_package_available("coloredlogs")
  96. # `importlib.metadata.util` doesn't work with `opencv-python-headless`.
  97. _cv2_available = importlib.util.find_spec("cv2") is not None
  98. _datasets_available = _is_package_available("datasets")
  99. _detectron2_available = _is_package_available("detectron2")
  100. # We need to check both `faiss` and `faiss-cpu`.
  101. _faiss_available = importlib.util.find_spec("faiss") is not None
  102. try:
  103. _faiss_version = importlib.metadata.version("faiss")
  104. logger.debug(f"Successfully imported faiss version {_faiss_version}")
  105. except importlib.metadata.PackageNotFoundError:
  106. try:
  107. _faiss_version = importlib.metadata.version("faiss-cpu")
  108. logger.debug(f"Successfully imported faiss version {_faiss_version}")
  109. except importlib.metadata.PackageNotFoundError:
  110. _faiss_available = False
  111. _ftfy_available = _is_package_available("ftfy")
  112. _g2p_en_available = _is_package_available("g2p_en")
  113. _ipex_available, _ipex_version = _is_package_available("intel_extension_for_pytorch", return_version=True)
  114. _jieba_available = _is_package_available("jieba")
  115. _jinja_available = _is_package_available("jinja2")
  116. _kenlm_available = _is_package_available("kenlm")
  117. _keras_nlp_available = _is_package_available("keras_nlp")
  118. _levenshtein_available = _is_package_available("Levenshtein")
  119. _librosa_available = _is_package_available("librosa")
  120. _natten_available = _is_package_available("natten")
  121. _nltk_available = _is_package_available("nltk")
  122. _onnx_available = _is_package_available("onnx")
  123. _openai_available = _is_package_available("openai")
  124. _optimum_available = _is_package_available("optimum")
  125. _auto_gptq_available = _is_package_available("auto_gptq")
  126. # `importlib.metadata.version` doesn't work with `awq`
  127. _auto_awq_available = importlib.util.find_spec("awq") is not None
  128. _quanto_available = _is_package_available("quanto")
  129. _is_optimum_quanto_available = False
  130. try:
  131. importlib.metadata.version("optimum_quanto")
  132. _is_optimum_quanto_available = True
  133. except importlib.metadata.PackageNotFoundError:
  134. _is_optimum_quanto_available = False
  135. # For compressed_tensors, only check spec to allow compressed_tensors-nightly package
  136. _compressed_tensors_available = importlib.util.find_spec("compressed_tensors") is not None
  137. _pandas_available = _is_package_available("pandas")
  138. _peft_available = _is_package_available("peft")
  139. _phonemizer_available = _is_package_available("phonemizer")
  140. _uroman_available = _is_package_available("uroman")
  141. _psutil_available = _is_package_available("psutil")
  142. _py3nvml_available = _is_package_available("py3nvml")
  143. _pyctcdecode_available = _is_package_available("pyctcdecode")
  144. _pygments_available = _is_package_available("pygments")
  145. _pytesseract_available = _is_package_available("pytesseract")
  146. _pytest_available = _is_package_available("pytest")
  147. _pytorch_quantization_available = _is_package_available("pytorch_quantization")
  148. _rjieba_available = _is_package_available("rjieba")
  149. _sacremoses_available = _is_package_available("sacremoses")
  150. _safetensors_available = _is_package_available("safetensors")
  151. _scipy_available = _is_package_available("scipy")
  152. _sentencepiece_available = _is_package_available("sentencepiece")
  153. _is_seqio_available = _is_package_available("seqio")
  154. _is_gguf_available, _gguf_version = _is_package_available("gguf", return_version=True)
  155. _sklearn_available = importlib.util.find_spec("sklearn") is not None
  156. if _sklearn_available:
  157. try:
  158. importlib.metadata.version("scikit-learn")
  159. except importlib.metadata.PackageNotFoundError:
  160. _sklearn_available = False
  161. _smdistributed_available = importlib.util.find_spec("smdistributed") is not None
  162. _soundfile_available = _is_package_available("soundfile")
  163. _spacy_available = _is_package_available("spacy")
  164. _sudachipy_available, _sudachipy_version = _is_package_available("sudachipy", return_version=True)
  165. _tensorflow_probability_available = _is_package_available("tensorflow_probability")
  166. _tensorflow_text_available = _is_package_available("tensorflow_text")
  167. _tf2onnx_available = _is_package_available("tf2onnx")
  168. _timm_available = _is_package_available("timm")
  169. _tokenizers_available = _is_package_available("tokenizers")
  170. _torchaudio_available = _is_package_available("torchaudio")
  171. _torchao_available = _is_package_available("torchao")
  172. _torchdistx_available = _is_package_available("torchdistx")
  173. _torchvision_available, _torchvision_version = _is_package_available("torchvision", return_version=True)
  174. _mlx_available = _is_package_available("mlx")
  175. _hqq_available, _hqq_version = _is_package_available("hqq", return_version=True)
  176. _tiktoken_available = _is_package_available("tiktoken")
  177. _blobfile_available = _is_package_available("blobfile")
  178. _liger_kernel_available = _is_package_available("liger_kernel")
  179. _torch_version = "N/A"
  180. _torch_available = False
  181. if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
  182. _torch_available, _torch_version = _is_package_available("torch", return_version=True)
  183. else:
  184. logger.info("Disabling PyTorch because USE_TF is set")
  185. _torch_available = False
  186. _tf_version = "N/A"
  187. _tf_available = False
  188. if FORCE_TF_AVAILABLE in ENV_VARS_TRUE_VALUES:
  189. _tf_available = True
  190. else:
  191. if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
  192. # Note: _is_package_available("tensorflow") fails for tensorflow-cpu. Please test any changes to the line below
  193. # with tensorflow-cpu to make sure it still works!
  194. _tf_available = importlib.util.find_spec("tensorflow") is not None
  195. if _tf_available:
  196. candidates = (
  197. "tensorflow",
  198. "tensorflow-cpu",
  199. "tensorflow-gpu",
  200. "tf-nightly",
  201. "tf-nightly-cpu",
  202. "tf-nightly-gpu",
  203. "tf-nightly-rocm",
  204. "intel-tensorflow",
  205. "intel-tensorflow-avx512",
  206. "tensorflow-rocm",
  207. "tensorflow-macos",
  208. "tensorflow-aarch64",
  209. )
  210. _tf_version = None
  211. # For the metadata, we have to look for both tensorflow and tensorflow-cpu
  212. for pkg in candidates:
  213. try:
  214. _tf_version = importlib.metadata.version(pkg)
  215. break
  216. except importlib.metadata.PackageNotFoundError:
  217. pass
  218. _tf_available = _tf_version is not None
  219. if _tf_available:
  220. if version.parse(_tf_version) < version.parse("2"):
  221. logger.info(
  222. f"TensorFlow found but with version {_tf_version}. Transformers requires version 2 minimum."
  223. )
  224. _tf_available = False
  225. else:
  226. logger.info("Disabling Tensorflow because USE_TORCH is set")
  227. _essentia_available = importlib.util.find_spec("essentia") is not None
  228. try:
  229. _essentia_version = importlib.metadata.version("essentia")
  230. logger.debug(f"Successfully imported essentia version {_essentia_version}")
  231. except importlib.metadata.PackageNotFoundError:
  232. _essentia_version = False
  233. _pretty_midi_available = importlib.util.find_spec("pretty_midi") is not None
  234. try:
  235. _pretty_midi_version = importlib.metadata.version("pretty_midi")
  236. logger.debug(f"Successfully imported pretty_midi version {_pretty_midi_version}")
  237. except importlib.metadata.PackageNotFoundError:
  238. _pretty_midi_available = False
  239. ccl_version = "N/A"
  240. _is_ccl_available = (
  241. importlib.util.find_spec("torch_ccl") is not None
  242. or importlib.util.find_spec("oneccl_bindings_for_pytorch") is not None
  243. )
  244. try:
  245. ccl_version = importlib.metadata.version("oneccl_bind_pt")
  246. logger.debug(f"Detected oneccl_bind_pt version {ccl_version}")
  247. except importlib.metadata.PackageNotFoundError:
  248. _is_ccl_available = False
  249. _flax_available = False
  250. if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
  251. _flax_available, _flax_version = _is_package_available("flax", return_version=True)
  252. if _flax_available:
  253. _jax_available, _jax_version = _is_package_available("jax", return_version=True)
  254. if _jax_available:
  255. logger.info(f"JAX version {_jax_version}, Flax version {_flax_version} available.")
  256. else:
  257. _flax_available = _jax_available = False
  258. _jax_version = _flax_version = "N/A"
  259. _torch_fx_available = False
  260. if _torch_available:
  261. torch_version = version.parse(_torch_version)
  262. _torch_fx_available = (torch_version.major, torch_version.minor) >= (
  263. TORCH_FX_REQUIRED_VERSION.major,
  264. TORCH_FX_REQUIRED_VERSION.minor,
  265. )
  266. _torch_xla_available = False
  267. if USE_TORCH_XLA in ENV_VARS_TRUE_VALUES:
  268. _torch_xla_available, _torch_xla_version = _is_package_available("torch_xla", return_version=True)
  269. if _torch_xla_available:
  270. logger.info(f"Torch XLA version {_torch_xla_version} available.")
  271. def is_kenlm_available():
  272. return _kenlm_available
  273. def is_cv2_available():
  274. return _cv2_available
  275. def is_torch_available():
  276. return _torch_available
  277. def is_accelerate_available(min_version: str = ACCELERATE_MIN_VERSION):
  278. return _accelerate_available and version.parse(_accelerate_version) >= version.parse(min_version)
  279. def is_torch_deterministic():
  280. """
  281. Check whether pytorch uses deterministic algorithms by looking if torch.set_deterministic_debug_mode() is set to 1 or 2"
  282. """
  283. import torch
  284. if torch.get_deterministic_debug_mode() == 0:
  285. return False
  286. else:
  287. return True
  288. def is_hqq_available(min_version: str = HQQ_MIN_VERSION):
  289. return _hqq_available and version.parse(_hqq_version) >= version.parse(min_version)
  290. def is_pygments_available():
  291. return _pygments_available
  292. def get_torch_version():
  293. return _torch_version
  294. def is_torch_sdpa_available():
  295. if not is_torch_available():
  296. return False
  297. elif _torch_version == "N/A":
  298. return False
  299. # NOTE: We require torch>=2.1 (and not torch>=2.0) to use SDPA in Transformers for two reasons:
  300. # - Allow the global use of the `scale` argument introduced in https://github.com/pytorch/pytorch/pull/95259
  301. # - Memory-efficient attention supports arbitrary attention_mask: https://github.com/pytorch/pytorch/pull/104310
  302. # NOTE: MLU is OK with non-contiguous inputs.
  303. if is_torch_mlu_available():
  304. return version.parse(_torch_version) >= version.parse("2.1.0")
  305. # NOTE: We require torch>=2.1.1 to avoid a numerical issue in SDPA with non-contiguous inputs: https://github.com/pytorch/pytorch/issues/112577
  306. return version.parse(_torch_version) >= version.parse("2.1.1")
  307. def is_torchvision_available():
  308. return _torchvision_available
  309. def is_torchvision_v2_available():
  310. if not is_torchvision_available():
  311. return False
  312. # NOTE: We require torchvision>=0.15 as v2 transforms are available from this version: https://pytorch.org/vision/stable/transforms.html#v1-or-v2-which-one-should-i-use
  313. return version.parse(_torchvision_version) >= version.parse("0.15")
  314. def is_galore_torch_available():
  315. return _galore_torch_available
  316. def is_lomo_available():
  317. return _lomo_available
  318. def is_grokadamw_available():
  319. return _grokadamw_available
  320. def is_schedulefree_available():
  321. return _schedulefree_available
  322. def is_pyctcdecode_available():
  323. return _pyctcdecode_available
  324. def is_librosa_available():
  325. return _librosa_available
  326. def is_essentia_available():
  327. return _essentia_available
  328. def is_pretty_midi_available():
  329. return _pretty_midi_available
  330. def is_torch_cuda_available():
  331. if is_torch_available():
  332. import torch
  333. return torch.cuda.is_available()
  334. else:
  335. return False
  336. def is_mamba_ssm_available():
  337. if is_torch_available():
  338. import torch
  339. if not torch.cuda.is_available():
  340. return False
  341. else:
  342. return _is_package_available("mamba_ssm")
  343. return False
  344. def is_mamba_2_ssm_available():
  345. if is_torch_available():
  346. import torch
  347. if not torch.cuda.is_available():
  348. return False
  349. else:
  350. if _is_package_available("mamba_ssm"):
  351. import mamba_ssm
  352. if version.parse(mamba_ssm.__version__) >= version.parse("2.0.4"):
  353. return True
  354. return False
  355. def is_causal_conv1d_available():
  356. if is_torch_available():
  357. import torch
  358. if not torch.cuda.is_available():
  359. return False
  360. return _is_package_available("causal_conv1d")
  361. return False
  362. def is_mambapy_available():
  363. if is_torch_available():
  364. return _is_package_available("mambapy")
  365. return False
  366. def is_torch_mps_available(min_version: Optional[str] = None):
  367. if is_torch_available():
  368. import torch
  369. if hasattr(torch.backends, "mps"):
  370. backend_available = torch.backends.mps.is_available() and torch.backends.mps.is_built()
  371. if min_version is not None:
  372. flag = version.parse(_torch_version) >= version.parse(min_version)
  373. backend_available = backend_available and flag
  374. return backend_available
  375. return False
  376. def is_torch_bf16_gpu_available():
  377. if not is_torch_available():
  378. return False
  379. import torch
  380. return torch.cuda.is_available() and torch.cuda.is_bf16_supported()
  381. def is_torch_bf16_cpu_available():
  382. if not is_torch_available():
  383. return False
  384. import torch
  385. try:
  386. # multiple levels of AttributeError depending on the pytorch version so do them all in one check
  387. _ = torch.cpu.amp.autocast
  388. except AttributeError:
  389. return False
  390. return True
  391. def is_torch_bf16_available():
  392. # the original bf16 check was for gpu only, but later a cpu/bf16 combo has emerged so this util
  393. # has become ambiguous and therefore deprecated
  394. warnings.warn(
  395. "The util is_torch_bf16_available is deprecated, please use is_torch_bf16_gpu_available "
  396. "or is_torch_bf16_cpu_available instead according to whether it's used with cpu or gpu",
  397. FutureWarning,
  398. )
  399. return is_torch_bf16_gpu_available()
  400. @lru_cache()
  401. def is_torch_fp16_available_on_device(device):
  402. if not is_torch_available():
  403. return False
  404. import torch
  405. try:
  406. x = torch.zeros(2, 2, dtype=torch.float16).to(device)
  407. _ = x @ x
  408. # At this moment, let's be strict of the check: check if `LayerNorm` is also supported on device, because many
  409. # models use this layer.
  410. batch, sentence_length, embedding_dim = 3, 4, 5
  411. embedding = torch.randn(batch, sentence_length, embedding_dim, dtype=torch.float16, device=device)
  412. layer_norm = torch.nn.LayerNorm(embedding_dim, dtype=torch.float16, device=device)
  413. _ = layer_norm(embedding)
  414. except: # noqa: E722
  415. # TODO: more precise exception matching, if possible.
  416. # most backends should return `RuntimeError` however this is not guaranteed.
  417. return False
  418. return True
  419. @lru_cache()
  420. def is_torch_bf16_available_on_device(device):
  421. if not is_torch_available():
  422. return False
  423. import torch
  424. if device == "cuda":
  425. return is_torch_bf16_gpu_available()
  426. try:
  427. x = torch.zeros(2, 2, dtype=torch.bfloat16).to(device)
  428. _ = x @ x
  429. except: # noqa: E722
  430. # TODO: more precise exception matching, if possible.
  431. # most backends should return `RuntimeError` however this is not guaranteed.
  432. return False
  433. return True
  434. def is_torch_tf32_available():
  435. if not is_torch_available():
  436. return False
  437. import torch
  438. if not torch.cuda.is_available() or torch.version.cuda is None:
  439. return False
  440. if torch.cuda.get_device_properties(torch.cuda.current_device()).major < 8:
  441. return False
  442. if int(torch.version.cuda.split(".")[0]) < 11:
  443. return False
  444. if version.parse(version.parse(torch.__version__).base_version) < version.parse("1.7"):
  445. return False
  446. return True
  447. def is_torch_fx_available():
  448. return _torch_fx_available
  449. def is_peft_available():
  450. return _peft_available
  451. def is_bs4_available():
  452. return _bs4_available
  453. def is_tf_available():
  454. return _tf_available
  455. def is_coloredlogs_available():
  456. return _coloredlogs_available
  457. def is_tf2onnx_available():
  458. return _tf2onnx_available
  459. def is_onnx_available():
  460. return _onnx_available
  461. def is_openai_available():
  462. return _openai_available
  463. def is_flax_available():
  464. return _flax_available
  465. def is_ftfy_available():
  466. return _ftfy_available
  467. def is_g2p_en_available():
  468. return _g2p_en_available
  469. @lru_cache()
  470. def is_torch_tpu_available(check_device=True):
  471. "Checks if `torch_xla` is installed and potentially if a TPU is in the environment"
  472. warnings.warn(
  473. "`is_torch_tpu_available` is deprecated and will be removed in 4.41.0. "
  474. "Please use the `is_torch_xla_available` instead.",
  475. FutureWarning,
  476. )
  477. if not _torch_available:
  478. return False
  479. if importlib.util.find_spec("torch_xla") is not None:
  480. if check_device:
  481. # We need to check if `xla_device` can be found, will raise a RuntimeError if not
  482. try:
  483. import torch_xla.core.xla_model as xm
  484. _ = xm.xla_device()
  485. return True
  486. except RuntimeError:
  487. return False
  488. return True
  489. return False
  490. @lru_cache
  491. def is_torch_xla_available(check_is_tpu=False, check_is_gpu=False):
  492. """
  493. Check if `torch_xla` is available. To train a native pytorch job in an environment with torch xla installed, set
  494. the USE_TORCH_XLA to false.
  495. """
  496. assert not (check_is_tpu and check_is_gpu), "The check_is_tpu and check_is_gpu cannot both be true."
  497. if not _torch_xla_available:
  498. return False
  499. import torch_xla
  500. if check_is_gpu:
  501. return torch_xla.runtime.device_type() in ["GPU", "CUDA"]
  502. elif check_is_tpu:
  503. return torch_xla.runtime.device_type() == "TPU"
  504. return True
  505. @lru_cache()
  506. def is_torch_neuroncore_available(check_device=True):
  507. if importlib.util.find_spec("torch_neuronx") is not None:
  508. return is_torch_xla_available()
  509. return False
  510. @lru_cache()
  511. def is_torch_npu_available(check_device=False):
  512. "Checks if `torch_npu` is installed and potentially if a NPU is in the environment"
  513. if not _torch_available or importlib.util.find_spec("torch_npu") is None:
  514. return False
  515. import torch
  516. import torch_npu # noqa: F401
  517. if check_device:
  518. try:
  519. # Will raise a RuntimeError if no NPU is found
  520. _ = torch.npu.device_count()
  521. return torch.npu.is_available()
  522. except RuntimeError:
  523. return False
  524. return hasattr(torch, "npu") and torch.npu.is_available()
  525. @lru_cache()
  526. def is_torch_mlu_available(check_device=False):
  527. "Checks if `torch_mlu` is installed and potentially if a MLU is in the environment"
  528. if not _torch_available or importlib.util.find_spec("torch_mlu") is None:
  529. return False
  530. import torch
  531. import torch_mlu # noqa: F401
  532. from ..dependency_versions_table import deps
  533. deps["deepspeed"] = "deepspeed-mlu>=0.10.1"
  534. if check_device:
  535. try:
  536. # Will raise a RuntimeError if no MLU is found
  537. _ = torch.mlu.device_count()
  538. return torch.mlu.is_available()
  539. except RuntimeError:
  540. return False
  541. return hasattr(torch, "mlu") and torch.mlu.is_available()
  542. @lru_cache()
  543. def is_torch_musa_available(check_device=False):
  544. "Checks if `torch_musa` is installed and potentially if a MUSA is in the environment"
  545. if not _torch_available or importlib.util.find_spec("torch_musa") is None:
  546. return False
  547. import torch
  548. import torch_musa # noqa: F401
  549. torch_musa_min_version = "0.33.0"
  550. if _accelerate_available and version.parse(_accelerate_version) < version.parse(torch_musa_min_version):
  551. return False
  552. if check_device:
  553. try:
  554. # Will raise a RuntimeError if no MUSA is found
  555. _ = torch.musa.device_count()
  556. return torch.musa.is_available()
  557. except RuntimeError:
  558. return False
  559. return hasattr(torch, "musa") and torch.musa.is_available()
  560. def is_torchdynamo_available():
  561. if not is_torch_available():
  562. return False
  563. return version.parse(_torch_version) >= version.parse("2.0.0")
  564. def is_torch_compile_available():
  565. if not is_torch_available():
  566. return False
  567. import torch
  568. # We don't do any version check here to support nighlies marked as 1.14. Ultimately needs to check version against
  569. # 2.0 but let's do it later.
  570. return hasattr(torch, "compile")
  571. def is_torchdynamo_compiling():
  572. if not is_torch_available():
  573. return False
  574. # Importing torch._dynamo causes issues with PyTorch profiler (https://github.com/pytorch/pytorch/issues/130622)
  575. # hence rather relying on `torch.compiler.is_compiling()` when possible (torch>=2.3)
  576. try:
  577. import torch
  578. return torch.compiler.is_compiling()
  579. except Exception:
  580. try:
  581. import torch._dynamo as dynamo # noqa: F401
  582. return dynamo.is_compiling()
  583. except Exception:
  584. return False
  585. def is_torch_tensorrt_fx_available():
  586. if importlib.util.find_spec("torch_tensorrt") is None:
  587. return False
  588. return importlib.util.find_spec("torch_tensorrt.fx") is not None
  589. def is_datasets_available():
  590. return _datasets_available
  591. def is_detectron2_available():
  592. return _detectron2_available
  593. def is_rjieba_available():
  594. return _rjieba_available
  595. def is_psutil_available():
  596. return _psutil_available
  597. def is_py3nvml_available():
  598. return _py3nvml_available
  599. def is_sacremoses_available():
  600. return _sacremoses_available
  601. def is_apex_available():
  602. return _apex_available
  603. def is_aqlm_available():
  604. return _aqlm_available
  605. def is_av_available():
  606. return _av_available
  607. def is_ninja_available():
  608. r"""
  609. Code comes from *torch.utils.cpp_extension.is_ninja_available()*. Returns `True` if the
  610. [ninja](https://ninja-build.org/) build system is available on the system, `False` otherwise.
  611. """
  612. try:
  613. subprocess.check_output("ninja --version".split())
  614. except Exception:
  615. return False
  616. else:
  617. return True
  618. def is_ipex_available():
  619. def get_major_and_minor_from_version(full_version):
  620. return str(version.parse(full_version).major) + "." + str(version.parse(full_version).minor)
  621. if not is_torch_available() or not _ipex_available:
  622. return False
  623. torch_major_and_minor = get_major_and_minor_from_version(_torch_version)
  624. ipex_major_and_minor = get_major_and_minor_from_version(_ipex_version)
  625. if torch_major_and_minor != ipex_major_and_minor:
  626. logger.warning(
  627. f"Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*,"
  628. f" but PyTorch {_torch_version} is found. Please switch to the matching version and run again."
  629. )
  630. return False
  631. return True
  632. @lru_cache
  633. def is_torch_xpu_available(check_device=False):
  634. """
  635. Checks if XPU acceleration is available either via `intel_extension_for_pytorch` or
  636. via stock PyTorch (>=2.4) and potentially if a XPU is in the environment
  637. """
  638. if not is_torch_available():
  639. return False
  640. torch_version = version.parse(_torch_version)
  641. if is_ipex_available():
  642. import intel_extension_for_pytorch # noqa: F401
  643. elif torch_version.major < 2 or (torch_version.major == 2 and torch_version.minor < 4):
  644. return False
  645. import torch
  646. if check_device:
  647. try:
  648. # Will raise a RuntimeError if no XPU is found
  649. _ = torch.xpu.device_count()
  650. return torch.xpu.is_available()
  651. except RuntimeError:
  652. return False
  653. return hasattr(torch, "xpu") and torch.xpu.is_available()
  654. @lru_cache()
  655. def is_bitsandbytes_available():
  656. if not is_torch_available() or not _bitsandbytes_available:
  657. return False
  658. import torch
  659. # `bitsandbytes` versions older than 0.43.1 eagerly require CUDA at import time,
  660. # so those versions of the library are practically only available when CUDA is too.
  661. if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.43.1"):
  662. return torch.cuda.is_available()
  663. # Newer versions of `bitsandbytes` can be imported on systems without CUDA.
  664. return True
  665. def is_bitsandbytes_multi_backend_available() -> bool:
  666. if not is_bitsandbytes_available():
  667. return False
  668. import bitsandbytes as bnb
  669. return "multi_backend" in getattr(bnb, "features", set())
  670. def is_flash_attn_2_available():
  671. if not is_torch_available():
  672. return False
  673. if not _is_package_available("flash_attn"):
  674. return False
  675. # Let's add an extra check to see if cuda is available
  676. import torch
  677. if not (torch.cuda.is_available() or is_torch_mlu_available()):
  678. return False
  679. if torch.version.cuda:
  680. return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.1.0")
  681. elif torch.version.hip:
  682. # TODO: Bump the requirement to 2.1.0 once released in https://github.com/ROCmSoftwarePlatform/flash-attention
  683. return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.0.4")
  684. elif is_torch_mlu_available():
  685. return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.3.3")
  686. else:
  687. return False
  688. def is_flash_attn_greater_or_equal_2_10():
  689. if not _is_package_available("flash_attn"):
  690. return False
  691. return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.1.0")
  692. @lru_cache()
  693. def is_flash_attn_greater_or_equal(library_version: str):
  694. if not _is_package_available("flash_attn"):
  695. return False
  696. return version.parse(importlib.metadata.version("flash_attn")) >= version.parse(library_version)
  697. def is_torchdistx_available():
  698. return _torchdistx_available
  699. def is_faiss_available():
  700. return _faiss_available
  701. def is_scipy_available():
  702. return _scipy_available
  703. def is_sklearn_available():
  704. return _sklearn_available
  705. def is_sentencepiece_available():
  706. return _sentencepiece_available
  707. def is_seqio_available():
  708. return _is_seqio_available
  709. def is_gguf_available(min_version: str = GGUF_MIN_VERSION):
  710. return _is_gguf_available and version.parse(_gguf_version) >= version.parse(min_version)
  711. def is_protobuf_available():
  712. if importlib.util.find_spec("google") is None:
  713. return False
  714. return importlib.util.find_spec("google.protobuf") is not None
  715. def is_fsdp_available(min_version: str = FSDP_MIN_VERSION):
  716. return is_torch_available() and version.parse(_torch_version) >= version.parse(min_version)
  717. def is_optimum_available():
  718. return _optimum_available
  719. def is_auto_awq_available():
  720. return _auto_awq_available
  721. def is_quanto_available():
  722. logger.warning_once(
  723. "Importing from quanto will be deprecated in v4.47. Please install optimum-quanto instrad `pip install optimum-quanto`"
  724. )
  725. return _quanto_available
  726. def is_optimum_quanto_available():
  727. # `importlib.metadata.version` doesn't work with `optimum.quanto`, need to put `optimum_quanto`
  728. return _is_optimum_quanto_available
  729. def is_compressed_tensors_available():
  730. return _compressed_tensors_available
  731. def is_auto_gptq_available():
  732. return _auto_gptq_available
  733. def is_eetq_available():
  734. return _eetq_available
  735. def is_fbgemm_gpu_available():
  736. return _fbgemm_gpu_available
  737. def is_levenshtein_available():
  738. return _levenshtein_available
  739. def is_optimum_neuron_available():
  740. return _optimum_available and _is_package_available("optimum.neuron")
  741. def is_safetensors_available():
  742. return _safetensors_available
  743. def is_tokenizers_available():
  744. return _tokenizers_available
  745. @lru_cache
  746. def is_vision_available():
  747. _pil_available = importlib.util.find_spec("PIL") is not None
  748. if _pil_available:
  749. try:
  750. package_version = importlib.metadata.version("Pillow")
  751. except importlib.metadata.PackageNotFoundError:
  752. try:
  753. package_version = importlib.metadata.version("Pillow-SIMD")
  754. except importlib.metadata.PackageNotFoundError:
  755. return False
  756. logger.debug(f"Detected PIL version {package_version}")
  757. return _pil_available
  758. def is_pytesseract_available():
  759. return _pytesseract_available
  760. def is_pytest_available():
  761. return _pytest_available
  762. def is_spacy_available():
  763. return _spacy_available
  764. def is_tensorflow_text_available():
  765. return is_tf_available() and _tensorflow_text_available
  766. def is_keras_nlp_available():
  767. return is_tensorflow_text_available() and _keras_nlp_available
  768. def is_in_notebook():
  769. try:
  770. # Test adapted from tqdm.autonotebook: https://github.com/tqdm/tqdm/blob/master/tqdm/autonotebook.py
  771. get_ipython = sys.modules["IPython"].get_ipython
  772. if "IPKernelApp" not in get_ipython().config:
  773. raise ImportError("console")
  774. if "VSCODE_PID" in os.environ:
  775. raise ImportError("vscode")
  776. if "DATABRICKS_RUNTIME_VERSION" in os.environ and os.environ["DATABRICKS_RUNTIME_VERSION"] < "11.0":
  777. # Databricks Runtime 11.0 and above uses IPython kernel by default so it should be compatible with Jupyter notebook
  778. # https://docs.microsoft.com/en-us/azure/databricks/notebooks/ipython-kernel
  779. raise ImportError("databricks")
  780. return importlib.util.find_spec("IPython") is not None
  781. except (AttributeError, ImportError, KeyError):
  782. return False
  783. def is_pytorch_quantization_available():
  784. return _pytorch_quantization_available
  785. def is_tensorflow_probability_available():
  786. return _tensorflow_probability_available
  787. def is_pandas_available():
  788. return _pandas_available
  789. def is_sagemaker_dp_enabled():
  790. # Get the sagemaker specific env variable.
  791. sagemaker_params = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
  792. try:
  793. # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
  794. sagemaker_params = json.loads(sagemaker_params)
  795. if not sagemaker_params.get("sagemaker_distributed_dataparallel_enabled", False):
  796. return False
  797. except json.JSONDecodeError:
  798. return False
  799. # Lastly, check if the `smdistributed` module is present.
  800. return _smdistributed_available
  801. def is_sagemaker_mp_enabled():
  802. # Get the sagemaker specific mp parameters from smp_options variable.
  803. smp_options = os.getenv("SM_HP_MP_PARAMETERS", "{}")
  804. try:
  805. # Parse it and check the field "partitions" is included, it is required for model parallel.
  806. smp_options = json.loads(smp_options)
  807. if "partitions" not in smp_options:
  808. return False
  809. except json.JSONDecodeError:
  810. return False
  811. # Get the sagemaker specific framework parameters from mpi_options variable.
  812. mpi_options = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
  813. try:
  814. # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
  815. mpi_options = json.loads(mpi_options)
  816. if not mpi_options.get("sagemaker_mpi_enabled", False):
  817. return False
  818. except json.JSONDecodeError:
  819. return False
  820. # Lastly, check if the `smdistributed` module is present.
  821. return _smdistributed_available
  822. def is_training_run_on_sagemaker():
  823. return "SAGEMAKER_JOB_NAME" in os.environ
  824. def is_soundfile_availble():
  825. return _soundfile_available
  826. def is_timm_available():
  827. return _timm_available
  828. def is_natten_available():
  829. return _natten_available
  830. def is_nltk_available():
  831. return _nltk_available
  832. def is_torchaudio_available():
  833. return _torchaudio_available
  834. def is_torchao_available():
  835. return _torchao_available
  836. def is_speech_available():
  837. # For now this depends on torchaudio but the exact dependency might evolve in the future.
  838. return _torchaudio_available
  839. def is_phonemizer_available():
  840. return _phonemizer_available
  841. def is_uroman_available():
  842. return _uroman_available
  843. def torch_only_method(fn):
  844. def wrapper(*args, **kwargs):
  845. if not _torch_available:
  846. raise ImportError(
  847. "You need to install pytorch to use this method or class, "
  848. "or activate it with environment variables USE_TORCH=1 and USE_TF=0."
  849. )
  850. else:
  851. return fn(*args, **kwargs)
  852. return wrapper
  853. def is_ccl_available():
  854. return _is_ccl_available
  855. def is_sudachi_available():
  856. return _sudachipy_available
  857. def get_sudachi_version():
  858. return _sudachipy_version
  859. def is_sudachi_projection_available():
  860. if not is_sudachi_available():
  861. return False
  862. # NOTE: We require sudachipy>=0.6.8 to use projection option in sudachi_kwargs for the constructor of BertJapaneseTokenizer.
  863. # - `projection` option is not supported in sudachipy<0.6.8, see https://github.com/WorksApplications/sudachi.rs/issues/230
  864. return version.parse(_sudachipy_version) >= version.parse("0.6.8")
  865. def is_jumanpp_available():
  866. return (importlib.util.find_spec("rhoknp") is not None) and (shutil.which("jumanpp") is not None)
  867. def is_cython_available():
  868. return importlib.util.find_spec("pyximport") is not None
  869. def is_jieba_available():
  870. return _jieba_available
  871. def is_jinja_available():
  872. return _jinja_available
  873. def is_mlx_available():
  874. return _mlx_available
  875. def is_tiktoken_available():
  876. return _tiktoken_available and _blobfile_available
  877. def is_liger_kernel_available():
  878. if not _liger_kernel_available:
  879. return False
  880. return version.parse(importlib.metadata.version("liger_kernel")) >= version.parse("0.3.0")
  881. # docstyle-ignore
  882. AV_IMPORT_ERROR = """
  883. {0} requires the PyAv library but it was not found in your environment. You can install it with:
  884. ```
  885. pip install av
  886. ```
  887. Please note that you may need to restart your runtime after installation.
  888. """
  889. # docstyle-ignore
  890. CV2_IMPORT_ERROR = """
  891. {0} requires the OpenCV library but it was not found in your environment. You can install it with:
  892. ```
  893. pip install opencv-python
  894. ```
  895. Please note that you may need to restart your runtime after installation.
  896. """
  897. # docstyle-ignore
  898. DATASETS_IMPORT_ERROR = """
  899. {0} requires the 🤗 Datasets library but it was not found in your environment. You can install it with:
  900. ```
  901. pip install datasets
  902. ```
  903. In a notebook or a colab, you can install it by executing a cell with
  904. ```
  905. !pip install datasets
  906. ```
  907. then restarting your kernel.
  908. Note that if you have a local folder named `datasets` or a local python file named `datasets.py` in your current
  909. working directory, python may try to import this instead of the 🤗 Datasets library. You should rename this folder or
  910. that python file if that's the case. Please note that you may need to restart your runtime after installation.
  911. """
  912. # docstyle-ignore
  913. TOKENIZERS_IMPORT_ERROR = """
  914. {0} requires the 🤗 Tokenizers library but it was not found in your environment. You can install it with:
  915. ```
  916. pip install tokenizers
  917. ```
  918. In a notebook or a colab, you can install it by executing a cell with
  919. ```
  920. !pip install tokenizers
  921. ```
  922. Please note that you may need to restart your runtime after installation.
  923. """
  924. # docstyle-ignore
  925. SENTENCEPIECE_IMPORT_ERROR = """
  926. {0} requires the SentencePiece library but it was not found in your environment. Checkout the instructions on the
  927. installation page of its repo: https://github.com/google/sentencepiece#installation and follow the ones
  928. that match your environment. Please note that you may need to restart your runtime after installation.
  929. """
  930. # docstyle-ignore
  931. PROTOBUF_IMPORT_ERROR = """
  932. {0} requires the protobuf library but it was not found in your environment. Checkout the instructions on the
  933. installation page of its repo: https://github.com/protocolbuffers/protobuf/tree/master/python#installation and follow the ones
  934. that match your environment. Please note that you may need to restart your runtime after installation.
  935. """
  936. # docstyle-ignore
  937. FAISS_IMPORT_ERROR = """
  938. {0} requires the faiss library but it was not found in your environment. Checkout the instructions on the
  939. installation page of its repo: https://github.com/facebookresearch/faiss/blob/master/INSTALL.md and follow the ones
  940. that match your environment. Please note that you may need to restart your runtime after installation.
  941. """
  942. # docstyle-ignore
  943. PYTORCH_IMPORT_ERROR = """
  944. {0} requires the PyTorch library but it was not found in your environment. Checkout the instructions on the
  945. installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment.
  946. Please note that you may need to restart your runtime after installation.
  947. """
  948. # docstyle-ignore
  949. TORCHVISION_IMPORT_ERROR = """
  950. {0} requires the Torchvision library but it was not found in your environment. Checkout the instructions on the
  951. installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment.
  952. Please note that you may need to restart your runtime after installation.
  953. """
  954. # docstyle-ignore
  955. PYTORCH_IMPORT_ERROR_WITH_TF = """
  956. {0} requires the PyTorch library but it was not found in your environment.
  957. However, we were able to find a TensorFlow installation. TensorFlow classes begin
  958. with "TF", but are otherwise identically named to our PyTorch classes. This
  959. means that the TF equivalent of the class you tried to import would be "TF{0}".
  960. If you want to use TensorFlow, please use TF classes instead!
  961. If you really do want to use PyTorch please go to
  962. https://pytorch.org/get-started/locally/ and follow the instructions that
  963. match your environment.
  964. """
  965. # docstyle-ignore
  966. TF_IMPORT_ERROR_WITH_PYTORCH = """
  967. {0} requires the TensorFlow library but it was not found in your environment.
  968. However, we were able to find a PyTorch installation. PyTorch classes do not begin
  969. with "TF", but are otherwise identically named to our TF classes.
  970. If you want to use PyTorch, please use those classes instead!
  971. If you really do want to use TensorFlow, please follow the instructions on the
  972. installation page https://www.tensorflow.org/install that match your environment.
  973. """
  974. # docstyle-ignore
  975. BS4_IMPORT_ERROR = """
  976. {0} requires the Beautiful Soup library but it was not found in your environment. You can install it with pip:
  977. `pip install beautifulsoup4`. Please note that you may need to restart your runtime after installation.
  978. """
  979. # docstyle-ignore
  980. SKLEARN_IMPORT_ERROR = """
  981. {0} requires the scikit-learn library but it was not found in your environment. You can install it with:
  982. ```
  983. pip install -U scikit-learn
  984. ```
  985. In a notebook or a colab, you can install it by executing a cell with
  986. ```
  987. !pip install -U scikit-learn
  988. ```
  989. Please note that you may need to restart your runtime after installation.
  990. """
  991. # docstyle-ignore
  992. TENSORFLOW_IMPORT_ERROR = """
  993. {0} requires the TensorFlow library but it was not found in your environment. Checkout the instructions on the
  994. installation page: https://www.tensorflow.org/install and follow the ones that match your environment.
  995. Please note that you may need to restart your runtime after installation.
  996. """
  997. # docstyle-ignore
  998. DETECTRON2_IMPORT_ERROR = """
  999. {0} requires the detectron2 library but it was not found in your environment. Checkout the instructions on the
  1000. installation page: https://github.com/facebookresearch/detectron2/blob/master/INSTALL.md and follow the ones
  1001. that match your environment. Please note that you may need to restart your runtime after installation.
  1002. """
  1003. # docstyle-ignore
  1004. FLAX_IMPORT_ERROR = """
  1005. {0} requires the FLAX library but it was not found in your environment. Checkout the instructions on the
  1006. installation page: https://github.com/google/flax and follow the ones that match your environment.
  1007. Please note that you may need to restart your runtime after installation.
  1008. """
  1009. # docstyle-ignore
  1010. FTFY_IMPORT_ERROR = """
  1011. {0} requires the ftfy library but it was not found in your environment. Checkout the instructions on the
  1012. installation section: https://github.com/rspeer/python-ftfy/tree/master#installing and follow the ones
  1013. that match your environment. Please note that you may need to restart your runtime after installation.
  1014. """
  1015. LEVENSHTEIN_IMPORT_ERROR = """
  1016. {0} requires the python-Levenshtein library but it was not found in your environment. You can install it with pip: `pip
  1017. install python-Levenshtein`. Please note that you may need to restart your runtime after installation.
  1018. """
  1019. # docstyle-ignore
  1020. G2P_EN_IMPORT_ERROR = """
  1021. {0} requires the g2p-en library but it was not found in your environment. You can install it with pip:
  1022. `pip install g2p-en`. Please note that you may need to restart your runtime after installation.
  1023. """
  1024. # docstyle-ignore
  1025. PYTORCH_QUANTIZATION_IMPORT_ERROR = """
  1026. {0} requires the pytorch-quantization library but it was not found in your environment. You can install it with pip:
  1027. `pip install pytorch-quantization --extra-index-url https://pypi.ngc.nvidia.com`
  1028. Please note that you may need to restart your runtime after installation.
  1029. """
  1030. # docstyle-ignore
  1031. TENSORFLOW_PROBABILITY_IMPORT_ERROR = """
  1032. {0} requires the tensorflow_probability library but it was not found in your environment. You can install it with pip as
  1033. explained here: https://github.com/tensorflow/probability. Please note that you may need to restart your runtime after installation.
  1034. """
  1035. # docstyle-ignore
  1036. TENSORFLOW_TEXT_IMPORT_ERROR = """
  1037. {0} requires the tensorflow_text library but it was not found in your environment. You can install it with pip as
  1038. explained here: https://www.tensorflow.org/text/guide/tf_text_intro.
  1039. Please note that you may need to restart your runtime after installation.
  1040. """
  1041. # docstyle-ignore
  1042. TORCHAUDIO_IMPORT_ERROR = """
  1043. {0} requires the torchaudio library but it was not found in your environment. Please install it and restart your
  1044. runtime.
  1045. """
  1046. # docstyle-ignore
  1047. PANDAS_IMPORT_ERROR = """
  1048. {0} requires the pandas library but it was not found in your environment. You can install it with pip as
  1049. explained here: https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html.
  1050. Please note that you may need to restart your runtime after installation.
  1051. """
  1052. # docstyle-ignore
  1053. PHONEMIZER_IMPORT_ERROR = """
  1054. {0} requires the phonemizer library but it was not found in your environment. You can install it with pip:
  1055. `pip install phonemizer`. Please note that you may need to restart your runtime after installation.
  1056. """
  1057. # docstyle-ignore
  1058. UROMAN_IMPORT_ERROR = """
  1059. {0} requires the uroman library but it was not found in your environment. You can install it with pip:
  1060. `pip install uroman`. Please note that you may need to restart your runtime after installation.
  1061. """
  1062. # docstyle-ignore
  1063. SACREMOSES_IMPORT_ERROR = """
  1064. {0} requires the sacremoses library but it was not found in your environment. You can install it with pip:
  1065. `pip install sacremoses`. Please note that you may need to restart your runtime after installation.
  1066. """
  1067. # docstyle-ignore
  1068. SCIPY_IMPORT_ERROR = """
  1069. {0} requires the scipy library but it was not found in your environment. You can install it with pip:
  1070. `pip install scipy`. Please note that you may need to restart your runtime after installation.
  1071. """
  1072. # docstyle-ignore
  1073. SPEECH_IMPORT_ERROR = """
  1074. {0} requires the torchaudio library but it was not found in your environment. You can install it with pip:
  1075. `pip install torchaudio`. Please note that you may need to restart your runtime after installation.
  1076. """
  1077. # docstyle-ignore
  1078. TIMM_IMPORT_ERROR = """
  1079. {0} requires the timm library but it was not found in your environment. You can install it with pip:
  1080. `pip install timm`. Please note that you may need to restart your runtime after installation.
  1081. """
  1082. # docstyle-ignore
  1083. NATTEN_IMPORT_ERROR = """
  1084. {0} requires the natten library but it was not found in your environment. You can install it by referring to:
  1085. shi-labs.com/natten . You can also install it with pip (may take longer to build):
  1086. `pip install natten`. Please note that you may need to restart your runtime after installation.
  1087. """
  1088. NUMEXPR_IMPORT_ERROR = """
  1089. {0} requires the numexpr library but it was not found in your environment. You can install it by referring to:
  1090. https://numexpr.readthedocs.io/en/latest/index.html.
  1091. """
  1092. # docstyle-ignore
  1093. NLTK_IMPORT_ERROR = """
  1094. {0} requires the NLTK library but it was not found in your environment. You can install it by referring to:
  1095. https://www.nltk.org/install.html. Please note that you may need to restart your runtime after installation.
  1096. """
  1097. # docstyle-ignore
  1098. VISION_IMPORT_ERROR = """
  1099. {0} requires the PIL library but it was not found in your environment. You can install it with pip:
  1100. `pip install pillow`. Please note that you may need to restart your runtime after installation.
  1101. """
  1102. # docstyle-ignore
  1103. PYTESSERACT_IMPORT_ERROR = """
  1104. {0} requires the PyTesseract library but it was not found in your environment. You can install it with pip:
  1105. `pip install pytesseract`. Please note that you may need to restart your runtime after installation.
  1106. """
  1107. # docstyle-ignore
  1108. PYCTCDECODE_IMPORT_ERROR = """
  1109. {0} requires the pyctcdecode library but it was not found in your environment. You can install it with pip:
  1110. `pip install pyctcdecode`. Please note that you may need to restart your runtime after installation.
  1111. """
  1112. # docstyle-ignore
  1113. ACCELERATE_IMPORT_ERROR = """
  1114. {0} requires the accelerate library >= {ACCELERATE_MIN_VERSION} it was not found in your environment.
  1115. You can install or update it with pip: `pip install --upgrade accelerate`. Please note that you may need to restart your
  1116. runtime after installation.
  1117. """
  1118. # docstyle-ignore
  1119. CCL_IMPORT_ERROR = """
  1120. {0} requires the torch ccl library but it was not found in your environment. You can install it with pip:
  1121. `pip install oneccl_bind_pt -f https://developer.intel.com/ipex-whl-stable`
  1122. Please note that you may need to restart your runtime after installation.
  1123. """
  1124. # docstyle-ignore
  1125. ESSENTIA_IMPORT_ERROR = """
  1126. {0} requires essentia library. But that was not found in your environment. You can install them with pip:
  1127. `pip install essentia==2.1b6.dev1034`
  1128. Please note that you may need to restart your runtime after installation.
  1129. """
  1130. # docstyle-ignore
  1131. LIBROSA_IMPORT_ERROR = """
  1132. {0} requires thes librosa library. But that was not found in your environment. You can install them with pip:
  1133. `pip install librosa`
  1134. Please note that you may need to restart your runtime after installation.
  1135. """
  1136. # docstyle-ignore
  1137. PRETTY_MIDI_IMPORT_ERROR = """
  1138. {0} requires thes pretty_midi library. But that was not found in your environment. You can install them with pip:
  1139. `pip install pretty_midi`
  1140. Please note that you may need to restart your runtime after installation.
  1141. """
  1142. CYTHON_IMPORT_ERROR = """
  1143. {0} requires the Cython library but it was not found in your environment. You can install it with pip: `pip install
  1144. Cython`. Please note that you may need to restart your runtime after installation.
  1145. """
  1146. JIEBA_IMPORT_ERROR = """
  1147. {0} requires the jieba library but it was not found in your environment. You can install it with pip: `pip install
  1148. jieba`. Please note that you may need to restart your runtime after installation.
  1149. """
  1150. PEFT_IMPORT_ERROR = """
  1151. {0} requires the peft library but it was not found in your environment. You can install it with pip: `pip install
  1152. peft`. Please note that you may need to restart your runtime after installation.
  1153. """
  1154. JINJA_IMPORT_ERROR = """
  1155. {0} requires the jinja library but it was not found in your environment. You can install it with pip: `pip install
  1156. jinja2`. Please note that you may need to restart your runtime after installation.
  1157. """
  1158. BACKENDS_MAPPING = OrderedDict(
  1159. [
  1160. ("av", (is_av_available, AV_IMPORT_ERROR)),
  1161. ("bs4", (is_bs4_available, BS4_IMPORT_ERROR)),
  1162. ("cv2", (is_cv2_available, CV2_IMPORT_ERROR)),
  1163. ("datasets", (is_datasets_available, DATASETS_IMPORT_ERROR)),
  1164. ("detectron2", (is_detectron2_available, DETECTRON2_IMPORT_ERROR)),
  1165. ("essentia", (is_essentia_available, ESSENTIA_IMPORT_ERROR)),
  1166. ("faiss", (is_faiss_available, FAISS_IMPORT_ERROR)),
  1167. ("flax", (is_flax_available, FLAX_IMPORT_ERROR)),
  1168. ("ftfy", (is_ftfy_available, FTFY_IMPORT_ERROR)),
  1169. ("g2p_en", (is_g2p_en_available, G2P_EN_IMPORT_ERROR)),
  1170. ("pandas", (is_pandas_available, PANDAS_IMPORT_ERROR)),
  1171. ("phonemizer", (is_phonemizer_available, PHONEMIZER_IMPORT_ERROR)),
  1172. ("uroman", (is_uroman_available, UROMAN_IMPORT_ERROR)),
  1173. ("pretty_midi", (is_pretty_midi_available, PRETTY_MIDI_IMPORT_ERROR)),
  1174. ("levenshtein", (is_levenshtein_available, LEVENSHTEIN_IMPORT_ERROR)),
  1175. ("librosa", (is_librosa_available, LIBROSA_IMPORT_ERROR)),
  1176. ("protobuf", (is_protobuf_available, PROTOBUF_IMPORT_ERROR)),
  1177. ("pyctcdecode", (is_pyctcdecode_available, PYCTCDECODE_IMPORT_ERROR)),
  1178. ("pytesseract", (is_pytesseract_available, PYTESSERACT_IMPORT_ERROR)),
  1179. ("sacremoses", (is_sacremoses_available, SACREMOSES_IMPORT_ERROR)),
  1180. ("pytorch_quantization", (is_pytorch_quantization_available, PYTORCH_QUANTIZATION_IMPORT_ERROR)),
  1181. ("sentencepiece", (is_sentencepiece_available, SENTENCEPIECE_IMPORT_ERROR)),
  1182. ("sklearn", (is_sklearn_available, SKLEARN_IMPORT_ERROR)),
  1183. ("speech", (is_speech_available, SPEECH_IMPORT_ERROR)),
  1184. ("tensorflow_probability", (is_tensorflow_probability_available, TENSORFLOW_PROBABILITY_IMPORT_ERROR)),
  1185. ("tf", (is_tf_available, TENSORFLOW_IMPORT_ERROR)),
  1186. ("tensorflow_text", (is_tensorflow_text_available, TENSORFLOW_TEXT_IMPORT_ERROR)),
  1187. ("timm", (is_timm_available, TIMM_IMPORT_ERROR)),
  1188. ("torchaudio", (is_torchaudio_available, TORCHAUDIO_IMPORT_ERROR)),
  1189. ("natten", (is_natten_available, NATTEN_IMPORT_ERROR)),
  1190. ("nltk", (is_nltk_available, NLTK_IMPORT_ERROR)),
  1191. ("tokenizers", (is_tokenizers_available, TOKENIZERS_IMPORT_ERROR)),
  1192. ("torch", (is_torch_available, PYTORCH_IMPORT_ERROR)),
  1193. ("torchvision", (is_torchvision_available, TORCHVISION_IMPORT_ERROR)),
  1194. ("vision", (is_vision_available, VISION_IMPORT_ERROR)),
  1195. ("scipy", (is_scipy_available, SCIPY_IMPORT_ERROR)),
  1196. ("accelerate", (is_accelerate_available, ACCELERATE_IMPORT_ERROR)),
  1197. ("oneccl_bind_pt", (is_ccl_available, CCL_IMPORT_ERROR)),
  1198. ("cython", (is_cython_available, CYTHON_IMPORT_ERROR)),
  1199. ("jieba", (is_jieba_available, JIEBA_IMPORT_ERROR)),
  1200. ("peft", (is_peft_available, PEFT_IMPORT_ERROR)),
  1201. ("jinja", (is_jinja_available, JINJA_IMPORT_ERROR)),
  1202. ]
  1203. )
  1204. def requires_backends(obj, backends):
  1205. if not isinstance(backends, (list, tuple)):
  1206. backends = [backends]
  1207. name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
  1208. # Raise an error for users who might not realize that classes without "TF" are torch-only
  1209. if "torch" in backends and "tf" not in backends and not is_torch_available() and is_tf_available():
  1210. raise ImportError(PYTORCH_IMPORT_ERROR_WITH_TF.format(name))
  1211. # Raise the inverse error for PyTorch users trying to load TF classes
  1212. if "tf" in backends and "torch" not in backends and is_torch_available() and not is_tf_available():
  1213. raise ImportError(TF_IMPORT_ERROR_WITH_PYTORCH.format(name))
  1214. checks = (BACKENDS_MAPPING[backend] for backend in backends)
  1215. failed = [msg.format(name) for available, msg in checks if not available()]
  1216. if failed:
  1217. raise ImportError("".join(failed))
  1218. class DummyObject(type):
  1219. """
  1220. Metaclass for the dummy objects. Any class inheriting from it will return the ImportError generated by
  1221. `requires_backend` each time a user tries to access any method of that class.
  1222. """
  1223. def __getattribute__(cls, key):
  1224. if key.startswith("_") and key != "_from_config":
  1225. return super().__getattribute__(key)
  1226. requires_backends(cls, cls._backends)
  1227. def is_torch_fx_proxy(x):
  1228. if is_torch_fx_available():
  1229. import torch.fx
  1230. return isinstance(x, torch.fx.Proxy)
  1231. return False
  1232. BACKENDS_T = FrozenSet[str]
  1233. IMPORT_STRUCTURE_T = Dict[BACKENDS_T, Dict[str, Set[str]]]
  1234. class _LazyModule(ModuleType):
  1235. """
  1236. Module class that surfaces all objects but only performs associated imports when the objects are requested.
  1237. """
  1238. # Very heavily inspired by optuna.integration._IntegrationModule
  1239. # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py
  1240. def __init__(
  1241. self,
  1242. name: str,
  1243. module_file: str,
  1244. import_structure: IMPORT_STRUCTURE_T,
  1245. module_spec: importlib.machinery.ModuleSpec = None,
  1246. extra_objects: Dict[str, object] = None,
  1247. ):
  1248. super().__init__(name)
  1249. self._object_missing_backend = {}
  1250. if any(isinstance(key, frozenset) for key in import_structure.keys()):
  1251. self._modules = set()
  1252. self._class_to_module = {}
  1253. self.__all__ = []
  1254. _import_structure = {}
  1255. for backends, module in import_structure.items():
  1256. missing_backends = []
  1257. for backend in backends:
  1258. if backend not in BACKENDS_MAPPING:
  1259. raise ValueError(
  1260. f"Error: the following backend: '{backend}' was specified around object {module} but isn't specified in the backends mapping."
  1261. )
  1262. callable, error = BACKENDS_MAPPING[backend]
  1263. if not callable():
  1264. missing_backends.append(backend)
  1265. self._modules = self._modules.union(set(module.keys()))
  1266. for key, values in module.items():
  1267. if len(missing_backends):
  1268. self._object_missing_backend[key] = missing_backends
  1269. for value in values:
  1270. self._class_to_module[value] = key
  1271. if len(missing_backends):
  1272. self._object_missing_backend[value] = missing_backends
  1273. _import_structure.setdefault(key, []).extend(values)
  1274. # Needed for autocompletion in an IDE
  1275. self.__all__.extend(list(module.keys()) + list(chain(*module.values())))
  1276. self.__file__ = module_file
  1277. self.__spec__ = module_spec
  1278. self.__path__ = [os.path.dirname(module_file)]
  1279. self._objects = {} if extra_objects is None else extra_objects
  1280. self._name = name
  1281. self._import_structure = _import_structure
  1282. # This can be removed once every exportable object has a `export()` export.
  1283. else:
  1284. self._modules = set(import_structure.keys())
  1285. self._class_to_module = {}
  1286. for key, values in import_structure.items():
  1287. for value in values:
  1288. self._class_to_module[value] = key
  1289. # Needed for autocompletion in an IDE
  1290. self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values()))
  1291. self.__file__ = module_file
  1292. self.__spec__ = module_spec
  1293. self.__path__ = [os.path.dirname(module_file)]
  1294. self._objects = {} if extra_objects is None else extra_objects
  1295. self._name = name
  1296. self._import_structure = import_structure
  1297. # Needed for autocompletion in an IDE
  1298. def __dir__(self):
  1299. result = super().__dir__()
  1300. # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether
  1301. # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir.
  1302. for attr in self.__all__:
  1303. if attr not in result:
  1304. result.append(attr)
  1305. return result
  1306. def __getattr__(self, name: str) -> Any:
  1307. if name in self._objects:
  1308. return self._objects[name]
  1309. if name in self._object_missing_backend.keys():
  1310. missing_backends = self._object_missing_backend[name]
  1311. class Placeholder(metaclass=DummyObject):
  1312. _backends = missing_backends
  1313. def __init__(self, *args, **kwargs):
  1314. requires_backends(self, missing_backends)
  1315. Placeholder.__name__ = name
  1316. Placeholder.__module__ = self.__spec__
  1317. value = Placeholder
  1318. elif name in self._class_to_module.keys():
  1319. module = self._get_module(self._class_to_module[name])
  1320. value = getattr(module, name)
  1321. elif name in self._modules:
  1322. value = self._get_module(name)
  1323. else:
  1324. raise AttributeError(f"module {self.__name__} has no attribute {name}")
  1325. setattr(self, name, value)
  1326. return value
  1327. def _get_module(self, module_name: str):
  1328. try:
  1329. return importlib.import_module("." + module_name, self.__name__)
  1330. except Exception as e:
  1331. raise RuntimeError(
  1332. f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
  1333. f" traceback):\n{e}"
  1334. ) from e
  1335. def __reduce__(self):
  1336. return (self.__class__, (self._name, self.__file__, self._import_structure))
  1337. class OptionalDependencyNotAvailable(BaseException):
  1338. """Internally used error class for signalling an optional dependency was not found."""
  1339. def direct_transformers_import(path: str, file="__init__.py") -> ModuleType:
  1340. """Imports transformers directly
  1341. Args:
  1342. path (`str`): The path to the source file
  1343. file (`str`, *optional*): The file to join with the path. Defaults to "__init__.py".
  1344. Returns:
  1345. `ModuleType`: The resulting imported module
  1346. """
  1347. name = "transformers"
  1348. location = os.path.join(path, file)
  1349. spec = importlib.util.spec_from_file_location(name, location, submodule_search_locations=[path])
  1350. module = importlib.util.module_from_spec(spec)
  1351. spec.loader.exec_module(module)
  1352. module = sys.modules[name]
  1353. return module
  1354. def export(*, backends=()):
  1355. """
  1356. This decorator enables two things:
  1357. - Attaching a `__backends` tuple to an object to see what are the necessary backends for it
  1358. to execute correctly without instantiating it
  1359. - The '@export' string is used to dynamically import objects
  1360. """
  1361. for backend in backends:
  1362. if backend not in BACKENDS_MAPPING:
  1363. raise ValueError(f"Backend should be defined in the BACKENDS_MAPPING. Offending backend: {backend}")
  1364. if not isinstance(backends, tuple):
  1365. raise ValueError("Backends should be a tuple.")
  1366. def inner_fn(fun):
  1367. fun.__backends = backends
  1368. return fun
  1369. return inner_fn
  1370. BASE_FILE_REQUIREMENTS = {
  1371. lambda e: "modeling_tf_" in e: ("tf",),
  1372. lambda e: "modeling_flax_" in e: ("flax",),
  1373. lambda e: "modeling_" in e: ("torch",),
  1374. lambda e: e.startswith("tokenization_") and e.endswith("_fast"): ("tokenizers",),
  1375. }
  1376. def fetch__all__(file_content):
  1377. """
  1378. Returns the content of the __all__ variable in the file content.
  1379. Returns None if not defined, otherwise returns a list of strings.
  1380. """
  1381. if "__all__" not in file_content:
  1382. return []
  1383. lines = file_content.splitlines()
  1384. for index, line in enumerate(lines):
  1385. if line.startswith("__all__"):
  1386. start_index = index
  1387. lines = lines[start_index:]
  1388. if not lines[0].startswith("__all__"):
  1389. raise ValueError(
  1390. "fetch__all__ accepts a list of lines, with the first line being the __all__ variable declaration"
  1391. )
  1392. # __all__ is defined on a single line
  1393. if lines[0].endswith("]"):
  1394. return [obj.strip("\"' ") for obj in lines[0].split("=")[1].strip(" []").split(",")]
  1395. # __all__ is defined on multiple lines
  1396. else:
  1397. _all = []
  1398. for __all__line_index in range(1, len(lines)):
  1399. if lines[__all__line_index].strip() == "]":
  1400. return _all
  1401. else:
  1402. _all.append(lines[__all__line_index].strip("\"', "))
  1403. return _all
  1404. @lru_cache()
  1405. def create_import_structure_from_path(module_path):
  1406. """
  1407. This method takes the path to a file/a folder and returns the import structure.
  1408. If a file is given, it will return the import structure of the parent folder.
  1409. Import structures are designed to be digestible by `_LazyModule` objects. They are
  1410. created from the __all__ definitions in each files as well as the `@export` decorators
  1411. above methods and objects.
  1412. The import structure allows explicit display of the required backends for a given object.
  1413. These backends are specified in two ways:
  1414. 1. Through their `@export`, if they are exported with that decorator. This `@export` decorator
  1415. accepts a `backend` tuple kwarg mentioning which backends are required to run this object.
  1416. 2. If an object is defined in a file with "default" backends, it will have, at a minimum, this
  1417. backend specified. The default backends are defined according to the filename:
  1418. - If a file is named like `modeling_*.py`, it will have a `torch` backend
  1419. - If a file is named like `modeling_tf_*.py`, it will have a `tf` backend
  1420. - If a file is named like `modeling_flax_*.py`, it will have a `flax` backend
  1421. - If a file is named like `tokenization_*_fast.py`, it will have a `tokenizers` backend
  1422. Backends serve the purpose of displaying a clear error message to the user in case the backends are not installed.
  1423. Should an object be imported without its required backends being in the environment, any attempt to use the
  1424. object will raise an error mentioning which backend(s) should be added to the environment in order to use
  1425. that object.
  1426. Here's an example of an input import structure at the src.transformers.models level:
  1427. {
  1428. 'albert': {
  1429. frozenset(): {
  1430. 'configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'}
  1431. },
  1432. frozenset({'tokenizers'}): {
  1433. 'tokenization_albert_fast': {'AlbertTokenizerFast'}
  1434. },
  1435. },
  1436. 'align': {
  1437. frozenset(): {
  1438. 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
  1439. 'processing_align': {'AlignProcessor'}
  1440. },
  1441. },
  1442. 'altclip': {
  1443. frozenset(): {
  1444. 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
  1445. 'processing_altclip': {'AltCLIPProcessor'},
  1446. }
  1447. }
  1448. }
  1449. """
  1450. import_structure = {}
  1451. if os.path.isdir(module_path):
  1452. directory = module_path
  1453. adjacent_modules = []
  1454. for f in os.listdir(module_path):
  1455. if f != "__pycache__" and os.path.isdir(os.path.join(module_path, f)):
  1456. import_structure[f] = create_import_structure_from_path(os.path.join(module_path, f))
  1457. elif not os.path.isdir(os.path.join(directory, f)):
  1458. adjacent_modules.append(f)
  1459. else:
  1460. directory = os.path.dirname(module_path)
  1461. adjacent_modules = [f for f in os.listdir(directory) if not os.path.isdir(os.path.join(directory, f))]
  1462. # We're only taking a look at files different from __init__.py
  1463. # We could theoretically export things directly from the __init__.py
  1464. # files, but this is not supported at this time.
  1465. if "__init__.py" in adjacent_modules:
  1466. adjacent_modules.remove("__init__.py")
  1467. # Modular files should not be imported
  1468. def find_substring(substring, list_):
  1469. return any(substring in x for x in list_)
  1470. if find_substring("modular_", adjacent_modules) and find_substring("modeling_", adjacent_modules):
  1471. adjacent_modules = [module for module in adjacent_modules if "modular_" not in module]
  1472. module_requirements = {}
  1473. for module_name in adjacent_modules:
  1474. # Only modules ending in `.py` are accepted here.
  1475. if not module_name.endswith(".py"):
  1476. continue
  1477. with open(os.path.join(directory, module_name), encoding="utf-8") as f:
  1478. file_content = f.read()
  1479. # Remove the .py suffix
  1480. module_name = module_name[:-3]
  1481. previous_line = ""
  1482. previous_index = 0
  1483. # Some files have some requirements by default.
  1484. # For example, any file named `modeling_tf_xxx.py`
  1485. # should have TensorFlow as a required backend.
  1486. base_requirements = ()
  1487. for string_check, requirements in BASE_FILE_REQUIREMENTS.items():
  1488. if string_check(module_name):
  1489. base_requirements = requirements
  1490. break
  1491. # Objects that have a `@export` assigned to them will get exported
  1492. # with the backends specified in the decorator as well as the file backends.
  1493. exported_objects = set()
  1494. if "@export" in file_content:
  1495. lines = file_content.split("\n")
  1496. for index, line in enumerate(lines):
  1497. # This allows exporting items with other decorators. We'll take a look
  1498. # at the line that follows at the same indentation level.
  1499. if line.startswith((" ", "\t", "@", ")")) and not line.startswith("@export"):
  1500. continue
  1501. # Skipping line enables putting whatever we want between the
  1502. # export() call and the actual class/method definition.
  1503. # This is what enables having # Copied from statements, docs, etc.
  1504. skip_line = False
  1505. if "@export" in previous_line:
  1506. skip_line = False
  1507. # Backends are defined on the same line as export
  1508. if "backends" in previous_line:
  1509. backends_string = previous_line.split("backends=")[1].split("(")[1].split(")")[0]
  1510. backends = tuple(sorted([b.strip("'\",") for b in backends_string.split(", ") if b]))
  1511. # Backends are defined in the lines following export, for example such as:
  1512. # @export(
  1513. # backends=(
  1514. # "sentencepiece",
  1515. # "torch",
  1516. # "tf",
  1517. # )
  1518. # )
  1519. #
  1520. # or
  1521. #
  1522. # @export(
  1523. # backends=(
  1524. # "sentencepiece", "tf"
  1525. # )
  1526. # )
  1527. elif "backends" in lines[previous_index + 1]:
  1528. backends = []
  1529. for backend_line in lines[previous_index:index]:
  1530. if "backends" in backend_line:
  1531. backend_line = backend_line.split("=")[1]
  1532. if '"' in backend_line or "'" in backend_line:
  1533. if ", " in backend_line:
  1534. backends.extend(backend.strip("()\"', ") for backend in backend_line.split(", "))
  1535. else:
  1536. backends.append(backend_line.strip("()\"', "))
  1537. # If the line is only a ')', then we reached the end of the backends and we break.
  1538. if backend_line.strip() == ")":
  1539. break
  1540. backends = tuple(backends)
  1541. # No backends are registered for export
  1542. else:
  1543. backends = ()
  1544. backends = frozenset(backends + base_requirements)
  1545. if backends not in module_requirements:
  1546. module_requirements[backends] = {}
  1547. if module_name not in module_requirements[backends]:
  1548. module_requirements[backends][module_name] = set()
  1549. if not line.startswith("class") and not line.startswith("def"):
  1550. skip_line = True
  1551. else:
  1552. start_index = 6 if line.startswith("class") else 4
  1553. object_name = line[start_index:].split("(")[0].strip(":")
  1554. module_requirements[backends][module_name].add(object_name)
  1555. exported_objects.add(object_name)
  1556. if not skip_line:
  1557. previous_line = line
  1558. previous_index = index
  1559. # All objects that are in __all__ should be exported by default.
  1560. # These objects are exported with the file backends.
  1561. if "__all__" in file_content:
  1562. for _all_object in fetch__all__(file_content):
  1563. if _all_object not in exported_objects:
  1564. backends = frozenset(base_requirements)
  1565. if backends not in module_requirements:
  1566. module_requirements[backends] = {}
  1567. if module_name not in module_requirements[backends]:
  1568. module_requirements[backends][module_name] = set()
  1569. module_requirements[backends][module_name].add(_all_object)
  1570. import_structure = {**module_requirements, **import_structure}
  1571. return import_structure
  1572. def spread_import_structure(nested_import_structure):
  1573. """
  1574. This method takes as input an unordered import structure and brings the required backends at the top-level,
  1575. aggregating modules and objects under their required backends.
  1576. Here's an example of an input import structure at the src.transformers.models level:
  1577. {
  1578. 'albert': {
  1579. frozenset(): {
  1580. 'configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'}
  1581. },
  1582. frozenset({'tokenizers'}): {
  1583. 'tokenization_albert_fast': {'AlbertTokenizerFast'}
  1584. },
  1585. },
  1586. 'align': {
  1587. frozenset(): {
  1588. 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
  1589. 'processing_align': {'AlignProcessor'}
  1590. },
  1591. },
  1592. 'altclip': {
  1593. frozenset(): {
  1594. 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
  1595. 'processing_altclip': {'AltCLIPProcessor'},
  1596. }
  1597. }
  1598. }
  1599. Here's an example of an output import structure at the src.transformers.models level:
  1600. {
  1601. frozenset({'tokenizers'}): {
  1602. 'albert.tokenization_albert_fast': {'AlbertTokenizerFast'}
  1603. },
  1604. frozenset(): {
  1605. 'albert.configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'},
  1606. 'align.processing_align': {'AlignProcessor'},
  1607. 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
  1608. 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
  1609. 'altclip.processing_altclip': {'AltCLIPProcessor'}
  1610. }
  1611. }
  1612. """
  1613. def propagate_frozenset(unordered_import_structure):
  1614. tuple_first_import_structure = {}
  1615. for _key, _value in unordered_import_structure.items():
  1616. if not isinstance(_value, dict):
  1617. tuple_first_import_structure[_key] = _value
  1618. elif any(isinstance(v, frozenset) for v in _value.keys()):
  1619. # Here we want to switch around key and v
  1620. for k, v in _value.items():
  1621. if isinstance(k, frozenset):
  1622. if k not in tuple_first_import_structure:
  1623. tuple_first_import_structure[k] = {}
  1624. tuple_first_import_structure[k][_key] = v
  1625. else:
  1626. tuple_first_import_structure[_key] = propagate_frozenset(_value)
  1627. return tuple_first_import_structure
  1628. def flatten_dict(_dict, previous_key=None):
  1629. items = []
  1630. for _key, _value in _dict.items():
  1631. _key = f"{previous_key}.{_key}" if previous_key is not None else _key
  1632. if isinstance(_value, dict):
  1633. items.extend(flatten_dict(_value, _key).items())
  1634. else:
  1635. items.append((_key, _value))
  1636. return dict(items)
  1637. # The tuples contain the necessary backends. We want these first, so we propagate them up the
  1638. # import structure.
  1639. ordered_import_structure = nested_import_structure
  1640. # 6 is a number that gives us sufficient depth to go through all files and foreseeable folder depths
  1641. # while not taking too long to parse.
  1642. for i in range(6):
  1643. ordered_import_structure = propagate_frozenset(ordered_import_structure)
  1644. # We then flatten the dict so that it references a module path.
  1645. flattened_import_structure = {}
  1646. for key, value in ordered_import_structure.copy().items():
  1647. if isinstance(key, str):
  1648. del ordered_import_structure[key]
  1649. else:
  1650. flattened_import_structure[key] = flatten_dict(value)
  1651. return flattened_import_structure
  1652. def define_import_structure(module_path: str) -> IMPORT_STRUCTURE_T:
  1653. """
  1654. This method takes a module_path as input and creates an import structure digestible by a _LazyModule.
  1655. Here's an example of an output import structure at the src.transformers.models level:
  1656. {
  1657. frozenset({'tokenizers'}): {
  1658. 'albert.tokenization_albert_fast': {'AlbertTokenizerFast'}
  1659. },
  1660. frozenset(): {
  1661. 'albert.configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'},
  1662. 'align.processing_align': {'AlignProcessor'},
  1663. 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
  1664. 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
  1665. 'altclip.processing_altclip': {'AltCLIPProcessor'}
  1666. }
  1667. }
  1668. The import structure is a dict defined with frozensets as keys, and dicts of strings to sets of objects.
  1669. """
  1670. import_structure = create_import_structure_from_path(module_path)
  1671. return spread_import_structure(import_structure)