_api.py 7.56 KB
Newer Older
1
2
3
import importlib
import inspect
import sys
4
from dataclasses import dataclass, fields
5
from inspect import signature
6
7
8
9
from types import ModuleType
from typing import Any, Callable, cast, Dict, List, Mapping, Optional, TypeVar, Union

from torch import nn
10

Philip Meier's avatar
Philip Meier committed
11
12
from torchvision._utils import StrEnum

13
from .._internally_replaced_utils import load_state_dict_from_url
14
15


16
__all__ = ["WeightsEnum", "Weights", "get_model", "get_model_builder", "get_model_weights", "get_weight", "list_models"]
17
18
19


@dataclass
20
class Weights:
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    """
    This class is used to group important attributes associated with the pre-trained weights.

    Args:
        url (str): The location where we find the weights.
        transforms (Callable): A callable that constructs the preprocessing method (or validation preset transforms)
            needed to use the model. The reason we attach a constructor method rather than an already constructed
            object is because the specific object might have memory and thus we want to delay initialization until
            needed.
        meta (Dict[str, Any]): Stores meta-data related to the weights of the model and its configuration. These can be
            informative attributes (for example the number of parameters/flops, recipe link/methods used in training
            etc), configuration parameters (for example the `num_classes`) needed to construct the model or important
            meta-data (for example the `classes` of a classification model) needed to use the model.
    """

    url: str
    transforms: Callable
    meta: Dict[str, Any]


Philip Meier's avatar
Philip Meier committed
41
class WeightsEnum(StrEnum):
42
43
44
    """
    This class is the parent class of all model weights. Each model building method receives an optional `weights`
    parameter with its associated pre-trained weights. It inherits from `Enum` and its values should be of type
45
    `Weights`.
46
47

    Args:
48
        value (Weights): The data class entry with the weight information.
49
50
    """

51
    def __init__(self, value: Weights):
52
53
54
55
56
57
        self._value_ = value

    @classmethod
    def verify(cls, obj: Any) -> Any:
        if obj is not None:
            if type(obj) is str:
58
                obj = cls.from_str(obj.replace(cls.__name__ + ".", ""))
59
            elif not isinstance(obj, cls):
60
                raise TypeError(
61
                    f"Invalid Weight class provided; expected {cls.__name__} but received {obj.__class__.__name__}."
62
63
64
                )
        return obj

65
    def get_state_dict(self, progress: bool) -> Mapping[str, Any]:
66
67
        return load_state_dict_from_url(self.url, progress=progress)

Joao Gomes's avatar
Joao Gomes committed
68
    def __repr__(self) -> str:
69
70
71
        return f"{self.__class__.__name__}.{self._name_}"

    def __getattr__(self, name):
72
73
        # Be able to fetch Weights attributes directly
        for f in fields(Weights):
74
75
76
            if f.name == name:
                return object.__getattribute__(self.value, name)
        return super().__getattr__(name)
77

78
79
80
    def __deepcopy__(self, memodict=None):
        return self

81

82
def get_weight(name: str) -> WeightsEnum:
83
    """
84
85
86
    Gets the weights enum value by its full name. Example: "ResNet50_Weights.IMAGENET1K_V1"

    .. betastatus:: function
87
88

    Args:
89
        name (str): The name of the weight enum entry.
90
91

    Returns:
92
        WeightsEnum: The requested weight enum.
93
    """
94
95
96
97
98
99
100
101
102
103
    try:
        enum_name, value_name = name.split(".")
    except ValueError:
        raise ValueError(f"Invalid weight name provided: '{name}'.")

    base_module_name = ".".join(sys.modules[__name__].__name__.split(".")[:-1])
    base_module = importlib.import_module(base_module_name)
    model_modules = [base_module] + [
        x[1] for x in inspect.getmembers(base_module, inspect.ismodule) if x[1].__file__.endswith("__init__.py")
    ]
104

105
    weights_enum = None
