We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Flash `Trainer.from_argparse_args` not working
## 🐛 Bug

Looks like from_argparse_args isn't working for flash trainer. Likely related to #343

cc @aribornstein 

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `flash/core/trainer.py`
Content:
```
1 # Copyright The PyTorch Lightning team.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 import warnings
15 from argparse import ArgumentParser
16 from functools import wraps
17 from typing import Callable, List, Optional, Union
18 
19 import torch
20 from pytorch_lightning import LightningDataModule, LightningModule
21 from pytorch_lightning import Trainer as PlTrainer
22 from pytorch_lightning.callbacks import BaseFinetuning
23 from pytorch_lightning.utilities import rank_zero_warn
24 from pytorch_lightning.utilities.argparse import add_argparse_args, get_init_arguments_and_types, parse_env_variables
25 from pytorch_lightning.utilities.exceptions import MisconfigurationException
26 from torch.utils.data import DataLoader
27 
28 import flash
29 from flash.core.finetuning import _DEFAULTS_FINETUNE_STRATEGIES, instantiate_default_finetuning_callbacks
30 
31 
32 def _defaults_from_env_vars(fn: Callable) -> Callable:
33     """Copy of ``pytorch_lightning.trainer.connectors.env_vars_connector._defaults_from_env_vars``. Required to fix
34     build error in readthedocs."""
35 
36     @wraps(fn)
37     def insert_env_defaults(self, *args, **kwargs):
38         cls = self.__class__  # get the class
39         if args:  # inace any args passed move them to kwargs
40             # parse only the argument names
41             cls_arg_names = [arg[0] for arg in get_init_arguments_and_types(cls)]
42             # convert args to kwargs
43             kwargs.update({k: v for k, v in zip(cls_arg_names, args)})
44         env_variables = vars(parse_env_variables(cls))
45         # update the kwargs by env variables
46         kwargs = dict(list(env_variables.items()) + list(kwargs.items()))
47 
48         # all args were already moved to kwargs
49         return fn(self, **kwargs)
50 
51     return insert_env_defaults
52 
53 
54 class Trainer(PlTrainer):
55 
56     @_defaults_from_env_vars
57     def __init__(self, *args, **kwargs):
58         if flash._IS_TESTING:
59             if torch.cuda.is_available():
60                 kwargs["gpus"] = 1
61                 kwargs["max_epochs"] = 3
62                 kwargs["limit_train_batches"] = 1.0
63                 kwargs["limit_val_batches"] = 1.0
64                 kwargs["limit_test_batches"] = 1.0
65                 kwargs["fast_dev_run"] = False
66             else:
67                 kwargs["fast_dev_run"] = True
68         super().__init__(*args, **kwargs)
69 
70     def fit(
71         self,
72         model: LightningModule,
73         train_dataloader: Optional[DataLoader] = None,
74         val_dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None,
75         datamodule: Optional[LightningDataModule] = None,
76     ):
77         r"""
78         Runs the full optimization routine. Same as :meth:`pytorch_lightning.Trainer.fit`
79 
80         Args:
81             datamodule: A instance of :class:`LightningDataModule`.
82 
83             model: Model to fit.
84 
85             train_dataloader: A Pytorch DataLoader with training samples. If the model has
86                 a predefined train_dataloader method this will be skipped.
87 
88             val_dataloaders: Either a single Pytorch Dataloader or a list of them, specifying validation samples.
89                 If the model has a predefined val_dataloaders method this will be skipped
90         """
91         if any(isinstance(c, BaseFinetuning) for c in self.callbacks):
92             # TODO: if we find a finetuning callback in the trainer should we remove it? or just warn the user?
93             warnings.warn("Warning: You are calling fit(), but your trainer is using a fine-tuning callback")
94         return super().fit(model, train_dataloader, val_dataloaders, datamodule)
95 
96     def finetune(
97         self,
98         model: LightningModule,
99         train_dataloader: Optional[DataLoader] = None,
100         val_dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None,
101         datamodule: Optional[LightningDataModule] = None,
102         strategy: Optional[Union[str, BaseFinetuning]] = None,
103     ):
104         r"""
105 
106         Runs the full optimization routine. Same as :meth:`pytorch_lightning.Trainer.fit`, but unfreezes layers
107         of the backbone throughout training layers of the backbone throughout training.
108 
109         Args:
110             datamodule: A instance of :class:`LightningDataModule`.
111 
112             model: Model to fit.
113 
114             train_dataloader: A PyTorch DataLoader with training samples. If the model has
115                 a predefined train_dataloader method this will be skipped.
116 
117             val_dataloaders: Either a single PyTorch Dataloader or a list of them, specifying validation samples.
118                 If the model has a predefined val_dataloaders method this will be skipped
119 
120             strategy: Should either be a string or a finetuning callback subclassing
121                 :class:`pytorch_lightning.callbacks.BaseFinetuning`.
122 
123                 Default strategies can be enabled with these strings:
124 
125                 - ``"no_freeze"``,
126                 - ``"freeze"``,
127                 - ``"freeze_unfreeze"``,
128                 - ``"unfreeze_milestones"``.
129         """
130         self._resolve_callbacks(model, strategy)
131         return super().fit(model, train_dataloader, val_dataloaders, datamodule)
132 
133     def _resolve_callbacks(self, model, strategy):
134         """
135         This function is used to select the `BaseFinetuning` to be used for finetuning.
136         """
137         if strategy is not None and not isinstance(strategy, (str, BaseFinetuning)):
138             raise MisconfigurationException(
139                 "strategy should be a ``pytorch_lightning.callbacks.BaseFinetuning``"
140                 f"callback or a str within {list(_DEFAULTS_FINETUNE_STRATEGIES.keys())}"
141             )
142 
143         if isinstance(strategy, BaseFinetuning):
144             callback = [strategy]
145         else:
146             # todo: change to ``configure_callbacks`` when merged to Lightning.
147             model_callback = model.configure_finetune_callback()
148             if len(model_callback) > 1:
149                 raise MisconfigurationException(
150                     f"{model} configure_finetune_callback should create a list with only 1 callback"
151                 )
152             if len(model_callback) == 1:
153                 if strategy is not None:
154                     rank_zero_warn(
155                         "The model contains a default finetune callback. The provided {strategy} will be overriden.\n"
156                         " HINT: Provide a `BaseFinetuning` callback as strategy to make it prioritized. ", UserWarning
157                     )
158                 callback = model_callback
159             else:
160                 callback = instantiate_default_finetuning_callbacks(strategy)
161 
162         self.callbacks = self._merge_callbacks(self.callbacks, callback)
163 
164     @staticmethod
165     def _merge_callbacks(old_callbacks: List, new_callbacks: List) -> List:
166         """
167         This function keeps only 1 instance of each callback type,
168         extending new_callbacks with old_callbacks
169         """
170         if len(new_callbacks) == 0:
171             return old_callbacks
172         new_callbacks_types = set(type(c) for c in new_callbacks)
173         old_callbacks_types = set(type(c) for c in old_callbacks)
174         override_types = new_callbacks_types.intersection(old_callbacks_types)
175         new_callbacks.extend(c for c in old_callbacks if type(c) not in override_types)
176         return new_callbacks
177 
178     @classmethod
179     def add_argparse_args(cls, *args, **kwargs) -> ArgumentParser:
180         # the lightning trainer implementation does not support subclasses.
181         # context: https://github.com/PyTorchLightning/lightning-flash/issues/342#issuecomment-848892447
182         return add_argparse_args(PlTrainer, *args, **kwargs)
183
```
--- 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/flash/core/trainer.py b/flash/core/trainer.py
--- a/flash/core/trainer.py
+++ b/flash/core/trainer.py
@@ -11,8 +11,9 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
+import inspect
 import warnings
