We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Instantiation exception also raises an exception sometimes
# 🐛 Bug
## Description

When there's an instantiation exception, raising a chained exception sometimes also fails because it doesn't take an argument:

https://github.com/facebookresearch/hydra/blob/9759f87673be1d41fe33279e1b7980f8efb38b19/hydra/_internal/instantiate/_instantiate2.py#L63-L66

## Checklist
- [x] I checked on the latest version of Hydra
- [ ] I created a minimal repro (See [this](https://stackoverflow.com/help/minimal-reproducible-example) for tips).

## To reproduce

Try to instantiate an object such that it raises an exception that doesn't take any argument.

## Expected Behavior

Maybe it should try to show another type of exception instead? Or chaining (`from e`).

## System information
- **Hydra Version** :  1.1
- **Python version** : 3.8
- **Virtual environment type and version** : conda 4.11
- **Operating system** : Ubuntu 18.04

## Additional context
Add any other context about the problem here.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `hydra/_internal/instantiate/_instantiate2.py`
Content:
```
1 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2 
3 import copy
4 import functools
5 import sys
6 from enum import Enum
7 from typing import Any, Callable, Sequence, Tuple, Union
8 
9 from omegaconf import OmegaConf, SCMode
10 from omegaconf._utils import is_structured_config
11 
12 from hydra._internal.utils import _locate
13 from hydra.errors import InstantiationException
14 from hydra.types import ConvertMode, TargetConf
15 
16 
17 class _Keys(str, Enum):
18     """Special keys in configs used by instantiate."""
19 
20     TARGET = "_target_"
21     CONVERT = "_convert_"
22     RECURSIVE = "_recursive_"
23     ARGS = "_args_"
24     PARTIAL = "_partial_"
25 
26 
27 def _is_target(x: Any) -> bool:
28     if isinstance(x, dict):
29         return "_target_" in x
30     if OmegaConf.is_dict(x):
31         return "_target_" in x
32     return False
33 
34 
35 def _extract_pos_args(*input_args: Any, **kwargs: Any) -> Tuple[Any, Any]:
36     config_args = kwargs.pop(_Keys.ARGS, ())
37     output_args = config_args
38 
39     if isinstance(config_args, Sequence):
40         if len(input_args) > 0:
41             output_args = input_args
42     else:
43         raise InstantiationException(
44             f"Unsupported _args_ type: {type(config_args).__name__}. value: {config_args}"
45         )
46 
47     return output_args, kwargs
48 
49 
50 def _call_target(_target_: Callable, _partial_: bool, *args, **kwargs) -> Any:  # type: ignore
51     """Call target (type) with args and kwargs."""
52     try:
53         args, kwargs = _extract_pos_args(*args, **kwargs)
54         # detaching configs from parent.
55         # At this time, everything is resolved and the parent link can cause
56         # issues when serializing objects in some scenarios.
57         for arg in args:
58             if OmegaConf.is_config(arg):
59                 arg._set_parent(None)
60         for v in kwargs.values():
61             if OmegaConf.is_config(v):
62                 v._set_parent(None)
63         if _partial_:
64             return functools.partial(_target_, *args, **kwargs)
65         return _target_(*args, **kwargs)
66     except Exception as e:
67         raise type(e)(
68             f"Error instantiating '{_convert_target_to_string(_target_)}' : {e}"
69         ).with_traceback(sys.exc_info()[2])
70 
71 
72 def _convert_target_to_string(t: Any) -> Any:
73     if callable(t):
74         return f"{t.__module__}.{t.__qualname__}"
75     else:
76         return t
77 
78 
79 def _prepare_input_dict(d: Any) -> Any:
80     res: Any
81     if isinstance(d, dict):
82         res = {}
83         for k, v in d.items():
84             if k == "_target_":
85                 v = _convert_target_to_string(d["_target_"])
86             elif isinstance(v, (dict, list)):
87                 v = _prepare_input_dict(v)
88             res[k] = v
89     elif isinstance(d, list):
90         res = []
91         for v in d:
92             if isinstance(v, (list, dict)):
93                 v = _prepare_input_dict(v)
94             res.append(v)
95     else:
96         assert False
97     return res
98 
99 
100 def _resolve_target(
101     target: Union[str, type, Callable[..., Any]]
102 ) -> Union[type, Callable[..., Any]]:
103     """Resolve target string, type or callable into type or callable."""
104     if isinstance(target, str):
105         return _locate(target)
106     if isinstance(target, type):
107         return target
108     if callable(target):
109         return target
110     raise InstantiationException(
111         f"Unsupported target type: {type(target).__name__}. value: {target}"
112     )
113 
114 
115 def instantiate(config: Any, *args: Any, **kwargs: Any) -> Any:
116     """
117     :param config: An config object describing what to call and what params to use.
118                    In addition to the parameters, the config must contain:
119                    _target_ : target class or callable name (str)
120                    And may contain:
121                    _args_: List-like of positional arguments to pass to the target
122                    _recursive_: Construct nested objects as well (bool).
123                                 True by default.
124                                 may be overridden via a _recursive_ key in
125                                 the kwargs
126                    _convert_: Conversion strategy
127                         none    : Passed objects are DictConfig and ListConfig, default
128                         partial : Passed objects are converted to dict and list, with
129                                   the exception of Structured Configs (and their fields).
130                         all     : Passed objects are dicts, lists and primitives without
131                                   a trace of OmegaConf containers
132                    _partial_: If True, return functools.partial wrapped method or object
133                               False by default. Configure per target.
134     :param args: Optional positional parameters pass-through
135     :param kwargs: Optional named parameters to override
136                    parameters in the config object. Parameters not present
137                    in the config objects are being passed as is to the target.
138                    IMPORTANT: dataclasses instances in kwargs are interpreted as config
139                               and cannot be used as passthrough
140     :return: if _target_ is a class name: the instantiated object
141              if _target_ is a callable: the return value of the call
142     """
143 
144     # Return None if config is None
145     if config is None:
146         return None
147 
148     # TargetConf edge case
149     if isinstance(config, TargetConf) and config._target_ == "???":
150         # Specific check to give a good warning about failure to annotate _target_ as a string.
151         raise InstantiationException(
152             f"Missing value for {type(config).__name__}._target_. Check that it's properly annotated and overridden."
153             f"\nA common problem is forgetting to annotate _target_ as a string : '_target_: str = ...'"
154         )
155 
156     if isinstance(config, dict):
157         config = _prepare_input_dict(config)
158 
159     kwargs = _prepare_input_dict(kwargs)
160 
161     # Structured Config always converted first to OmegaConf
162     if is_structured_config(config) or isinstance(config, dict):
163         config = OmegaConf.structured(config, flags={"allow_objects": True})
164 
165     if OmegaConf.is_dict(config):
166         # Finalize config (convert targets to strings, merge with kwargs)
167         config_copy = copy.deepcopy(config)
168         config_copy._set_flag(
169             flags=["allow_objects", "struct", "readonly"], values=[True, False, False]
170         )
171         config_copy._set_parent(config._get_parent())
172         config = config_copy
173 
174         if kwargs:
175             config = OmegaConf.merge(config, kwargs)
176 
177         OmegaConf.resolve(config)
178 
179         _recursive_ = config.pop(_Keys.RECURSIVE, True)
180         _convert_ = config.pop(_Keys.CONVERT, ConvertMode.NONE)
181         _partial_ = config.pop(_Keys.PARTIAL, False)
182 
183         return instantiate_node(
184             config, *args, recursive=_recursive_, convert=_convert_, partial=_partial_
185         )
186     else:
187         raise InstantiationException(
188             "Top level config has to be OmegaConf DictConfig, plain dict, or a Structured Config class or instance"
189         )
190 
191 
192 def _convert_node(node: Any, convert: Union[ConvertMode, str]) -> Any:
193     if OmegaConf.is_config(node):
194         if convert == ConvertMode.ALL:
195             node = OmegaConf.to_container(node, resolve=True)
196         elif convert == ConvertMode.PARTIAL:
197             node = OmegaConf.to_container(
198                 node, resolve=True, structured_config_mode=SCMode.DICT_CONFIG
199             )
200     return node
201 
202 
203 def instantiate_node(
204     node: Any,
205     *args: Any,
206     convert: Union[str, ConvertMode] = ConvertMode.NONE,
207     recursive: bool = True,
208     partial: bool = False,
209 ) -> Any:
210     # Return None if config is None
211     if node is None or (OmegaConf.is_config(node) and node._is_none()):
212         return None
213 
214     if not OmegaConf.is_config(node):
215         return node
216 
217     # Override parent modes from config if specified
218     if OmegaConf.is_dict(node):
219         # using getitem instead of get(key, default) because OmegaConf will raise an exception
220         # if the key type is incompatible on get.
221         convert = node[_Keys.CONVERT] if _Keys.CONVERT in node else convert
222         recursive = node[_Keys.RECURSIVE] if _Keys.RECURSIVE in node else recursive
223         partial = node[_Keys.PARTIAL] if _Keys.PARTIAL in node else partial
224 
225     if not isinstance(recursive, bool):
226         raise TypeError(f"_recursive_ flag must be a bool, got {type(recursive)}")
227 
228     if not isinstance(partial, bool):
229         raise TypeError(f"_partial_ flag must be a bool, got {type( partial )}")
230 
231     # If OmegaConf list, create new list of instances if recursive
232     if OmegaConf.is_list(node):
233         items = [
234             instantiate_node(item, convert=convert, recursive=recursive)
235             for item in node._iter_ex(resolve=True)
236         ]
237 
238         if convert in (ConvertMode.ALL, ConvertMode.PARTIAL):
239             # If ALL or PARTIAL, use plain list as container
240             return items
241         else:
242             # Otherwise, use ListConfig as container
243             lst = OmegaConf.create(items, flags={"allow_objects": True})
244             lst._set_parent(node)
245             return lst
246 
247     elif OmegaConf.is_dict(node):
248         exclude_keys = set({"_target_", "_convert_", "_recursive_", "_partial_"})
249         if _is_target(node):
250             _target_ = _resolve_target(node.get(_Keys.TARGET))
251             kwargs = {}
252             for key, value in node.items():
253                 if key not in exclude_keys:
254                     if recursive:
255                         value = instantiate_node(
256                             value, convert=convert, recursive=recursive
257                         )
258                     kwargs[key] = _convert_node(value, convert)
259 
260             return _call_target(_target_, partial, *args, **kwargs)
261         else:
262             # If ALL or PARTIAL non structured, instantiate in dict and resolve interpolations eagerly.
263             if convert == ConvertMode.ALL or (
264                 convert == ConvertMode.PARTIAL and node._metadata.object_type is None
265             ):
266                 dict_items = {}
267                 for key, value in node.items():
268                     # list items inherits recursive flag from the containing dict.
269                     dict_items[key] = instantiate_node(
270                         value, convert=convert, recursive=recursive
271                     )
272                 return dict_items
273             else:
274                 # Otherwise use DictConfig and resolve interpolations lazily.
275                 cfg = OmegaConf.create({}, flags={"allow_objects": True})
276                 for key, value in node.items():
277                     cfg[key] = instantiate_node(
278                         value, convert=convert, recursive=recursive
279                     )
280                 cfg._set_parent(node)
281                 cfg._metadata.object_type = node._metadata.object_type
282                 return cfg
283 
284     else:
285         assert False, f"Unexpected config type : {type(node).__name__}"
286
```
--- 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/hydra/_internal/instantiate/_instantiate2.py b/hydra/_internal/instantiate/_instantiate2.py
--- a/hydra/_internal/instantiate/_instantiate2.py
+++ b/hydra/_internal/instantiate/_instantiate2.py
@@ -60,14 +60,20 @@
         for v in kwargs.values():
             if OmegaConf.is_config(v):
                 v._set_parent(None)
-        if _partial_:
-            return functools.partial(_target_, *args, **kwargs)
-        return _target_(*args, **kwargs)
     except Exception as e:
         raise type(e)(
             f"Error instantiating '{_convert_target_to_string(_target_)}' : {e}"
         ).with_traceback(sys.exc_info()[2])
 
+    try:
+        if _partial_:
+            return functools.partial(_target_, *args, **kwargs)
+        return _target_(*args, **kwargs)
+    except Exception as e:
+        raise InstantiationException(
+            f"Error instantiating '{_convert_target_to_string(_target_)}' : {repr(e)}"
+        ) from e
+
 
 def _convert_target_to_string(t: Any) -> Any:
     if callable(t):

{"golden_diff": "diff --git a/hydra/_internal/instantiate/_instantiate2.py b/hydra/_internal/instantiate/_instantiate2.py\n--- a/hydra/_internal/instantiate/_instantiate2.py\n+++ b/hydra/_internal/instantiate/_instantiate2.py\n@@ -60,14 +60,20 @@\n         for v in kwargs.values():\n             if OmegaConf.is_config(v):\n                 v._set_parent(None)\n-        if _partial_:\n-            return functools.partial(_target_, *args, **kwargs)\n-        return _target_(*args, **kwargs)\n     except Exception as e:\n         raise type(e)(\n             f\"Error instantiating '{_convert_target_to_string(_target_)}' : {e}\"\n         ).with_traceback(sys.exc_info()[2])\n \n+    try:\n+        if _partial_:\n+            return functools.partial(_target_, *args, **kwargs)\n+        return _target_(*args, **kwargs)\n+    except Exception as e:\n+        raise InstantiationException(\n+            f\"Error instantiating '{_convert_target_to_string(_target_)}' : {repr(e)}\"\n+        ) from e\n+\n \n def _convert_target_to_string(t: Any) -> Any:\n     if callable(t):\n", "issue": "Instantiation exception also raises an exception sometimes\n# \ud83d\udc1b Bug\r\n## Description\r\n\r\nWhen there's an instantiation exception, raising a chained exception sometimes also fails because it doesn't take an argument:\r\n\r\nhttps://github.com/facebookresearch/hydra/blob/9759f87673be1d41fe33279e1b7980f8efb38b19/hydra/_internal/instantiate/_instantiate2.py#L63-L66\r\n\r\n## Checklist\r\n- [x] I checked on the latest version of Hydra\r\n- [ ] I created a minimal repro (See [this](https://stackoverflow.com/help/minimal-reproducible-example) for tips).\r\n\r\n## To reproduce\r\n\r\nTry to instantiate an object such that it raises an exception that doesn't take any argument.\r\n\r\n## Expected Behavior\r\n\r\nMaybe it should try to show another type of exception instead? Or chaining (`from e`).\r\n\r\n## System information\r\n- **Hydra Version** :  1.1\r\n- **Python version** : 3.8\r\n- **Virtual environment type and version** : conda 4.11\r\n- **Operating system** : Ubuntu 18.04\r\n\r\n## Additional context\r\nAdd any other context about the problem here.\r\n\n", "before_files": [{"content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\nimport copy\nimport functools\nimport sys\nfrom enum import Enum\nfrom typing import Any, Callable, Sequence, Tuple, Union\n\nfrom omegaconf import OmegaConf, SCMode\nfrom omegaconf._utils import is_structured_config\n\nfrom hydra._internal.utils import _locate\nfrom hydra.errors import InstantiationException\nfrom hydra.types import ConvertMode, TargetConf\n\n\nclass _Keys(str, Enum):\n    \"\"\"Special keys in configs used by instantiate.\"\"\"\n\n    TARGET = \"_target_\"\n    CONVERT = \"_convert_\"\n    RECURSIVE = \"_recursive_\"\n    ARGS = \"_args_\"\n    PARTIAL = \"_partial_\"\n\n\ndef _is_target(x: Any) -> bool:\n    if isinstance(x, dict):\n        return \"_target_\" in x\n    if OmegaConf.is_dict(x):\n        return \"_target_\" in x\n    return False\n\n\ndef _extract_pos_args(*input_args: Any, **kwargs: Any) -> Tuple[Any, Any]:\n    config_args = kwargs.pop(_Keys.ARGS, ())\n    output_args = config_args\n\n    if isinstance(config_args, Sequence):\n        if len(input_args) > 0:\n            output_args = input_args\n    else:\n        raise InstantiationException(\n            f\"Unsupported _args_ type: {type(config_args).__name__}. value: {config_args}\"\n        )\n\n    return output_args, kwargs\n\n\ndef _call_target(_target_: Callable, _partial_: bool, *args, **kwargs) -> Any:  # type: ignore\n    \"\"\"Call target (type) with args and kwargs.\"\"\"\n    try:\n        args, kwargs = _extract_pos_args(*args, **kwargs)\n        # detaching configs from parent.\n        # At this time, everything is resolved and the parent link can cause\n        # issues when serializing objects in some scenarios.\n        for arg in args:\n            if OmegaConf.is_config(arg):\n                arg._set_parent(None)\n        for v in kwargs.values():\n            if OmegaConf.is_config(v):\n                v._set_parent(None)\n        if _partial_:\n            return functools.partial(_target_, *args, **kwargs)\n        return _target_(*args, **kwargs)\n    except Exception as e:\n        raise type(e)(\n            f\"Error instantiating '{_convert_target_to_string(_target_)}' : {e}\"\n        ).with_traceback(sys.exc_info()[2])\n\n\ndef _convert_target_to_string(t: Any) -> Any:\n    if callable(t):\n        return f\"{t.__module__}.{t.__qualname__}\"\n    else:\n        return t\n\n\ndef _prepare_input_dict(d: Any) -> Any:\n    res: Any\n    if isinstance(d, dict):\n        res = {}\n        for k, v in d.items():\n            if k == \"_target_\":\n                v = _convert_target_to_string(d[\"_target_\"])\n            elif isinstance(v, (dict, list)):\n                v = _prepare_input_dict(v)\n            res[k] = v\n    elif isinstance(d, list):\n        res = []\n        for v in d:\n            if isinstance(v, (list, dict)):\n                v = _prepare_input_dict(v)\n            res.append(v)\n    else:\n        assert False\n    return res\n\n\ndef _resolve_target(\n    target: Union[str, type, Callable[..., Any]]\n) -> Union[type, Callable[..., Any]]:\n    \"\"\"Resolve target string, type or callable into type or callable.\"\"\"\n    if isinstance(target, str):\n        return _locate(target)\n    if isinstance(target, type):\n        return target\n    if callable(target):\n        return target\n    raise InstantiationException(\n        f\"Unsupported target type: {type(target).__name__}. value: {target}\"\n    )\n\n\ndef instantiate(config: Any, *args: Any, **kwargs: Any) -> Any:\n    \"\"\"\n    :param config: An config object describing what to call and what params to use.\n                   In addition to the parameters, the config must contain:\n                   _target_ : target class or callable name (str)\n                   And may contain:\n                   _args_: List-like of positional arguments to pass to the target\n                   _recursive_: Construct nested objects as well (bool).\n                                True by default.\n                                may be overridden via a _recursive_ key in\n                                the kwargs\n                   _convert_: Conversion strategy\n                        none    : Passed objects are DictConfig and ListConfig, default\n                        partial : Passed objects are converted to dict and list, with\n                                  the exception of Structured Configs (and their fields).\n                        all     : Passed objects are dicts, lists and primitives without\n                                  a trace of OmegaConf containers\n                   _partial_: If True, return functools.partial wrapped method or object\n                              False by default. Configure per target.\n    :param args: Optional positional parameters pass-through\n    :param kwargs: Optional named parameters to override\n                   parameters in the config object. Parameters not present\n                   in the config objects are being passed as is to the target.\n                   IMPORTANT: dataclasses instances in kwargs are interpreted as config\n                              and cannot be used as passthrough\n    :return: if _target_ is a class name: the instantiated object\n             if _target_ is a callable: the return value of the call\n    \"\"\"\n\n    # Return None if config is None\n    if config is None:\n        return None\n\n    # TargetConf edge case\n    if isinstance(config, TargetConf) and config._target_ == \"???\":\n        # Specific check to give a good warning about failure to annotate _target_ as a string.\n        raise InstantiationException(\n            f\"Missing value for {type(config).__name__}._target_. Check that it's properly annotated and overridden.\"\n            f\"\\nA common problem is forgetting to annotate _target_ as a string : '_target_: str = ...'\"\n        )\n\n    if isinstance(config, dict):\n        config = _prepare_input_dict(config)\n\n    kwargs = _prepare_input_dict(kwargs)\n\n    # Structured Config always converted first to OmegaConf\n    if is_structured_config(config) or isinstance(config, dict):\n        config = OmegaConf.structured(config, flags={\"allow_objects\": True})\n\n    if OmegaConf.is_dict(config):\n        # Finalize config (convert targets to strings, merge with kwargs)\n        config_copy = copy.deepcopy(config)\n        config_copy._set_flag(\n            flags=[\"allow_objects\", \"struct\", \"readonly\"], values=[True, False, False]\n        )\n        config_copy._set_parent(config._get_parent())\n        config = config_copy\n\n        if kwargs:\n            config = OmegaConf.merge(config, kwargs)\n\n        OmegaConf.resolve(config)\n\n        _recursive_ = config.pop(_Keys.RECURSIVE, True)\n        _convert_ = config.pop(_Keys.CONVERT, ConvertMode.NONE)\n        _partial_ = config.pop(_Keys.PARTIAL, False)\n\n        return instantiate_node(\n            config, *args, recursive=_recursive_, convert=_convert_, partial=_partial_\n        )\n    else:\n        raise InstantiationException(\n            \"Top level config has to be OmegaConf DictConfig, plain dict, or a Structured Config class or instance\"\n        )\n\n\ndef _convert_node(node: Any, convert: Union[ConvertMode, str]) -> Any:\n    if OmegaConf.is_config(node):\n        if convert == ConvertMode.ALL:\n            node = OmegaConf.to_container(node, resolve=True)\n        elif convert == ConvertMode.PARTIAL:\n            node = OmegaConf.to_container(\n                node, resolve=True, structured_config_mode=SCMode.DICT_CONFIG\n            )\n    return node\n\n\ndef instantiate_node(\n    node: Any,\n    *args: Any,\n    convert: Union[str, ConvertMode] = ConvertMode.NONE,\n    recursive: bool = True,\n    partial: bool = False,\n) -> Any:\n    # Return None if config is None\n    if node is None or (OmegaConf.is_config(node) and node._is_none()):\n        return None\n\n    if not OmegaConf.is_config(node):\n        return node\n\n    # Override parent modes from config if specified\n    if OmegaConf.is_dict(node):\n        # using getitem instead of get(key, default) because OmegaConf will raise an exception\n        # if the key type is incompatible on get.\n        convert = node[_Keys.CONVERT] if _Keys.CONVERT in node else convert\n        recursive = node[_Keys.RECURSIVE] if _Keys.RECURSIVE in node else recursive\n        partial = node[_Keys.PARTIAL] if _Keys.PARTIAL in node else partial\n\n    if not isinstance(recursive, bool):\n        raise TypeError(f\"_recursive_ flag must be a bool, got {type(recursive)}\")\n\n    if not isinstance(partial, bool):\n        raise TypeError(f\"_partial_ flag must be a bool, got {type( partial )}\")\n\n    # If OmegaConf list, create new list of instances if recursive\n    if OmegaConf.is_list(node):\n        items = [\n            instantiate_node(item, convert=convert, recursive=recursive)\n            for item in node._iter_ex(resolve=True)\n        ]\n\n        if convert in (ConvertMode.ALL, ConvertMode.PARTIAL):\n            # If ALL or PARTIAL, use plain list as container\n            return items\n        else:\n            # Otherwise, use ListConfig as container\n            lst = OmegaConf.create(items, flags={\"allow_objects\": True})\n            lst._set_parent(node)\n            return lst\n\n    elif OmegaConf.is_dict(node):\n        exclude_keys = set({\"_target_\", \"_convert_\", \"_recursive_\", \"_partial_\"})\n        if _is_target(node):\n            _target_ = _resolve_target(node.get(_Keys.TARGET))\n            kwargs = {}\n            for key, value in node.items():\n                if key not in exclude_keys:\n                    if recursive:\n                        value = instantiate_node(\n                            value, convert=convert, recursive=recursive\n                        )\n                    kwargs[key] = _convert_node(value, convert)\n\n            return _call_target(_target_, partial, *args, **kwargs)\n        else:\n            # If ALL or PARTIAL non structured, instantiate in dict and resolve interpolations eagerly.\n            if convert == ConvertMode.ALL or (\n                convert == ConvertMode.PARTIAL and node._metadata.object_type is None\n            ):\n                dict_items = {}\n                for key, value in node.items():\n                    # list items inherits recursive flag from the containing dict.\n                    dict_items[key] = instantiate_node(\n                        value, convert=convert, recursive=recursive\n                    )\n                return dict_items\n            else:\n                # Otherwise use DictConfig and resolve interpolations lazily.\n                cfg = OmegaConf.create({}, flags={\"allow_objects\": True})\n                for key, value in node.items():\n                    cfg[key] = instantiate_node(\n                        value, convert=convert, recursive=recursive\n                    )\n                cfg._set_parent(node)\n                cfg._metadata.object_type = node._metadata.object_type\n                return cfg\n\n    else:\n        assert False, f\"Unexpected config type : {type(node).__name__}\"\n", "path": "hydra/_internal/instantiate/_instantiate2.py"}], "after_files": [{"content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\nimport copy\nimport functools\nimport sys\nfrom enum import Enum\nfrom typing import Any, Callable, Sequence, Tuple, Union\n\nfrom omegaconf import OmegaConf, SCMode\nfrom omegaconf._utils import is_structured_config\n\nfrom hydra._internal.utils import _locate\nfrom hydra.errors import InstantiationException\nfrom hydra.types import ConvertMode, TargetConf\n\n\nclass _Keys(str, Enum):\n    \"\"\"Special keys in configs used by instantiate.\"\"\"\n\n    TARGET = \"_target_\"\n    CONVERT = \"_convert_\"\n    RECURSIVE = \"_recursive_\"\n    ARGS = \"_args_\"\n    PARTIAL = \"_partial_\"\n\n\ndef _is_target(x: Any) -> bool:\n    if isinstance(x, dict):\n        return \"_target_\" in x\n    if OmegaConf.is_dict(x):\n        return \"_target_\" in x\n    return False\n\n\ndef _extract_pos_args(*input_args: Any, **kwargs: Any) -> Tuple[Any, Any]:\n    config_args = kwargs.pop(_Keys.ARGS, ())\n    output_args = config_args\n\n    if isinstance(config_args, Sequence):\n        if len(input_args) > 0:\n            output_args = input_args\n    else:\n        raise InstantiationException(\n            f\"Unsupported _args_ type: {type(config_args).__name__}. value: {config_args}\"\n        )\n\n    return output_args, kwargs\n\n\ndef _call_target(_target_: Callable, _partial_: bool, *args, **kwargs) -> Any:  # type: ignore\n    \"\"\"Call target (type) with args and kwargs.\"\"\"\n    try:\n        args, kwargs = _extract_pos_args(*args, **kwargs)\n        # detaching configs from parent.\n        # At this time, everything is resolved and the parent link can cause\n        # issues when serializing objects in some scenarios.\n        for arg in args:\n            if OmegaConf.is_config(arg):\n                arg._set_parent(None)\n        for v in kwargs.values():\n            if OmegaConf.is_config(v):\n                v._set_parent(None)\n    except Exception as e:\n        raise type(e)(\n            f\"Error instantiating '{_convert_target_to_string(_target_)}' : {e}\"\n        ).with_traceback(sys.exc_info()[2])\n\n    try:\n        if _partial_:\n            return functools.partial(_target_, *args, **kwargs)\n        return _target_(*args, **kwargs)\n    except Exception as e:\n        raise InstantiationException(\n            f\"Error instantiating '{_convert_target_to_string(_target_)}' : {repr(e)}\"\n        ) from e\n\n\ndef _convert_target_to_string(t: Any) -> Any:\n    if callable(t):\n        return f\"{t.__module__}.{t.__qualname__}\"\n    else:\n        return t\n\n\ndef _prepare_input_dict(d: Any) -> Any:\n    res: Any\n    if isinstance(d, dict):\n        res = {}\n        for k, v in d.items():\n            if k == \"_target_\":\n                v = _convert_target_to_string(d[\"_target_\"])\n            elif isinstance(v, (dict, list)):\n                v = _prepare_input_dict(v)\n            res[k] = v\n    elif isinstance(d, list):\n        res = []\n        for v in d:\n            if isinstance(v, (list, dict)):\n                v = _prepare_input_dict(v)\n            res.append(v)\n    else:\n        assert False\n    return res\n\n\ndef _resolve_target(\n    target: Union[str, type, Callable[..., Any]]\n) -> Union[type, Callable[..., Any]]:\n    \"\"\"Resolve target string, type or callable into type or callable.\"\"\"\n    if isinstance(target, str):\n        return _locate(target)\n    if isinstance(target, type):\n        return target\n    if callable(target):\n        return target\n    raise InstantiationException(\n        f\"Unsupported target type: {type(target).__name__}. value: {target}\"\n    )\n\n\ndef instantiate(config: Any, *args: Any, **kwargs: Any) -> Any:\n    \"\"\"\n    :param config: An config object describing what to call and what params to use.\n                   In addition to the parameters, the config must contain:\n                   _target_ : target class or callable name (str)\n                   And may contain:\n                   _args_: List-like of positional arguments to pass to the target\n                   _recursive_: Construct nested objects as well (bool).\n                                True by default.\n                                may be overridden via a _recursive_ key in\n                                the kwargs\n                   _convert_: Conversion strategy\n                        none    : Passed objects are DictConfig and ListConfig, default\n                        partial : Passed objects are converted to dict and list, with\n                                  the exception of Structured Configs (and their fields).\n                        all     : Passed objects are dicts, lists and primitives without\n                                  a trace of OmegaConf containers\n                   _partial_: If True, return functools.partial wrapped method or object\n                              False by default. Configure per target.\n    :param args: Optional positional parameters pass-through\n    :param kwargs: Optional named parameters to override\n                   parameters in the config object. Parameters not present\n                   in the config objects are being passed as is to the target.\n                   IMPORTANT: dataclasses instances in kwargs are interpreted as config\n                              and cannot be used as passthrough\n    :return: if _target_ is a class name: the instantiated object\n             if _target_ is a callable: the return value of the call\n    \"\"\"\n\n    # Return None if config is None\n    if config is None:\n        return None\n\n    # TargetConf edge case\n    if isinstance(config, TargetConf) and config._target_ == \"???\":\n        # Specific check to give a good warning about failure to annotate _target_ as a string.\n        raise InstantiationException(\n            f\"Missing value for {type(config).__name__}._target_. Check that it's properly annotated and overridden.\"\n            f\"\\nA common problem is forgetting to annotate _target_ as a string : '_target_: str = ...'\"\n        )\n\n    if isinstance(config, dict):\n        config = _prepare_input_dict(config)\n\n    kwargs = _prepare_input_dict(kwargs)\n\n    # Structured Config always converted first to OmegaConf\n    if is_structured_config(config) or isinstance(config, dict):\n        config = OmegaConf.structured(config, flags={\"allow_objects\": True})\n\n    if OmegaConf.is_dict(config):\n        # Finalize config (convert targets to strings, merge with kwargs)\n        config_copy = copy.deepcopy(config)\n        config_copy._set_flag(\n            flags=[\"allow_objects\", \"struct\", \"readonly\"], values=[True, False, False]\n        )\n        config_copy._set_parent(config._get_parent())\n        config = config_copy\n\n        if kwargs:\n            config = OmegaConf.merge(config, kwargs)\n\n        OmegaConf.resolve(config)\n\n        _recursive_ = config.pop(_Keys.RECURSIVE, True)\n        _convert_ = config.pop(_Keys.CONVERT, ConvertMode.NONE)\n        _partial_ = config.pop(_Keys.PARTIAL, False)\n\n        return instantiate_node(\n            config, *args, recursive=_recursive_, convert=_convert_, partial=_partial_\n        )\n    else:\n        raise InstantiationException(\n            \"Top level config has to be OmegaConf DictConfig, plain dict, or a Structured Config class or instance\"\n        )\n\n\ndef _convert_node(node: Any, convert: Union[ConvertMode, str]) -> Any:\n    if OmegaConf.is_config(node):\n        if convert == ConvertMode.ALL:\n            node = OmegaConf.to_container(node, resolve=True)\n        elif convert == ConvertMode.PARTIAL:\n            node = OmegaConf.to_container(\n                node, resolve=True, structured_config_mode=SCMode.DICT_CONFIG\n            )\n    return node\n\n\ndef instantiate_node(\n    node: Any,\n    *args: Any,\n    convert: Union[str, ConvertMode] = ConvertMode.NONE,\n    recursive: bool = True,\n    partial: bool = False,\n) -> Any:\n    # Return None if config is None\n    if node is None or (OmegaConf.is_config(node) and node._is_none()):\n        return None\n\n    if not OmegaConf.is_config(node):\n        return node\n\n    # Override parent modes from config if specified\n    if OmegaConf.is_dict(node):\n        # using getitem instead of get(key, default) because OmegaConf will raise an exception\n        # if the key type is incompatible on get.\n        convert = node[_Keys.CONVERT] if _Keys.CONVERT in node else convert\n        recursive = node[_Keys.RECURSIVE] if _Keys.RECURSIVE in node else recursive\n        partial = node[_Keys.PARTIAL] if _Keys.PARTIAL in node else partial\n\n    if not isinstance(recursive, bool):\n        raise TypeError(f\"_recursive_ flag must be a bool, got {type(recursive)}\")\n\n    if not isinstance(partial, bool):\n        raise TypeError(f\"_partial_ flag must be a bool, got {type( partial )}\")\n\n    # If OmegaConf list, create new list of instances if recursive\n    if OmegaConf.is_list(node):\n        items = [\n            instantiate_node(item, convert=convert, recursive=recursive)\n            for item in node._iter_ex(resolve=True)\n        ]\n\n        if convert in (ConvertMode.ALL, ConvertMode.PARTIAL):\n            # If ALL or PARTIAL, use plain list as container\n            return items\n        else:\n            # Otherwise, use ListConfig as container\n            lst = OmegaConf.create(items, flags={\"allow_objects\": True})\n            lst._set_parent(node)\n            return lst\n\n    elif OmegaConf.is_dict(node):\n        exclude_keys = set({\"_target_\", \"_convert_\", \"_recursive_\", \"_partial_\"})\n        if _is_target(node):\n            _target_ = _resolve_target(node.get(_Keys.TARGET))\n            kwargs = {}\n            for key, value in node.items():\n                if key not in exclude_keys:\n                    if recursive:\n                        value = instantiate_node(\n                            value, convert=convert, recursive=recursive\n                        )\n                    kwargs[key] = _convert_node(value, convert)\n\n            return _call_target(_target_, partial, *args, **kwargs)\n        else:\n            # If ALL or PARTIAL non structured, instantiate in dict and resolve interpolations eagerly.\n            if convert == ConvertMode.ALL or (\n                convert == ConvertMode.PARTIAL and node._metadata.object_type is None\n            ):\n                dict_items = {}\n                for key, value in node.items():\n                    # list items inherits recursive flag from the containing dict.\n                    dict_items[key] = instantiate_node(\n                        value, convert=convert, recursive=recursive\n                    )\n                return dict_items\n            else:\n                # Otherwise use DictConfig and resolve interpolations lazily.\n                cfg = OmegaConf.create({}, flags={\"allow_objects\": True})\n                for key, value in node.items():\n                    cfg[key] = instantiate_node(\n                        value, convert=convert, recursive=recursive\n                    )\n                cfg._set_parent(node)\n                cfg._metadata.object_type = node._metadata.object_type\n                return cfg\n\n    else:\n        assert False, f\"Unexpected config type : {type(node).__name__}\"\n", "path": "hydra/_internal/instantiate/_instantiate2.py"}]}