Skip to content

Tabular AutoML

FastAPI app init for the tabular AutoML service.

TabularSupervisedClassificationTask

Bases: TabularTask

Tabular classification task configuration.

Typical use-cases: churn prediction, loan approval, disease type, etc.

Source code in app/tabular_automl/models.py
25
26
27
28
29
30
31
class TabularSupervisedClassificationTask(TabularTask):
    """Tabular classification task configuration.

    Typical use-cases: churn prediction, loan approval, disease type, etc.
    """

    task_type: str = "tabular_classification"

TabularSupervisedRegressionTask

Bases: TabularTask

Tabular regression task configuration.

Predicts continuous numeric values (e.g., price, salary, demand).

Source code in app/tabular_automl/models.py
34
35
36
37
38
39
40
class TabularSupervisedRegressionTask(TabularTask):
    """Tabular regression task configuration.

    Predicts continuous numeric values (e.g., price, salary, demand).
    """

    task_type: str = "tabular_regression"

TabularSupervisedTimeSeriesTask

Bases: TabularTask

Time-series forecasting task configuration for tabular data.

Source code in app/tabular_automl/models.py
43
44
45
46
47
class TabularSupervisedTimeSeriesTask(TabularTask):
    """Time-series forecasting task configuration for tabular data."""

    task_type: str = "tabular_time_series"
    time_stamp_col: str = "timestamp"

TabularTask

Bases: BaseModel

Base Pydantic model describing common tabular task inputs.

Source code in app/tabular_automl/models.py
13
14
15
16
17
18
19
20
21
22
class TabularTask(BaseModel):
    """Base Pydantic model describing common tabular task inputs."""

    target_feature: str
    time_stamp_col: pd.DataFrame | None = None
    train_file_path: Path
    test_file_path: Path | None = None

    class Config:
        arbitrary_types_allowed: bool = True

AutoMLTrainer

Wrapper around AutoGluon Tabular training routines.

Source code in app/tabular_automl/modules.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class AutoMLTrainer:
    """Wrapper around AutoGluon Tabular training routines."""

    def __init__(
        self,
        save_model_path: Path,
        DatasetClass=TabularDataset,
        PredictorClass=TabularPredictor,
    ):
        self.save_model_path: Path = Path(save_model_path)
        self.DatasetClass = DatasetClass
        self.PredictorClass = PredictorClass
        logger.debug(f"Automl trainer, model path {self.save_model_path}")

    def train(
        self,
        train_df: pd.DataFrame,
        test_df: pd.DataFrame | None,
        target_column: str,
        time_limit: int,
    ) -> tuple[pd.DataFrame | str, TabularPredictor] | str:
        """Train AutoGluon Tabular and return leaderboard or error."""
        final_train_df, final_test_df = self.train_test_split(
            test_df=test_df, train_df=train_df
        )

        train_dataset = self.DatasetClass(final_train_df)
        test_dataset = self.DatasetClass(final_test_df)

        predictor = self.PredictorClass(
            label=target_column, path=str(self.save_model_path)
        ).fit(train_data=train_dataset, time_limit=time_limit)

        save_path_clone_opt = self.save_model_path / "-clone-opt"
        path_clone_opt = predictor.clone_for_deployment(path=str(save_path_clone_opt))
        predictor_clone_opt = self.PredictorClass.load(path=str(path_clone_opt))

        try:
            return predictor.leaderboard(test_dataset), predictor_clone_opt
        except Exception as e:
            logger.error(f"AutoML trainer failed {e}")
            return str(e)

    def train_test_split(
        self, test_df: pd.DataFrame | None, train_df: pd.DataFrame | None = None
    ):
        if test_df is None:
            logger.debug("Test dataset not found, creating split")
            if train_df is not None:
                final_train_df = train_df.sample(
                    frac=DEFAULT_TABULAR_TRAIN_TEST_SPLIT_SIZE, random_state=42
                )
                final_test_df = train_df.drop(index=final_train_df.index.tolist())
            else:
                logger.error("Train df is empty")
                return str("Train df is empty")
        else:
            logger.debug("Test dataset found")
            final_train_df = train_df
            final_test_df = test_df
        return final_train_df, final_test_df

