deps.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. # Copyright (c) 2024 PaddlePaddle Authors. 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. import importlib.metadata
  15. import importlib.util
  16. import inspect
  17. import re
  18. from collections import defaultdict
  19. from functools import lru_cache, wraps
  20. from packaging.requirements import Requirement
  21. from packaging.version import Version
  22. from . import logging
  23. _EXTRA_PATTERN = re.compile(
  24. r"(?:;|and)*[ \t]*extra[ \t]*==[ \t]*['\"]([a-z0-9]+(?:-[a-z0-9]+)*)['\"]"
  25. )
  26. _COLLECTIVE_EXTRA_NAMES = {"base", "plugins", "all"}
  27. _SUPPORTED_GENAI_ENGINE_BACKENDS = ["fastdeploy-server", "vllm-server", "sglang-server"]
  28. class DependencyError(Exception):
  29. pass
  30. def _get_extra_name_and_remove_extra_marker(dep_spec):
  31. # XXX: Not sure if this is correct
  32. m = _EXTRA_PATTERN.search(dep_spec)
  33. if m:
  34. return m.group(1), dep_spec[: m.start()] + dep_spec[m.end() :]
  35. else:
  36. return None, dep_spec
  37. def _get_extras():
  38. metadata = importlib.metadata.metadata("paddlex")
  39. extras = {}
  40. # XXX: The `metadata.get_all` used here is not well documented.
  41. for name in metadata.get_all("Provides-Extra", []):
  42. if name not in _COLLECTIVE_EXTRA_NAMES:
  43. extras[name] = defaultdict(list)
  44. for dep_spec in importlib.metadata.requires("paddlex"):
  45. extra_name, dep_spec = _get_extra_name_and_remove_extra_marker(dep_spec)
  46. if extra_name is not None and extra_name not in _COLLECTIVE_EXTRA_NAMES:
  47. dep_spec = dep_spec.rstrip()
  48. req = Requirement(dep_spec)
  49. assert extra_name in extras, extra_name
  50. extras[extra_name][req.name].append(dep_spec)
  51. return extras
  52. EXTRAS = _get_extras()
  53. def _get_base_dep_specs(required_only=False):
  54. dep_specs = defaultdict(list)
  55. for dep_spec in importlib.metadata.requires("paddlex"):
  56. extra_name, dep_spec = _get_extra_name_and_remove_extra_marker(dep_spec)
  57. if (required_only and extra_name is None) or (
  58. not required_only and (extra_name is None or extra_name == "base")
  59. ):
  60. dep_spec = dep_spec.rstrip()
  61. req = Requirement(dep_spec)
  62. dep_specs[req.name].append(dep_spec)
  63. return dep_specs
  64. BASE_DEP_SPECS = _get_base_dep_specs()
  65. REQUIRED_DEP_SPECS = _get_base_dep_specs(required_only=True)
  66. def get_dep_version(dep):
  67. try:
  68. return importlib.metadata.version(dep)
  69. except importlib.metadata.PackageNotFoundError:
  70. return None
  71. @lru_cache()
  72. def is_dep_available(dep, /, check_version=False):
  73. if (
  74. dep in ("paddlepaddle", "paddle-custom-device", "ultra-infer", "fastdeploy")
  75. and check_version
  76. ):
  77. raise ValueError(
  78. "`check_version` is not allowed to be `True` for `paddlepaddle`, `paddle-custom-device`, `ultra-infer`, and `fastdeploy`."
  79. )
  80. # Currently for several special deps we check if the import packages exist.
  81. if dep == "paddlepaddle":
  82. return importlib.util.find_spec("paddle") is not None
  83. elif dep == "paddle-custom-device":
  84. return importlib.util.find_spec("paddle_custom_device") is not None
  85. elif dep == "ultra-infer":
  86. return importlib.util.find_spec("ultra_infer") is not None
  87. elif dep == "fastdeploy":
  88. return importlib.util.find_spec("fastdeploy") is not None
  89. version = get_dep_version(dep)
  90. if version is None:
  91. return False
  92. if check_version:
  93. if dep not in BASE_DEP_SPECS:
  94. raise ValueError(
  95. f"Currently, `check_version=True` is supported only for base dependencies."
  96. )
  97. for dep_spec in BASE_DEP_SPECS[dep]:
  98. if Version(version) in Requirement(dep_spec).specifier:
  99. return True
  100. else:
  101. return True
  102. def require_deps(*deps, obj_name=None):
  103. unavailable_deps = [dep for dep in deps if not is_dep_available(dep)]
  104. if len(unavailable_deps) > 0:
  105. if obj_name is not None:
  106. msg = f"`{obj_name}` is not ready for use, because the"
  107. else:
  108. msg = "The"
  109. msg += " following dependencies are not available:\n" + "\n".join(
  110. unavailable_deps
  111. )
  112. raise DependencyError(msg)
  113. def function_requires_deps(*deps):
  114. def _deco(func):
  115. @wraps(func)
  116. def _wrapper(*args, **kwargs):
  117. require_deps(*func._deps_, obj_name=func.__name__)
  118. return func(*args, **kwargs)
  119. func._deps_ = set(deps)
  120. return _wrapper
  121. return _deco
  122. def class_requires_deps(*deps):
  123. def _deco(cls):
  124. @wraps(cls.__init__)
  125. def _wrapper(self, *args, **kwargs):
  126. require_deps(*cls._deps_, obj_name=cls.__name__)
  127. return old_init_func(self, *args, **kwargs)
  128. cls._deps_ = set(deps)
  129. for base_cls in inspect.getmro(cls)[1:-1]:
  130. if hasattr(base_cls, "_deps_"):
  131. cls._deps_.update(base_cls._deps_)
  132. if "__init__" in cls.__dict__:
  133. old_init_func = cls.__init__
  134. else:
  135. def _forward(self, *args, **kwargs):
  136. return super(cls, self).__init__(*args, **kwargs)
  137. old_init_func = _forward
  138. cls.__init__ = _wrapper
  139. return cls
  140. return _deco
  141. @lru_cache()
  142. def is_extra_available(extra):
  143. flags = [is_dep_available(dep) for dep in EXTRAS[extra]]
  144. if all(flags):
  145. return True
  146. logging.debug(
  147. "These dependencies are not available: %s",
  148. [d for d, f in zip(EXTRAS[extra], flags) if not f],
  149. )
  150. return False
  151. def require_extra(extra, *, obj_name=None, alt=None):
  152. if is_extra_available(extra) or (alt is not None and is_extra_available(alt)):
  153. return
  154. if obj_name is not None:
  155. msg = f"`{obj_name}` requires additional dependencies."
  156. else:
  157. msg = "Additional dependencies are required."
  158. msg += f' To install them, run `pip install "paddlex[{extra}]==<PADDLEX_VERSION>"` if you’re installing `paddlex` from an index, or `pip install -e "/path/to/PaddleX[{extra}]"` if you’re installing `paddlex` locally.'
  159. if alt is not None:
  160. msg += f" Alternatively, you can install `paddlex[{alt}]` instead."
  161. raise DependencyError(msg)
  162. def pipeline_requires_extra(extra, *, alt=None):
  163. def _deco(pipeline_cls):
  164. @wraps(pipeline_cls.__init__)
  165. def _wrapper(self, *args, **kwargs):
  166. require_extra(extra, obj_name=pipeline_name, alt=alt)
  167. return old_init_func(self, *args, **kwargs)
  168. old_init_func = pipeline_cls.__init__
  169. pipeline_name = pipeline_cls.entities
  170. if isinstance(pipeline_name, list):
  171. assert len(pipeline_name) == 1, pipeline_name
  172. pipeline_name = pipeline_name[0]
  173. pipeline_cls.__init__ = _wrapper
  174. return pipeline_cls
  175. return _deco
  176. def is_hpip_available():
  177. return is_dep_available("ultra-infer")
  178. def require_hpip():
  179. if not is_hpip_available():
  180. raise DependencyError(
  181. "The high-performance inference plugin is not available. Please install it properly."
  182. )
  183. def is_serving_plugin_available():
  184. return is_extra_available("serving")
  185. def require_serving_plugin():
  186. if not is_serving_plugin_available():
  187. raise DependencyError(
  188. "The serving plugin is not available. Please install it properly."
  189. )
  190. def get_serving_dep_specs():
  191. dep_specs = []
  192. for item in EXTRAS["serving"].values():
  193. dep_specs += item
  194. return dep_specs
  195. def is_paddle2onnx_plugin_available():
  196. return is_dep_available("paddle2onnx")
  197. def require_paddle2onnx_plugin():
  198. if not is_paddle2onnx_plugin_available():
  199. raise DependencyError(
  200. "The Paddle2ONNX plugin is not available. Please install it properly."
  201. )
  202. def get_paddle2onnx_dep_specs():
  203. dep_specs = []
  204. for item in EXTRAS["paddle2onnx"].values():
  205. dep_specs += item
  206. return dep_specs
  207. def is_genai_engine_plugin_available(backend="any"):
  208. if backend != "any" and backend not in _SUPPORTED_GENAI_ENGINE_BACKENDS:
  209. raise ValueError(f"Unknown backend type: {backend}")
  210. if backend == "any":
  211. for be in _SUPPORTED_GENAI_ENGINE_BACKENDS:
  212. if is_genai_engine_plugin_available(be):
  213. return True
  214. return False
  215. else:
  216. if "fastdeploy" in backend:
  217. return is_dep_available("fastdeploy")
  218. elif is_extra_available(f"genai-{backend}"):
  219. if "vllm" in backend or "sglang" in backend:
  220. return is_dep_available("flash-attn")
  221. return True
  222. return False
  223. def require_genai_engine_plugin(backend="any"):
  224. if not is_genai_engine_plugin_available(backend):
  225. if backend == "any":
  226. prefix = "The generative AI engine plugins are"
  227. else:
  228. prefix = f"The generative AI {repr(backend)} engine plugin is"
  229. raise RuntimeError(f"{prefix} not available. Please install it properly.")
  230. def is_genai_client_plugin_available():
  231. return is_extra_available("genai-client")
  232. def require_genai_client_plugin():
  233. if not is_genai_client_plugin_available():
  234. raise RuntimeError(
  235. "The generative AI client plugin is not available. Please install it properly."
  236. )
  237. def get_genai_fastdeploy_spec(device_type):
  238. SUPPORTED_DEVICE_TYPES = ("gpu",)
  239. if device_type not in SUPPORTED_DEVICE_TYPES:
  240. raise ValueError(f"Unsupported device type: {device_type}")
  241. if device_type == "gpu":
  242. return "fastdeploy-gpu == 2.0.3"
  243. else:
  244. raise AssertionError
  245. def get_genai_dep_specs(type):
  246. if type != "client" and type not in _SUPPORTED_GENAI_ENGINE_BACKENDS:
  247. raise ValueError(f"Invalid type: {type}")
  248. if "fastdeploy" in type:
  249. raise ValueError(f"{repr(type)} is not supported")
  250. dep_specs = []
  251. for item in EXTRAS[f"genai-{type}"].values():
  252. dep_specs += item
  253. return dep_specs