base.py 5.3 KB

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