train(train_df, test_df, target_column, time_limit)

Train AutoGluon Tabular and return leaderboard or error.

Source code in app/tabular_automl/modules.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def train(
    self,
    train_df: pd.DataFrame,
    test_df: pd.DataFrame | None,
    target_column: str,
    time_limit: int,
) -> tuple[pd.DataFrame | str, TabularPredictor] | str:
    """Train AutoGluon Tabular and return leaderboard or error."""
    final_train_df, final_test_df = self.train_test_split(
        test_df=test_df, train_df=train_df
    )

    train_dataset = self.DatasetClass(final_train_df)
    test_dataset = self.DatasetClass(final_test_df)

    predictor = self.PredictorClass(
        label=target_column, path=str(self.save_model_path)
    ).fit(train_data=train_dataset, time_limit=time_limit)

    save_path_clone_opt = self.save_model_path / "-clone-opt"
    path_clone_opt = predictor.clone_for_deployment(path=str(save_path_clone_opt))
    predictor_clone_opt = self.PredictorClass.load(path=str(path_clone_opt))

    try:
        return predictor.leaderboard(test_dataset), predictor_clone_opt
    except Exception as e:
        logger.error(f"AutoML trainer failed {e}")
        return str(e)

build_upload_payload(dataset_id, dataset_version, metadata, task_type, leaderboard_json)

Return (model_id, form_data_dict) for the AutoDW upload request.

Source code in app/tabular_automl/services.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def build_upload_payload(
    dataset_id: str,
    dataset_version: str | None,
    metadata: dict,
    task_type: str,
    leaderboard_json: list | dict,
) -> tuple[str, dict]:
    """Return (model_id, form_data_dict) for the AutoDW upload request."""
    model_id = f"automl_{dataset_id}_{int(datetime.utcnow().timestamp())}"
    data = {
        "model_id": model_id,
        "name": f"AutoML Model - {model_id}",
        "description": "AutoML trained model for tabular data",
        "framework": "sklearn",
        "model_type": task_type,
        "training_dataset": str(dataset_id),
        "training_dataset_version": dataset_version or metadata.get("version", "v1"),
        "leaderboard": json.dumps(leaderboard_json),
        "deployment_instructions": deployment_instructions(),
    }
    return model_id, data

create_session_directory(upload_root=UPLOAD_ROOT)

Create and return a new session id and directory path.

Source code in app/tabular_automl/services.py
36
37
38
39
40
41
42
def create_session_directory(upload_root: Path = UPLOAD_ROOT) -> tuple[str, Path]:
    """Create and return a new session id and directory path."""
    session_id = str(uuid.uuid4())
    session_dir = upload_root / session_id
    session_dir.mkdir(parents=True, exist_ok=True)
    logging.debug(f"Session directory created at {session_dir}")
    return session_id, session_dir

download_dataset(download_url, dest_path)

Stream-download a dataset file to dest_path.

Source code in app/tabular_automl/services.py
170
171
172
173
174
175
176
177
def download_dataset(download_url: str, dest_path: Path) -> None:
    """Stream-download a dataset file to dest_path."""
    with requests.get(download_url, stream=True, timeout=30) as resp:
        resp.raise_for_status()
        with open(dest_path, "wb") as f:
            for chunk in resp.iter_content(8192):
                f.write(chunk)
    logger.info(f"Dataset saved to {dest_path}")

fetch_dataset_metadata(autodw_base, user_id, dataset_id, dataset_version)

Fetch and return dataset metadata from AutoDW.

