We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
deepcopying retinanet fails
### 🐛 Describe the bug

Deepcoping retinanet fails

```py
from torchvision.models.detection.retinanet import retinanet_resnet50_fpn
from torchvision.models.resnet import ResNet50_Weights
from copy import deepcopy
from torch import nn


class RetinaNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.weights_backbone = ResNet50_Weights.IMAGENET1K_V1
        self.model = retinanet_resnet50_fpn(weights=None, weights_backbone=self.weights_backbone)

if __name__ == '__main__':
    deepcopy(RetinaNet())
```

Error:
```console
le "/Users/goku/Desktop/work/repos/lightning-bolts/build/tmp2.py", line 15, in <module>
    deepcopy(RetinaNet())
  File "/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/copy.py", line 172, in deepcopy
    y = _reconstruct(x, memo, *rv)
  File "/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/copy.py", line 270, in _reconstruct
    state = deepcopy(state, memo)
  File "/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/copy.py", line 146, in deepcopy
    y = copier(x, memo)
  File "/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/copy.py", line 230, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/copy.py", line 172, in deepcopy
    y = _reconstruct(x, memo, *rv)
  File "/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/copy.py", line 264, in _reconstruct
    y = func(*args)
  File "/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/enum.py", line 384, in __call__
    return cls.__new__(cls, value)
  File "/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/enum.py", line 702, in __new__
    raise ve_exc
ValueError: Weights(url='https://download.pytorch.org/models/resnet50-0676ba61.pth', transforms=functools.partial(<class 'torchvision.transforms._presets.ImageClassification'>, crop_size=224), meta={'min_size': (1, 1), 'categories': ['tench', 'goldfish', 'great white shark', ...}}, '_docs': 'These weights reproduce closely the results of the paper using a simple training recipe.'}) is not a valid ResNet50_Weights
```

In short this fails:
```python
from copy import deepcopy
from torchvision.models.resnet import ResNet50_Weights

deepcopy(ResNet50_Weights.IMAGENET1K_V1)
```

### Versions

