We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[Bug] Cannot use `target` kwarg when instantiating with `hydra.utils.instantiate()`
# 🐛 Bug
## Description
`hydra.utils.instantiate()` seems to fail when trying to instantiate a class with a keyword argument called `target`.
It seems like the two keys `_target_` and `target` are clashing, and this raises a 
`TypeError: _call_target() got multiple values for argument 'target'`.

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

## To reproduce

**Minimal Code/Config snippet to reproduce**
Available as a Colab Gists:
https://colab.research.google.com/gist/fabiocarrara/6bf5abaecf3f84c1e83239f8af3b8219/hydra_instantiate_bug.ipynb

**Stack trace/error message**
```
TypeError                                 Traceback (most recent call last)
<ipython-input-4-616e52dc8a9b> in <module>()
----> 1 foo = hydra.utils.instantiate(cfg.bar)
      2 foo.target

/usr/local/lib/python3.7/dist-packages/hydra/_internal/instantiate/_instantiate2.py in instantiate(config, *args, **kwargs)
    178         _convert_ = config.pop(_Keys.CONVERT, ConvertMode.NONE)
    179 
--> 180         return instantiate_node(config, *args, recursive=_recursive_, convert=_convert_)
    181     else:
    182         raise InstantiationException(

/usr/local/lib/python3.7/dist-packages/hydra/_internal/instantiate/_instantiate2.py in instantiate_node(node, convert, recursive, *args)
    247                         )
    248                     kwargs[key] = _convert_node(value, convert)
--> 249             return _call_target(target, *args, **kwargs)
    250         else:
    251             # If ALL or PARTIAL non structured, instantiate in dict and resolve interpolations eagerly.

TypeError: _call_target() got multiple values for argument 'target'
```

## Expected Behavior
`target` should be a permitted key name for callable/constructor's kwargs.

## System information
- **Hydra Version** :  1.1
- **Python version** : 3.7.10 (Colab)
- **Virtual environment type and version** : none
- **Operating system** :  Colab


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

{"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@@ -45,7 +45,7 @@\n     return output_args, kwargs\n \n \n-def _call_target(target: Callable, *args, **kwargs) -> Any:  # type: ignore\n+def _call_target(_target_: Callable, *args, **kwargs) -> Any:  # type: ignore\n     \"\"\"Call target (type) with args and kwargs.\"\"\"\n     try:\n         args, kwargs = _extract_pos_args(*args, **kwargs)\n@@ -59,10 +59,10 @@\n             if OmegaConf.is_config(v):\n                 v._set_parent(None)\n \n-        return 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+            f\"Error instantiating '{_convert_target_to_string(_target_)}' : {e}\"\n         ).with_traceback(sys.exc_info()[2])\n \n \n@@ -237,7 +237,7 @@\n     elif OmegaConf.is_dict(node):\n         exclude_keys = set({\"_target_\", \"_convert_\", \"_recursive_\"})\n         if _is_target(node):\n-            target = _resolve_target(node.get(_Keys.TARGET))\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@@ -246,7 +246,7 @@\n                             value, convert=convert, recursive=recursive\n                         )\n                     kwargs[key] = _convert_node(value, convert)\n-            return _call_target(target, *args, **kwargs)\n+            return _call_target(_target_, *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", "issue": "[Bug] Cannot use `target` kwarg when instantiating with `hydra.utils.instantiate()`\n# \ud83d\udc1b Bug\r\n## Description\r\n`hydra.utils.instantiate()` seems to fail when trying to instantiate a class with a keyword argument called `target`.\r\nIt seems like the two keys `_target_` and `target` are clashing, and this raises a \r\n`TypeError: _call_target() got multiple values for argument 'target'`.\r\n\r\n## Checklist\r\n- [x] I checked on the latest version of Hydra\r\n- [x] 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\n**Minimal Code/Config snippet to reproduce**\r\nAvailable as a Colab Gists:\r\nhttps://colab.research.google.com/gist/fabiocarrara/6bf5abaecf3f84c1e83239f8af3b8219/hydra_instantiate_bug.ipynb\r\n\r\n**Stack trace/error message**\r\n```\r\nTypeError                                 Traceback (most recent call last)\r\n<ipython-input-4-616e52dc8a9b> in <module>()\r\n----> 1 foo = hydra.utils.instantiate(cfg.bar)\r\n      2 foo.target\r\n\r\n/usr/local/lib/python3.7/dist-packages/hydra/_internal/instantiate/_instantiate2.py in instantiate(config, *args, **kwargs)\r\n    178         _convert_ = config.pop(_Keys.CONVERT, ConvertMode.NONE)\r\n    179 \r\n--> 180         return instantiate_node(config, *args, recursive=_recursive_, convert=_convert_)\r\n    181     else:\r\n    182         raise InstantiationException(\r\n\r\n/usr/local/lib/python3.7/dist-packages/hydra/_internal/instantiate/_instantiate2.py in instantiate_node(node, convert, recursive, *args)\r\n    247                         )\r\n    248                     kwargs[key] = _convert_node(value, convert)\r\n--> 249             return _call_target(target, *args, **kwargs)\r\n    250         else:\r\n    251             # If ALL or PARTIAL non structured, instantiate in dict and resolve interpolations eagerly.\r\n\r\nTypeError: _call_target() got multiple values for argument 'target'\r\n```\r\n\r\n## Expected Behavior\r\n`target` should be a permitted key name for callable/constructor's kwargs.\r\n\r\n## System information\r\n- **Hydra Version** :  1.1\r\n- **Python version** : 3.7.10 (Colab)\r\n- **Virtual environment type and version** : none\r\n- **Operating system** :  Colab\r\n\n", "before_files": [{"content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\nimport copy\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\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, *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\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 isinstance(t, type):\n        return f\"{t.__module__}.{t.__name__}\"\n    elif 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                   _args_: List-like of positional arguments\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\n        return instantiate_node(config, *args, recursive=_recursive_, convert=_convert_)\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) -> 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\n    if not isinstance(recursive, bool):\n        raise TypeError(f\"_recursive_ flag must be a bool, got {type(recursive)}\")\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_\"})\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            return _call_target(target, *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 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\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, *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\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 isinstance(t, type):\n        return f\"{t.__module__}.{t.__name__}\"\n    elif 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                   _args_: List-like of positional arguments\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\n        return instantiate_node(config, *args, recursive=_recursive_, convert=_convert_)\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) -> 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\n    if not isinstance(recursive, bool):\n        raise TypeError(f\"_recursive_ flag must be a bool, got {type(recursive)}\")\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_\"})\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            return _call_target(_target_, *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"}]}