Source code in app/tabular_automl/services.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def fetch_dataset_metadata(
    autodw_base: str,
    user_id: str,
    dataset_id: str,
    dataset_version: str | None,
) -> dict:
    """Fetch and return dataset metadata from AutoDW."""
    metadata_url = _build_metadata_url(
        autodw_base, user_id, dataset_id, dataset_version
    )
    logger.debug(f"Fetching dataset metadata: {metadata_url}")
    resp = requests.get(metadata_url, timeout=15)
    resp.raise_for_status()
    return resp.json()

load_table(file_path)

Load a table file into a DataFrame based on file extension.

Source code in app/tabular_automl/services.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def load_table(file_path: Path) -> pd.DataFrame:
    """Load a table file into a DataFrame based on file extension."""
    suffix = file_path.suffix.lower()
    if suffix in [".csv"]:
        logging.debug("csv file loaded")
        return pd.read_csv(file_path)
    if suffix in [".xls", ".xlsx", ".xlsm", ".xlsb"]:
        logging.debug("excel file loaded")
        return pd.read_excel(file_path)
    if suffix in [".parquet", ".pq"]:
        logging.debug("Parquet file loaded")
        return pd.read_parquet(file_path)
    if suffix in [".json"]:
        logging.debug("Json file loaded")
        return pd.read_json(file_path)
    # Fallback: try csv to keep previous behavior
    return pd.read_csv(file_path)

resolve_download_url(autodw_base, user_id, dataset_id, dataset_version, metadata, dataset_split)

Determine the correct dataset download URL, accounting for splits.

Source code in app/tabular_automl/services.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def resolve_download_url(
    autodw_base: str,
    user_id: str,
    dataset_id: str,
    dataset_version: str | None,
    metadata: dict,
    dataset_split: str | None,
) -> str:
    """Determine the correct dataset download URL, accounting for splits."""
    base_url = _build_metadata_url(autodw_base, user_id, dataset_id, dataset_version)
    download_url = f"{base_url}/download"

    has_split = bool(metadata.get("custom_metadata", {}).get("split"))
    effective_split = (
        dataset_split
        if (has_split and dataset_split in ("train", "test", "drift"))
        else None
    )

    if effective_split:
        download_url = f"{download_url}?split={effective_split}"
        logger.info(
            f"Dataset has splits; downloading '{effective_split}' split from: {download_url}"
        )
    else:
        if dataset_split and not has_split:
            logger.warning(
                f"dataset_split='{dataset_split}' was requested but dataset has no splits; "
                "downloading full dataset."
            )
        logger.debug(f"Downloading full dataset file: {download_url}")

    return download_url

save_upload(file, destination)

Persist an uploaded file to the given destination path.

Source code in app/tabular_automl/services.py
45
46
47
48
49
def save_upload(file: UploadFile, destination: Path) -> None:
    """Persist an uploaded file to the given destination path."""
    with open(destination, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)
        logging.debug(f"File saved to {destination}")

serialize_and_zip_predictor(predictor, save_model_path, tmp_path)

Pickle the predictor and zip the model directory. Returns the zip path.

Source code in app/tabular_automl/services.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def serialize_and_zip_predictor(
    predictor, save_model_path: Path, tmp_path: Path
) -> Path:
    """Pickle the predictor and zip the model directory. Returns the zip path."""
    predictor_path = save_model_path / "predictor.pkl"
    with open(predictor_path, "wb") as f:
        pickle.dump(predictor, f)

    try:
        with open(save_model_path / "tabular_deployment_instructions.md") as f:
            f.write(deployment_instructions())
    except Exception as e:
        logger.debug(f"No deployment_instructions found, {e}")

    zip_path = tmp_path / "automl_predictor.zip"
    shutil.make_archive(
        base_name=str(zip_path).replace(".zip", ""),
        format="zip",
        root_dir=save_model_path,
    )
    return zip_path

train_automl(dataset_path, save_model_path, target_column_name, task_type, time_budget)

Train an AutoML model and return (leaderboard, predictor).

