We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Typing for vgg_multi_layer_encoder is broken
#392 changed the generation of `vgg_(11|13|16|19)(_bn)?_multi_layer_encoder` from static to dynamic. While this reduces repetition, it also breaks the type checks with `mypy`:

```python
from pystiche.enc import vgg11_multi_layer_encoder
```

```
error: Module 'pystiche.enc' has no attribute 'vgg11_multi_layer_encoder'; maybe "alexnet_multi_layer_encoder"?  [attr-defined]
```

Since `mypy` only reads but not imports `pystiche.enc.models.vgg` it has no knowledge that the functions will exist after import.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pystiche/enc/models/vgg.py`
Content:
```
1 import functools
2 import re
3 import warnings
4 from copy import copy
5 from typing import Any, Callable, Dict, List, Optional, Tuple, cast
6 
7 import torchvision
8 from torch import hub, nn
9 
10 from pystiche.misc import build_deprecation_message
11 
12 from .utils import ModelMultiLayerEncoder
13 from .utils import select_url as _select_url
14 
15 __all__ = [
16     "VGGMultiLayerEncoder",
17     "vgg11_multi_layer_encoder",
18     "vgg11_bn_multi_layer_encoder",
19     "vgg13_multi_layer_encoder",
20     "vgg13_bn_multi_layer_encoder",
21     "vgg16_multi_layer_encoder",
22     "vgg16_bn_multi_layer_encoder",
23     "vgg19_multi_layer_encoder",
24     "vgg19_bn_multi_layer_encoder",
25 ]
26 
27 ARCH_PATTERN = re.compile(r"^vgg(?P<num_layers>(11|13|16|19)+)(?P<batch_norm>_bn)?$")
28 
29 NUM_LAYERS_TO_CONFIGURATION = {
30     11: "A",
31     13: "B",
32     16: "D",
33     19: "E",
34 }
35 
36 
37 def _parse_arch(arch: str) -> Tuple[int, bool]:
38     match = ARCH_PATTERN.match(arch)
39     if match is None:
40         raise ValueError(
41             f"Unknown arch '{arch}'. It has to match 'vgg_(11|13|16|19)(_bn)?'"
42         )
43 
44     num_layers = int(match.group("num_layers"))
45     batch_norm = match.group("batch_norm") is not None
46 
47     return num_layers, batch_norm
48 
49 
50 def _make_description(arch: str, multi_layer_encoder: bool) -> str:
51     num_layers, batch_norm = _parse_arch(arch)
52 
53     if multi_layer_encoder:
54         short = (
55             f"Multi-layer encoder based on :class:`~torchvision.models.VGG` "
56             f"{num_layers}{' with batch normalization' if batch_norm else ''}."
57         )
58     else:
59         short = f":class:`~torchvision.models.VGG` {num_layers} model"
60 
61     long = (
62         f"    The :class:`~torchvision.models.VGG` architecture was introduced by "
63         f"Krizhevsky, Sutskever, and Hinton in :cite:`KSH2012`. VGG{num_layers} "
64         f"corresponds to configuration ``{NUM_LAYERS_TO_CONFIGURATION[num_layers]}`` "
65         f"in the paper."
66     )
67     return "\n".join((short, "", long))
68 
69 
70 def _make_vgg_docstring(arch: str) -> str:
71     description = _make_description(arch, multi_layer_encoder=False)
72     args = r"""Args:
73     pretrained: If ``True``, loads weights from training on
74         :class:`~torchvision.models.ImageNet`. Defaults to ``False``.
75     framework: Framework that was used to train the model. Can be one of
76         ``"torch"`` (default) or ``"caffe"``.
77         .. note::
78 
79             The weights for ``"caffe"`` were generated by Karen Simonyan and
80             Andrew Zisserman. See https://download.pystiche.org/models/LICENSE for
81             details.
82     progress: If ``True``, displays a progress bar to STDERR during download of
83         pretrained weights. Defaults to ``True``.
84     num_classes: Size of the output layer. Defaults to ``1000``.
85         .. note::
86 
87             Pretrained weights are only available for ``num_classes == 1000``.
88     """
89     return "\n".join((description, "", args))
90 
91 
92 def select_url(arch: str, framework: str) -> str:
93     def format(key: Tuple[str, str]) -> str:
94         arch, framework = key
95         return "\n".join((f"arch={arch}", f"framework={framework}"))
96 
97     return _select_url(MODEL_URLS, (arch, framework), format=format)
98 
99 
100 def _vgg_loader(arch: str) -> Callable[..., torchvision.models.VGG]:
101     loader = cast(
102         Callable[..., torchvision.models.VGG], getattr(torchvision.models, arch)
103     )
104 
105     def vgg(
106         pretrained: bool = False,
107         framework: str = "torch",
108         progress: bool = True,
109         num_classes: int = 1000,
110     ) -> torchvision.models.VGG:
111         if pretrained and num_classes != 1000:
112             raise RuntimeError
113 
114         model = loader(pretrained=False, num_classes=num_classes)
115 
116         if not pretrained:
117             return model
118 
119         state_dict = hub.load_state_dict_from_url(
120             select_url(arch, framework), progress=progress, check_hash=True,
121         )
122         model.load_state_dict(state_dict)
123         return model
124 
125     vgg.__doc__ = _make_vgg_docstring(arch)
126 
127     return vgg
128 
129 
130 TORCH_MODEL_URLS = torchvision.models.vgg.model_urls
131 ARCHS = tuple(TORCH_MODEL_URLS.keys())
132 MODEL_URLS = {(arch, "torch"): TORCH_MODEL_URLS[arch] for arch in ARCHS}
133 MODEL_URLS.update(
134     {
135         ("vgg16", "caffe"): "https://download.pystiche.org/models/vgg16-781be684.pth",
136         ("vgg19", "caffe"): "https://download.pystiche.org/models/vgg19-74e45263.pth",
137     }
138 )
139 MODELS = {arch: _vgg_loader(arch) for arch in ARCHS}
140 
141 
142 class VGGMultiLayerEncoder(ModelMultiLayerEncoder):
143     r"""Multi-layer encoder based on :class:`~torchvision.models.VGG`.
144 
145     The :class:`~torchvision.models.VGG` architecture was introduced by  Krizhevsky,
146     Sutskever, and Hinton in :cite:`KSH2012`
147 
148     Args:
149         arch: :class:`~torchvision.models.VGG` architecture. Has to match
150             ``"vgg(11|13|16|19)(_bn)?"``.
151         pretrained: If ``True``, loads builtin weights. Defaults to ``True``.
152         framework: Name of the framework that was used to train the builtin weights.
153             Defaults to ``"torch"``.
154         kwargs: Optional arguments of :class:`ModelMultiLayerEncoder` .
155 
156     Raises:
157         RuntimeError: If ``pretrained is True`` and no weights are available for the
158             combination of ``arch`` and ``framework``.
159     """
160 
161     def __init__(self, arch: str, weights: Optional[str] = None, **kwargs: Any) -> None:
162         if weights is not None:
163             msg = build_deprecation_message(
164                 "The parameter weights", "0.6.0", info="It was renamed to framework"
165             )
166             warnings.warn(msg, UserWarning)
167             kwargs["framework"] = weights
168 
169         _parse_arch(arch)
170         self.arch = arch
171         super().__init__(**kwargs)
172 
173     def state_dict_url(self, framework: str) -> str:
174         return select_url(self.arch, framework)
175 
176     def collect_modules(
177         self, inplace: bool
178     ) -> Tuple[List[Tuple[str, nn.Module]], Dict[str, str]]:
179         model = MODELS[self.arch](pretrained=False)
180 
181         modules = []
182         state_dict_key_map = {}
183         block = depth = 1
184         for idx, module in model.features.named_children():
185             if isinstance(module, nn.Conv2d):
186                 name = f"conv{block}_{depth}"
187             elif isinstance(module, nn.BatchNorm2d):
188                 name = f"bn{block}_{depth}"
189             elif isinstance(module, nn.ReLU):
190                 module = nn.ReLU(inplace=inplace)
191                 name = f"relu{block}_{depth}"
192                 # each ReLU layer increases the depth of the current block
193                 depth += 1
194             else:  # isinstance(module, nn.MaxPool2d):
195                 name = f"pool{block}"
196                 # each pooling layer marks the end of the current block
197                 block += 1
198                 depth = 1
199 
200             modules.append((name, module))
201             state_dict_key_map.update(
202                 {
203                     f"features.{idx}.{key}": f"{name}.{key}"
204                     for key in module.state_dict().keys()
205                 }
206             )
207 
208         return modules, state_dict_key_map
209 
210     def _properties(self) -> Dict[str, Any]:
211         dct = super()._properties()
212 
213         dct["arch"] = self.arch
214         dct.move_to_end("arch", last=False)  # type: ignore[attr-defined]
215 
216         return dct
217 
218 
219 def _make_vgg_multi_layer_encoder_docstring(arch: str) -> str:
220     description = _make_description(arch, multi_layer_encoder=True)
221     args = r"""    Args:
222         kwargs: Optional arguments of :class:`VGGMultiLayerEncoder` .
223     """
224     return "\n".join((description, "", args))
225 
226 
227 def _update_loader_magic(loader: Callable, name: str, doc: str) -> None:
228     loader.__module__ = VGGMultiLayerEncoder.__module__
229     loader.__name__ = loader.__qualname__ = name
230 
231     annotations = copy(VGGMultiLayerEncoder.__init__.__annotations__)
232     del annotations["arch"]
233     annotations["return"] = VGGMultiLayerEncoder
234     loader.__annotations__ = annotations
235     loader.__doc__ = doc
236 
237 
238 for arch in ARCHS:
239     name = f"{arch}_multi_layer_encoder"
240     doc = _make_vgg_multi_layer_encoder_docstring(arch)
241     loader = functools.partial(VGGMultiLayerEncoder, arch)
242     _update_loader_magic(loader, name, doc)
243     locals()[name] = loader
244
```
--- 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/pystiche/enc/models/vgg.py b/pystiche/enc/models/vgg.py
--- a/pystiche/enc/models/vgg.py
+++ b/pystiche/enc/models/vgg.py
@@ -1,7 +1,5 @@
-import functools
 import re
 import warnings
-from copy import copy
 from typing import Any, Callable, Dict, List, Optional, Tuple, cast
 
 import torchvision
@@ -224,20 +222,39 @@
     return "\n".join((description, "", args))
 
 
-def _update_loader_magic(loader: Callable, name: str, doc: str) -> None:
-    loader.__module__ = VGGMultiLayerEncoder.__module__
-    loader.__name__ = loader.__qualname__ = name
+def vgg11_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:
+    return VGGMultiLayerEncoder("vgg11", **kwargs)
 
-    annotations = copy(VGGMultiLayerEncoder.__init__.__annotations__)
-    del annotations["arch"]
-    annotations["return"] = VGGMultiLayerEncoder
-    loader.__annotations__ = annotations
-    loader.__doc__ = doc
+
+def vgg11_bn_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:
+    return VGGMultiLayerEncoder("vgg11_bn", **kwargs)
+
+
+def vgg13_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:
+    return VGGMultiLayerEncoder("vgg13", **kwargs)
+
+
+def vgg13_bn_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:
+    return VGGMultiLayerEncoder("vgg13_bn", **kwargs)
+
+
+def vgg16_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:
+    return VGGMultiLayerEncoder("vgg16", **kwargs)
+
+
+def vgg16_bn_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:
+    return VGGMultiLayerEncoder("vgg16_bn", **kwargs)
+
+
+def vgg19_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:
+    return VGGMultiLayerEncoder("vgg19", **kwargs)
+
+
+def vgg19_bn_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:
+    return VGGMultiLayerEncoder("vgg19_bn", **kwargs)
 
 
 for arch in ARCHS:
     name = f"{arch}_multi_layer_encoder"
     doc = _make_vgg_multi_layer_encoder_docstring(arch)
-    loader = functools.partial(VGGMultiLayerEncoder, arch)
-    _update_loader_magic(loader, name, doc)
-    locals()[name] = loader
+    globals()[name].__doc__ = doc

{"golden_diff": "diff --git a/pystiche/enc/models/vgg.py b/pystiche/enc/models/vgg.py\n--- a/pystiche/enc/models/vgg.py\n+++ b/pystiche/enc/models/vgg.py\n@@ -1,7 +1,5 @@\n-import functools\n import re\n import warnings\n-from copy import copy\n from typing import Any, Callable, Dict, List, Optional, Tuple, cast\n \n import torchvision\n@@ -224,20 +222,39 @@\n     return \"\\n\".join((description, \"\", args))\n \n \n-def _update_loader_magic(loader: Callable, name: str, doc: str) -> None:\n-    loader.__module__ = VGGMultiLayerEncoder.__module__\n-    loader.__name__ = loader.__qualname__ = name\n+def vgg11_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n+    return VGGMultiLayerEncoder(\"vgg11\", **kwargs)\n \n-    annotations = copy(VGGMultiLayerEncoder.__init__.__annotations__)\n-    del annotations[\"arch\"]\n-    annotations[\"return\"] = VGGMultiLayerEncoder\n-    loader.__annotations__ = annotations\n-    loader.__doc__ = doc\n+\n+def vgg11_bn_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n+    return VGGMultiLayerEncoder(\"vgg11_bn\", **kwargs)\n+\n+\n+def vgg13_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n+    return VGGMultiLayerEncoder(\"vgg13\", **kwargs)\n+\n+\n+def vgg13_bn_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n+    return VGGMultiLayerEncoder(\"vgg13_bn\", **kwargs)\n+\n+\n+def vgg16_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n+    return VGGMultiLayerEncoder(\"vgg16\", **kwargs)\n+\n+\n+def vgg16_bn_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n+    return VGGMultiLayerEncoder(\"vgg16_bn\", **kwargs)\n+\n+\n+def vgg19_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n+    return VGGMultiLayerEncoder(\"vgg19\", **kwargs)\n+\n+\n+def vgg19_bn_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n+    return VGGMultiLayerEncoder(\"vgg19_bn\", **kwargs)\n \n \n for arch in ARCHS:\n     name = f\"{arch}_multi_layer_encoder\"\n     doc = _make_vgg_multi_layer_encoder_docstring(arch)\n-    loader = functools.partial(VGGMultiLayerEncoder, arch)\n-    _update_loader_magic(loader, name, doc)\n-    locals()[name] = loader\n+    globals()[name].__doc__ = doc\n", "issue": "Typing for vgg_multi_layer_encoder is broken\n#392 changed the generation of `vgg_(11|13|16|19)(_bn)?_multi_layer_encoder` from static to dynamic. While this reduces repetition, it also breaks the type checks with `mypy`:\r\n\r\n```python\r\nfrom pystiche.enc import vgg11_multi_layer_encoder\r\n```\r\n\r\n```\r\nerror: Module 'pystiche.enc' has no attribute 'vgg11_multi_layer_encoder'; maybe \"alexnet_multi_layer_encoder\"?  [attr-defined]\r\n```\r\n\r\nSince `mypy` only reads but not imports `pystiche.enc.models.vgg` it has no knowledge that the functions will exist after import.\n", "before_files": [{"content": "import functools\nimport re\nimport warnings\nfrom copy import copy\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, cast\n\nimport torchvision\nfrom torch import hub, nn\n\nfrom pystiche.misc import build_deprecation_message\n\nfrom .utils import ModelMultiLayerEncoder\nfrom .utils import select_url as _select_url\n\n__all__ = [\n    \"VGGMultiLayerEncoder\",\n    \"vgg11_multi_layer_encoder\",\n    \"vgg11_bn_multi_layer_encoder\",\n    \"vgg13_multi_layer_encoder\",\n    \"vgg13_bn_multi_layer_encoder\",\n    \"vgg16_multi_layer_encoder\",\n    \"vgg16_bn_multi_layer_encoder\",\n    \"vgg19_multi_layer_encoder\",\n    \"vgg19_bn_multi_layer_encoder\",\n]\n\nARCH_PATTERN = re.compile(r\"^vgg(?P<num_layers>(11|13|16|19)+)(?P<batch_norm>_bn)?$\")\n\nNUM_LAYERS_TO_CONFIGURATION = {\n    11: \"A\",\n    13: \"B\",\n    16: \"D\",\n    19: \"E\",\n}\n\n\ndef _parse_arch(arch: str) -> Tuple[int, bool]:\n    match = ARCH_PATTERN.match(arch)\n    if match is None:\n        raise ValueError(\n            f\"Unknown arch '{arch}'. It has to match 'vgg_(11|13|16|19)(_bn)?'\"\n        )\n\n    num_layers = int(match.group(\"num_layers\"))\n    batch_norm = match.group(\"batch_norm\") is not None\n\n    return num_layers, batch_norm\n\n\ndef _make_description(arch: str, multi_layer_encoder: bool) -> str:\n    num_layers, batch_norm = _parse_arch(arch)\n\n    if multi_layer_encoder:\n        short = (\n            f\"Multi-layer encoder based on :class:`~torchvision.models.VGG` \"\n            f\"{num_layers}{' with batch normalization' if batch_norm else ''}.\"\n        )\n    else:\n        short = f\":class:`~torchvision.models.VGG` {num_layers} model\"\n\n    long = (\n        f\"    The :class:`~torchvision.models.VGG` architecture was introduced by \"\n        f\"Krizhevsky, Sutskever, and Hinton in :cite:`KSH2012`. VGG{num_layers} \"\n        f\"corresponds to configuration ``{NUM_LAYERS_TO_CONFIGURATION[num_layers]}`` \"\n        f\"in the paper.\"\n    )\n    return \"\\n\".join((short, \"\", long))\n\n\ndef _make_vgg_docstring(arch: str) -> str:\n    description = _make_description(arch, multi_layer_encoder=False)\n    args = r\"\"\"Args:\n    pretrained: If ``True``, loads weights from training on\n        :class:`~torchvision.models.ImageNet`. Defaults to ``False``.\n    framework: Framework that was used to train the model. Can be one of\n        ``\"torch\"`` (default) or ``\"caffe\"``.\n        .. note::\n\n            The weights for ``\"caffe\"`` were generated by Karen Simonyan and\n            Andrew Zisserman. See https://download.pystiche.org/models/LICENSE for\n            details.\n    progress: If ``True``, displays a progress bar to STDERR during download of\n        pretrained weights. Defaults to ``True``.\n    num_classes: Size of the output layer. Defaults to ``1000``.\n        .. note::\n\n            Pretrained weights are only available for ``num_classes == 1000``.\n    \"\"\"\n    return \"\\n\".join((description, \"\", args))\n\n\ndef select_url(arch: str, framework: str) -> str:\n    def format(key: Tuple[str, str]) -> str:\n        arch, framework = key\n        return \"\\n\".join((f\"arch={arch}\", f\"framework={framework}\"))\n\n    return _select_url(MODEL_URLS, (arch, framework), format=format)\n\n\ndef _vgg_loader(arch: str) -> Callable[..., torchvision.models.VGG]:\n    loader = cast(\n        Callable[..., torchvision.models.VGG], getattr(torchvision.models, arch)\n    )\n\n    def vgg(\n        pretrained: bool = False,\n        framework: str = \"torch\",\n        progress: bool = True,\n        num_classes: int = 1000,\n    ) -> torchvision.models.VGG:\n        if pretrained and num_classes != 1000:\n            raise RuntimeError\n\n        model = loader(pretrained=False, num_classes=num_classes)\n\n        if not pretrained:\n            return model\n\n        state_dict = hub.load_state_dict_from_url(\n            select_url(arch, framework), progress=progress, check_hash=True,\n        )\n        model.load_state_dict(state_dict)\n        return model\n\n    vgg.__doc__ = _make_vgg_docstring(arch)\n\n    return vgg\n\n\nTORCH_MODEL_URLS = torchvision.models.vgg.model_urls\nARCHS = tuple(TORCH_MODEL_URLS.keys())\nMODEL_URLS = {(arch, \"torch\"): TORCH_MODEL_URLS[arch] for arch in ARCHS}\nMODEL_URLS.update(\n    {\n        (\"vgg16\", \"caffe\"): \"https://download.pystiche.org/models/vgg16-781be684.pth\",\n        (\"vgg19\", \"caffe\"): \"https://download.pystiche.org/models/vgg19-74e45263.pth\",\n    }\n)\nMODELS = {arch: _vgg_loader(arch) for arch in ARCHS}\n\n\nclass VGGMultiLayerEncoder(ModelMultiLayerEncoder):\n    r\"\"\"Multi-layer encoder based on :class:`~torchvision.models.VGG`.\n\n    The :class:`~torchvision.models.VGG` architecture was introduced by  Krizhevsky,\n    Sutskever, and Hinton in :cite:`KSH2012`\n\n    Args:\n        arch: :class:`~torchvision.models.VGG` architecture. Has to match\n            ``\"vgg(11|13|16|19)(_bn)?\"``.\n        pretrained: If ``True``, loads builtin weights. Defaults to ``True``.\n        framework: Name of the framework that was used to train the builtin weights.\n            Defaults to ``\"torch\"``.\n        kwargs: Optional arguments of :class:`ModelMultiLayerEncoder` .\n\n    Raises:\n        RuntimeError: If ``pretrained is True`` and no weights are available for the\n            combination of ``arch`` and ``framework``.\n    \"\"\"\n\n    def __init__(self, arch: str, weights: Optional[str] = None, **kwargs: Any) -> None:\n        if weights is not None:\n            msg = build_deprecation_message(\n                \"The parameter weights\", \"0.6.0\", info=\"It was renamed to framework\"\n            )\n            warnings.warn(msg, UserWarning)\n            kwargs[\"framework\"] = weights\n\n        _parse_arch(arch)\n        self.arch = arch\n        super().__init__(**kwargs)\n\n    def state_dict_url(self, framework: str) -> str:\n        return select_url(self.arch, framework)\n\n    def collect_modules(\n        self, inplace: bool\n    ) -> Tuple[List[Tuple[str, nn.Module]], Dict[str, str]]:\n        model = MODELS[self.arch](pretrained=False)\n\n        modules = []\n        state_dict_key_map = {}\n        block = depth = 1\n        for idx, module in model.features.named_children():\n            if isinstance(module, nn.Conv2d):\n                name = f\"conv{block}_{depth}\"\n            elif isinstance(module, nn.BatchNorm2d):\n                name = f\"bn{block}_{depth}\"\n            elif isinstance(module, nn.ReLU):\n                module = nn.ReLU(inplace=inplace)\n                name = f\"relu{block}_{depth}\"\n                # each ReLU layer increases the depth of the current block\n                depth += 1\n            else:  # isinstance(module, nn.MaxPool2d):\n                name = f\"pool{block}\"\n                # each pooling layer marks the end of the current block\n                block += 1\n                depth = 1\n\n            modules.append((name, module))\n            state_dict_key_map.update(\n                {\n                    f\"features.{idx}.{key}\": f\"{name}.{key}\"\n                    for key in module.state_dict().keys()\n                }\n            )\n\n        return modules, state_dict_key_map\n\n    def _properties(self) -> Dict[str, Any]:\n        dct = super()._properties()\n\n        dct[\"arch\"] = self.arch\n        dct.move_to_end(\"arch\", last=False)  # type: ignore[attr-defined]\n\n        return dct\n\n\ndef _make_vgg_multi_layer_encoder_docstring(arch: str) -> str:\n    description = _make_description(arch, multi_layer_encoder=True)\n    args = r\"\"\"    Args:\n        kwargs: Optional arguments of :class:`VGGMultiLayerEncoder` .\n    \"\"\"\n    return \"\\n\".join((description, \"\", args))\n\n\ndef _update_loader_magic(loader: Callable, name: str, doc: str) -> None:\n    loader.__module__ = VGGMultiLayerEncoder.__module__\n    loader.__name__ = loader.__qualname__ = name\n\n    annotations = copy(VGGMultiLayerEncoder.__init__.__annotations__)\n    del annotations[\"arch\"]\n    annotations[\"return\"] = VGGMultiLayerEncoder\n    loader.__annotations__ = annotations\n    loader.__doc__ = doc\n\n\nfor arch in ARCHS:\n    name = f\"{arch}_multi_layer_encoder\"\n    doc = _make_vgg_multi_layer_encoder_docstring(arch)\n    loader = functools.partial(VGGMultiLayerEncoder, arch)\n    _update_loader_magic(loader, name, doc)\n    locals()[name] = loader\n", "path": "pystiche/enc/models/vgg.py"}], "after_files": [{"content": "import re\nimport warnings\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, cast\n\nimport torchvision\nfrom torch import hub, nn\n\nfrom pystiche.misc import build_deprecation_message\n\nfrom .utils import ModelMultiLayerEncoder\nfrom .utils import select_url as _select_url\n\n__all__ = [\n    \"VGGMultiLayerEncoder\",\n    \"vgg11_multi_layer_encoder\",\n    \"vgg11_bn_multi_layer_encoder\",\n    \"vgg13_multi_layer_encoder\",\n    \"vgg13_bn_multi_layer_encoder\",\n    \"vgg16_multi_layer_encoder\",\n    \"vgg16_bn_multi_layer_encoder\",\n    \"vgg19_multi_layer_encoder\",\n    \"vgg19_bn_multi_layer_encoder\",\n]\n\nARCH_PATTERN = re.compile(r\"^vgg(?P<num_layers>(11|13|16|19)+)(?P<batch_norm>_bn)?$\")\n\nNUM_LAYERS_TO_CONFIGURATION = {\n    11: \"A\",\n    13: \"B\",\n    16: \"D\",\n    19: \"E\",\n}\n\n\ndef _parse_arch(arch: str) -> Tuple[int, bool]:\n    match = ARCH_PATTERN.match(arch)\n    if match is None:\n        raise ValueError(\n            f\"Unknown arch '{arch}'. It has to match 'vgg_(11|13|16|19)(_bn)?'\"\n        )\n\n    num_layers = int(match.group(\"num_layers\"))\n    batch_norm = match.group(\"batch_norm\") is not None\n\n    return num_layers, batch_norm\n\n\ndef _make_description(arch: str, multi_layer_encoder: bool) -> str:\n    num_layers, batch_norm = _parse_arch(arch)\n\n    if multi_layer_encoder:\n        short = (\n            f\"Multi-layer encoder based on :class:`~torchvision.models.VGG` \"\n            f\"{num_layers}{' with batch normalization' if batch_norm else ''}.\"\n        )\n    else:\n        short = f\":class:`~torchvision.models.VGG` {num_layers} model\"\n\n    long = (\n        f\"    The :class:`~torchvision.models.VGG` architecture was introduced by \"\n        f\"Krizhevsky, Sutskever, and Hinton in :cite:`KSH2012`. VGG{num_layers} \"\n        f\"corresponds to configuration ``{NUM_LAYERS_TO_CONFIGURATION[num_layers]}`` \"\n        f\"in the paper.\"\n    )\n    return \"\\n\".join((short, \"\", long))\n\n\ndef _make_vgg_docstring(arch: str) -> str:\n    description = _make_description(arch, multi_layer_encoder=False)\n    args = r\"\"\"Args:\n    pretrained: If ``True``, loads weights from training on\n        :class:`~torchvision.models.ImageNet`. Defaults to ``False``.\n    framework: Framework that was used to train the model. Can be one of\n        ``\"torch\"`` (default) or ``\"caffe\"``.\n        .. note::\n\n            The weights for ``\"caffe\"`` were generated by Karen Simonyan and\n            Andrew Zisserman. See https://download.pystiche.org/models/LICENSE for\n            details.\n    progress: If ``True``, displays a progress bar to STDERR during download of\n        pretrained weights. Defaults to ``True``.\n    num_classes: Size of the output layer. Defaults to ``1000``.\n        .. note::\n\n            Pretrained weights are only available for ``num_classes == 1000``.\n    \"\"\"\n    return \"\\n\".join((description, \"\", args))\n\n\ndef select_url(arch: str, framework: str) -> str:\n    def format(key: Tuple[str, str]) -> str:\n        arch, framework = key\n        return \"\\n\".join((f\"arch={arch}\", f\"framework={framework}\"))\n\n    return _select_url(MODEL_URLS, (arch, framework), format=format)\n\n\ndef _vgg_loader(arch: str) -> Callable[..., torchvision.models.VGG]:\n    loader = cast(\n        Callable[..., torchvision.models.VGG], getattr(torchvision.models, arch)\n    )\n\n    def vgg(\n        pretrained: bool = False,\n        framework: str = \"torch\",\n        progress: bool = True,\n        num_classes: int = 1000,\n    ) -> torchvision.models.VGG:\n        if pretrained and num_classes != 1000:\n            raise RuntimeError\n\n        model = loader(pretrained=False, num_classes=num_classes)\n\n        if not pretrained:\n            return model\n\n        state_dict = hub.load_state_dict_from_url(\n            select_url(arch, framework), progress=progress, check_hash=True,\n        )\n        model.load_state_dict(state_dict)\n        return model\n\n    vgg.__doc__ = _make_vgg_docstring(arch)\n\n    return vgg\n\n\nTORCH_MODEL_URLS = torchvision.models.vgg.model_urls\nARCHS = tuple(TORCH_MODEL_URLS.keys())\nMODEL_URLS = {(arch, \"torch\"): TORCH_MODEL_URLS[arch] for arch in ARCHS}\nMODEL_URLS.update(\n    {\n        (\"vgg16\", \"caffe\"): \"https://download.pystiche.org/models/vgg16-781be684.pth\",\n        (\"vgg19\", \"caffe\"): \"https://download.pystiche.org/models/vgg19-74e45263.pth\",\n    }\n)\nMODELS = {arch: _vgg_loader(arch) for arch in ARCHS}\n\n\nclass VGGMultiLayerEncoder(ModelMultiLayerEncoder):\n    r\"\"\"Multi-layer encoder based on :class:`~torchvision.models.VGG`.\n\n    The :class:`~torchvision.models.VGG` architecture was introduced by  Krizhevsky,\n    Sutskever, and Hinton in :cite:`KSH2012`\n\n    Args:\n        arch: :class:`~torchvision.models.VGG` architecture. Has to match\n            ``\"vgg(11|13|16|19)(_bn)?\"``.\n        pretrained: If ``True``, loads builtin weights. Defaults to ``True``.\n        framework: Name of the framework that was used to train the builtin weights.\n            Defaults to ``\"torch\"``.\n        kwargs: Optional arguments of :class:`ModelMultiLayerEncoder` .\n\n    Raises:\n        RuntimeError: If ``pretrained is True`` and no weights are available for the\n            combination of ``arch`` and ``framework``.\n    \"\"\"\n\n    def __init__(self, arch: str, weights: Optional[str] = None, **kwargs: Any) -> None:\n        if weights is not None:\n            msg = build_deprecation_message(\n                \"The parameter weights\", \"0.6.0\", info=\"It was renamed to framework\"\n            )\n            warnings.warn(msg, UserWarning)\n            kwargs[\"framework\"] = weights\n\n        _parse_arch(arch)\n        self.arch = arch\n        super().__init__(**kwargs)\n\n    def state_dict_url(self, framework: str) -> str:\n        return select_url(self.arch, framework)\n\n    def collect_modules(\n        self, inplace: bool\n    ) -> Tuple[List[Tuple[str, nn.Module]], Dict[str, str]]:\n        model = MODELS[self.arch](pretrained=False)\n\n        modules = []\n        state_dict_key_map = {}\n        block = depth = 1\n        for idx, module in model.features.named_children():\n            if isinstance(module, nn.Conv2d):\n                name = f\"conv{block}_{depth}\"\n            elif isinstance(module, nn.BatchNorm2d):\n                name = f\"bn{block}_{depth}\"\n            elif isinstance(module, nn.ReLU):\n                module = nn.ReLU(inplace=inplace)\n                name = f\"relu{block}_{depth}\"\n                # each ReLU layer increases the depth of the current block\n                depth += 1\n            else:  # isinstance(module, nn.MaxPool2d):\n                name = f\"pool{block}\"\n                # each pooling layer marks the end of the current block\n                block += 1\n                depth = 1\n\n            modules.append((name, module))\n            state_dict_key_map.update(\n                {\n                    f\"features.{idx}.{key}\": f\"{name}.{key}\"\n                    for key in module.state_dict().keys()\n                }\n            )\n\n        return modules, state_dict_key_map\n\n    def _properties(self) -> Dict[str, Any]:\n        dct = super()._properties()\n\n        dct[\"arch\"] = self.arch\n        dct.move_to_end(\"arch\", last=False)  # type: ignore[attr-defined]\n\n        return dct\n\n\ndef _make_vgg_multi_layer_encoder_docstring(arch: str) -> str:\n    description = _make_description(arch, multi_layer_encoder=True)\n    args = r\"\"\"    Args:\n        kwargs: Optional arguments of :class:`VGGMultiLayerEncoder` .\n    \"\"\"\n    return \"\\n\".join((description, \"\", args))\n\n\ndef vgg11_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n    return VGGMultiLayerEncoder(\"vgg11\", **kwargs)\n\n\ndef vgg11_bn_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n    return VGGMultiLayerEncoder(\"vgg11_bn\", **kwargs)\n\n\ndef vgg13_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n    return VGGMultiLayerEncoder(\"vgg13\", **kwargs)\n\n\ndef vgg13_bn_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n    return VGGMultiLayerEncoder(\"vgg13_bn\", **kwargs)\n\n\ndef vgg16_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n    return VGGMultiLayerEncoder(\"vgg16\", **kwargs)\n\n\ndef vgg16_bn_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n    return VGGMultiLayerEncoder(\"vgg16_bn\", **kwargs)\n\n\ndef vgg19_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n    return VGGMultiLayerEncoder(\"vgg19\", **kwargs)\n\n\ndef vgg19_bn_multi_layer_encoder(**kwargs: Any) -> VGGMultiLayerEncoder:\n    return VGGMultiLayerEncoder(\"vgg19_bn\", **kwargs)\n\n\nfor arch in ARCHS:\n    name = f\"{arch}_multi_layer_encoder\"\n    doc = _make_vgg_multi_layer_encoder_docstring(arch)\n    globals()[name].__doc__ = doc\n", "path": "pystiche/enc/models/vgg.py"}]}