```console
Collecting environment information...
PyTorch version: 1.13.0
Is debug build: False
CUDA used to build PyTorch: None
ROCM used to build PyTorch: N/A

OS: macOS 11.6 (x86_64)
GCC version: Could not collect
Clang version: 13.0.0 (clang-1300.0.29.3)
CMake version: version 3.21.3
Libc version: N/A

Python version: 3.9.13 (main, Oct 13 2022, 16:12:30)  [Clang 12.0.0 ] (64-
Python platform: macOS-10.16-x86_64-i386-64bit
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

Versions of relevant libraries:
[pip3] numpy==1.23.4
[pip3] pytorch-lightning==1.8.0rc1
[pip3] torch==1.13.0
[pip3] torchmetrics==0.10.1
[pip3] torchvision==0.14.0
[conda] numpy                     1.23.4                   pypi_0    pypi
[conda] pytorch-lightning         1.8.0rc1                 pypi_0    pypi
[conda] torch                     1.13.0                   pypi_0    pypi
[conda] torchmetrics              0.10.1                   pypi_0    pypi
[conda] torchvision               0.14.0                   pypi_0    pypi
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `torchvision/models/_api.py`
Content:
```
1 import importlib
2 import inspect
3 import sys
4 from dataclasses import dataclass, fields
5 from inspect import signature
6 from types import ModuleType
7 from typing import Any, Callable, cast, Dict, List, Mapping, Optional, TypeVar, Union
8 
9 from torch import nn
10 
11 from torchvision._utils import StrEnum
12 
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     This class is used to group important attributes associated with the pre-trained weights.
23 
24     Args:
25         url (str): The location where we find the weights.
26         transforms (Callable): A callable that constructs the preprocessing method (or validation preset transforms)
27             needed to use the model. The reason we attach a constructor method rather than an already constructed
28             object is because the specific object might have memory and thus we want to delay initialization until
29             needed.
30         meta (Dict[str, Any]): Stores meta-data related to the weights of the model and its configuration. These can be
31             informative attributes (for example the number of parameters/flops, recipe link/methods used in training
32             etc), configuration parameters (for example the `num_classes`) needed to construct the model or important
33             meta-data (for example the `classes` of a classification model) needed to use the model.
34     """
35 
36     url: str
37     transforms: Callable
38     meta: Dict[str, Any]
39 
40 
41 class WeightsEnum(StrEnum):
42     """
43     This class is the parent class of all model weights. Each model building method receives an optional `weights`
44     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         self._value_ = value
53 
54     @classmethod
55     def verify(cls, obj: Any) -> Any:
56         if obj is not None:
57             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         return obj
64 
65     def get_state_dict(self, progress: bool) -> Mapping[str, Any]:
66         return load_state_dict_from_url(self.url, progress=progress)
67 
68     def __repr__(self) -> str:
69         return f"{self.__class__.__name__}.{self._name_}"
70 
71     def __getattr__(self, name):
72         # Be able to fetch Weights attributes directly
73         for f in fields(Weights):
74             if f.name == name:
75                 return object.__getattribute__(self.value, name)
76         return super().__getattr__(name)
77 
78 
79 def get_weight(name: str) -> WeightsEnum:
80     """
81     Gets the weights enum value by its full name. Example: "ResNet50_Weights.IMAGENET1K_V1"
82 
83     .. betastatus:: function
84 
85     Args:
86         name (str): The name of the weight enum entry.
87 
88     Returns:
89         WeightsEnum: The requested weight enum.
90     """
91     try:
92         enum_name, value_name = name.split(".")
93     except ValueError:
94         raise ValueError(f"Invalid weight name provided: '{name}'.")
95 
96     base_module_name = ".".join(sys.modules[__name__].__name__.split(".")[:-1])
97     base_module = importlib.import_module(base_module_name)
98     model_modules = [base_module] + [
99         x[1] for x in inspect.getmembers(base_module, inspect.ismodule) if x[1].__file__.endswith("__init__.py")
100     ]
101 
102     weights_enum = None
103     for m in model_modules:
104         potential_class = m.__dict__.get(enum_name, None)
105         if potential_class is not None and issubclass(potential_class, WeightsEnum):
106             weights_enum = potential_class
107             break
108 
109     if weights_enum is None:
110         raise ValueError(f"The weight enum '{enum_name}' for the specific method couldn't be retrieved.")
111 
112     return weights_enum.from_str(value_name)
113 
114 
115 def get_model_weights(name: Union[Callable, str]) -> WeightsEnum:
116     """
117     Retuns the weights enum class associated to the given model.
118 
119     .. betastatus:: function
120 
121     Args:
122         name (callable or str): The model builder function or the name under which it is registered.
123 
124     Returns:
125         weights_enum (WeightsEnum): The weights enum class associated with the model.
126     """
127     model = get_model_builder(name) if isinstance(name, str) else name
128     return _get_enum_from_fn(model)
129 
130 
131 def _get_enum_from_fn(fn: Callable) -> WeightsEnum:
132     """
133     Internal method that gets the weight enum of a specific model builder method.
134 
135     Args:
136         fn (Callable): The builder method used to create the model.
137         weight_name (str): The name of the weight enum entry of the specific model.
138     Returns:
139         WeightsEnum: The requested weight enum.
140     """
141     sig = signature(fn)
142     if "weights" not in sig.parameters:
143         raise ValueError("The method is missing the 'weights' argument.")
144 
145     ann = signature(fn).parameters["weights"].annotation
146     weights_enum = None
147     if isinstance(ann, type) and issubclass(ann, WeightsEnum):
148         weights_enum = ann
149     else:
150         # handle cases like Union[Optional, T]
151         # TODO: Replace ann.__args__ with typing.get_args(ann) after python >= 3.8
152         for t in ann.__args__:  # type: ignore[union-attr]
153             if isinstance(t, type) and issubclass(t, WeightsEnum):
154                 weights_enum = t
155                 break
156 
157     if weights_enum is None:
158         raise ValueError(
159             "The WeightsEnum class for the specific method couldn't be retrieved. Make sure the typing info is correct."
160         )
161 
162     return cast(WeightsEnum, weights_enum)
163 
164 
165 M = TypeVar("M", bound=nn.Module)
166 
167 BUILTIN_MODELS = {}
168 
169 
170 def register_model(name: Optional[str] = None) -> Callable[[Callable[..., M]], Callable[..., M]]:
171     def wrapper(fn: Callable[..., M]) -> Callable[..., M]:
172         key = name if name is not None else fn.__name__
173         if key in BUILTIN_MODELS:
174             raise ValueError(f"An entry is already registered under the name '{key}'.")
175         BUILTIN_MODELS[key] = fn
176         return fn
177 
178     return wrapper
179 
180 
181 def list_models(module: Optional[ModuleType] = None) -> List[str]:
182     """
183     Returns a list with the names of registered models.
184 
185     .. betastatus:: function
186 
187     Args:
188         module (ModuleType, optional): The module from which we want to extract the available models.
189 
190     Returns:
191         models (list): A list with the names of available models.
192     """
193     models = [
194         k for k, v in BUILTIN_MODELS.items() if module is None or v.__module__.rsplit(".", 1)[0] == module.__name__
195     ]
196     return sorted(models)
197 
198 
199 def get_model_builder(name: str) -> Callable[..., nn.Module]:
200     """
201     Gets the model name and returns the model builder method.
202 
203     .. betastatus:: function
204 
205     Args:
206         name (str): The name under which the model is registered.
207 
208     Returns:
209         fn (Callable): The model builder method.
210     """
211     name = name.lower()
212     try:
213         fn = BUILTIN_MODELS[name]
214     except KeyError:
215         raise ValueError(f"Unknown model {name}")
216     return fn
217 
218 
219 def get_model(name: str, **config: Any) -> nn.Module:
220     """
221     Gets the model name and configuration and returns an instantiated model.
222 
223     .. betastatus:: function
224 
225     Args:
226         name (str): The name under which the model is registered.
227         **config (Any): parameters passed to the model builder method.
228 
229     Returns:
230         model (nn.Module): The initialized model.
231     """
232     fn = get_model_builder(name)
233     return fn(**config)
234
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/torchvision/models/_api.py b/torchvision/models/_api.py
--- a/torchvision/models/_api.py
+++ b/torchvision/models/_api.py
@@ -75,6 +75,9 @@
                 return object.__getattribute__(self.value, name)
         return super().__getattr__(name)
 
