_api.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. import importlib
  2. import inspect
  3. import sys
  4. from dataclasses import dataclass, fields
  5. from inspect import signature
  6. from typing import Any, Callable, Dict, cast
  7. from torchvision._utils import StrEnum
  8. from .._internally_replaced_utils import load_state_dict_from_url
  9. __all__ = ["WeightsEnum", "Weights", "get_weight"]
  10. @dataclass
  11. class Weights:
  12. """
  13. This class is used to group important attributes associated with the pre-trained weights.
  14. Args:
  15. url (str): The location where we find the weights.
  16. transforms (Callable): A callable that constructs the preprocessing method (or validation preset transforms)
  17. needed to use the model. The reason we attach a constructor method rather than an already constructed
  18. object is because the specific object might have memory and thus we want to delay initialization until
  19. needed.
  20. meta (Dict[str, Any]): Stores meta-data related to the weights of the model and its configuration. These can be
  21. informative attributes (for example the number of parameters/flops, recipe link/methods used in training
  22. etc), configuration parameters (for example the `num_classes`) needed to construct the model or important
  23. meta-data (for example the `classes` of a classification model) needed to use the model.
  24. """
  25. url: str
  26. transforms: Callable
  27. meta: Dict[str, Any]
  28. class WeightsEnum(StrEnum):
  29. """
  30. This class is the parent class of all model weights. Each model building method receives an optional `weights`
  31. parameter with its associated pre-trained weights. It inherits from `Enum` and its values should be of type
  32. `Weights`.
  33. Args:
  34. value (Weights): The data class entry with the weight information.
  35. """
  36. def __init__(self, value: Weights):
  37. self._value_ = value
  38. @classmethod
  39. def verify(cls, obj: Any) -> Any:
  40. if obj is not None:
  41. if type(obj) is str:
  42. obj = cls.from_str(obj.replace(cls.__name__ + ".", ""))
  43. elif not isinstance(obj, cls):
  44. raise TypeError(
  45. f"Invalid Weight class provided; expected {cls.__name__} but received {obj.__class__.__name__}."
  46. )
  47. return obj
  48. def get_state_dict(self, progress: bool) -> Dict[str, Any]:
  49. return load_state_dict_from_url(self.url, progress=progress)
  50. def __repr__(self) -> str:
  51. return f"{self.__class__.__name__}.{self._name_}"
  52. def __getattr__(self, name):
  53. # Be able to fetch Weights attributes directly
  54. for f in fields(Weights):
  55. if f.name == name:
  56. return object.__getattribute__(self.value, name)
  57. return super().__getattr__(name)
  58. def get_weight(name: str) -> WeightsEnum:
  59. """
  60. Gets the weight enum value by its full name. Example: "ResNet50_Weights.IMAGENET1K_V1"
  61. Args:
  62. name (str): The name of the weight enum entry.
  63. Returns:
  64. WeightsEnum: The requested weight enum.
  65. """
  66. try:
  67. enum_name, value_name = name.split(".")
  68. except ValueError:
  69. raise ValueError(f"Invalid weight name provided: '{name}'.")
  70. base_module_name = ".".join(sys.modules[__name__].__name__.split(".")[:-1])
  71. base_module = importlib.import_module(base_module_name)
  72. model_modules = [base_module] + [
  73. x[1] for x in inspect.getmembers(base_module, inspect.ismodule) if x[1].__file__.endswith("__init__.py")
  74. ]
  75. weights_enum = None
  76. for m in model_modules:
  77. potential_class = m.__dict__.get(enum_name, None)
  78. if potential_class is not None and issubclass(potential_class, WeightsEnum):
  79. weights_enum = potential_class
  80. break
  81. if weights_enum is None:
  82. raise ValueError(f"The weight enum '{enum_name}' for the specific method couldn't be retrieved.")
  83. return weights_enum.from_str(value_name)
  84. def _get_enum_from_fn(fn: Callable) -> WeightsEnum:
  85. """
  86. Internal method that gets the weight enum of a specific model builder method.
  87. Might be removed after the handle_legacy_interface is removed.
  88. Args:
  89. fn (Callable): The builder method used to create the model.
  90. weight_name (str): The name of the weight enum entry of the specific model.
  91. Returns:
  92. WeightsEnum: The requested weight enum.
  93. """
  94. sig = signature(fn)
  95. if "weights" not in sig.parameters:
  96. raise ValueError("The method is missing the 'weights' argument.")
  97. ann = signature(fn).parameters["weights"].annotation
  98. weights_enum = None
  99. if isinstance(ann, type) and issubclass(ann, WeightsEnum):
  100. weights_enum = ann
  101. else:
  102. # handle cases like Union[Optional, T]
  103. # TODO: Replace ann.__args__ with typing.get_args(ann) after python >= 3.8
  104. for t in ann.__args__: # type: ignore[union-attr]
  105. if isinstance(t, type) and issubclass(t, WeightsEnum):
  106. weights_enum = t
  107. break
  108. if weights_enum is None:
  109. raise ValueError(
  110. "The WeightsEnum class for the specific method couldn't be retrieved. Make sure the typing info is correct."
  111. )
  112. return cast(WeightsEnum, weights_enum)