Source code in app/tabular_automl/services.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def train_automl(
    dataset_path: Path,
    save_model_path: Path,
    target_column_name: str,
    task_type: str,
    time_budget: int,
):
    """Train an AutoML model and return (leaderboard, predictor)."""
    os.makedirs(save_model_path, exist_ok=True)
    trainer = AutoMLTrainer(save_model_path=save_model_path)
    train_df = load_table(dataset_path)
    return trainer.train(
        train_df=train_df,
        test_df=None,
        target_column=target_column_name,
        time_limit=int(time_budget),
    )

upload_model(upload_url, zip_path, payload, task_id)

Upload the zipped model to AutoDW. Returns the raw response.

Source code in app/tabular_automl/services.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def upload_model(
    upload_url: str,
    zip_path: Path,
    payload: dict,
    task_id: str | None,
) -> requests.Response:
    """Upload the zipped model to AutoDW. Returns the raw response."""
    headers = {"X-Task-ID": task_id} if task_id else {}
    if task_id:
        logger.debug(f"Including X-Task-ID header: {task_id}")

    with open(zip_path, "rb") as f:
        files = {"file": (zip_path.name, f, "application/octet-stream")}
        logger.debug(f"Uploading model to {upload_url}")
        return requests.post(
            upload_url, headers=headers, files=files, data=payload, timeout=120
        )

validate_tabular_inputs(train_path, target_column_name, time_stamp_column_name=None, task_type='tabular_classification')

Validate required columns and task type for tabular training.

Source code in app/tabular_automl/services.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def validate_tabular_inputs(
    train_path: Path,
    target_column_name: str,
    time_stamp_column_name: str | None = None,
    task_type: str = "tabular_classification",
) -> str | None:
    """Validate required columns and task type for tabular training."""

    if task_type not in SUPPORTED_TABULAR_TASK_TYPES:
        logger.error(f"Invalid task type {task_type}")
        return f"Invalid task_type '{task_type}'"

    try:
        train_df = load_table(train_path)
    except Exception as e:
        logging.error(f"Could not read training data {e}")
        return f"Could not read training data: {e}"

    if target_column_name not in train_df.columns:
        logger.error(f"Target column '{target_column_name}' not found.")
        return f"Target column '{target_column_name}' not found."

    if time_stamp_column_name and time_stamp_column_name not in train_df.columns:
        logger.error(f"Timestampl column '{time_stamp_column_name}' not found.")
        return f"Timestamp column '{time_stamp_column_name}' not found."

    return None

Route definitions for the tabular AutoML service.

find_best_model_for_mvp(request, user_id, dataset_id, dataset_version='', target_column_name='', time_stamp_column_name=None, task_type='classification', time_budget=10, dataset_split=None) async

Fetch a tabular dataset from AutoDW, run AutoML training, and upload the best model.

Steps
  1. Fetch dataset metadata from AutoDW.
  2. Resolve the correct download URL (respecting splits if present).
  3. Download the dataset file to a temporary directory.
  4. Validate user-supplied parameters against the dataset.
  5. Train an AutoML model within the given time budget.
  6. Serialize and zip the best predictor.
  7. Upload the model and leaderboard back to AutoDW.

Returns:

Type Description
JSONResponse

200 – success message and leaderboard summary.

JSONResponse

400 – validation error (bad inputs or unsupported file type).

JSONResponse

502 – AutoDW communication failure.

JSONResponse

500 – unexpected runtime error.

