We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
`TabularClassifier` fails with `embedding_sizes=None` (the default)
## 🐛 Bug

Passes if you provide embedding sizes as an empty list.


--- 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/tabular/regression/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 functools import partial
15 from typing import Any, Callable, Dict, List, Optional, Tuple, Type
16 
17 import torch
18 from torch.nn import functional as F
19 
20 from flash.core.data.io.input import DataKeys, ServeInput
21 from flash.core.data.io.input_transform import InputTransform
22 from flash.core.regression import RegressionTask
23 from flash.core.serve import Composition
24 from flash.core.utilities.imports import _TABULAR_AVAILABLE, requires
25 from flash.core.utilities.types import (
26     INPUT_TRANSFORM_TYPE,
27     LR_SCHEDULER_TYPE,
28     METRICS_TYPE,
29     OPTIMIZER_TYPE,
30     OUTPUT_TYPE,
31 )
32 from flash.tabular.input import TabularDeserializer
33 
34 if _TABULAR_AVAILABLE:
35     from pytorch_tabnet.tab_network import TabNet
36 
37 
38 class TabularRegressor(RegressionTask):
39     """The ``TabularRegressor`` is a :class:`~flash.Task` for regression tabular data.
40 
41     Args:
42         num_features: Number of columns in table (not including target column).
43         embedding_sizes: List of (num_classes, emb_dim) to form categorical embeddings.
44         loss_fn: Loss function for training, defaults to cross entropy.
45         optimizer: Optimizer to use for training.
46         lr_scheduler: The LR scheduler to use during training.
47         metrics: Metrics to compute for training and evaluation. Can either be an metric from the `torchmetrics`
48             package, a custom metric inherenting from `torchmetrics.Metric`, a callable function or a list/dict
49             containing a combination of the aforementioned. In all cases, each metric needs to have the signature
50             `metric(preds,target)` and return a single scalar tensor.
51         learning_rate: Learning rate to use for training.
52         multi_label: Whether the targets are multi-label or not.
53         output: The :class:`~flash.core.data.io.output.Output` to use when formatting prediction outputs.
54         **tabnet_kwargs: Optional additional arguments for the TabNet model, see
55             `pytorch_tabnet <https://dreamquark-ai.github.io/tabnet/_modules/pytorch_tabnet/tab_network.html#TabNet>`_.
56     """
57 
58     required_extras: str = "tabular"
59 
60     def __init__(
61         self,
62         num_features: int,
63         embedding_sizes: List[Tuple[int, int]] = None,
64         loss_fn: Callable = F.mse_loss,
65         optimizer: OPTIMIZER_TYPE = "Adam",
66         lr_scheduler: LR_SCHEDULER_TYPE = None,
67         metrics: METRICS_TYPE = None,
68         learning_rate: float = 1e-2,
69         output: OUTPUT_TYPE = None,
70         **tabnet_kwargs,
71     ):
72         self.save_hyperparameters()
73 
74         cat_dims, cat_emb_dim = zip(*embedding_sizes) if embedding_sizes else ([], [])
75         model = TabNet(
76             input_dim=num_features,
77             output_dim=1,
78             cat_idxs=list(range(len(embedding_sizes))),
79             cat_dims=list(cat_dims),
80             cat_emb_dim=list(cat_emb_dim),
81             **tabnet_kwargs,
82         )
83 
84         super().__init__(
85             model=model,
86             loss_fn=loss_fn,
87             optimizer=optimizer,
88             lr_scheduler=lr_scheduler,
89             metrics=metrics,
90             learning_rate=learning_rate,
91             output=output,
92         )
93 
94         self.save_hyperparameters()
95 
96     def forward(self, x_in) -> torch.Tensor:
97         # TabNet takes single input, x_in is composed of (categorical, numerical)
98         xs = [x for x in x_in if x.numel()]
99         x = torch.cat(xs, dim=1)
100         return self.model(x)[0].flatten()
101 
102     def training_step(self, batch: Any, batch_idx: int) -> Any:
103         batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])
104         return super().training_step(batch, batch_idx)
105 
106     def validation_step(self, batch: Any, batch_idx: int) -> Any:
107         batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])
108         return super().validation_step(batch, batch_idx)
109 
110     def test_step(self, batch: Any, batch_idx: int) -> Any:
111         batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])
112         return super().test_step(batch, batch_idx)
113 
114     def predict_step(self, batch: Any, batch_idx: int, dataloader_idx: int = 0) -> Any:
115         batch = batch[DataKeys.INPUT]
116         return self(batch)
117 
118     @classmethod
119     def from_data(cls, datamodule, **kwargs) -> "TabularRegressor":
120         model = cls(datamodule.num_features, datamodule.embedding_sizes, **kwargs)
121         return model
122 
123     @requires("serve")
124     def serve(
125         self,
126         host: str = "127.0.0.1",
127         port: int = 8000,
128         sanity_check: bool = True,
129         input_cls: Optional[Type[ServeInput]] = TabularDeserializer,
130         transform: INPUT_TRANSFORM_TYPE = InputTransform,
131         transform_kwargs: Optional[Dict] = None,
132         parameters: Optional[Dict[str, Any]] = None,
133     ) -> Composition:
134         return super().serve(
135             host, port, sanity_check, partial(input_cls, parameters=parameters), transform, transform_kwargs
136         )
137
```

Path: `flash/tabular/classification/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 functools import partial
15 from typing import Any, Callable, Dict, List, Optional, Tuple, Type
16 
17 import torch
18 from torch.nn import functional as F
19 
20 from flash.core.classification import ClassificationTask, ProbabilitiesOutput
21 from flash.core.data.io.input import DataKeys, ServeInput
22 from flash.core.data.io.input_transform import InputTransform
23 from flash.core.serve import Composition
24 from flash.core.utilities.imports import _TABULAR_AVAILABLE, requires
25 from flash.core.utilities.types import (
26     INPUT_TRANSFORM_TYPE,
27     LR_SCHEDULER_TYPE,
28     METRICS_TYPE,
29     OPTIMIZER_TYPE,
30     OUTPUT_TYPE,
31 )
32 from flash.tabular.input import TabularDeserializer
33 
34 if _TABULAR_AVAILABLE:
35     from pytorch_tabnet.tab_network import TabNet
36 
37 
38 class TabularClassifier(ClassificationTask):
39     """The ``TabularClassifier`` is a :class:`~flash.Task` for classifying tabular data. For more details, see
40     :ref:`tabular_classification`.
41 
42     Args:
43         num_features: Number of columns in table (not including target column).
44         num_classes: Number of classes to classify.
45         embedding_sizes: List of (num_classes, emb_dim) to form categorical embeddings.
46         loss_fn: Loss function for training, defaults to cross entropy.
47         optimizer: Optimizer to use for training.
48         lr_scheduler: The LR scheduler to use during training.
49         metrics: Metrics to compute for training and evaluation. Can either be an metric from the `torchmetrics`
50             package, a custom metric inherenting from `torchmetrics.Metric`, a callable function or a list/dict
51             containing a combination of the aforementioned. In all cases, each metric needs to have the signature
52             `metric(preds,target)` and return a single scalar tensor. Defaults to :class:`torchmetrics.Accuracy`.
53         learning_rate: Learning rate to use for training.
54         multi_label: Whether the targets are multi-label or not.
55         output: The :class:`~flash.core.data.io.output.Output` to use when formatting prediction outputs.
56         **tabnet_kwargs: Optional additional arguments for the TabNet model, see
57             `pytorch_tabnet <https://dreamquark-ai.github.io/tabnet/_modules/pytorch_tabnet/tab_network.html#TabNet>`_.
58     """
59 
60     required_extras: str = "tabular"
61 
62     def __init__(
63         self,
64         num_features: int,
65         num_classes: int,
66         embedding_sizes: List[Tuple[int, int]] = None,
67         loss_fn: Callable = F.cross_entropy,
68         optimizer: OPTIMIZER_TYPE = "Adam",
69         lr_scheduler: LR_SCHEDULER_TYPE = None,
70         metrics: METRICS_TYPE = None,
71         learning_rate: float = 1e-2,
72         multi_label: bool = False,
73         output: OUTPUT_TYPE = None,
74         **tabnet_kwargs,
75     ):
76         self.save_hyperparameters()
77 
78         cat_dims, cat_emb_dim = zip(*embedding_sizes) if embedding_sizes else ([], [])
79         model = TabNet(
80             input_dim=num_features,
81             output_dim=num_classes,
82             cat_idxs=list(range(len(embedding_sizes))),
83             cat_dims=list(cat_dims),
84             cat_emb_dim=list(cat_emb_dim),
85             **tabnet_kwargs,
86         )
87 
88         super().__init__(
89             model=model,
90             loss_fn=loss_fn,
91             optimizer=optimizer,
92             lr_scheduler=lr_scheduler,
93             metrics=metrics,
94             learning_rate=learning_rate,
95             multi_label=multi_label,
96             output=output or ProbabilitiesOutput(),
97         )
98 
99         self.save_hyperparameters()
100 
101     def forward(self, x_in) -> torch.Tensor:
102         # TabNet takes single input, x_in is composed of (categorical, numerical)
103         xs = [x for x in x_in if x.numel()]
104         x = torch.cat(xs, dim=1)
105         return self.model(x)[0]
106 
107     def training_step(self, batch: Any, batch_idx: int) -> Any:
108         batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])
109         return super().training_step(batch, batch_idx)
110 
111     def validation_step(self, batch: Any, batch_idx: int) -> Any:
112         batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])
113         return super().validation_step(batch, batch_idx)
114 
115     def test_step(self, batch: Any, batch_idx: int) -> Any:
116         batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])
117         return super().test_step(batch, batch_idx)
118 
119     def predict_step(self, batch: Any, batch_idx: int, dataloader_idx: int = 0) -> Any:
120         batch = batch[DataKeys.INPUT]
121         return self(batch)
122 
123     @classmethod
124     def from_data(cls, datamodule, **kwargs) -> "TabularClassifier":
125         model = cls(datamodule.num_features, datamodule.num_classes, datamodule.embedding_sizes, **kwargs)
126         return model
127 
128     @staticmethod
129     def _ci_benchmark_fn(history: List[Dict[str, Any]]):
130         """This function is used only for debugging usage with CI."""
131         assert history[-1]["val_accuracy"] > 0.6, history[-1]["val_accuracy"]
132 
133     @requires("serve")
134     def serve(
135         self,
136         host: str = "127.0.0.1",
137         port: int = 8000,
138         sanity_check: bool = True,
139         input_cls: Optional[Type[ServeInput]] = TabularDeserializer,
140         transform: INPUT_TRANSFORM_TYPE = InputTransform,
141         transform_kwargs: Optional[Dict] = None,
142         parameters: Optional[Dict[str, Any]] = None,
143     ) -> Composition:
144         return super().serve(
145             host, port, sanity_check, partial(input_cls, parameters=parameters), transform, transform_kwargs
146         )
147
```
--- 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/tabular/classification/model.py b/flash/tabular/classification/model.py
--- a/flash/tabular/classification/model.py
+++ b/flash/tabular/classification/model.py
@@ -42,7 +42,8 @@
     Args:
         num_features: Number of columns in table (not including target column).
         num_classes: Number of classes to classify.
-        embedding_sizes: List of (num_classes, emb_dim) to form categorical embeddings.
+        embedding_sizes: List of (num_classes, emb_dim) to form categorical embeddings (or ``None`` if there are no
+            categorical fields in the data).
         loss_fn: Loss function for training, defaults to cross entropy.
         optimizer: Optimizer to use for training.
         lr_scheduler: The LR scheduler to use during training.
@@ -63,7 +64,7 @@
         self,
         num_features: int,
         num_classes: int,
-        embedding_sizes: List[Tuple[int, int]] = None,
+        embedding_sizes: Optional[List[Tuple[int, int]]] = None,
         loss_fn: Callable = F.cross_entropy,
         optimizer: OPTIMIZER_TYPE = "Adam",
         lr_scheduler: LR_SCHEDULER_TYPE = None,
@@ -75,7 +76,11 @@
     ):
         self.save_hyperparameters()
 
-        cat_dims, cat_emb_dim = zip(*embedding_sizes) if embedding_sizes else ([], [])
+        if embedding_sizes:
+            cat_dims, cat_emb_dim = zip(*embedding_sizes)
+        else:
+            cat_dims, cat_emb_dim, embedding_sizes = [], [], []
+
         model = TabNet(
             input_dim=num_features,
             output_dim=num_classes,
diff --git a/flash/tabular/regression/model.py b/flash/tabular/regression/model.py
--- a/flash/tabular/regression/model.py
+++ b/flash/tabular/regression/model.py
@@ -40,7 +40,8 @@
 
     Args:
         num_features: Number of columns in table (not including target column).
-        embedding_sizes: List of (num_classes, emb_dim) to form categorical embeddings.
+        embedding_sizes: List of (num_classes, emb_dim) to form categorical embeddings (or ``None`` if there are no
+            categorical fields in the data).
         loss_fn: Loss function for training, defaults to cross entropy.
         optimizer: Optimizer to use for training.
         lr_scheduler: The LR scheduler to use during training.
@@ -60,7 +61,7 @@
     def __init__(
         self,
         num_features: int,
-        embedding_sizes: List[Tuple[int, int]] = None,
+        embedding_sizes: Optional[List[Tuple[int, int]]] = None,
         loss_fn: Callable = F.mse_loss,
         optimizer: OPTIMIZER_TYPE = "Adam",
         lr_scheduler: LR_SCHEDULER_TYPE = None,
@@ -71,7 +72,11 @@
     ):
         self.save_hyperparameters()
 
-        cat_dims, cat_emb_dim = zip(*embedding_sizes) if embedding_sizes else ([], [])
+        if embedding_sizes:
+            cat_dims, cat_emb_dim = zip(*embedding_sizes)
+        else:
+            cat_dims, cat_emb_dim, embedding_sizes = [], [], []
+
         model = TabNet(
             input_dim=num_features,
             output_dim=1,

{"golden_diff": "diff --git a/flash/tabular/classification/model.py b/flash/tabular/classification/model.py\n--- a/flash/tabular/classification/model.py\n+++ b/flash/tabular/classification/model.py\n@@ -42,7 +42,8 @@\n     Args:\n         num_features: Number of columns in table (not including target column).\n         num_classes: Number of classes to classify.\n-        embedding_sizes: List of (num_classes, emb_dim) to form categorical embeddings.\n+        embedding_sizes: List of (num_classes, emb_dim) to form categorical embeddings (or ``None`` if there are no\n+            categorical fields in the data).\n         loss_fn: Loss function for training, defaults to cross entropy.\n         optimizer: Optimizer to use for training.\n         lr_scheduler: The LR scheduler to use during training.\n@@ -63,7 +64,7 @@\n         self,\n         num_features: int,\n         num_classes: int,\n-        embedding_sizes: List[Tuple[int, int]] = None,\n+        embedding_sizes: Optional[List[Tuple[int, int]]] = None,\n         loss_fn: Callable = F.cross_entropy,\n         optimizer: OPTIMIZER_TYPE = \"Adam\",\n         lr_scheduler: LR_SCHEDULER_TYPE = None,\n@@ -75,7 +76,11 @@\n     ):\n         self.save_hyperparameters()\n \n-        cat_dims, cat_emb_dim = zip(*embedding_sizes) if embedding_sizes else ([], [])\n+        if embedding_sizes:\n+            cat_dims, cat_emb_dim = zip(*embedding_sizes)\n+        else:\n+            cat_dims, cat_emb_dim, embedding_sizes = [], [], []\n+\n         model = TabNet(\n             input_dim=num_features,\n             output_dim=num_classes,\ndiff --git a/flash/tabular/regression/model.py b/flash/tabular/regression/model.py\n--- a/flash/tabular/regression/model.py\n+++ b/flash/tabular/regression/model.py\n@@ -40,7 +40,8 @@\n \n     Args:\n         num_features: Number of columns in table (not including target column).\n-        embedding_sizes: List of (num_classes, emb_dim) to form categorical embeddings.\n+        embedding_sizes: List of (num_classes, emb_dim) to form categorical embeddings (or ``None`` if there are no\n+            categorical fields in the data).\n         loss_fn: Loss function for training, defaults to cross entropy.\n         optimizer: Optimizer to use for training.\n         lr_scheduler: The LR scheduler to use during training.\n@@ -60,7 +61,7 @@\n     def __init__(\n         self,\n         num_features: int,\n-        embedding_sizes: List[Tuple[int, int]] = None,\n+        embedding_sizes: Optional[List[Tuple[int, int]]] = None,\n         loss_fn: Callable = F.mse_loss,\n         optimizer: OPTIMIZER_TYPE = \"Adam\",\n         lr_scheduler: LR_SCHEDULER_TYPE = None,\n@@ -71,7 +72,11 @@\n     ):\n         self.save_hyperparameters()\n \n-        cat_dims, cat_emb_dim = zip(*embedding_sizes) if embedding_sizes else ([], [])\n+        if embedding_sizes:\n+            cat_dims, cat_emb_dim = zip(*embedding_sizes)\n+        else:\n+            cat_dims, cat_emb_dim, embedding_sizes = [], [], []\n+\n         model = TabNet(\n             input_dim=num_features,\n             output_dim=1,\n", "issue": "`TabularClassifier` fails with `embedding_sizes=None` (the default)\n## \ud83d\udc1b Bug\r\n\r\nPasses if you provide embedding sizes as an empty list.\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 functools import partial\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Type\n\nimport torch\nfrom torch.nn import functional as F\n\nfrom flash.core.data.io.input import DataKeys, ServeInput\nfrom flash.core.data.io.input_transform import InputTransform\nfrom flash.core.regression import RegressionTask\nfrom flash.core.serve import Composition\nfrom flash.core.utilities.imports import _TABULAR_AVAILABLE, requires\nfrom flash.core.utilities.types import (\n    INPUT_TRANSFORM_TYPE,\n    LR_SCHEDULER_TYPE,\n    METRICS_TYPE,\n    OPTIMIZER_TYPE,\n    OUTPUT_TYPE,\n)\nfrom flash.tabular.input import TabularDeserializer\n\nif _TABULAR_AVAILABLE:\n    from pytorch_tabnet.tab_network import TabNet\n\n\nclass TabularRegressor(RegressionTask):\n    \"\"\"The ``TabularRegressor`` is a :class:`~flash.Task` for regression tabular data.\n\n    Args:\n        num_features: Number of columns in table (not including target column).\n        embedding_sizes: List of (num_classes, emb_dim) to form categorical embeddings.\n        loss_fn: Loss function for training, defaults to cross entropy.\n        optimizer: Optimizer to use for training.\n        lr_scheduler: The LR scheduler to use during training.\n        metrics: Metrics to compute for training and evaluation. Can either be an metric from the `torchmetrics`\n            package, a custom metric inherenting from `torchmetrics.Metric`, a callable function or a list/dict\n            containing a combination of the aforementioned. In all cases, each metric needs to have the signature\n            `metric(preds,target)` and return a single scalar tensor.\n        learning_rate: Learning rate to use for training.\n        multi_label: Whether the targets are multi-label or not.\n        output: The :class:`~flash.core.data.io.output.Output` to use when formatting prediction outputs.\n        **tabnet_kwargs: Optional additional arguments for the TabNet model, see\n            `pytorch_tabnet <https://dreamquark-ai.github.io/tabnet/_modules/pytorch_tabnet/tab_network.html#TabNet>`_.\n    \"\"\"\n\n    required_extras: str = \"tabular\"\n\n    def __init__(\n        self,\n        num_features: int,\n        embedding_sizes: List[Tuple[int, int]] = None,\n        loss_fn: Callable = F.mse_loss,\n        optimizer: OPTIMIZER_TYPE = \"Adam\",\n        lr_scheduler: LR_SCHEDULER_TYPE = None,\n        metrics: METRICS_TYPE = None,\n        learning_rate: float = 1e-2,\n        output: OUTPUT_TYPE = None,\n        **tabnet_kwargs,\n    ):\n        self.save_hyperparameters()\n\n        cat_dims, cat_emb_dim = zip(*embedding_sizes) if embedding_sizes else ([], [])\n        model = TabNet(\n            input_dim=num_features,\n            output_dim=1,\n            cat_idxs=list(range(len(embedding_sizes))),\n            cat_dims=list(cat_dims),\n            cat_emb_dim=list(cat_emb_dim),\n            **tabnet_kwargs,\n        )\n\n        super().__init__(\n            model=model,\n            loss_fn=loss_fn,\n            optimizer=optimizer,\n            lr_scheduler=lr_scheduler,\n            metrics=metrics,\n            learning_rate=learning_rate,\n            output=output,\n        )\n\n        self.save_hyperparameters()\n\n    def forward(self, x_in) -> torch.Tensor:\n        # TabNet takes single input, x_in is composed of (categorical, numerical)\n        xs = [x for x in x_in if x.numel()]\n        x = torch.cat(xs, dim=1)\n        return self.model(x)[0].flatten()\n\n    def training_step(self, batch: Any, batch_idx: int) -> Any:\n        batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])\n        return super().training_step(batch, batch_idx)\n\n    def validation_step(self, batch: Any, batch_idx: int) -> Any:\n        batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])\n        return super().validation_step(batch, batch_idx)\n\n    def test_step(self, batch: Any, batch_idx: int) -> Any:\n        batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])\n        return super().test_step(batch, batch_idx)\n\n    def predict_step(self, batch: Any, batch_idx: int, dataloader_idx: int = 0) -> Any:\n        batch = batch[DataKeys.INPUT]\n        return self(batch)\n\n    @classmethod\n    def from_data(cls, datamodule, **kwargs) -> \"TabularRegressor\":\n        model = cls(datamodule.num_features, datamodule.embedding_sizes, **kwargs)\n        return model\n\n    @requires(\"serve\")\n    def serve(\n        self,\n        host: str = \"127.0.0.1\",\n        port: int = 8000,\n        sanity_check: bool = True,\n        input_cls: Optional[Type[ServeInput]] = TabularDeserializer,\n        transform: INPUT_TRANSFORM_TYPE = InputTransform,\n        transform_kwargs: Optional[Dict] = None,\n        parameters: Optional[Dict[str, Any]] = None,\n    ) -> Composition:\n        return super().serve(\n            host, port, sanity_check, partial(input_cls, parameters=parameters), transform, transform_kwargs\n        )\n", "path": "flash/tabular/regression/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.\nfrom functools import partial\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Type\n\nimport torch\nfrom torch.nn import functional as F\n\nfrom flash.core.classification import ClassificationTask, ProbabilitiesOutput\nfrom flash.core.data.io.input import DataKeys, ServeInput\nfrom flash.core.data.io.input_transform import InputTransform\nfrom flash.core.serve import Composition\nfrom flash.core.utilities.imports import _TABULAR_AVAILABLE, requires\nfrom flash.core.utilities.types import (\n    INPUT_TRANSFORM_TYPE,\n    LR_SCHEDULER_TYPE,\n    METRICS_TYPE,\n    OPTIMIZER_TYPE,\n    OUTPUT_TYPE,\n)\nfrom flash.tabular.input import TabularDeserializer\n\nif _TABULAR_AVAILABLE:\n    from pytorch_tabnet.tab_network import TabNet\n\n\nclass TabularClassifier(ClassificationTask):\n    \"\"\"The ``TabularClassifier`` is a :class:`~flash.Task` for classifying tabular data. For more details, see\n    :ref:`tabular_classification`.\n\n    Args:\n        num_features: Number of columns in table (not including target column).\n        num_classes: Number of classes to classify.\n        embedding_sizes: List of (num_classes, emb_dim) to form categorical embeddings.\n        loss_fn: Loss function for training, defaults to cross entropy.\n        optimizer: Optimizer to use for training.\n        lr_scheduler: The LR scheduler to use during training.\n        metrics: Metrics to compute for training and evaluation. Can either be an metric from the `torchmetrics`\n            package, a custom metric inherenting from `torchmetrics.Metric`, a callable function or a list/dict\n            containing a combination of the aforementioned. In all cases, each metric needs to have the signature\n            `metric(preds,target)` and return a single scalar tensor. Defaults to :class:`torchmetrics.Accuracy`.\n        learning_rate: Learning rate to use for training.\n        multi_label: Whether the targets are multi-label or not.\n        output: The :class:`~flash.core.data.io.output.Output` to use when formatting prediction outputs.\n        **tabnet_kwargs: Optional additional arguments for the TabNet model, see\n            `pytorch_tabnet <https://dreamquark-ai.github.io/tabnet/_modules/pytorch_tabnet/tab_network.html#TabNet>`_.\n    \"\"\"\n\n    required_extras: str = \"tabular\"\n\n    def __init__(\n        self,\n        num_features: int,\n        num_classes: int,\n        embedding_sizes: List[Tuple[int, int]] = None,\n        loss_fn: Callable = F.cross_entropy,\n        optimizer: OPTIMIZER_TYPE = \"Adam\",\n        lr_scheduler: LR_SCHEDULER_TYPE = None,\n        metrics: METRICS_TYPE = None,\n        learning_rate: float = 1e-2,\n        multi_label: bool = False,\n        output: OUTPUT_TYPE = None,\n        **tabnet_kwargs,\n    ):\n        self.save_hyperparameters()\n\n        cat_dims, cat_emb_dim = zip(*embedding_sizes) if embedding_sizes else ([], [])\n        model = TabNet(\n            input_dim=num_features,\n            output_dim=num_classes,\n            cat_idxs=list(range(len(embedding_sizes))),\n            cat_dims=list(cat_dims),\n            cat_emb_dim=list(cat_emb_dim),\n            **tabnet_kwargs,\n        )\n\n        super().__init__(\n            model=model,\n            loss_fn=loss_fn,\n            optimizer=optimizer,\n            lr_scheduler=lr_scheduler,\n            metrics=metrics,\n            learning_rate=learning_rate,\n            multi_label=multi_label,\n            output=output or ProbabilitiesOutput(),\n        )\n\n        self.save_hyperparameters()\n\n    def forward(self, x_in) -> torch.Tensor:\n        # TabNet takes single input, x_in is composed of (categorical, numerical)\n        xs = [x for x in x_in if x.numel()]\n        x = torch.cat(xs, dim=1)\n        return self.model(x)[0]\n\n    def training_step(self, batch: Any, batch_idx: int) -> Any:\n        batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])\n        return super().training_step(batch, batch_idx)\n\n    def validation_step(self, batch: Any, batch_idx: int) -> Any:\n        batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])\n        return super().validation_step(batch, batch_idx)\n\n    def test_step(self, batch: Any, batch_idx: int) -> Any:\n        batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])\n        return super().test_step(batch, batch_idx)\n\n    def predict_step(self, batch: Any, batch_idx: int, dataloader_idx: int = 0) -> Any:\n        batch = batch[DataKeys.INPUT]\n        return self(batch)\n\n    @classmethod\n    def from_data(cls, datamodule, **kwargs) -> \"TabularClassifier\":\n        model = cls(datamodule.num_features, datamodule.num_classes, datamodule.embedding_sizes, **kwargs)\n        return model\n\n    @staticmethod\n    def _ci_benchmark_fn(history: List[Dict[str, Any]]):\n        \"\"\"This function is used only for debugging usage with CI.\"\"\"\n        assert history[-1][\"val_accuracy\"] > 0.6, history[-1][\"val_accuracy\"]\n\n    @requires(\"serve\")\n    def serve(\n        self,\n        host: str = \"127.0.0.1\",\n        port: int = 8000,\n        sanity_check: bool = True,\n        input_cls: Optional[Type[ServeInput]] = TabularDeserializer,\n        transform: INPUT_TRANSFORM_TYPE = InputTransform,\n        transform_kwargs: Optional[Dict] = None,\n        parameters: Optional[Dict[str, Any]] = None,\n    ) -> Composition:\n        return super().serve(\n            host, port, sanity_check, partial(input_cls, parameters=parameters), transform, transform_kwargs\n        )\n", "path": "flash/tabular/classification/model.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 functools import partial\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Type\n\nimport torch\nfrom torch.nn import functional as F\n\nfrom flash.core.data.io.input import DataKeys, ServeInput\nfrom flash.core.data.io.input_transform import InputTransform\nfrom flash.core.regression import RegressionTask\nfrom flash.core.serve import Composition\nfrom flash.core.utilities.imports import _TABULAR_AVAILABLE, requires\nfrom flash.core.utilities.types import (\n    INPUT_TRANSFORM_TYPE,\n    LR_SCHEDULER_TYPE,\n    METRICS_TYPE,\n    OPTIMIZER_TYPE,\n    OUTPUT_TYPE,\n)\nfrom flash.tabular.input import TabularDeserializer\n\nif _TABULAR_AVAILABLE:\n    from pytorch_tabnet.tab_network import TabNet\n\n\nclass TabularRegressor(RegressionTask):\n    \"\"\"The ``TabularRegressor`` is a :class:`~flash.Task` for regression tabular data.\n\n    Args:\n        num_features: Number of columns in table (not including target column).\n        embedding_sizes: List of (num_classes, emb_dim) to form categorical embeddings (or ``None`` if there are no\n            categorical fields in the data).\n        loss_fn: Loss function for training, defaults to cross entropy.\n        optimizer: Optimizer to use for training.\n        lr_scheduler: The LR scheduler to use during training.\n        metrics: Metrics to compute for training and evaluation. Can either be an metric from the `torchmetrics`\n            package, a custom metric inherenting from `torchmetrics.Metric`, a callable function or a list/dict\n            containing a combination of the aforementioned. In all cases, each metric needs to have the signature\n            `metric(preds,target)` and return a single scalar tensor.\n        learning_rate: Learning rate to use for training.\n        multi_label: Whether the targets are multi-label or not.\n        output: The :class:`~flash.core.data.io.output.Output` to use when formatting prediction outputs.\n        **tabnet_kwargs: Optional additional arguments for the TabNet model, see\n            `pytorch_tabnet <https://dreamquark-ai.github.io/tabnet/_modules/pytorch_tabnet/tab_network.html#TabNet>`_.\n    \"\"\"\n\n    required_extras: str = \"tabular\"\n\n    def __init__(\n        self,\n        num_features: int,\n        embedding_sizes: Optional[List[Tuple[int, int]]] = None,\n        loss_fn: Callable = F.mse_loss,\n        optimizer: OPTIMIZER_TYPE = \"Adam\",\n        lr_scheduler: LR_SCHEDULER_TYPE = None,\n        metrics: METRICS_TYPE = None,\n        learning_rate: float = 1e-2,\n        output: OUTPUT_TYPE = None,\n        **tabnet_kwargs,\n    ):\n        self.save_hyperparameters()\n\n        if embedding_sizes:\n            cat_dims, cat_emb_dim = zip(*embedding_sizes)\n        else:\n            cat_dims, cat_emb_dim, embedding_sizes = [], [], []\n\n        model = TabNet(\n            input_dim=num_features,\n            output_dim=1,\n            cat_idxs=list(range(len(embedding_sizes))),\n            cat_dims=list(cat_dims),\n            cat_emb_dim=list(cat_emb_dim),\n            **tabnet_kwargs,\n        )\n\n        super().__init__(\n            model=model,\n            loss_fn=loss_fn,\n            optimizer=optimizer,\n            lr_scheduler=lr_scheduler,\n            metrics=metrics,\n            learning_rate=learning_rate,\n            output=output,\n        )\n\n        self.save_hyperparameters()\n\n    def forward(self, x_in) -> torch.Tensor:\n        # TabNet takes single input, x_in is composed of (categorical, numerical)\n        xs = [x for x in x_in if x.numel()]\n        x = torch.cat(xs, dim=1)\n        return self.model(x)[0].flatten()\n\n    def training_step(self, batch: Any, batch_idx: int) -> Any:\n        batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])\n        return super().training_step(batch, batch_idx)\n\n    def validation_step(self, batch: Any, batch_idx: int) -> Any:\n        batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])\n        return super().validation_step(batch, batch_idx)\n\n    def test_step(self, batch: Any, batch_idx: int) -> Any:\n        batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])\n        return super().test_step(batch, batch_idx)\n\n    def predict_step(self, batch: Any, batch_idx: int, dataloader_idx: int = 0) -> Any:\n        batch = batch[DataKeys.INPUT]\n        return self(batch)\n\n    @classmethod\n    def from_data(cls, datamodule, **kwargs) -> \"TabularRegressor\":\n        model = cls(datamodule.num_features, datamodule.embedding_sizes, **kwargs)\n        return model\n\n    @requires(\"serve\")\n    def serve(\n        self,\n        host: str = \"127.0.0.1\",\n        port: int = 8000,\n        sanity_check: bool = True,\n        input_cls: Optional[Type[ServeInput]] = TabularDeserializer,\n        transform: INPUT_TRANSFORM_TYPE = InputTransform,\n        transform_kwargs: Optional[Dict] = None,\n        parameters: Optional[Dict[str, Any]] = None,\n    ) -> Composition:\n        return super().serve(\n            host, port, sanity_check, partial(input_cls, parameters=parameters), transform, transform_kwargs\n        )\n", "path": "flash/tabular/regression/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.\nfrom functools import partial\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Type\n\nimport torch\nfrom torch.nn import functional as F\n\nfrom flash.core.classification import ClassificationTask, ProbabilitiesOutput\nfrom flash.core.data.io.input import DataKeys, ServeInput\nfrom flash.core.data.io.input_transform import InputTransform\nfrom flash.core.serve import Composition\nfrom flash.core.utilities.imports import _TABULAR_AVAILABLE, requires\nfrom flash.core.utilities.types import (\n    INPUT_TRANSFORM_TYPE,\n    LR_SCHEDULER_TYPE,\n    METRICS_TYPE,\n    OPTIMIZER_TYPE,\n    OUTPUT_TYPE,\n)\nfrom flash.tabular.input import TabularDeserializer\n\nif _TABULAR_AVAILABLE:\n    from pytorch_tabnet.tab_network import TabNet\n\n\nclass TabularClassifier(ClassificationTask):\n    \"\"\"The ``TabularClassifier`` is a :class:`~flash.Task` for classifying tabular data. For more details, see\n    :ref:`tabular_classification`.\n\n    Args:\n        num_features: Number of columns in table (not including target column).\n        num_classes: Number of classes to classify.\n        embedding_sizes: List of (num_classes, emb_dim) to form categorical embeddings (or ``None`` if there are no\n            categorical fields in the data).\n        loss_fn: Loss function for training, defaults to cross entropy.\n        optimizer: Optimizer to use for training.\n        lr_scheduler: The LR scheduler to use during training.\n        metrics: Metrics to compute for training and evaluation. Can either be an metric from the `torchmetrics`\n            package, a custom metric inherenting from `torchmetrics.Metric`, a callable function or a list/dict\n            containing a combination of the aforementioned. In all cases, each metric needs to have the signature\n            `metric(preds,target)` and return a single scalar tensor. Defaults to :class:`torchmetrics.Accuracy`.\n        learning_rate: Learning rate to use for training.\n        multi_label: Whether the targets are multi-label or not.\n        output: The :class:`~flash.core.data.io.output.Output` to use when formatting prediction outputs.\n        **tabnet_kwargs: Optional additional arguments for the TabNet model, see\n            `pytorch_tabnet <https://dreamquark-ai.github.io/tabnet/_modules/pytorch_tabnet/tab_network.html#TabNet>`_.\n    \"\"\"\n\n    required_extras: str = \"tabular\"\n\n    def __init__(\n        self,\n        num_features: int,\n        num_classes: int,\n        embedding_sizes: Optional[List[Tuple[int, int]]] = None,\n        loss_fn: Callable = F.cross_entropy,\n        optimizer: OPTIMIZER_TYPE = \"Adam\",\n        lr_scheduler: LR_SCHEDULER_TYPE = None,\n        metrics: METRICS_TYPE = None,\n        learning_rate: float = 1e-2,\n        multi_label: bool = False,\n        output: OUTPUT_TYPE = None,\n        **tabnet_kwargs,\n    ):\n        self.save_hyperparameters()\n\n        if embedding_sizes:\n            cat_dims, cat_emb_dim = zip(*embedding_sizes)\n        else:\n            cat_dims, cat_emb_dim, embedding_sizes = [], [], []\n\n        model = TabNet(\n            input_dim=num_features,\n            output_dim=num_classes,\n            cat_idxs=list(range(len(embedding_sizes))),\n            cat_dims=list(cat_dims),\n            cat_emb_dim=list(cat_emb_dim),\n            **tabnet_kwargs,\n        )\n\n        super().__init__(\n            model=model,\n            loss_fn=loss_fn,\n            optimizer=optimizer,\n            lr_scheduler=lr_scheduler,\n            metrics=metrics,\n            learning_rate=learning_rate,\n            multi_label=multi_label,\n            output=output or ProbabilitiesOutput(),\n        )\n\n        self.save_hyperparameters()\n\n    def forward(self, x_in) -> torch.Tensor:\n        # TabNet takes single input, x_in is composed of (categorical, numerical)\n        xs = [x for x in x_in if x.numel()]\n        x = torch.cat(xs, dim=1)\n        return self.model(x)[0]\n\n    def training_step(self, batch: Any, batch_idx: int) -> Any:\n        batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])\n        return super().training_step(batch, batch_idx)\n\n    def validation_step(self, batch: Any, batch_idx: int) -> Any:\n        batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])\n        return super().validation_step(batch, batch_idx)\n\n    def test_step(self, batch: Any, batch_idx: int) -> Any:\n        batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET])\n        return super().test_step(batch, batch_idx)\n\n    def predict_step(self, batch: Any, batch_idx: int, dataloader_idx: int = 0) -> Any:\n        batch = batch[DataKeys.INPUT]\n        return self(batch)\n\n    @classmethod\n    def from_data(cls, datamodule, **kwargs) -> \"TabularClassifier\":\n        model = cls(datamodule.num_features, datamodule.num_classes, datamodule.embedding_sizes, **kwargs)\n        return model\n\n    @staticmethod\n    def _ci_benchmark_fn(history: List[Dict[str, Any]]):\n        \"\"\"This function is used only for debugging usage with CI.\"\"\"\n        assert history[-1][\"val_accuracy\"] > 0.6, history[-1][\"val_accuracy\"]\n\n    @requires(\"serve\")\n    def serve(\n        self,\n        host: str = \"127.0.0.1\",\n        port: int = 8000,\n        sanity_check: bool = True,\n        input_cls: Optional[Type[ServeInput]] = TabularDeserializer,\n        transform: INPUT_TRANSFORM_TYPE = InputTransform,\n        transform_kwargs: Optional[Dict] = None,\n        parameters: Optional[Dict[str, Any]] = None,\n    ) -> Composition:\n        return super().serve(\n            host, port, sanity_check, partial(input_cls, parameters=parameters), transform, transform_kwargs\n        )\n", "path": "flash/tabular/classification/model.py"}]}