106
107
108
109
110
    for m in model_modules:
        potential_class = m.__dict__.get(enum_name, None)
        if potential_class is not None and issubclass(potential_class, WeightsEnum):
            weights_enum = potential_class
            break
111

112
    if weights_enum is None:
113
        raise ValueError(f"The weight enum '{enum_name}' for the specific method couldn't be retrieved.")
114

115
    return weights_enum.from_str(value_name)
116
117


118
def get_model_weights(name: Union[Callable, str]) -> WeightsEnum:
119
    """
120
    Returns the weights enum class associated to the given model.
121
122
123
124
125
126
127

    .. betastatus:: function

    Args:
        name (callable or str): The model builder function or the name under which it is registered.

    Returns:
128
        weights_enum (WeightsEnum): The weights enum class associated with the model.
129
    """
130
    model = get_model_builder(name) if isinstance(name, str) else name
131
    return _get_enum_from_fn(model)
132
133


134
def _get_enum_from_fn(fn: Callable) -> WeightsEnum:
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
    """
    Internal method that gets the weight enum of a specific model builder method.

    Args:
        fn (Callable): The builder method used to create the model.
    Returns:
        WeightsEnum: The requested weight enum.
    """
    sig = signature(fn)
    if "weights" not in sig.parameters:
        raise ValueError("The method is missing the 'weights' argument.")

    ann = signature(fn).parameters["weights"].annotation
    weights_enum = None
    if isinstance(ann, type) and issubclass(ann, WeightsEnum):
        weights_enum = ann
    else:
        # handle cases like Union[Optional, T]
        # TODO: Replace ann.__args__ with typing.get_args(ann) after python >= 3.8
        for t in ann.__args__:  # type: ignore[union-attr]
            if isinstance(t, type) and issubclass(t, WeightsEnum):
                weights_enum = t
                break

    if weights_enum is None:
        raise ValueError(
            "The WeightsEnum class for the specific method couldn't be retrieved. Make sure the typing info is correct."
        )

    return cast(WeightsEnum, weights_enum)
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200


M = TypeVar("M", bound=nn.Module)

BUILTIN_MODELS = {}


def register_model(name: Optional[str] = None) -> Callable[[Callable[..., M]], Callable[..., M]]:
    def wrapper(fn: Callable[..., M]) -> Callable[..., M]:
        key = name if name is not None else fn.__name__
        if key in BUILTIN_MODELS:
            raise ValueError(f"An entry is already registered under the name '{key}'.")
        BUILTIN_MODELS[key] = fn
        return fn

    return wrapper


def list_models(module: Optional[ModuleType] = None) -> List[str]:
    """
    Returns a list with the names of registered models.

    .. betastatus:: function

    Args:
        module (ModuleType, optional): The module from which we want to extract the available models.

    Returns:
        models (list): A list with the names of available models.
    """
    models = [
        k for k, v in BUILTIN_MODELS.items() if module is None or v.__module__.rsplit(".", 1)[0] == module.__name__
    ]
    return sorted(models)


201
def get_model_builder(name: str) -> Callable[..., nn.Module]:
202
203
204
205
206
207
208
209
210
211
212
    """
    Gets the model name and returns the model builder method.

    .. betastatus:: function

    Args:
        name (str): The name under which the model is registered.

    Returns:
        fn (Callable): The model builder method.
    """
213
214
215
216
217
218
219
220
    name = name.lower()
    try:
        fn = BUILTIN_MODELS[name]
    except KeyError:
        raise ValueError(f"Unknown model {name}")
    return fn


221
def get_model(name: str, **config: Any) -> nn.Module:
222
223
224
225
226
227
228
229
230
231
232
233
    """
    Gets the model name and configuration and returns an instantiated model.

    .. betastatus:: function

    Args:
        name (str): The name under which the model is registered.
        **config (Any): parameters passed to the model builder method.

    Returns:
        model (nn.Module): The initialized model.
    """
234
    fn = get_model_builder(name)
235
    return fn(**config)