Source code in app/tabular_automl/router.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
@router.post("/best_model/")
async def find_best_model_for_mvp(
    request: Request,
    user_id: Annotated[str, Form(..., description="User id from AutoDW")],
    dataset_id: Annotated[str, Form(..., description="Dataset id from AutoDW")],
    dataset_version: Annotated[
        str | None, Form(description="Dataset version (e.g., 'v1', 'v2')")
    ] = "",
    target_column_name: Annotated[
        str, Form(..., description="Name of the target column")
    ] = "",
    time_stamp_column_name: Annotated[
        str | None,
        Form(..., description="Timestamp column (required for time-series tasks)"),
    ] = None,
    task_type: Annotated[
        str,
        Form(
            ...,
            description="Type of ML task",
            examples=SUPPORTED_TABULAR_TASK_TYPES,
        ),
    ] = "classification",
    time_budget: Annotated[int, Form(..., description="Time budget in seconds")] = 10,
    dataset_split: Annotated[
        str | None,
        Form(description="Dataset split to use for training (e.g., 'train')."),
    ] = None,
) -> JSONResponse:
    """
    Fetch a tabular dataset from AutoDW, run AutoML training, and upload the best model.

    Steps:
      1. Fetch dataset metadata from AutoDW.
      2. Resolve the correct download URL (respecting splits if present).
      3. Download the dataset file to a temporary directory.
      4. Validate user-supplied parameters against the dataset.
      5. Train an AutoML model within the given time budget.
      6. Serialize and zip the best predictor.
      7. Upload the model and leaderboard back to AutoDW.

    Returns:
        200 – success message and leaderboard summary.
        400 – validation error (bad inputs or unsupported file type).
        502 – AutoDW communication failure.
        500 – unexpected runtime error.
    """
    autodw_base = os.getenv("AUTODW_URL", "http://localhost:8000")
    upload_url = f"{autodw_base}/ai-models/upload/single/{user_id}"

    try:
        # 1. Metadata
        metadata = fetch_dataset_metadata(
            autodw_base, user_id, dataset_id, dataset_version
        )

        file_type = metadata.get("file_type")
        if file_type not in SUPPORTED_FILE_TYPES:
            return JSONResponse(
                status_code=400,
                content={"error": f"Unsupported file type '{file_type}'."},
            )

        # 2. Download URL
        download_url = resolve_download_url(
            autodw_base, user_id, dataset_id, dataset_version, metadata, dataset_split
        )

        with tempfile.TemporaryDirectory() as tmp_dir:
            tmp_path = Path(tmp_dir)
            dataset_path = tmp_path / metadata.get("original_filename", "train.csv")

            # 3. Download
            download_dataset(download_url, dataset_path)

            # 4. Validate
            validation_error = validate_tabular_inputs(
                train_path=dataset_path,
                target_column_name=target_column_name,
                time_stamp_column_name=time_stamp_column_name,
                task_type=task_type,
            )
            if validation_error:
                return JSONResponse(
                    status_code=400, content={"error": validation_error}
                )

            # 5. Train
            save_model_path = tmp_path / "automl_model"
            leaderboard, predictor = train_automl(
                dataset_path,
                save_model_path,
                target_column_name,
                task_type,
                time_budget,
            )

            # 6. Serialize
            zip_path = serialize_and_zip_predictor(predictor, save_model_path, tmp_path)
            leaderboard_json, leaderboard_str = convert_leaderboard_safely(leaderboard)

            # 7. Upload
            _, payload = build_upload_payload(
                dataset_id, dataset_version, metadata, task_type, leaderboard_json
            )
            upload_resp = upload_model(
                upload_url, zip_path, payload, request.headers.get("X-Task-ID")
            )

            if upload_resp.status_code >= 400:
                logger.error(f"Model upload failed: {upload_resp.text}")
                return JSONResponse(
                    status_code=upload_resp.status_code,
                    content={"error": f"Failed to upload model: {upload_resp.text}"},
                )

        logger.info("AutoML training completed and model uploaded successfully.")
        return JSONResponse(
            status_code=200,
            content={
                "message": "AutoML training completed successfully and model uploaded to AutoDW",
                "leaderboard": leaderboard_str,
            },
        )

    except requests.RequestException as e:
        logger.exception("Network or HTTP error during AutoDW communication")
        return JSONResponse(
            status_code=502, content={"error": f"AutoDW communication failed: {e}"}
        )
    except Exception as e:
        logger.exception("Unexpected error during AutoML training or upload")
        return JSONResponse(status_code=500, content={"error": str(e)})