-from argparse import ArgumentParser
+from argparse import ArgumentParser, Namespace
 from functools import wraps
 from typing import Callable, List, Optional, Union
 
@@ -29,6 +30,22 @@
 from flash.core.finetuning import _DEFAULTS_FINETUNE_STRATEGIES, instantiate_default_finetuning_callbacks
 
 
+def from_argparse_args(cls, args: Union[Namespace, ArgumentParser], **kwargs):
+    """Modified version of ``pytorch_lightning.utilities.argparse.from_argparse_args`` which populates ``valid_kwargs``
+    from ``pytorch_lightning.Trainer``."""
+    if isinstance(args, ArgumentParser):
+        args = cls.parse_argparser(args)
+
+    params = vars(args)
+
+    # we only want to pass in valid PLTrainer args, the rest may be user specific
+    valid_kwargs = inspect.signature(PlTrainer.__init__).parameters
+    trainer_kwargs = dict((name, params[name]) for name in valid_kwargs if name in params)
+    trainer_kwargs.update(**kwargs)
+
+    return cls(**trainer_kwargs)
+
+
 def _defaults_from_env_vars(fn: Callable) -> Callable:
     """Copy of ``pytorch_lightning.trainer.connectors.env_vars_connector._defaults_from_env_vars``. Required to fix
     build error in readthedocs."""