+    def __deepcopy__(self, memodict=None):
+        return self
+
 
 def get_weight(name: str) -> WeightsEnum:
     """

{"golden_diff": "diff --git a/torchvision/models/_api.py b/torchvision/models/_api.py\n--- a/torchvision/models/_api.py\n+++ b/torchvision/models/_api.py\n@@ -75,6 +75,9 @@\n                 return object.__getattribute__(self.value, name)\n         return super().__getattr__(name)\n \n+    def __deepcopy__(self, memodict=None):\n+        return self\n+\n \n def get_weight(name: str) -> WeightsEnum:\n     \"\"\"\n", "issue": "deepcopying retinanet fails\n### \ud83d\udc1b Describe the bug\n\nDeepcoping retinanet fails\r\n\r\n```py\r\nfrom torchvision.models.detection.retinanet import retinanet_resnet50_fpn\r\nfrom torchvision.models.resnet import ResNet50_Weights\r\nfrom copy import deepcopy\r\nfrom torch import nn\r\n\r\n\r\nclass RetinaNet(nn.Module):\r\n    def __init__(self):\r\n        super().__init__()\r\n        self.weights_backbone = ResNet50_Weights.IMAGENET1K_V1\r\n        self.model = retinanet_resnet50_fpn(weights=None, weights_backbone=self.weights_backbone)\r\n\r\nif __name__ == '__main__':\r\n    deepcopy(RetinaNet())\r\n```\r\n\r\nError:\r\n```console\r\nle \"/Users/goku/Desktop/work/repos/lightning-bolts/build/tmp2.py\", line 15, in <module>\r\n    deepcopy(RetinaNet())\r\n  File \"/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/copy.py\", line 172, in deepcopy\r\n    y = _reconstruct(x, memo, *rv)\r\n  File \"/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/copy.py\", line 270, in _reconstruct\r\n    state = deepcopy(state, memo)\r\n  File \"/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/copy.py\", line 146, in deepcopy\r\n    y = copier(x, memo)\r\n  File \"/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/copy.py\", line 230, in _deepcopy_dict\r\n    y[deepcopy(key, memo)] = deepcopy(value, memo)\r\n  File \"/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/copy.py\", line 172, in deepcopy\r\n    y = _reconstruct(x, memo, *rv)\r\n  File \"/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/copy.py\", line 264, in _reconstruct\r\n    y = func(*args)\r\n  File \"/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/enum.py\", line 384, in __call__\r\n    return cls.__new__(cls, value)\r\n  File \"/Users/goku/miniconda3/envs/lit_bolts/lib/python3.9/enum.py\", line 702, in __new__\r\n    raise ve_exc\r\nValueError: Weights(url='https://download.pytorch.org/models/resnet50-0676ba61.pth', transforms=functools.partial(<class 'torchvision.transforms._presets.ImageClassification'>, crop_size=224), meta={'min_size': (1, 1), 'categories': ['tench', 'goldfish', 'great white shark', ...}}, '_docs': 'These weights reproduce closely the results of the paper using a simple training recipe.'}) is not a valid ResNet50_Weights\r\n```\r\n\r\nIn short this fails:\r\n```python\r\nfrom copy import deepcopy\r\nfrom torchvision.models.resnet import ResNet50_Weights\r\n\r\ndeepcopy(ResNet50_Weights.IMAGENET1K_V1)\r\n```\n\n### Versions\n\n```console\r\nCollecting environment information...\r\nPyTorch version: 1.13.0\r\nIs debug build: False\r\nCUDA used to build PyTorch: None\r\nROCM used to build PyTorch: N/A\r\n\r\nOS: macOS 11.6 (x86_64)\r\nGCC version: Could not collect\r\nClang version: 13.0.0 (clang-1300.0.29.3)\r\nCMake version: version 3.21.3\r\nLibc version: N/A\r\n\r\nPython version: 3.9.13 (main, Oct 13 2022, 16:12:30)  [Clang 12.0.0 ] (64-\r\nPython platform: macOS-10.16-x86_64-i386-64bit\r\nIs CUDA available: False\r\nCUDA runtime version: No CUDA\r\nCUDA_MODULE_LOADING set to: N/A\r\nGPU models and configuration: No CUDA\r\nNvidia driver version: No CUDA\r\ncuDNN version: No CUDA\r\nHIP runtime version: N/A\r\nMIOpen runtime version: N/A\r\nIs XNNPACK available: True\r\n\r\nVersions of relevant libraries:\r\n[pip3] numpy==1.23.4\r\n[pip3] pytorch-lightning==1.8.0rc1\r\n[pip3] torch==1.13.0\r\n[pip3] torchmetrics==0.10.1\r\n[pip3] torchvision==0.14.0\r\n[conda] numpy                     1.23.4                   pypi_0    pypi\r\n[conda] pytorch-lightning         1.8.0rc1                 pypi_0    pypi\r\n[conda] torch                     1.13.0                   pypi_0    pypi\r\n[conda] torchmetrics              0.10.1                   pypi_0    pypi\r\n[conda] torchvision               0.14.0                   pypi_0    pypi\r\n```\n", "before_files": [{"content": "import importlib\nimport inspect\nimport sys\nfrom dataclasses import dataclass, fields\nfrom inspect import signature\nfrom types import ModuleType\nfrom typing import Any, Callable, cast, Dict, List, Mapping, Optional, TypeVar, Union\n\nfrom torch import nn\n\nfrom torchvision._utils import StrEnum\n\nfrom .._internally_replaced_utils import load_state_dict_from_url\n\n\n__all__ = [\"WeightsEnum\", \"Weights\", \"get_model\", \"get_model_builder\", \"get_model_weights\", \"get_weight\", \"list_models\"]\n\n\n@dataclass\nclass Weights:\n    \"\"\"\n    This class is used to group important attributes associated with the pre-trained weights.\n\n    Args:\n        url (str): The location where we find the weights.\n        transforms (Callable): A callable that constructs the preprocessing method (or validation preset transforms)\n            needed to use the model. The reason we attach a constructor method rather than an already constructed\n            object is because the specific object might have memory and thus we want to delay initialization until\n            needed.\n        meta (Dict[str, Any]): Stores meta-data related to the weights of the model and its configuration. These can be\n            informative attributes (for example the number of parameters/flops, recipe link/methods used in training\n            etc), configuration parameters (for example the `num_classes`) needed to construct the model or important\n            meta-data (for example the `classes` of a classification model) needed to use the model.\n    \"\"\"\n\n    url: str\n    transforms: Callable\n    meta: Dict[str, Any]\n\n\nclass WeightsEnum(StrEnum):\n    \"\"\"\n    This class is the parent class of all model weights. Each model building method receives an optional `weights`\n    parameter with its associated pre-trained weights. It inherits from `Enum` and its values should be of type\n    `Weights`.\n\n    Args:\n        value (Weights): The data class entry with the weight information.\n    \"\"\"\n\n    def __init__(self, value: Weights):\n        self._value_ = value\n\n    @classmethod\n    def verify(cls, obj: Any) -> Any:\n        if obj is not None:\n            if type(obj) is str:\n                obj = cls.from_str(obj.replace(cls.__name__ + \".\", \"\"))\n            elif not isinstance(obj, cls):\n                raise TypeError(\n                    f\"Invalid Weight class provided; expected {cls.__name__} but received {obj.__class__.__name__}.\"\n                )\n        return obj\n\n    def get_state_dict(self, progress: bool) -> Mapping[str, Any]:\n        return load_state_dict_from_url(self.url, progress=progress)\n\n    def __repr__(self) -> str:\n        return f\"{self.__class__.__name__}.{self._name_}\"\n\n    def __getattr__(self, name):\n        # Be able to fetch Weights attributes directly\n        for f in fields(Weights):\n            if f.name == name:\n                return object.__getattribute__(self.value, name)\n        return super().__getattr__(name)\n\n\ndef get_weight(name: str) -> WeightsEnum:\n    \"\"\"\n    Gets the weights enum value by its full name. Example: \"ResNet50_Weights.IMAGENET1K_V1\"\n\n    .. betastatus:: function\n\n    Args:\n        name (str): The name of the weight enum entry.\n\n    Returns:\n        WeightsEnum: The requested weight enum.\n    \"\"\"\n    try:\n        enum_name, value_name = name.split(\".\")\n    except ValueError:\n        raise ValueError(f\"Invalid weight name provided: '{name}'.\")\n\n    base_module_name = \".\".join(sys.modules[__name__].__name__.split(\".\")[:-1])\n    base_module = importlib.import_module(base_module_name)\n    model_modules = [base_module] + [\n        x[1] for x in inspect.getmembers(base_module, inspect.ismodule) if x[1].__file__.endswith(\"__init__.py\")\n    ]\n\n    weights_enum = None\n    for m in model_modules:\n        potential_class = m.__dict__.get(enum_name, None)\n        if potential_class is not None and issubclass(potential_class, WeightsEnum):\n            weights_enum = potential_class\n            break\n\n    if weights_enum is None:\n        raise ValueError(f\"The weight enum '{enum_name}' for the specific method couldn't be retrieved.\")\n\n    return weights_enum.from_str(value_name)\n\n\ndef get_model_weights(name: Union[Callable, str]) -> WeightsEnum:\n    \"\"\"\n    Retuns the weights enum class associated to the given model.\n\n    .. betastatus:: function\n\n    Args:\n        name (callable or str): The model builder function or the name under which it is registered.\n\n    Returns:\n        weights_enum (WeightsEnum): The weights enum class associated with the model.\n    \"\"\"\n    model = get_model_builder(name) if isinstance(name, str) else name\n    return _get_enum_from_fn(model)\n\n\ndef _get_enum_from_fn(fn: Callable) -> WeightsEnum:\n    \"\"\"\n    Internal method that gets the weight enum of a specific model builder method.\n\n    Args:\n        fn (Callable): The builder method used to create the model.\n        weight_name (str): The name of the weight enum entry of the specific model.\n    Returns:\n        WeightsEnum: The requested weight enum.\n    \"\"\"\n    sig = signature(fn)\n    if \"weights\" not in sig.parameters:\n        raise ValueError(\"The method is missing the 'weights' argument.\")\n\n    ann = signature(fn).parameters[\"weights\"].annotation\n    weights_enum = None\n    if isinstance(ann, type) and issubclass(ann, WeightsEnum):\n        weights_enum = ann\n    else:\n        # handle cases like Union[Optional, T]\n        # TODO: Replace ann.__args__ with typing.get_args(ann) after python >= 3.8\n        for t in ann.__args__:  # type: ignore[union-attr]\n            if isinstance(t, type) and issubclass(t, WeightsEnum):\n                weights_enum = t\n                break\n\n    if weights_enum is None:\n        raise ValueError(\n            \"The WeightsEnum class for the specific method couldn't be retrieved. Make sure the typing info is correct.\"\n        )\n\n    return cast(WeightsEnum, weights_enum)\n\n\nM = TypeVar(\"M\", bound=nn.Module)\n\nBUILTIN_MODELS = {}\n\n\ndef register_model(name: Optional[str] = None) -> Callable[[Callable[..., M]], Callable[..., M]]:\n    def wrapper(fn: Callable[..., M]) -> Callable[..., M]:\n        key = name if name is not None else fn.__name__\n        if key in BUILTIN_MODELS:\n            raise ValueError(f\"An entry is already registered under the name '{key}'.\")\n        BUILTIN_MODELS[key] = fn\n        return fn\n\n    return wrapper\n\n\ndef list_models(module: Optional[ModuleType] = None) -> List[str]:\n    \"\"\"\n    Returns a list with the names of registered models.\n\n    .. betastatus:: function\n\n    Args:\n        module (ModuleType, optional): The module from which we want to extract the available models.\n\n    Returns:\n        models (list): A list with the names of available models.\n    \"\"\"\n    models = [\n        k for k, v in BUILTIN_MODELS.items() if module is None or v.__module__.rsplit(\".\", 1)[0] == module.__name__\n    ]\n    return sorted(models)\n\n\ndef get_model_builder(name: str) -> Callable[..., nn.Module]:\n    \"\"\"\n    Gets the model name and returns the model builder method.\n\n    .. betastatus:: function\n\n    Args:\n        name (str): The name under which the model is registered.\n\n    Returns:\n        fn (Callable): The model builder method.\n    \"\"\"\n    name = name.lower()\n    try:\n        fn = BUILTIN_MODELS[name]\n    except KeyError:\n        raise ValueError(f\"Unknown model {name}\")\n    return fn\n\n\ndef get_model(name: str, **config: Any) -> nn.Module:\n    \"\"\"\n    Gets the model name and configuration and returns an instantiated model.\n\n    .. betastatus:: function\n\n    Args:\n        name (str): The name under which the model is registered.\n        **config (Any): parameters passed to the model builder method.\n\n    Returns:\n        model (nn.Module): The initialized model.\n    \"\"\"\n    fn = get_model_builder(name)\n    return fn(**config)\n", "path": "torchvision/models/_api.py"}], "after_files": [{"content": "import importlib\nimport inspect\nimport sys\nfrom dataclasses import dataclass, fields\nfrom inspect import signature\nfrom types import ModuleType\nfrom typing import Any, Callable, cast, Dict, List, Mapping, Optional, TypeVar, Union\n\nfrom torch import nn\n\nfrom torchvision._utils import StrEnum\n\nfrom .._internally_replaced_utils import load_state_dict_from_url\n\n\n__all__ = [\"WeightsEnum\", \"Weights\", \"get_model\", \"get_model_builder\", \"get_model_weights\", \"get_weight\", \"list_models\"]\n\n\n@dataclass\nclass Weights:\n    \"\"\"\n    This class is used to group important attributes associated with the pre-trained weights.\n\n    Args:\n        url (str): The location where we find the weights.\n        transforms (Callable): A callable that constructs the preprocessing method (or validation preset transforms)\n            needed to use the model. The reason we attach a constructor method rather than an already constructed\n            object is because the specific object might have memory and thus we want to delay initialization until\n            needed.\n        meta (Dict[str, Any]): Stores meta-data related to the weights of the model and its configuration. These can be\n            informative attributes (for example the number of parameters/flops, recipe link/methods used in training\n            etc), configuration parameters (for example the `num_classes`) needed to construct the model or important\n            meta-data (for example the `classes` of a classification model) needed to use the model.\n    \"\"\"\n\n    url: str\n    transforms: Callable\n    meta: Dict[str, Any]\n\n\nclass WeightsEnum(StrEnum):\n    \"\"\"\n    This class is the parent class of all model weights. Each model building method receives an optional `weights`\n    parameter with its associated pre-trained weights. It inherits from `Enum` and its values should be of type\n    `Weights`.\n\n    Args:\n        value (Weights): The data class entry with the weight information.\n    \"\"\"\n\n    def __init__(self, value: Weights):\n        self._value_ = value\n\n    @classmethod\n    def verify(cls, obj: Any) -> Any:\n        if obj is not None:\n            if type(obj) is str:\n                obj = cls.from_str(obj.replace(cls.__name__ + \".\", \"\"))\n            elif not isinstance(obj, cls):\n                raise TypeError(\n                    f\"Invalid Weight class provided; expected {cls.__name__} but received {obj.__class__.__name__}.\"\n                )\n        return obj\n\n    def get_state_dict(self, progress: bool) -> Mapping[str, Any]:\n        return load_state_dict_from_url(self.url, progress=progress)\n\n    def __repr__(self) -> str:\n        return f\"{self.__class__.__name__}.{self._name_}\"\n\n    def __getattr__(self, name):\n        # Be able to fetch Weights attributes directly\n        for f in fields(Weights):\n            if f.name == name:\n                return object.__getattribute__(self.value, name)\n        return super().__getattr__(name)\n\n    def __deepcopy__(self, memodict=None):\n        return self\n\n\ndef get_weight(name: str) -> WeightsEnum:\n    \"\"\"\n    Gets the weights enum value by its full name. Example: \"ResNet50_Weights.IMAGENET1K_V1\"\n\n    .. betastatus:: function\n\n    Args:\n        name (str): The name of the weight enum entry.\n\n    Returns:\n        WeightsEnum: The requested weight enum.\n    \"\"\"\n    try:\n        enum_name, value_name = name.split(\".\")\n    except ValueError:\n        raise ValueError(f\"Invalid weight name provided: '{name}'.\")\n\n    base_module_name = \".\".join(sys.modules[__name__].__name__.split(\".\")[:-1])\n    base_module = importlib.import_module(base_module_name)\n    model_modules = [base_module] + [\n        x[1] for x in inspect.getmembers(base_module, inspect.ismodule) if x[1].__file__.endswith(\"__init__.py\")\n    ]\n\n    weights_enum = None\n    for m in model_modules:\n        potential_class = m.__dict__.get(enum_name, None)\n        if potential_class is not None and issubclass(potential_class, WeightsEnum):\n            weights_enum = potential_class\n            break\n\n    if weights_enum is None:\n        raise ValueError(f\"The weight enum '{enum_name}' for the specific method couldn't be retrieved.\")\n\n    return weights_enum.from_str(value_name)\n\n\ndef get_model_weights(name: Union[Callable, str]) -> WeightsEnum:\n    \"\"\"\n    Retuns the weights enum class associated to the given model.\n\n    .. betastatus:: function\n\n    Args:\n        name (callable or str): The model builder function or the name under which it is registered.\n\n    Returns:\n        weights_enum (WeightsEnum): The weights enum class associated with the model.\n    \"\"\"\n    model = get_model_builder(name) if isinstance(name, str) else name\n    return _get_enum_from_fn(model)\n\n\ndef _get_enum_from_fn(fn: Callable) -> WeightsEnum:\n    \"\"\"\n    Internal method that gets the weight enum of a specific model builder method.\n\n    Args:\n        fn (Callable): The builder method used to create the model.\n        weight_name (str): The name of the weight enum entry of the specific model.\n    Returns:\n        WeightsEnum: The requested weight enum.\n    \"\"\"\n    sig = signature(fn)\n    if \"weights\" not in sig.parameters:\n        raise ValueError(\"The method is missing the 'weights' argument.\")\n\n    ann = signature(fn).parameters[\"weights\"].annotation\n    weights_enum = None\n    if isinstance(ann, type) and issubclass(ann, WeightsEnum):\n        weights_enum = ann\n    else:\n        # handle cases like Union[Optional, T]\n        # TODO: Replace ann.__args__ with typing.get_args(ann) after python >= 3.8\n        for t in ann.__args__:  # type: ignore[union-attr]\n            if isinstance(t, type) and issubclass(t, WeightsEnum):\n                weights_enum = t\n                break\n\n    if weights_enum is None:\n        raise ValueError(\n            \"The WeightsEnum class for the specific method couldn't be retrieved. Make sure the typing info is correct.\"\n        )\n\n    return cast(WeightsEnum, weights_enum)\n\n\nM = TypeVar(\"M\", bound=nn.Module)\n\nBUILTIN_MODELS = {}\n\n\ndef register_model(name: Optional[str] = None) -> Callable[[Callable[..., M]], Callable[..., M]]:\n    def wrapper(fn: Callable[..., M]) -> Callable[..., M]:\n        key = name if name is not None else fn.__name__\n        if key in BUILTIN_MODELS:\n            raise ValueError(f\"An entry is already registered under the name '{key}'.\")\n        BUILTIN_MODELS[key] = fn\n        return fn\n\n    return wrapper\n\n\ndef list_models(module: Optional[ModuleType] = None) -> List[str]:\n    \"\"\"\n    Returns a list with the names of registered models.\n\n    .. betastatus:: function\n\n    Args:\n        module (ModuleType, optional): The module from which we want to extract the available models.\n\n    Returns:\n        models (list): A list with the names of available models.\n    \"\"\"\n    models = [\n        k for k, v in BUILTIN_MODELS.items() if module is None or v.__module__.rsplit(\".\", 1)[0] == module.__name__\n    ]\n    return sorted(models)\n\n\ndef get_model_builder(name: str) -> Callable[..., nn.Module]:\n    \"\"\"\n    Gets the model name and returns the model builder method.\n\n    .. betastatus:: function\n\n    Args:\n        name (str): The name under which the model is registered.\n\n    Returns:\n        fn (Callable): The model builder method.\n    \"\"\"\n    name = name.lower()\n    try:\n        fn = BUILTIN_MODELS[name]\n    except KeyError:\n        raise ValueError(f\"Unknown model {name}\")\n    return fn\n\n\ndef get_model(name: str, **config: Any) -> nn.Module:\n    \"\"\"\n    Gets the model name and configuration and returns an instantiated model.\n\n    .. betastatus:: function\n\n    Args:\n        name (str): The name under which the model is registered.\n        **config (Any): parameters passed to the model builder method.\n\n    Returns:\n        model (nn.Module): The initialized model.\n    \"\"\"\n    fn = get_model_builder(name)\n    return fn(**config)\n", "path": "torchvision/models/_api.py"}]}