_api.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import fnmatch
  2. import importlib
  3. import inspect
  4. import sys
  5. from dataclasses import dataclass
  6. from enum import Enum
  7. from functools import partial
  8. from inspect import signature
  9. from types import ModuleType
  10. from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Set, Type, TypeVar, Union
  11. from torch import nn
  12. from .._internally_replaced_utils import load_state_dict_from_url
  13. __all__ = ["WeightsEnum", "Weights", "get_model", "get_model_builder", "get_model_weights", "get_weight", "list_models"]
  14. @dataclass
  15. class Weights:
  16. """
  17. This class is used to group important attributes associated with the pre-trained weights.
  18. Args:
  19. url (str): The location where we find the weights.
  20. transforms (Callable): A callable that constructs the preprocessing method (or validation preset transforms)
  21. needed to use the model. The reason we attach a constructor method rather than an already constructed
  22. object is because the specific object might have memory and thus we want to delay initialization until
  23. needed.
  24. meta (Dict[str, Any]): Stores meta-data related to the weights of the model and its configuration. These can be
  25. informative attributes (for example the number of parameters/flops, recipe link/methods used in training
  26. etc), configuration parameters (for example the `num_classes`) needed to construct the model or important
  27. meta-data (for example the `classes` of a classification model) needed to use the model.
  28. """
  29. url: str
  30. transforms: Callable
  31. meta: Dict[str, Any]
  32. def __eq__(self, other: Any) -> bool:
  33. # We need this custom implementation for correct deep-copy and deserialization behavior.
  34. # TL;DR: After the definition of an enum, creating a new instance, i.e. by deep-copying or deserializing it,
  35. # involves an equality check against the defined members. Unfortunately, the `transforms` attribute is often
  36. # defined with `functools.partial` and `fn = partial(...); assert deepcopy(fn) != fn`. Without custom handling
  37. # for it, the check against the defined members would fail and effectively prevent the weights from being
  38. # deep-copied or deserialized.
  39. # See https://github.com/pytorch/vision/pull/7107 for details.
  40. if not isinstance(other, Weights):
  41. return NotImplemented
  42. if self.url != other.url:
  43. return False
  44. if self.meta != other.meta:
  45. return False
  46. if isinstance(self.transforms, partial) and isinstance(other.transforms, partial):
  47. return (
  48. self.transforms.func == other.transforms.func
  49. and self.transforms.args == other.transforms.args
  50. and self.transforms.keywords == other.transforms.keywords
  51. )
  52. else:
  53. return self.transforms == other.transforms
  54. class WeightsEnum(Enum):
  55. """
  56. This class is the parent class of all model weights. Each model building method receives an optional `weights`
  57. parameter with its associated pre-trained weights. It inherits from `Enum` and its values should be of type
  58. `Weights`.
  59. Args:
  60. value (Weights): The data class entry with the weight information.
  61. """
  62. @classmethod
  63. def verify(cls, obj: Any) -> Any:
  64. if obj is not None:
  65. if type(obj) is str:
  66. obj = cls[obj.replace(cls.__name__ + ".", "")]
  67. elif not isinstance(obj, cls):
  68. raise TypeError(
  69. f"Invalid Weight class provided; expected {cls.__name__} but received {obj.__class__.__name__}."
  70. )
  71. return obj
  72. def get_state_dict(self, *args: Any, **kwargs: Any) -> Mapping[str, Any]:
  73. return load_state_dict_from_url(self.url, *args, **kwargs)
  74. def __repr__(self) -> str:
  75. return f"{self.__class__.__name__}.{self._name_}"
  76. @property
  77. def url(self):
  78. return self.value.url
  79. @property
  80. def transforms(self):
  81. return self.value.transforms
  82. @property
  83. def meta(self):
  84. return self.value.meta
  85. def get_weight(name: str) -> WeightsEnum:
  86. """
  87. Gets the weights enum value by its full name. Example: "ResNet50_Weights.IMAGENET1K_V1"
  88. Args:
  89. name (str): The name of the weight enum entry.
  90. Returns:
  91. WeightsEnum: The requested weight enum.
  92. """
  93. try:
  94. enum_name, value_name = name.split(".")
  95. except ValueError:
  96. raise ValueError(f"Invalid weight name provided: '{name}'.")
  97. base_module_name = ".".join(sys.modules[__name__].__name__.split(".")[:-1])
  98. base_module = importlib.import_module(base_module_name)
  99. model_modules = [base_module] + [
  100. x[1]
  101. for x in inspect.getmembers(base_module, inspect.ismodule)
  102. if x[1].__file__.endswith("__init__.py") # type: ignore[union-attr]
  103. ]
  104. weights_enum = None
  105. for m in model_modules:
  106. potential_class = m.__dict__.get(enum_name, None)
  107. if potential_class is not None and issubclass(potential_class, WeightsEnum):
  108. weights_enum = potential_class
  109. break
  110. if weights_enum is None:
  111. raise ValueError(f"The weight enum '{enum_name}' for the specific method couldn't be retrieved.")
  112. return weights_enum[value_name]
  113. def get_model_weights(name: Union[Callable, str]) -> Type[WeightsEnum]:
  114. """
  115. Returns the weights enum class associated to the given model.
  116. Args:
  117. name (callable or str): The model builder function or the name under which it is registered.
  118. Returns:
  119. weights_enum (WeightsEnum): The weights enum class associated with the model.
  120. """
  121. model = get_model_builder(name) if isinstance(name, str) else name
  122. return _get_enum_from_fn(model)
  123. def _get_enum_from_fn(fn: Callable) -> Type[WeightsEnum]:
  124. """
  125. Internal method that gets the weight enum of a specific model builder method.
  126. Args:
  127. fn (Callable): The builder method used to create the model.
  128. Returns:
  129. WeightsEnum: The requested weight enum.
  130. """
  131. sig = signature(fn)
  132. if "weights" not in sig.parameters:
  133. raise ValueError("The method is missing the 'weights' argument.")
  134. ann = signature(fn).parameters["weights"].annotation
  135. weights_enum = None
  136. if isinstance(ann, type) and issubclass(ann, WeightsEnum):
  137. weights_enum = ann
  138. else:
  139. # handle cases like Union[Optional, T]
  140. # TODO: Replace ann.__args__ with typing.get_args(ann) after python >= 3.8
  141. for t in ann.__args__: # type: ignore[union-attr]
  142. if isinstance(t, type) and issubclass(t, WeightsEnum):
  143. weights_enum = t
  144. break
  145. if weights_enum is None:
  146. raise ValueError(
  147. "The WeightsEnum class for the specific method couldn't be retrieved. Make sure the typing info is correct."
  148. )
  149. return weights_enum
  150. M = TypeVar("M", bound=nn.Module)
  151. BUILTIN_MODELS = {}
  152. def register_model(name: Optional[str] = None) -> Callable[[Callable[..., M]], Callable[..., M]]:
  153. def wrapper(fn: Callable[..., M]) -> Callable[..., M]:
  154. key = name if name is not None else fn.__name__
  155. if key in BUILTIN_MODELS:
  156. raise ValueError(f"An entry is already registered under the name '{key}'.")
  157. BUILTIN_MODELS[key] = fn
  158. return fn
  159. return wrapper
  160. def list_models(
  161. module: Optional[ModuleType] = None,
  162. include: Union[Iterable[str], str, None] = None,
  163. exclude: Union[Iterable[str], str, None] = None,
  164. ) -> List[str]:
  165. """
  166. Returns a list with the names of registered models.
  167. Args:
  168. module (ModuleType, optional): The module from which we want to extract the available models.
  169. include (str or Iterable[str], optional): Filter(s) for including the models from the set of all models.
  170. Filters are passed to `fnmatch <https://docs.python.org/3/library/fnmatch.html>`__ to match Unix shell-style
  171. wildcards. In case of many filters, the results is the union of individual filters.
  172. exclude (str or Iterable[str], optional): Filter(s) applied after include_filters to remove models.
  173. Filter are passed to `fnmatch <https://docs.python.org/3/library/fnmatch.html>`__ to match Unix shell-style
  174. wildcards. In case of many filters, the results is removal of all the models that match any individual filter.
  175. Returns:
  176. models (list): A list with the names of available models.
  177. """
  178. all_models = {
  179. k for k, v in BUILTIN_MODELS.items() if module is None or v.__module__.rsplit(".", 1)[0] == module.__name__
  180. }
  181. if include:
  182. models: Set[str] = set()
  183. if isinstance(include, str):
  184. include = [include]
  185. for include_filter in include:
  186. models = models | set(fnmatch.filter(all_models, include_filter))
  187. else:
  188. models = all_models
  189. if exclude:
  190. if isinstance(exclude, str):
  191. exclude = [exclude]
  192. for exclude_filter in exclude:
  193. models = models - set(fnmatch.filter(all_models, exclude_filter))
  194. return sorted(models)
  195. def get_model_builder(name: str) -> Callable[..., nn.Module]:
  196. """
  197. Gets the model name and returns the model builder method.
  198. Args:
  199. name (str): The name under which the model is registered.
  200. Returns:
  201. fn (Callable): The model builder method.
  202. """
  203. name = name.lower()
  204. try:
  205. fn = BUILTIN_MODELS[name]
  206. except KeyError:
  207. raise ValueError(f"Unknown model {name}")
  208. return fn
  209. def get_model(name: str, **config: Any) -> nn.Module:
  210. """
  211. Gets the model name and configuration and returns an instantiated model.
  212. Args:
  213. name (str): The name under which the model is registered.
  214. **config (Any): parameters passed to the model builder method.
  215. Returns:
  216. model (nn.Module): The initialized model.
  217. """
  218. fn = get_model_builder(name)
  219. return fn(**config)