We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Trainer.finetune broken for Keypoint detection module
## 🐛 Bug

Finetuning the `KeypointDetector` with freeze strategy does not freeze the parameters.


### To Reproduce

Follow the [Keypoint detection example]( https://lightning-flash.readthedocs.io/en/latest/reference/keypoint_detection.html)


#### Code sample

```python
import flash
print(flash.__version__)
from flash.core.utilities.imports import example_requires
from flash.image import KeypointDetectionData, KeypointDetector

example_requires("image")

import icedata  # noqa: E402

data_dir = icedata.biwi.load_data()

datamodule = KeypointDetectionData.from_icedata(
    train_folder=data_dir,
    val_split=0.1,
    batch_size=4,
    parser=icedata.biwi.parser,
)

# 2. Build the task
model = KeypointDetector(
    head="keypoint_rcnn",
    backbone="resnet18_fpn",
    num_keypoints=1,
    num_classes=datamodule.num_classes,
)

# 3. Create the trainer and finetune the model
trainer = flash.Trainer(max_epochs=100, gpus=1)
trainer.finetune(model, datamodule=datamodule, strategy="freeze")

trainable = 0
for name, param in model.adapter.model.named_parameters(): # or try from torchsummary import summary?
    if param.requires_grad:
        o = (name, np.product(param.shape), param.requires_grad)
        if o[2]:
            trainable += o[1]
        print(*o)
print(trainable)
    
```




### Expected behavior

The number of trainable parameters should be smaller than 45.8M. Also, `trainer.fit` takes about as much time as `trainer.finetune`:

```
  | Name          | Type                              | Params
--------------------------------------------------------------------
0 | train_metrics | ModuleDict                        | 0     
1 | val_metrics   | ModuleDict                        | 0     
2 | test_metrics  | ModuleDict                        | 0     
3 | adapter       | IceVisionKeypointDetectionAdapter | 46.0 M
--------------------------------------------------------------------
45.8 M    Trainable params
156 K     Non-trainable params
46.0 M    Total params
183.924   Total estimated model params size (MB)
```

### Environment

```
efficientnet-pytorch          0.6.3
icevision                     0.11.0
lightning-bolts               0.4.0
lightning-flash               0.7.0.dev0
pytorch-lightning             1.5.6
segmentation-models-pytorch   0.2.1
torch                         1.10.0+cu111
torchaudio                    0.10.0+cu111
torchmetrics                  0.6.2
torchsummary                  1.5.1
torchtext                     0.11.0
torchvision                   0.11.1+cu111
```

### 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: `flash/core/integrations/icevision/backbones.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 from inspect import getmembers
15 
16 from torch import nn
17 
18 from flash.core.registry import FlashRegistry
19 from flash.core.utilities.imports import _ICEVISION_AVAILABLE
20 
21 if _ICEVISION_AVAILABLE:
22     from icevision.backbones import BackboneConfig
23 
24 
25 def icevision_model_adapter(model_type):
26     class IceVisionModelAdapter(model_type.lightning.ModelAdapter):
27         def log(self, name, value, **kwargs):
28             if "prog_bar" not in kwargs:
29                 kwargs["prog_bar"] = True
30             return super().log(name.split("/")[-1], value, **kwargs)
31 
32     return IceVisionModelAdapter
33 
34 
35 def load_icevision(adapter, model_type, backbone, num_classes, **kwargs):
36     model = model_type.model(backbone=backbone, num_classes=num_classes, **kwargs)
37 
38     backbone = nn.Module()
39     params = model.param_groups()[0]
40     for i, param in enumerate(params):
41         backbone.register_parameter(f"backbone_{i}", param)
42 
43     return model_type, model, adapter(model_type), backbone
44 
45 
46 def load_icevision_ignore_image_size(adapter, model_type, backbone, num_classes, image_size=None, **kwargs):
47     return load_icevision(adapter, model_type, backbone, num_classes, **kwargs)
48 
49 
50 def load_icevision_with_image_size(adapter, model_type, backbone, num_classes, image_size=None, **kwargs):
51     kwargs["img_size"] = image_size
52     return load_icevision(adapter, model_type, backbone, num_classes, **kwargs)
53 
54 
55 def get_backbones(model_type):
56     _BACKBONES = FlashRegistry("backbones")
57 
58     for backbone_name, backbone_config in getmembers(model_type.backbones, lambda x: isinstance(x, BackboneConfig)):
59         _BACKBONES(
60             backbone_config,
61             name=backbone_name,
62         )
63     return _BACKBONES
64
```

Path: `flash/image/detection/model.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 from typing import Any, Dict, List, Optional
15 
16 from flash.core.adapter import AdapterTask
17 from flash.core.data.output import PredsOutput
18 from flash.core.registry import FlashRegistry
19 from flash.core.utilities.types import LR_SCHEDULER_TYPE, OPTIMIZER_TYPE, OUTPUT_TYPE
20 from flash.image.detection.backbones import OBJECT_DETECTION_HEADS
21 
22 
23 class ObjectDetector(AdapterTask):
24     """The ``ObjectDetector`` is a :class:`~flash.Task` for detecting objects in images. For more details, see
25     :ref:`object_detection`.
26 
27     Args:
28         num_classes: The number of object classes.
29         backbone: String indicating the backbone CNN architecture to use.
30         head: String indicating the head module to use ontop of the backbone.
31         pretrained: Whether the model should be loaded with it's pretrained weights.
32         optimizer: Optimizer to use for training.
33         lr_scheduler: The LR scheduler to use during training.
34         learning_rate: The learning rate to use for training.
35         output: The :class:`~flash.core.data.io.output.Output` to use when formatting prediction outputs.
36         predict_kwargs: dictionary containing parameters that will be used during the prediction phase.
37         kwargs: additional kwargs nessesary for initializing the backbone task
38     """
39 
40     heads: FlashRegistry = OBJECT_DETECTION_HEADS
41 
42     required_extras: List[str] = ["image", "icevision", "effdet"]
43 
44     def __init__(
45         self,
46         num_classes: int,
47         backbone: Optional[str] = "resnet18_fpn",
48         head: Optional[str] = "retinanet",
49         pretrained: bool = True,
50         optimizer: OPTIMIZER_TYPE = "Adam",
51         lr_scheduler: LR_SCHEDULER_TYPE = None,
52         learning_rate: float = 5e-3,
53         output: OUTPUT_TYPE = None,
54         predict_kwargs: Dict = None,
55         **kwargs: Any,
56     ):
57         self.save_hyperparameters()
58 
59         predict_kwargs = predict_kwargs if predict_kwargs else {}
60         metadata = self.heads.get(head, with_metadata=True)
61         adapter = metadata["metadata"]["adapter"].from_task(
62             self,
63             num_classes=num_classes,
64             backbone=backbone,
65             head=head,
66             pretrained=pretrained,
67             predict_kwargs=predict_kwargs,
68             **kwargs,
69         )
70 
71         super().__init__(
72             adapter,
73             learning_rate=learning_rate,
74             optimizer=optimizer,
75             lr_scheduler=lr_scheduler,
76             output=output or PredsOutput(),
77         )
78 
79     def _ci_benchmark_fn(self, history: List[Dict[str, Any]]) -> None:
80         """This function is used only for debugging usage with CI."""
81         # todo
82 
83     @property
84     def predict_kwargs(self) -> Dict[str, Any]:
85         """The kwargs used for the prediction step."""
86         return self.adapter.predict_kwargs
87 
88     @predict_kwargs.setter
89     def predict_kwargs(self, predict_kwargs: Dict[str, Any]):
90         self.adapter.predict_kwargs = predict_kwargs
91
```

Path: `flash_examples/integrations/fiftyone/object_detection.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 os
15 from itertools import chain
16 
17 import flash
18 from flash.core.integrations.fiftyone import visualize
19 from flash.core.utilities.imports import example_requires
20 from flash.image import ObjectDetectionData, ObjectDetector
21 from flash.image.detection.output import FiftyOneDetectionLabelsOutput
22 
23 example_requires("image")
24 
25 import icedata  # noqa: E402
26 
27 # 1. Create the DataModule
28 data_dir = icedata.fridge.load_data()
29 
30 datamodule = ObjectDetectionData.from_icedata(
31     train_folder=data_dir,
32     predict_folder=os.path.join(data_dir, "odFridgeObjects", "images"),
33     val_split=0.1,
34     transform_kwargs={"image_size": 128},
35     parser=icedata.fridge.parser,
36     batch_size=4,
37 )
38 
39 # 2. Build the task
40 model = ObjectDetector(head="efficientdet", backbone="d0", num_classes=datamodule.num_classes, image_size=128)
41 
42 # 3. Create the trainer and finetune the model
43 trainer = flash.Trainer(max_epochs=1)
44 trainer.finetune(model, datamodule=datamodule, strategy="freeze")
45 
46 # 4. Set the output and get some predictions
47 model.output = FiftyOneDetectionLabelsOutput(return_filepath=True)  # output FiftyOne format
48 predictions = trainer.predict(model, datamodule=datamodule)
49 predictions = list(chain.from_iterable(predictions))  # flatten batches
50 
51 # 5. Visualize predictions in FiftyOne app
52 # Optional: pass `wait=True` to block execution until App is closed
53 session = visualize(predictions, wait=True)
54
```
--- 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/integrations/icevision/backbones.py b/flash/core/integrations/icevision/backbones.py
--- a/flash/core/integrations/icevision/backbones.py
+++ b/flash/core/integrations/icevision/backbones.py
@@ -36,7 +36,7 @@
     model = model_type.model(backbone=backbone, num_classes=num_classes, **kwargs)
 
     backbone = nn.Module()
-    params = model.param_groups()[0]
+    params = sum(model.param_groups()[:-1], [])
     for i, param in enumerate(params):
         backbone.register_parameter(f"backbone_{i}", param)
 
diff --git a/flash/image/detection/model.py b/flash/image/detection/model.py
--- a/flash/image/detection/model.py
+++ b/flash/image/detection/model.py
@@ -49,7 +49,7 @@
         pretrained: bool = True,
         optimizer: OPTIMIZER_TYPE = "Adam",
         lr_scheduler: LR_SCHEDULER_TYPE = None,
-        learning_rate: float = 5e-3,
+        learning_rate: float = 1e-2,
         output: OUTPUT_TYPE = None,
         predict_kwargs: Dict = None,
         **kwargs: Any,
diff --git a/flash_examples/integrations/fiftyone/object_detection.py b/flash_examples/integrations/fiftyone/object_detection.py
--- a/flash_examples/integrations/fiftyone/object_detection.py
+++ b/flash_examples/integrations/fiftyone/object_detection.py
@@ -33,14 +33,20 @@
     val_split=0.1,
     transform_kwargs={"image_size": 128},
     parser=icedata.fridge.parser,
-    batch_size=4,
+    batch_size=8,
 )
 
 # 2. Build the task
-model = ObjectDetector(head="efficientdet", backbone="d0", num_classes=datamodule.num_classes, image_size=128)
+model = ObjectDetector(
+    head="efficientdet",
+    backbone="d0",
+    num_classes=datamodule.num_classes,
+    image_size=128,
+    lr_scheduler=("multisteplr", {"milestones": [20]}),
+)
 
 # 3. Create the trainer and finetune the model
-trainer = flash.Trainer(max_epochs=1)
+trainer = flash.Trainer(max_epochs=30)
 trainer.finetune(model, datamodule=datamodule, strategy="freeze")
 
 # 4. Set the output and get some predictions

{"golden_diff": "diff --git a/flash/core/integrations/icevision/backbones.py b/flash/core/integrations/icevision/backbones.py\n--- a/flash/core/integrations/icevision/backbones.py\n+++ b/flash/core/integrations/icevision/backbones.py\n@@ -36,7 +36,7 @@\n     model = model_type.model(backbone=backbone, num_classes=num_classes, **kwargs)\n \n     backbone = nn.Module()\n-    params = model.param_groups()[0]\n+    params = sum(model.param_groups()[:-1], [])\n     for i, param in enumerate(params):\n         backbone.register_parameter(f\"backbone_{i}\", param)\n \ndiff --git a/flash/image/detection/model.py b/flash/image/detection/model.py\n--- a/flash/image/detection/model.py\n+++ b/flash/image/detection/model.py\n@@ -49,7 +49,7 @@\n         pretrained: bool = True,\n         optimizer: OPTIMIZER_TYPE = \"Adam\",\n         lr_scheduler: LR_SCHEDULER_TYPE = None,\n-        learning_rate: float = 5e-3,\n+        learning_rate: float = 1e-2,\n         output: OUTPUT_TYPE = None,\n         predict_kwargs: Dict = None,\n         **kwargs: Any,\ndiff --git a/flash_examples/integrations/fiftyone/object_detection.py b/flash_examples/integrations/fiftyone/object_detection.py\n--- a/flash_examples/integrations/fiftyone/object_detection.py\n+++ b/flash_examples/integrations/fiftyone/object_detection.py\n@@ -33,14 +33,20 @@\n     val_split=0.1,\n     transform_kwargs={\"image_size\": 128},\n     parser=icedata.fridge.parser,\n-    batch_size=4,\n+    batch_size=8,\n )\n \n # 2. Build the task\n-model = ObjectDetector(head=\"efficientdet\", backbone=\"d0\", num_classes=datamodule.num_classes, image_size=128)\n+model = ObjectDetector(\n+    head=\"efficientdet\",\n+    backbone=\"d0\",\n+    num_classes=datamodule.num_classes,\n+    image_size=128,\n+    lr_scheduler=(\"multisteplr\", {\"milestones\": [20]}),\n+)\n \n # 3. Create the trainer and finetune the model\n-trainer = flash.Trainer(max_epochs=1)\n+trainer = flash.Trainer(max_epochs=30)\n trainer.finetune(model, datamodule=datamodule, strategy=\"freeze\")\n \n # 4. Set the output and get some predictions\n", "issue": "Trainer.finetune broken for Keypoint detection module\n## \ud83d\udc1b Bug\r\n\r\nFinetuning the `KeypointDetector` with freeze strategy does not freeze the parameters.\r\n\r\n\r\n### To Reproduce\r\n\r\nFollow the [Keypoint detection example]( https://lightning-flash.readthedocs.io/en/latest/reference/keypoint_detection.html)\r\n\r\n\r\n#### Code sample\r\n\r\n```python\r\nimport flash\r\nprint(flash.__version__)\r\nfrom flash.core.utilities.imports import example_requires\r\nfrom flash.image import KeypointDetectionData, KeypointDetector\r\n\r\nexample_requires(\"image\")\r\n\r\nimport icedata  # noqa: E402\r\n\r\ndata_dir = icedata.biwi.load_data()\r\n\r\ndatamodule = KeypointDetectionData.from_icedata(\r\n    train_folder=data_dir,\r\n    val_split=0.1,\r\n    batch_size=4,\r\n    parser=icedata.biwi.parser,\r\n)\r\n\r\n# 2. Build the task\r\nmodel = KeypointDetector(\r\n    head=\"keypoint_rcnn\",\r\n    backbone=\"resnet18_fpn\",\r\n    num_keypoints=1,\r\n    num_classes=datamodule.num_classes,\r\n)\r\n\r\n# 3. Create the trainer and finetune the model\r\ntrainer = flash.Trainer(max_epochs=100, gpus=1)\r\ntrainer.finetune(model, datamodule=datamodule, strategy=\"freeze\")\r\n\r\ntrainable = 0\r\nfor name, param in model.adapter.model.named_parameters(): # or try from torchsummary import summary?\r\n    if param.requires_grad:\r\n        o = (name, np.product(param.shape), param.requires_grad)\r\n        if o[2]:\r\n            trainable += o[1]\r\n        print(*o)\r\nprint(trainable)\r\n    \r\n```\r\n\r\n\r\n\r\n\r\n### Expected behavior\r\n\r\nThe number of trainable parameters should be smaller than 45.8M. Also, `trainer.fit` takes about as much time as `trainer.finetune`:\r\n\r\n```\r\n  | Name          | Type                              | Params\r\n--------------------------------------------------------------------\r\n0 | train_metrics | ModuleDict                        | 0     \r\n1 | val_metrics   | ModuleDict                        | 0     \r\n2 | test_metrics  | ModuleDict                        | 0     \r\n3 | adapter       | IceVisionKeypointDetectionAdapter | 46.0 M\r\n--------------------------------------------------------------------\r\n45.8 M    Trainable params\r\n156 K     Non-trainable params\r\n46.0 M    Total params\r\n183.924   Total estimated model params size (MB)\r\n```\r\n\r\n### Environment\r\n\r\n```\r\nefficientnet-pytorch          0.6.3\r\nicevision                     0.11.0\r\nlightning-bolts               0.4.0\r\nlightning-flash               0.7.0.dev0\r\npytorch-lightning             1.5.6\r\nsegmentation-models-pytorch   0.2.1\r\ntorch                         1.10.0+cu111\r\ntorchaudio                    0.10.0+cu111\r\ntorchmetrics                  0.6.2\r\ntorchsummary                  1.5.1\r\ntorchtext                     0.11.0\r\ntorchvision                   0.11.1+cu111\r\n```\r\n\r\n### Additional context\r\n\r\n<!-- Add any other context about the problem here. -->\r\n\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.\nfrom inspect import getmembers\n\nfrom torch import nn\n\nfrom flash.core.registry import FlashRegistry\nfrom flash.core.utilities.imports import _ICEVISION_AVAILABLE\n\nif _ICEVISION_AVAILABLE:\n    from icevision.backbones import BackboneConfig\n\n\ndef icevision_model_adapter(model_type):\n    class IceVisionModelAdapter(model_type.lightning.ModelAdapter):\n        def log(self, name, value, **kwargs):\n            if \"prog_bar\" not in kwargs:\n                kwargs[\"prog_bar\"] = True\n            return super().log(name.split(\"/\")[-1], value, **kwargs)\n\n    return IceVisionModelAdapter\n\n\ndef load_icevision(adapter, model_type, backbone, num_classes, **kwargs):\n    model = model_type.model(backbone=backbone, num_classes=num_classes, **kwargs)\n\n    backbone = nn.Module()\n    params = model.param_groups()[0]\n    for i, param in enumerate(params):\n        backbone.register_parameter(f\"backbone_{i}\", param)\n\n    return model_type, model, adapter(model_type), backbone\n\n\ndef load_icevision_ignore_image_size(adapter, model_type, backbone, num_classes, image_size=None, **kwargs):\n    return load_icevision(adapter, model_type, backbone, num_classes, **kwargs)\n\n\ndef load_icevision_with_image_size(adapter, model_type, backbone, num_classes, image_size=None, **kwargs):\n    kwargs[\"img_size\"] = image_size\n    return load_icevision(adapter, model_type, backbone, num_classes, **kwargs)\n\n\ndef get_backbones(model_type):\n    _BACKBONES = FlashRegistry(\"backbones\")\n\n    for backbone_name, backbone_config in getmembers(model_type.backbones, lambda x: isinstance(x, BackboneConfig)):\n        _BACKBONES(\n            backbone_config,\n            name=backbone_name,\n        )\n    return _BACKBONES\n", "path": "flash/core/integrations/icevision/backbones.py"}, {"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.\nfrom typing import Any, Dict, List, Optional\n\nfrom flash.core.adapter import AdapterTask\nfrom flash.core.data.output import PredsOutput\nfrom flash.core.registry import FlashRegistry\nfrom flash.core.utilities.types import LR_SCHEDULER_TYPE, OPTIMIZER_TYPE, OUTPUT_TYPE\nfrom flash.image.detection.backbones import OBJECT_DETECTION_HEADS\n\n\nclass ObjectDetector(AdapterTask):\n    \"\"\"The ``ObjectDetector`` is a :class:`~flash.Task` for detecting objects in images. For more details, see\n    :ref:`object_detection`.\n\n    Args:\n        num_classes: The number of object classes.\n        backbone: String indicating the backbone CNN architecture to use.\n        head: String indicating the head module to use ontop of the backbone.\n        pretrained: Whether the model should be loaded with it's pretrained weights.\n        optimizer: Optimizer to use for training.\n        lr_scheduler: The LR scheduler to use during training.\n        learning_rate: The learning rate to use for training.\n        output: The :class:`~flash.core.data.io.output.Output` to use when formatting prediction outputs.\n        predict_kwargs: dictionary containing parameters that will be used during the prediction phase.\n        kwargs: additional kwargs nessesary for initializing the backbone task\n    \"\"\"\n\n    heads: FlashRegistry = OBJECT_DETECTION_HEADS\n\n    required_extras: List[str] = [\"image\", \"icevision\", \"effdet\"]\n\n    def __init__(\n        self,\n        num_classes: int,\n        backbone: Optional[str] = \"resnet18_fpn\",\n        head: Optional[str] = \"retinanet\",\n        pretrained: bool = True,\n        optimizer: OPTIMIZER_TYPE = \"Adam\",\n        lr_scheduler: LR_SCHEDULER_TYPE = None,\n        learning_rate: float = 5e-3,\n        output: OUTPUT_TYPE = None,\n        predict_kwargs: Dict = None,\n        **kwargs: Any,\n    ):\n        self.save_hyperparameters()\n\n        predict_kwargs = predict_kwargs if predict_kwargs else {}\n        metadata = self.heads.get(head, with_metadata=True)\n        adapter = metadata[\"metadata\"][\"adapter\"].from_task(\n            self,\n            num_classes=num_classes,\n            backbone=backbone,\n            head=head,\n            pretrained=pretrained,\n            predict_kwargs=predict_kwargs,\n            **kwargs,\n        )\n\n        super().__init__(\n            adapter,\n            learning_rate=learning_rate,\n            optimizer=optimizer,\n            lr_scheduler=lr_scheduler,\n            output=output or PredsOutput(),\n        )\n\n    def _ci_benchmark_fn(self, history: List[Dict[str, Any]]) -> None:\n        \"\"\"This function is used only for debugging usage with CI.\"\"\"\n        # todo\n\n    @property\n    def predict_kwargs(self) -> Dict[str, Any]:\n        \"\"\"The kwargs used for the prediction step.\"\"\"\n        return self.adapter.predict_kwargs\n\n    @predict_kwargs.setter\n    def predict_kwargs(self, predict_kwargs: Dict[str, Any]):\n        self.adapter.predict_kwargs = predict_kwargs\n", "path": "flash/image/detection/model.py"}, {"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 os\nfrom itertools import chain\n\nimport flash\nfrom flash.core.integrations.fiftyone import visualize\nfrom flash.core.utilities.imports import example_requires\nfrom flash.image import ObjectDetectionData, ObjectDetector\nfrom flash.image.detection.output import FiftyOneDetectionLabelsOutput\n\nexample_requires(\"image\")\n\nimport icedata  # noqa: E402\n\n# 1. Create the DataModule\ndata_dir = icedata.fridge.load_data()\n\ndatamodule = ObjectDetectionData.from_icedata(\n    train_folder=data_dir,\n    predict_folder=os.path.join(data_dir, \"odFridgeObjects\", \"images\"),\n    val_split=0.1,\n    transform_kwargs={\"image_size\": 128},\n    parser=icedata.fridge.parser,\n    batch_size=4,\n)\n\n# 2. Build the task\nmodel = ObjectDetector(head=\"efficientdet\", backbone=\"d0\", num_classes=datamodule.num_classes, image_size=128)\n\n# 3. Create the trainer and finetune the model\ntrainer = flash.Trainer(max_epochs=1)\ntrainer.finetune(model, datamodule=datamodule, strategy=\"freeze\")\n\n# 4. Set the output and get some predictions\nmodel.output = FiftyOneDetectionLabelsOutput(return_filepath=True)  # output FiftyOne format\npredictions = trainer.predict(model, datamodule=datamodule)\npredictions = list(chain.from_iterable(predictions))  # flatten batches\n\n# 5. Visualize predictions in FiftyOne app\n# Optional: pass `wait=True` to block execution until App is closed\nsession = visualize(predictions, wait=True)\n", "path": "flash_examples/integrations/fiftyone/object_detection.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.\nfrom inspect import getmembers\n\nfrom torch import nn\n\nfrom flash.core.registry import FlashRegistry\nfrom flash.core.utilities.imports import _ICEVISION_AVAILABLE\n\nif _ICEVISION_AVAILABLE:\n    from icevision.backbones import BackboneConfig\n\n\ndef icevision_model_adapter(model_type):\n    class IceVisionModelAdapter(model_type.lightning.ModelAdapter):\n        def log(self, name, value, **kwargs):\n            if \"prog_bar\" not in kwargs:\n                kwargs[\"prog_bar\"] = True\n            return super().log(name.split(\"/\")[-1], value, **kwargs)\n\n    return IceVisionModelAdapter\n\n\ndef load_icevision(adapter, model_type, backbone, num_classes, **kwargs):\n    model = model_type.model(backbone=backbone, num_classes=num_classes, **kwargs)\n\n    backbone = nn.Module()\n    params = sum(model.param_groups()[:-1], [])\n    for i, param in enumerate(params):\n        backbone.register_parameter(f\"backbone_{i}\", param)\n\n    return model_type, model, adapter(model_type), backbone\n\n\ndef load_icevision_ignore_image_size(adapter, model_type, backbone, num_classes, image_size=None, **kwargs):\n    return load_icevision(adapter, model_type, backbone, num_classes, **kwargs)\n\n\ndef load_icevision_with_image_size(adapter, model_type, backbone, num_classes, image_size=None, **kwargs):\n    kwargs[\"img_size\"] = image_size\n    return load_icevision(adapter, model_type, backbone, num_classes, **kwargs)\n\n\ndef get_backbones(model_type):\n    _BACKBONES = FlashRegistry(\"backbones\")\n\n    for backbone_name, backbone_config in getmembers(model_type.backbones, lambda x: isinstance(x, BackboneConfig)):\n        _BACKBONES(\n            backbone_config,\n            name=backbone_name,\n        )\n    return _BACKBONES\n", "path": "flash/core/integrations/icevision/backbones.py"}, {"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.\nfrom typing import Any, Dict, List, Optional\n\nfrom flash.core.adapter import AdapterTask\nfrom flash.core.data.output import PredsOutput\nfrom flash.core.registry import FlashRegistry\nfrom flash.core.utilities.types import LR_SCHEDULER_TYPE, OPTIMIZER_TYPE, OUTPUT_TYPE\nfrom flash.image.detection.backbones import OBJECT_DETECTION_HEADS\n\n\nclass ObjectDetector(AdapterTask):\n    \"\"\"The ``ObjectDetector`` is a :class:`~flash.Task` for detecting objects in images. For more details, see\n    :ref:`object_detection`.\n\n    Args:\n        num_classes: The number of object classes.\n        backbone: String indicating the backbone CNN architecture to use.\n        head: String indicating the head module to use ontop of the backbone.\n        pretrained: Whether the model should be loaded with it's pretrained weights.\n        optimizer: Optimizer to use for training.\n        lr_scheduler: The LR scheduler to use during training.\n        learning_rate: The learning rate to use for training.\n        output: The :class:`~flash.core.data.io.output.Output` to use when formatting prediction outputs.\n        predict_kwargs: dictionary containing parameters that will be used during the prediction phase.\n        kwargs: additional kwargs nessesary for initializing the backbone task\n    \"\"\"\n\n    heads: FlashRegistry = OBJECT_DETECTION_HEADS\n\n    required_extras: List[str] = [\"image\", \"icevision\", \"effdet\"]\n\n    def __init__(\n        self,\n        num_classes: int,\n        backbone: Optional[str] = \"resnet18_fpn\",\n        head: Optional[str] = \"retinanet\",\n        pretrained: bool = True,\n        optimizer: OPTIMIZER_TYPE = \"Adam\",\n        lr_scheduler: LR_SCHEDULER_TYPE = None,\n        learning_rate: float = 1e-2,\n        output: OUTPUT_TYPE = None,\n        predict_kwargs: Dict = None,\n        **kwargs: Any,\n    ):\n        self.save_hyperparameters()\n\n        predict_kwargs = predict_kwargs if predict_kwargs else {}\n        metadata = self.heads.get(head, with_metadata=True)\n        adapter = metadata[\"metadata\"][\"adapter\"].from_task(\n            self,\n            num_classes=num_classes,\n            backbone=backbone,\n            head=head,\n            pretrained=pretrained,\n            predict_kwargs=predict_kwargs,\n            **kwargs,\n        )\n\n        super().__init__(\n            adapter,\n            learning_rate=learning_rate,\n            optimizer=optimizer,\n            lr_scheduler=lr_scheduler,\n            output=output or PredsOutput(),\n        )\n\n    def _ci_benchmark_fn(self, history: List[Dict[str, Any]]) -> None:\n        \"\"\"This function is used only for debugging usage with CI.\"\"\"\n        # todo\n\n    @property\n    def predict_kwargs(self) -> Dict[str, Any]:\n        \"\"\"The kwargs used for the prediction step.\"\"\"\n        return self.adapter.predict_kwargs\n\n    @predict_kwargs.setter\n    def predict_kwargs(self, predict_kwargs: Dict[str, Any]):\n        self.adapter.predict_kwargs = predict_kwargs\n", "path": "flash/image/detection/model.py"}, {"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 os\nfrom itertools import chain\n\nimport flash\nfrom flash.core.integrations.fiftyone import visualize\nfrom flash.core.utilities.imports import example_requires\nfrom flash.image import ObjectDetectionData, ObjectDetector\nfrom flash.image.detection.output import FiftyOneDetectionLabelsOutput\n\nexample_requires(\"image\")\n\nimport icedata  # noqa: E402\n\n# 1. Create the DataModule\ndata_dir = icedata.fridge.load_data()\n\ndatamodule = ObjectDetectionData.from_icedata(\n    train_folder=data_dir,\n    predict_folder=os.path.join(data_dir, \"odFridgeObjects\", \"images\"),\n    val_split=0.1,\n    transform_kwargs={\"image_size\": 128},\n    parser=icedata.fridge.parser,\n    batch_size=8,\n)\n\n# 2. Build the task\nmodel = ObjectDetector(\n    head=\"efficientdet\",\n    backbone=\"d0\",\n    num_classes=datamodule.num_classes,\n    image_size=128,\n    lr_scheduler=(\"multisteplr\", {\"milestones\": [20]}),\n)\n\n# 3. Create the trainer and finetune the model\ntrainer = flash.Trainer(max_epochs=30)\ntrainer.finetune(model, datamodule=datamodule, strategy=\"freeze\")\n\n# 4. Set the output and get some predictions\nmodel.output = FiftyOneDetectionLabelsOutput(return_filepath=True)  # output FiftyOne format\npredictions = trainer.predict(model, datamodule=datamodule)\npredictions = list(chain.from_iterable(predictions))  # flatten batches\n\n# 5. Visualize predictions in FiftyOne app\n# Optional: pass `wait=True` to block execution until App is closed\nsession = visualize(predictions, wait=True)\n", "path": "flash_examples/integrations/fiftyone/object_detection.py"}]}