base.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. from __future__ import annotations
  2. import pickle
  3. from abc import ABC, abstractmethod
  4. from pathlib import Path
  5. from shutil import rmtree
  6. from typing import Any
  7. import onnxruntime as ort
  8. from huggingface_hub import snapshot_download
  9. from typing_extensions import Buffer
  10. from ..config import get_cache_dir, get_hf_model_name, log, settings
  11. from ..schemas import ModelType
  12. class InferenceModel(ABC):
  13. _model_type: ModelType
  14. def __init__(
  15. self,
  16. model_name: str,
  17. cache_dir: Path | str | None = None,
  18. inter_op_num_threads: int = settings.model_inter_op_threads,
  19. intra_op_num_threads: int = settings.model_intra_op_threads,
  20. **model_kwargs: Any,
  21. ) -> None:
  22. self.model_name = model_name
  23. self.loaded = False
  24. self._cache_dir = Path(cache_dir) if cache_dir is not None else None
  25. self.providers = model_kwargs.pop("providers", ["CPUExecutionProvider"])
  26. # don't pre-allocate more memory than needed
  27. self.provider_options = model_kwargs.pop(
  28. "provider_options", [{"arena_extend_strategy": "kSameAsRequested"}] * len(self.providers)
  29. )
  30. log.debug(
  31. (
  32. f"Setting '{self.model_name}' execution providers to {self.providers}"
  33. "in descending order of preference"
  34. ),
  35. )
  36. log.debug(f"Setting execution provider options to {self.provider_options}")
  37. self.sess_options = PicklableSessionOptions()
  38. # avoid thread contention between models
  39. if inter_op_num_threads > 1:
  40. self.sess_options.execution_mode = ort.ExecutionMode.ORT_PARALLEL
  41. log.debug(f"Setting execution_mode to {self.sess_options.execution_mode.name}")
  42. log.debug(f"Setting inter_op_num_threads to {inter_op_num_threads}")
  43. log.debug(f"Setting intra_op_num_threads to {intra_op_num_threads}")
  44. self.sess_options.inter_op_num_threads = inter_op_num_threads
  45. self.sess_options.intra_op_num_threads = intra_op_num_threads
  46. self.sess_options.enable_cpu_mem_arena = False
  47. def download(self) -> None:
  48. if not self.cached:
  49. log.info(
  50. (f"Downloading {self.model_type.replace('-', ' ')} model '{self.model_name}'." "This may take a while.")
  51. )
  52. self._download()
  53. def load(self) -> None:
  54. if self.loaded:
  55. return
  56. self.download()
  57. log.info(f"Loading {self.model_type.replace('-', ' ')} model '{self.model_name}'")
  58. self._load()
  59. self.loaded = True
  60. def predict(self, inputs: Any, **model_kwargs: Any) -> Any:
  61. self.load()
  62. if model_kwargs:
  63. self.configure(**model_kwargs)
  64. return self._predict(inputs)
  65. @abstractmethod
  66. def _predict(self, inputs: Any) -> Any:
  67. ...
  68. def configure(self, **model_kwargs: Any) -> None:
  69. pass
  70. def _download(self) -> None:
  71. snapshot_download(
  72. get_hf_model_name(self.model_name),
  73. cache_dir=self.cache_dir,
  74. local_dir=self.cache_dir,
  75. local_dir_use_symlinks=False,
  76. )
  77. @abstractmethod
  78. def _load(self) -> None:
  79. ...
  80. @property
  81. def model_type(self) -> ModelType:
  82. return self._model_type
  83. @property
  84. def cache_dir(self) -> Path:
  85. return self._cache_dir if self._cache_dir is not None else get_cache_dir(self.model_name, self.model_type)
  86. @cache_dir.setter
  87. def cache_dir(self, cache_dir: Path) -> None:
  88. self._cache_dir = cache_dir
  89. @property
  90. def cached(self) -> bool:
  91. return self.cache_dir.exists() and any(self.cache_dir.iterdir())
  92. @classmethod
  93. def from_model_type(cls, model_type: ModelType, model_name: str, **model_kwargs: Any) -> InferenceModel:
  94. subclasses = {subclass._model_type: subclass for subclass in cls.__subclasses__()}
  95. if model_type not in subclasses:
  96. raise ValueError(f"Unsupported model type: {model_type}")
  97. return subclasses[model_type](model_name, **model_kwargs)
  98. def clear_cache(self) -> None:
  99. if not self.cache_dir.exists():
  100. log.warn(
  101. f"Attempted to clear cache for model '{self.model_name}' but cache directory does not exist.",
  102. )
  103. return
  104. if not rmtree.avoids_symlink_attacks:
  105. raise RuntimeError("Attempted to clear cache, but rmtree is not safe on this platform.")
  106. if self.cache_dir.is_dir():
  107. log.info(f"Cleared cache directory for model '{self.model_name}'.")
  108. rmtree(self.cache_dir)
  109. else:
  110. log.warn(
  111. (
  112. f"Encountered file instead of directory at cache path "
  113. f"for '{self.model_name}'. Removing file and replacing with a directory."
  114. ),
  115. )
  116. self.cache_dir.unlink()
  117. self.cache_dir.mkdir(parents=True, exist_ok=True)
  118. # HF deep copies configs, so we need to make session options picklable
  119. class PicklableSessionOptions(ort.SessionOptions): # type: ignore[misc]
  120. def __getstate__(self) -> bytes:
  121. return pickle.dumps([(attr, getattr(self, attr)) for attr in dir(self) if not callable(getattr(self, attr))])
  122. def __setstate__(self, state: Buffer) -> None:
  123. self.__init__() # type: ignore[misc]
  124. attrs: list[tuple[str, Any]] = pickle.loads(state)
  125. for attr, val in attrs:
  126. setattr(self, attr, val)