@@ -180,3 +197,9 @@
         # the lightning trainer implementation does not support subclasses.
         # context: https://github.com/PyTorchLightning/lightning-flash/issues/342#issuecomment-848892447
         return add_argparse_args(PlTrainer, *args, **kwargs)
+
+    @classmethod
+    def from_argparse_args(cls, args: Union[Namespace, ArgumentParser], **kwargs) -> 'Trainer':
+        # the lightning trainer implementation does not support subclasses.
+        # context: https://github.com/PyTorchLightning/lightning-flash/issues/342#issuecomment-848892447
+        return from_argparse_args(PlTrainer, args, **kwargs)

{"golden_diff": "diff --git a/flash/core/trainer.py b/flash/core/trainer.py\n--- a/flash/core/trainer.py\n+++ b/flash/core/trainer.py\n@@ -11,8 +11,9 @@\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n+import inspect\n import warnings\n-from argparse import ArgumentParser\n+from argparse import ArgumentParser, Namespace\n from functools import wraps\n from typing import Callable, List, Optional, Union\n \n@@ -29,6 +30,22 @@\n from flash.core.finetuning import _DEFAULTS_FINETUNE_STRATEGIES, instantiate_default_finetuning_callbacks\n \n \n+def from_argparse_args(cls, args: Union[Namespace, ArgumentParser], **kwargs):\n+    \"\"\"Modified version of ``pytorch_lightning.utilities.argparse.from_argparse_args`` which populates ``valid_kwargs``\n+    from ``pytorch_lightning.Trainer``.\"\"\"\n+    if isinstance(args, ArgumentParser):\n+        args = cls.parse_argparser(args)\n+\n+    params = vars(args)\n+\n+    # we only want to pass in valid PLTrainer args, the rest may be user specific\n+    valid_kwargs = inspect.signature(PlTrainer.__init__).parameters\n+    trainer_kwargs = dict((name, params[name]) for name in valid_kwargs if name in params)\n+    trainer_kwargs.update(**kwargs)\n+\n+    return cls(**trainer_kwargs)\n+\n+\n def _defaults_from_env_vars(fn: Callable) -> Callable:\n     \"\"\"Copy of ``pytorch_lightning.trainer.connectors.env_vars_connector._defaults_from_env_vars``. Required to fix\n     build error in readthedocs.\"\"\"\n@@ -180,3 +197,9 @@\n         # the lightning trainer implementation does not support subclasses.\n         # context: https://github.com/PyTorchLightning/lightning-flash/issues/342#issuecomment-848892447\n         return add_argparse_args(PlTrainer, *args, **kwargs)\n+\n+    @classmethod\n+    def from_argparse_args(cls, args: Union[Namespace, ArgumentParser], **kwargs) -> 'Trainer':\n+        # the lightning trainer implementation does not support subclasses.\n+        # context: https://github.com/PyTorchLightning/lightning-flash/issues/342#issuecomment-848892447\n+        return from_argparse_args(PlTrainer, args, **kwargs)\n", "issue": "Flash `Trainer.from_argparse_args` not working\n## \ud83d\udc1b Bug\r\n\r\nLooks like from_argparse_args isn't working for flash trainer. Likely related to #343\r\n\r\ncc @aribornstein \n", "before_files": [{"content": "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport warnings\nfrom argparse import ArgumentParser\nfrom functools import wraps\nfrom typing import Callable, List, Optional, Union\n\nimport torch\nfrom pytorch_lightning import LightningDataModule, LightningModule\nfrom pytorch_lightning import Trainer as PlTrainer\nfrom pytorch_lightning.callbacks import BaseFinetuning\nfrom pytorch_lightning.utilities import rank_zero_warn\nfrom pytorch_lightning.utilities.argparse import add_argparse_args, get_init_arguments_and_types, parse_env_variables\nfrom pytorch_lightning.utilities.exceptions import MisconfigurationException\nfrom torch.utils.data import DataLoader\n\nimport flash\nfrom flash.core.finetuning import _DEFAULTS_FINETUNE_STRATEGIES, instantiate_default_finetuning_callbacks\n\n\ndef _defaults_from_env_vars(fn: Callable) -> Callable:\n    \"\"\"Copy of ``pytorch_lightning.trainer.connectors.env_vars_connector._defaults_from_env_vars``. Required to fix\n    build error in readthedocs.\"\"\"\n\n    @wraps(fn)\n    def insert_env_defaults(self, *args, **kwargs):\n        cls = self.__class__  # get the class\n        if args:  # inace any args passed move them to kwargs\n            # parse only the argument names\n            cls_arg_names = [arg[0] for arg in get_init_arguments_and_types(cls)]\n            # convert args to kwargs\n            kwargs.update({k: v for k, v in zip(cls_arg_names, args)})\n        env_variables = vars(parse_env_variables(cls))\n        # update the kwargs by env variables\n        kwargs = dict(list(env_variables.items()) + list(kwargs.items()))\n\n        # all args were already moved to kwargs\n        return fn(self, **kwargs)\n\n    return insert_env_defaults\n\n\nclass Trainer(PlTrainer):\n\n    @_defaults_from_env_vars\n    def __init__(self, *args, **kwargs):\n        if flash._IS_TESTING:\n            if torch.cuda.is_available():\n                kwargs[\"gpus\"] = 1\n                kwargs[\"max_epochs\"] = 3\n                kwargs[\"limit_train_batches\"] = 1.0\n                kwargs[\"limit_val_batches\"] = 1.0\n                kwargs[\"limit_test_batches\"] = 1.0\n                kwargs[\"fast_dev_run\"] = False\n            else:\n                kwargs[\"fast_dev_run\"] = True\n        super().__init__(*args, **kwargs)\n\n    def fit(\n        self,\n        model: LightningModule,\n        train_dataloader: Optional[DataLoader] = None,\n        val_dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None,\n        datamodule: Optional[LightningDataModule] = None,\n    ):\n        r\"\"\"\n        Runs the full optimization routine. Same as :meth:`pytorch_lightning.Trainer.fit`\n\n        Args:\n            datamodule: A instance of :class:`LightningDataModule`.\n\n            model: Model to fit.\n\n            train_dataloader: A Pytorch DataLoader with training samples. If the model has\n                a predefined train_dataloader method this will be skipped.\n\n            val_dataloaders: Either a single Pytorch Dataloader or a list of them, specifying validation samples.\n                If the model has a predefined val_dataloaders method this will be skipped\n        \"\"\"\n        if any(isinstance(c, BaseFinetuning) for c in self.callbacks):\n            # TODO: if we find a finetuning callback in the trainer should we remove it? or just warn the user?\n            warnings.warn(\"Warning: You are calling fit(), but your trainer is using a fine-tuning callback\")\n        return super().fit(model, train_dataloader, val_dataloaders, datamodule)\n\n    def finetune(\n        self,\n        model: LightningModule,\n        train_dataloader: Optional[DataLoader] = None,\n        val_dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None,\n        datamodule: Optional[LightningDataModule] = None,\n        strategy: Optional[Union[str, BaseFinetuning]] = None,\n    ):\n        r\"\"\"\n\n        Runs the full optimization routine. Same as :meth:`pytorch_lightning.Trainer.fit`, but unfreezes layers\n        of the backbone throughout training layers of the backbone throughout training.\n\n        Args:\n            datamodule: A instance of :class:`LightningDataModule`.\n\n            model: Model to fit.\n\n            train_dataloader: A PyTorch DataLoader with training samples. If the model has\n                a predefined train_dataloader method this will be skipped.\n\n            val_dataloaders: Either a single PyTorch Dataloader or a list of them, specifying validation samples.\n                If the model has a predefined val_dataloaders method this will be skipped\n\n            strategy: Should either be a string or a finetuning callback subclassing\n                :class:`pytorch_lightning.callbacks.BaseFinetuning`.\n\n                Default strategies can be enabled with these strings:\n\n                - ``\"no_freeze\"``,\n                - ``\"freeze\"``,\n                - ``\"freeze_unfreeze\"``,\n                - ``\"unfreeze_milestones\"``.\n        \"\"\"\n        self._resolve_callbacks(model, strategy)\n        return super().fit(model, train_dataloader, val_dataloaders, datamodule)\n\n    def _resolve_callbacks(self, model, strategy):\n        \"\"\"\n        This function is used to select the `BaseFinetuning` to be used for finetuning.\n        \"\"\"\n        if strategy is not None and not isinstance(strategy, (str, BaseFinetuning)):\n            raise MisconfigurationException(\n                \"strategy should be a ``pytorch_lightning.callbacks.BaseFinetuning``\"\n                f\"callback or a str within {list(_DEFAULTS_FINETUNE_STRATEGIES.keys())}\"\n            )\n\n        if isinstance(strategy, BaseFinetuning):\n            callback = [strategy]\n        else:\n            # todo: change to ``configure_callbacks`` when merged to Lightning.\n            model_callback = model.configure_finetune_callback()\n            if len(model_callback) > 1:\n                raise MisconfigurationException(\n                    f\"{model} configure_finetune_callback should create a list with only 1 callback\"\n                )\n            if len(model_callback) == 1:\n                if strategy is not None:\n                    rank_zero_warn(\n                        \"The model contains a default finetune callback. The provided {strategy} will be overriden.\\n\"\n                        \" HINT: Provide a `BaseFinetuning` callback as strategy to make it prioritized. \", UserWarning\n                    )\n                callback = model_callback\n            else:\n                callback = instantiate_default_finetuning_callbacks(strategy)\n\n        self.callbacks = self._merge_callbacks(self.callbacks, callback)\n\n    @staticmethod\n    def _merge_callbacks(old_callbacks: List, new_callbacks: List) -> List:\n        \"\"\"\n        This function keeps only 1 instance of each callback type,\n        extending new_callbacks with old_callbacks\n        \"\"\"\n        if len(new_callbacks) == 0:\n            return old_callbacks\n        new_callbacks_types = set(type(c) for c in new_callbacks)\n        old_callbacks_types = set(type(c) for c in old_callbacks)\n        override_types = new_callbacks_types.intersection(old_callbacks_types)\n        new_callbacks.extend(c for c in old_callbacks if type(c) not in override_types)\n        return new_callbacks\n\n    @classmethod\n    def add_argparse_args(cls, *args, **kwargs) -> ArgumentParser:\n        # the lightning trainer implementation does not support subclasses.\n        # context: https://github.com/PyTorchLightning/lightning-flash/issues/342#issuecomment-848892447\n        return add_argparse_args(PlTrainer, *args, **kwargs)\n", "path": "flash/core/trainer.py"}], "after_files": [{"content": "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport inspect\nimport warnings\nfrom argparse import ArgumentParser, Namespace\nfrom functools import wraps\nfrom typing import Callable, List, Optional, Union\n\nimport torch\nfrom pytorch_lightning import LightningDataModule, LightningModule\nfrom pytorch_lightning import Trainer as PlTrainer\nfrom pytorch_lightning.callbacks import BaseFinetuning\nfrom pytorch_lightning.utilities import rank_zero_warn\nfrom pytorch_lightning.utilities.argparse import add_argparse_args, get_init_arguments_and_types, parse_env_variables\nfrom pytorch_lightning.utilities.exceptions import MisconfigurationException\nfrom torch.utils.data import DataLoader\n\nimport flash\nfrom flash.core.finetuning import _DEFAULTS_FINETUNE_STRATEGIES, instantiate_default_finetuning_callbacks\n\n\ndef from_argparse_args(cls, args: Union[Namespace, ArgumentParser], **kwargs):\n    \"\"\"Modified version of ``pytorch_lightning.utilities.argparse.from_argparse_args`` which populates ``valid_kwargs``\n    from ``pytorch_lightning.Trainer``.\"\"\"\n    if isinstance(args, ArgumentParser):\n        args = cls.parse_argparser(args)\n\n    params = vars(args)\n\n    # we only want to pass in valid PLTrainer args, the rest may be user specific\n    valid_kwargs = inspect.signature(PlTrainer.__init__).parameters\n    trainer_kwargs = dict((name, params[name]) for name in valid_kwargs if name in params)\n    trainer_kwargs.update(**kwargs)\n\n    return cls(**trainer_kwargs)\n\n\ndef _defaults_from_env_vars(fn: Callable) -> Callable:\n    \"\"\"Copy of ``pytorch_lightning.trainer.connectors.env_vars_connector._defaults_from_env_vars``. Required to fix\n    build error in readthedocs.\"\"\"\n\n    @wraps(fn)\n    def insert_env_defaults(self, *args, **kwargs):\n        cls = self.__class__  # get the class\n        if args:  # inace any args passed move them to kwargs\n            # parse only the argument names\n            cls_arg_names = [arg[0] for arg in get_init_arguments_and_types(cls)]\n            # convert args to kwargs\n            kwargs.update({k: v for k, v in zip(cls_arg_names, args)})\n        env_variables = vars(parse_env_variables(cls))\n        # update the kwargs by env variables\n        kwargs = dict(list(env_variables.items()) + list(kwargs.items()))\n\n        # all args were already moved to kwargs\n        return fn(self, **kwargs)\n\n    return insert_env_defaults\n\n\nclass Trainer(PlTrainer):\n\n    @_defaults_from_env_vars\n    def __init__(self, *args, **kwargs):\n        if flash._IS_TESTING:\n            if torch.cuda.is_available():\n                kwargs[\"gpus\"] = 1\n                kwargs[\"max_epochs\"] = 3\n                kwargs[\"limit_train_batches\"] = 1.0\n                kwargs[\"limit_val_batches\"] = 1.0\n                kwargs[\"limit_test_batches\"] = 1.0\n                kwargs[\"fast_dev_run\"] = False\n            else:\n                kwargs[\"fast_dev_run\"] = True\n        super().__init__(*args, **kwargs)\n\n    def fit(\n        self,\n        model: LightningModule,\n        train_dataloader: Optional[DataLoader] = None,\n        val_dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None,\n        datamodule: Optional[LightningDataModule] = None,\n    ):\n        r\"\"\"\n        Runs the full optimization routine. Same as :meth:`pytorch_lightning.Trainer.fit`\n\n        Args:\n            datamodule: A instance of :class:`LightningDataModule`.\n\n            model: Model to fit.\n\n            train_dataloader: A Pytorch DataLoader with training samples. If the model has\n                a predefined train_dataloader method this will be skipped.\n\n            val_dataloaders: Either a single Pytorch Dataloader or a list of them, specifying validation samples.\n                If the model has a predefined val_dataloaders method this will be skipped\n        \"\"\"\n        if any(isinstance(c, BaseFinetuning) for c in self.callbacks):\n            # TODO: if we find a finetuning callback in the trainer should we remove it? or just warn the user?\n            warnings.warn(\"Warning: You are calling fit(), but your trainer is using a fine-tuning callback\")\n        return super().fit(model, train_dataloader, val_dataloaders, datamodule)\n\n    def finetune(\n        self,\n        model: LightningModule,\n        train_dataloader: Optional[DataLoader] = None,\n        val_dataloaders: Optional[Union[DataLoader, List[DataLoader]]] = None,\n        datamodule: Optional[LightningDataModule] = None,\n        strategy: Optional[Union[str, BaseFinetuning]] = None,\n    ):\n        r\"\"\"\n\n        Runs the full optimization routine. Same as :meth:`pytorch_lightning.Trainer.fit`, but unfreezes layers\n        of the backbone throughout training layers of the backbone throughout training.\n\n        Args:\n            datamodule: A instance of :class:`LightningDataModule`.\n\n            model: Model to fit.\n\n            train_dataloader: A PyTorch DataLoader with training samples. If the model has\n                a predefined train_dataloader method this will be skipped.\n\n            val_dataloaders: Either a single PyTorch Dataloader or a list of them, specifying validation samples.\n                If the model has a predefined val_dataloaders method this will be skipped\n\n            strategy: Should either be a string or a finetuning callback subclassing\n                :class:`pytorch_lightning.callbacks.BaseFinetuning`.\n\n                Default strategies can be enabled with these strings:\n\n                - ``\"no_freeze\"``,\n                - ``\"freeze\"``,\n                - ``\"freeze_unfreeze\"``,\n                - ``\"unfreeze_milestones\"``.\n        \"\"\"\n        self._resolve_callbacks(model, strategy)\n        return super().fit(model, train_dataloader, val_dataloaders, datamodule)\n\n    def _resolve_callbacks(self, model, strategy):\n        \"\"\"\n        This function is used to select the `BaseFinetuning` to be used for finetuning.\n        \"\"\"\n        if strategy is not None and not isinstance(strategy, (str, BaseFinetuning)):\n            raise MisconfigurationException(\n                \"strategy should be a ``pytorch_lightning.callbacks.BaseFinetuning``\"\n                f\"callback or a str within {list(_DEFAULTS_FINETUNE_STRATEGIES.keys())}\"\n            )\n\n        if isinstance(strategy, BaseFinetuning):\n            callback = [strategy]\n        else:\n            # todo: change to ``configure_callbacks`` when merged to Lightning.\n            model_callback = model.configure_finetune_callback()\n            if len(model_callback) > 1:\n                raise MisconfigurationException(\n                    f\"{model} configure_finetune_callback should create a list with only 1 callback\"\n                )\n            if len(model_callback) == 1:\n                if strategy is not None:\n                    rank_zero_warn(\n                        \"The model contains a default finetune callback. The provided {strategy} will be overriden.\\n\"\n                        \" HINT: Provide a `BaseFinetuning` callback as strategy to make it prioritized. \", UserWarning\n                    )\n                callback = model_callback\n            else:\n                callback = instantiate_default_finetuning_callbacks(strategy)\n\n        self.callbacks = self._merge_callbacks(self.callbacks, callback)\n\n    @staticmethod\n    def _merge_callbacks(old_callbacks: List, new_callbacks: List) -> List:\n        \"\"\"\n        This function keeps only 1 instance of each callback type,\n        extending new_callbacks with old_callbacks\n        \"\"\"\n        if len(new_callbacks) == 0:\n            return old_callbacks\n        new_callbacks_types = set(type(c) for c in new_callbacks)\n        old_callbacks_types = set(type(c) for c in old_callbacks)\n        override_types = new_callbacks_types.intersection(old_callbacks_types)\n        new_callbacks.extend(c for c in old_callbacks if type(c) not in override_types)\n        return new_callbacks\n\n    @classmethod\n    def add_argparse_args(cls, *args, **kwargs) -> ArgumentParser:\n        # the lightning trainer implementation does not support subclasses.\n        # context: https://github.com/PyTorchLightning/lightning-flash/issues/342#issuecomment-848892447\n        return add_argparse_args(PlTrainer, *args, **kwargs)\n\n    @classmethod\n    def from_argparse_args(cls, args: Union[Namespace, ArgumentParser], **kwargs) -> 'Trainer':\n        # the lightning trainer implementation does not support subclasses.\n        # context: https://github.com/PyTorchLightning/lightning-flash/issues/342#issuecomment-848892447\n        return from_argparse_args(PlTrainer, args, **kwargs)\n", "path": "flash/core/trainer.py"}]}