diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d223219..023a5ee 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,8 +14,8 @@ jobs: lint: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v5 + - uses: actions/setup-python@v6 with: python-version: "3.12" - uses: pre-commit/action@v3.0.1 @@ -30,8 +30,8 @@ jobs: env: AUTODEEP_DEVICE: cpu steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v5 + - uses: actions/setup-python@v6 with: python-version: ${{ matrix.python-version }} cache: pip @@ -41,7 +41,7 @@ jobs: pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu pip install -e ".[dev,files]" - name: Cache TabICL weights - uses: actions/cache@v4 + uses: actions/cache@v5 with: path: ~/.cache/huggingface key: hf-tabicl-v2 diff --git a/.gitignore b/.gitignore index faf378d..b15798a 100644 --- a/.gitignore +++ b/.gitignore @@ -91,4 +91,4 @@ jspm_packages/ # benchmark outputs (summarised in benchmarks/README.md) -benchmarks/results/ +benchmarks/results*/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6844664..f52f0b2 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -3,7 +3,7 @@ repos: rev: v0.6.9 hooks: - id: ruff - args: [--fix, --select, "E,F,W,I,B", --ignore, "E501,B008,B904,B905"] + args: [--fix, --select, "E,F,W,I,B,UP", --ignore, "E501,B008,B904,B905", --target-version, py310] files: ^(autodeep|tests|examples)/.*\.py$ exclude: ^autodeep/modelutils/igtdutilities\.py$ diff --git a/CHANGELOG.md b/CHANGELOG.md index 30e2055..391c9b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,54 @@ # Changelog +## 0.5.0 (2026-11-13): competition tools, LightGBM + +### New +- **LightGBM** (`lgbm`, CPU, native categorical columns) with a default search space; it is part of the `fast` preset and of the `models: auto` candidates (after CatBoost). +- **Offset columns (GLM-boost).** XGBoost and LightGBM accept `default_params: {offset_column: }`: that column holds log-odds from another model (e.g. an out-of-fold logistic regression), boosting starts from it (`base_margin` / `init_score`) and predictions add it back. The column is not used as a feature. Binary classification only. +- **Residual MLP** (`resmlp`, PyTorch): with an offset column the output is `offset + net(x)` with a zero-initialised head, so training starts at the offset model and learns its residual; otherwise a plain MLP. Early stopping on validation AUC (binary) or loss. +- **`search_folds: K`** in a model's `default_params`: every trial is scored on K stratified folds (mean validation metric) instead of one split. Use it when candidates differ by less than the noise of a single validation split (K times the cost). +- **`autodeep.ensemble.Stacker`**: stacks out-of-fold predictions (from AutoDeep or anywhere else) with Caruana hill climbing or an L2 logistic regression on logit-ranks, scored by nested cross-validation (`nested_score_`, `weights_`, `predict()`). + +### Also +- README: a demo clip of the web app, new screenshots and a minimal Python quick start. + +## 0.4.0 (2026-11-13): use the models, sensible defaults + +### New +- **Saved, ready-to-use models.** Every run keeps the best model of each dataset (chosen on the validation score, never the test score) and saves it with its preprocessing to `/models//best`. `runner.best_model("churn").predict(new_rows)`, `autodeep.load_model(path)`, `autodeep predict new.csv -o predictions.csv` and `autodeep info `. New rows need the original columns: missing values, unseen categories and numbers stored as text are handled like during training, and predictions use the original class labels. `predict_proba` returns one column per class; `evaluate` scores labelled rows. In the web app, each run has a "Use the best models" card to download a model or predict an uploaded file. +- `save_models=True` now saves every model in the same loadable format (`models//`); `save_best=False` turns saving off. The leaderboard has a `selected` column. +- All 17 models can be saved and loaded. Models trained on a GPU load on machines without one (checked for XGBoost, RealMLP, TabM, the 1D-CNN, TabICL and, before the port, the pytorch-tabular models). +- **`models: auto` (the new default) with a time budget.** AutoDeep measures the machine (cores, RAM, GPU, a ~0.5 s CPU benchmark) and picks the models, trials and per-model time limit that fit `time_budget` (default 15 minutes), explaining what it skipped and why. `AutoRunner(time_budget="20m")`, `autodeep run data.csv --target y --budget 20m`, `time_budget:` in YAML, and an Auto mode in the web app. With explicit models, a budget sets `timeout_per_model`. +- `autodeep run` / `estimate` accept a data file and `--target` directly, no YAML needed. `autodeep system` shows what AutoDeep sees on the machine. +- Runtime estimates scale the built-in cost curves by the measured CPU speed until timings from the machine itself are available. + +- **No more pytorch-tabular dependency; pandas 3 supported.** The nine deep tabular architectures (CategoryEmbedding, TabNet, FT-Transformer, TabTransformer, AutoInt, GANDALF, GATE, NODE, DANet) were ported from pytorch-tabular 1.2.0 (MIT) to plain PyTorch modules in `autodeep/modelsdefinition/tabular_nets/` and are trained by AutoDeep's own loop, like the 1D-CNN and the ResNet. pytorch-tabular was the only dependency pinning `pandas<3`; the lock file now resolves pandas 3.1 (2.3 on Python 3.10). `pytorch-tabular`, `requests` and the `pytorch-tabnet<4.2` cap are gone, and so are omegaconf, rich and their transitive dependencies. hyperopt 0.3 no longer needs `pkg_resources`, so the `setuptools<81` pin is gone as well (no dependency is held back any more). + +### Changed +- TabICL predicts the test set with every training row as context (the validation score still comes from the 80% split), and no longer reports train metrics, which scored the context rows against themselves. Models can opt in with `refit_on_full_train` and `compute_train_metrics = False`. +- Estimates warn when a model that is much faster on a GPU (TabICL, TabM, the 1D-CNN, ResNet) would take more than 5 minutes on CPU. `autodeep estimate` and the run log now print the per-job warnings, which only the web app showed before. +- **XGBoost and CatBoost search spaces are now competitive baselines.** XGBoost used to search 50-200 trees with learning rates down to 0.01 (badly underfit at low rates, and early stopping after 100 rounds could never trigger), and CatBoost only searched `iterations` between 100 and 500. Both now train up to 2000 trees with early stopping on the validation split (50 / 100 rounds) and search learning rate, depth and regularisation (XGBoost also row/column subsampling and `gamma`). Trials take longer; GBDT scores from 0.3.0 are not comparable. +- `AutoRunner(models=None)` means `"auto"` instead of the fixed `default` preset; pass `models="default"` for the old behaviour. `max_evals` defaults to the plan's value (25 with explicit models). +- Preprocessing is a fitted `TabularPreprocessor` object (identical output to 0.3.0 on four built-in datasets × all normalisation/encoding options). Mixed-type text columns are now always treated as categorical strings, and datetime columns with missing values no longer produce huge negative numbers. +- The deep tabular models keep pytorch-tabular's hyperparameter names and defaults, so existing `param_grid`s work unchanged. Scores differ slightly from 0.3.0: binary targets use one logit with a class-balanced BCE loss (as the other PyTorch models do) instead of two-class cross-entropy, categories are encoded on the whole training set, and the batch size falls back to `default_params.batch_size`. +- AutoInt's grid now searches `deep_layers` (true/false); its `layers` / `activation` / `dropout` entries had no effect without it. +- Two pytorch-tabular options that were silently ignored now take effect: TabTransformer's `out_ff_layers` / `out_ff_activation` / `out_ff_dropout` / `out_ff_initialization` configure its MLP head, and `transformer_head_dim` sets the attention head size of TabTransformer and FT-Transformer. +- Models saved with 0.3.0's pytorch-tabular trainers cannot be loaded; retrain them. All trained PyTorch models are now saved as weights plus build arguments. +- The hyperparameter search hands over to TPE after a third of the trials (5 to 10) instead of hyperopt's fixed 20. A 25-trial search used to be 20 random trials and only 5 guided ones. +- `autodeep.modelsdefinition.pytorch_tabular_models` is kept as an alias of the new `deep_tabular_models` module. +- The scikit-learn MLP's runtime prior was re-measured (it was ~15x too optimistic above 10,000 rows). + +### Also +- `benchmarks/README.md`: results of `larger_datasets.py` (TabICLv2, RealMLP, TabM, CatBoost, XGBoost on three datasets of 20k-50k rows) and measured GPU speed-ups. The estimator's GPU factors for TabICLv2 (now 50x), TabM (12x) and RealMLP (1.5x) and its XGBoost/CatBoost CPU priors (for the new grids) were updated from these runs. +- `benchmarks/larger_datasets.py` has suites (`core`, `deep`), resumes interrupted runs and stops when the GPU fills up. `benchmarks/search_diagnostics.py` reports, per search, whether TPE improved on the start-up trials, when the best trial came, and which hyperparameters sit at the edge of their range. +- README screenshots of the web app. +- `examples/walkthrough.ipynb` was executed end to end in Jupyter (nbconvert). + +### Fixed +- `openml:` datasets failed on pandas 3 with scikit-learn 1.9 ("expected string or bytes-like object, got 'int'" in the ARFF parser); AutoDeep now retries with scikit-learn's `liac-arff` parser. +- Web app: model checkboxes on cards with longer descriptions were squeezed into tiny dots. +- XGBoost trained on a GPU printed a "mismatched devices" warning on every prediction. + ## 0.3.0: modern tabular models ### New diff --git a/README.md b/README.md index 16c06a7..8ea583f 100644 --- a/README.md +++ b/README.md @@ -6,20 +6,47 @@ **Benchmark gradient-boosted trees and deep learning models on your tabular data, with hyperparameter search, runtime estimates and a local web app.** -AutoDeep trains and tunes up to 17 models (XGBoost, CatBoost, the TabICLv2 foundation model, RealMLP, TabM, an MLP, nine PyTorch Tabular architectures, a Soft-Ordering 1D-CNN and a ResNet on IGTD images) on one or more datasets, evaluates them on a held-out test set and gives you a leaderboard. You can drive it from a browser, from the command line, or from Python. +

+ AutoDeep web app: add a dataset, let Auto pick the models for a 3-minute budget, watch the run and get the leaderboard and the saved best model
+ The web app on a 6-core desktop CPU: one dataset, a 3-minute budget, 8 models picked automatically (the run is sped up 15x). Full-resolution video. +

+ +## Description + +AutoDeep is a flexible and easy-to-use API for automating machine learning experiments (AutoML) on tabular datasets. It facilitates testing various deep learning models as well as tree based models to compare their performance on multiple datasets with hyperparameter optimization and evaluation. By using the AutoRunner class (or the command line, or the web app), you can quickly train and evaluate models like XGBoost, LightGBM, CatBoost, the TabICLv2 foundation model, RealMLP, TabM, FT-Transformer, ResNet, and more on tabular data. + +The goal of this project is to provide an easy interface for training, hyperparameter tuning, and evaluating models, so researchers and developers can quickly benchmark different models on their datasets. By default it picks the models that fit your time budget on your machine, and it saves the best model of each dataset, ready to predict new rows. + +```bash +autodeep run data/churn.csv --target churned --budget 10m # plan, train, compare, save the best model +autodeep predict output/models/churn/best new_customers.csv -o predictions.csv +``` + +## Features + +- **Supports multiple machine learning models**: 19 models, from gradient-boosted trees (XGBoost, LightGBM, CatBoost) to the TabICLv2 foundation model, RealMLP, TabM, nine deep tabular architectures (FT-Transformer, TabNet, GANDALF, …), a 1D-CNN and a ResNet on IGTD images. +- **Hyperparameter optimization**: Automatically tunes hyperparameters using Bayesian Optimization (Hyperopt TPE), with a search space per model and per dataset size. +- **Fits your time budget**: `models: auto` measures your machine and picks the models, trials and time limits that fit, and tells you what it skipped and why. Runtime estimates before anything is trained, live ETA while it runs. +- **Data configuration**: Only a path and a target column are needed. Problem type, metric, column types and preprocessing are inferred; CSV, Parquet, Excel, JSON, built-in datasets and OpenML work out of the box. +- **Web app, CLI and Python API**: the same experiments from a browser, a terminal or a notebook. +- **Ready-to-use models**: the best model of each dataset is saved with its preprocessing. Load it and call `predict` on new rows, or use `autodeep predict`. +- **Output handling**: Saves the results of experiments, including evaluation metrics, every trial and the best hyperparameters, in CSV format. +- **Easy integration**: Simple to configure and extend with additional models or datasets. --- -## Install +## Installation You need Python 3.10 – 3.13. A GPU is optional. +1. Clone the repository: + ```bash git clone https://github.com/mdicio/AutoDeep.git cd AutoDeep ``` -**With [uv](https://docs.astral.sh/uv/) (recommended, uses the exact tested versions from `uv.lock`):** +2. Install the dependencies. **With [uv](https://docs.astral.sh/uv/)** (recommended, uses the exact tested versions from `uv.lock`): ```bash uv sync @@ -40,7 +67,26 @@ Optional extras: `pip install -e ".[files]"` adds Parquet/Feather/Excel input, ` --- -## Three ways to use it +## Quick start in Python + +```python +from autodeep import AutoRunner + +runner = AutoRunner( + datasets={"churn": {"path": "data/churn.csv", "target": "churned"}}, + time_budget="10m", # AutoDeep picks the models that fit 10 minutes on this machine +) +leaderboard = runner.run() # pandas DataFrame, best test score first + +model = runner.best_model("churn") # saved with its preprocessing in output/models/churn/best +model.predict(new_customers) # original labels, one per row +``` + +That is all you need. The sections below show the three ways to use AutoDeep in more detail. + +--- + +## How to Use ### 1. Web app @@ -51,21 +97,32 @@ autodeep ui This opens `http://127.0.0.1:8765` (or the next free port). Then: 1. **Datasets.** Add a built-in example, upload a CSV/TSV/Parquet/Excel/JSON file, or point to a local path or `openml:`. The target, problem type and metric are detected; you can change them, set a split column, subsample, and untick columns to exclude (IDs and free text are flagged for you). -2. **Models.** Pick models one by one or use a preset (Fast, Default, Deep, All). -3. **Settings and estimate.** Set trials per model, an optional time budget, a max-epochs cap and the device. The estimated runtime updates as you change things. +2. **Models.** **Auto** (the default) picks the models, trials and time limits that fit your time budget on this machine and tells you why it skipped the others. Or pick models one by one, or use a preset (Fast, Default, Modern, Deep, All). +3. **Settings and estimate.** Set trials per model, a time limit per model, a max-epochs cap and the device (Auto fills these in). The estimated runtime updates as you change things. 4. **Run.** Each experiment runs in its own background process. You get a live progress bar with an ETA, an activity feed, the log, and a leaderboard that fills in as models finish. You can stop a run at any time, close the browser and come back later, and download the results as CSV. +5. **Use the model.** The best model of each dataset is saved. Download it, or upload a file and get its predictions back as CSV. Uploaded files and runs are stored in `./autodeep_workspace` (change it with `--workspace`). Everything stays on your machine. +| Set up an experiment | Watch it run | +|---|---| +| ![Datasets, the Auto plan and the model picker](images/ui_new_experiment.png) | ![Live progress, leaderboard and activity feed](images/ui_run_progress.png) | + +![A finished run: the saved best model, ready to download or predict a file, and the leaderboard](images/ui_results.png) + ### 2. Command line ```bash autodeep models # what can I train? autodeep datasets # built-in datasets autodeep profile data/churn.csv --target churned # column types, missing values, inferred problem type -autodeep estimate examples/experiment.yaml # how long will it take? -autodeep run examples/experiment.yaml # shows the estimate, asks to confirm, then runs with live progress +autodeep system # cores, RAM, GPU and CPU speed as AutoDeep sees them +autodeep estimate data/churn.csv --target churned --budget 20m # the automatic plan and how long it takes +autodeep run data/churn.csv --target churned --budget 20m # shows the plan, asks to confirm, runs with live progress +autodeep run examples/experiment.yaml # several datasets and options in a YAML file autodeep run examples/experiment.yaml --models fast --max-evals 5 --max-epochs 20 -y +autodeep predict output/models/churn/best new.csv -o predictions.csv # use the saved best model +autodeep info output/models/churn/best # its input columns, scores and parameters ``` An experiment file looks like this (full commented version: [`examples/experiment.yaml`](examples/experiment.yaml)): @@ -78,38 +135,87 @@ datasets: path: data/churn.csv target: churned drop_columns: [customer_id] -models: [xgb, catboost, fttransformer] # or: fast | default | modern | deep | all -max_evals: 20 -timeout_per_model: 600 # seconds, optional +models: auto # default; or [xgb, catboost, fttransformer], or a preset +time_budget: 20m # whole run output_folder: results ``` ### 3. Python +#### Prepare the data configuration + +Define the datasets you want to run experiments on in the `datasets` dictionary. Each dataset needs a `path` and a `target` column; everything else (problem type, metric, test size, split column, evaluation metrics, …) is optional and listed in [Defining datasets](#defining-datasets). + +#### Define the models to use + +`models="auto"` (the default) chooses for you within `time_budget`. You can also give a list such as `["xgb", "catboost", "mlp"]`, or a preset (`"fast"`, `"default"`, `"modern"`, `"deep"`, `"all"`). The supported models are listed in [Models](#models). + +#### Initialize AutoRunner and run the experiment + ```python -from autodeep import AutoRunner, ResultsAnalyzer +from autodeep import AutoRunner runner = AutoRunner( datasets={ "iris": {"path": "builtin:iris"}, "churn": {"path": "data/churn.csv", "target": "churned", "drop_columns": ["customer_id"]}, }, - models=["xgb", "catboost", "fttransformer"], - max_evals=20, - output_folder="results", + time_budget="20m", # models="auto": what fits 20 minutes on this machine + # models=["xgb", "catboost", "fttransformer"], max_evals=20, # ...or choose yourself + output_folder="results", # where you want experiment outputs and logs to be saved + random_state=42, ) +print(runner.plan().describe()) # chosen models, trials, time limits and why print(runner.estimate()) # runtime estimate per (dataset, model) leaderboard = runner.run() # pandas DataFrame, best test score first +model = runner.best_model("churn") # saved in results/models/churn/best +model.predict(new_customers) # original labels +model.predict_proba(new_customers) # one column per class +``` + +This will start the training and evaluation of models on the specified datasets. The results will be saved in the output folder. + +#### View results + +After the experiment finishes, the results are saved in a CSV format in the `output_folder`, including performance metrics (train, validation, test) and hyperparameters. `ResultsAnalyzer` reads them back, also later from another session: + +```python +from autodeep import ResultsAnalyzer + analyzer = ResultsAnalyzer(runner.results_path) -analyzer.view_performance(dataset_name="churn") -analyzer.view_parameters(model_name="xgb") +analyzer.view_results(dataset_name="churn", model_name="xgb") # key columns, metrics and hyperparameters +analyzer.view_performance(dataset_name="churn") # performance columns only +analyzer.view_parameters(model_name="xgb") # hyperparameter columns only ``` +All three filter by `dataset_name` and `model_name`. + See [`examples/quickstart.py`](examples/quickstart.py) and the notebook [`examples/walkthrough.ipynb`](examples/walkthrough.ipynb). The original constructor arguments (`data_config=`, `default_models=`, `dataset_path`/`target_col` keys) still work. --- +## Using the trained model + +After a run, the best model of each dataset (highest validation score; the test set is never used to choose) is saved with everything needed to use it: the preprocessing fitted on the training data, the model and the original class labels. + +```python +import autodeep + +model = autodeep.load_model("results/models/churn/best") # device="cpu" | "cuda" | "auto" +model.predict(df) # labels / values, one per row +model.predict_proba(df) # DataFrame, one column per class +model.predict_frame(df) # prediction + proba_ columns, aligned with df +model.evaluate(labelled_df) # metrics on rows that include the target column +model.info # dataset, model, scores, parameters, input columns +``` + +`df` needs the columns the model was trained on (extra columns, including the target, are ignored). Missing values, categories never seen in training and numbers stored as text are handled the same way as during training. From the command line: `autodeep predict new.csv -o predictions.csv`. In the web app: the "Use the best models" card of a run. + +`save_models=True` saves every model, not only the best one (`results/models//`); `save_best=False` turns saving off. A saved model is a folder with `predictor.pt` and a readable `info.json`. It is a pickle, so only load models from sources you trust. Models trained on a GPU load on machines without one. TabICL keeps its training rows as context (that is how it predicts), so its saved file contains them; its pretrained weights are re-downloaded from Hugging Face if they are not cached. + +--- + ## Defining datasets Only `path` and `target` are required; everything else is inferred or has a default. @@ -133,7 +239,7 @@ Only `path` and `target` are required; everything else is inferred or has a defa - Missing values are imputed using statistics from the training split only (median or mode). - Classification targets are label-encoded. The original labels are kept. - Column names are sanitised. -- Categorical columns are passed natively to CatBoost and the PyTorch Tabular models, and one-hot encoded for XGBoost, the MLP and the CNNs. Rare levels are grouped beyond the 30 most frequent. +- Categorical columns are passed natively to CatBoost and the embedding-based deep tabular models, and one-hot encoded for XGBoost, the MLP and the CNNs. Rare levels are grouped beyond the 30 most frequent. - Numeric features are standardised. **Built-in datasets:** `iris`, `wine`, `breast_cancer`, `diabetes`, `digits`, `synthetic_mixed` (numeric, categorical and boolean columns with missing values) and `california_housing` (downloaded once). @@ -145,28 +251,34 @@ Only `path` and `target` are required; everything else is inferred or has a defa | Name | Model | Family | |---|---|---| | `xgb` | XGBoost | gradient-boosted trees | +| `lgbm` | LightGBM | gradient-boosted trees | | `catboost` | CatBoost | gradient-boosted trees | | `tabicl` | [TabICLv2](https://github.com/soda-inria/tabicl), a pretrained in-context learner: no training, no tuning | foundation model | | `realmlp` | [RealMLP](https://github.com/dholzmueller/pytabkit) (tuned-default MLP with numerical embeddings) | neural network | | `tabm` | [TabM](https://github.com/yandex-research/tabm) (parameter-efficient MLP ensemble) | neural network | +| `resmlp` | Residual MLP (PyTorch); can start from another model's prediction via an offset column | neural network | | `mlp` | scikit-learn MLP | neural network | | `s1dcnn` | Soft-Ordering 1D-CNN | neural network | -| `categoryembedding` | Category-embedding MLP | PyTorch Tabular | -| `fttransformer` | FT-Transformer | PyTorch Tabular | -| `tabtransformer` | TabTransformer | PyTorch Tabular | -| `tabnet` | TabNet | PyTorch Tabular | -| `autoint` | AutoInt | PyTorch Tabular | -| `gandalf` | GANDALF | PyTorch Tabular | -| `gate` | GATE | PyTorch Tabular | -| `node` | NODE | PyTorch Tabular | -| `danet` | DANet | PyTorch Tabular | +| `categoryembedding` | Category-embedding MLP | deep tabular | +| `fttransformer` | FT-Transformer | deep tabular | +| `tabtransformer` | TabTransformer | deep tabular | +| `tabnet` | TabNet | deep tabular | +| `autoint` | AutoInt | deep tabular | +| `gandalf` | GANDALF | deep tabular | +| `gate` | GATE | deep tabular | +| `node` | NODE | deep tabular | +| `danet` | DANet | deep tabular | | `resnet` | ResNet-18/34/50 on [IGTD](https://doi.org/10.1038/s41598-021-90923-y) images | tabular-as-image | -**Presets:** `fast` = xgb, catboost, mlp · `default` = fast + tabicl, realmlp, categoryembedding, fttransformer, gandalf · `modern` = tabicl, realmlp, tabm · `deep` = realmlp, tabm and all PyTorch Tabular models · `all`. +**Auto (default):** AutoDeep picks models in order of expected value for the device (on CPU: xgb, catboost, lgbm, tabicl, realmlp, gandalf, categoryembedding, tabm, fttransformer, mlp; on a GPU the deep models move up) and keeps each one whose minimum search (1 TabICL pass, 10 trials for boosted trees, 3 for neural networks) fits in its share of `time_budget` (default 15 minutes), with no model taking more than half of it. Every model then gets up to 30 trials and the same time limit, chosen so fast models finish all their trials and slow ones use the remaining time. `autodeep estimate` (or `runner.plan()`) shows the plan and why each skipped model was skipped. Explicit `max_evals` / `timeout_per_model` override the plan. + +**Presets:** `fast` = xgb, lgbm, catboost, mlp · `default` = fast + tabicl, realmlp, categoryembedding, fttransformer, gandalf · `modern` = tabicl, realmlp, tabm · `deep` = realmlp, tabm and the nine deep tabular models · `all`. + +**Which deep models to try first?** On the [TabArena](https://huggingface.co/spaces/TabArena/leaderboard) benchmark, TabICLv2, RealMLP and TabM are among the strongest tabular models, ahead of the older deep tabular architectures (which TabArena does not include). In AutoDeep's own [benchmark](benchmarks/README.md) on three datasets of 20,000-50,000 rows, TabICLv2 was the best model on two of them without any tuning, and tuned CatBoost/XGBoost won on the third (adult, mostly categorical). -**Which deep models to try first?** On the [TabArena](https://huggingface.co/spaces/TabArena/leaderboard) benchmark, TabICLv2, RealMLP and TabM are among the strongest tabular models, ahead of the PyTorch Tabular architectures (which TabArena does not include). +The nine deep tabular architectures were ported from [PyTorch Tabular](https://github.com/manujosephv/pytorch_tabular) (MIT) to plain PyTorch modules in `autodeep/modelsdefinition/tabular_nets/`, and are trained by AutoDeep's own loop (early stopping, best weights kept in memory). Hyperparameter names are the same as in PyTorch Tabular's model configs. AutoDeep no longer depends on PyTorch Tabular, which pins `pandas<3`. -- **TabICLv2** makes predictions in one forward pass with the training rows as context, so a search always runs a single trial whatever `max_evals` is. Its weights (~110 MB, one checkpoint for classification and one for regression) are downloaded from Hugging Face on first use. It is quick on a GPU but slow on CPU, because prediction cost grows with rows × context. Training sets above 50,000 rows are subsampled to that size for the context (`max_context_rows`). +- **TabICLv2** makes predictions in one forward pass with the training rows as context, so a search always runs a single trial whatever `max_evals` is. Its weights (~110 MB, one checkpoint for classification and one for regression) are downloaded from Hugging Face on first use. It is quick on a GPU but slow on CPU, because prediction cost grows with rows × context. Validation scores come from the usual 80% split, and test predictions then use every training row as context. Its train metrics are not reported, because they would score the context rows against themselves. Training sets above 50,000 rows are subsampled to that size for the context (`max_context_rows`). The estimate warns when TabICL, TabM or the CNNs would take more than 5 minutes on CPU. - **RealMLP** and **TabM** come from [pytabkit](https://github.com/dholzmueller/pytabkit). The first trial always uses the published tuned defaults (RealMLP-TD, TabM-D), and later trials search around them. In a `param_grid`, `null` means "the library's default". - All three handle categorical columns and feature scaling themselves. @@ -184,7 +296,7 @@ Search spaces live in [`autodeep/configuration/model_config.yml`](autodeep/confi Before anything is trained, AutoDeep estimates how long each (dataset, model) search will take: -1. **Built-in cost curves** per model, measured on a 12-thread CPU. They scale with rows, features, epochs and the device. +1. **Built-in cost curves** per model, measured on a 12-thread CPU. They scale with rows, features, epochs and the device. On a new machine they are scaled by a ~0.5 s CPU benchmark (cached for 30 days in `~/.cache/autodeep/machine.json`; `autodeep system --benchmark` re-runs it). 2. **Your machine's history.** Every finished trial is recorded in `~/.cache/autodeep/timings.jsonl`, and later estimates are rescaled to how fast your hardware actually was. The estimate table shows `history (n trials)` when this applies. 3. **A live ETA** during the run, recomputed after every trial from the observed trial times. @@ -201,7 +313,8 @@ Everything is written to `output_folder` (default `./output`): | `experiments.csv` | One row per (dataset, model): status, validation and test score, all metrics (JSON), best hyperparameters, duration, error if any | | `trials/__.csv` | Every hyperparameter trial with its train/validation metrics and duration | | `autodeep.log` | Full log | -| `models/` | Best model per run, if `save_models=True` | +| `models//best/` | The best model of each dataset, ready for `autodeep.load_model` / `autodeep predict` | +| `models///` | Every model, if `save_models=True` | A model that fails is recorded with its error, and the run continues with the next one. Use `fail_fast=True` to stop at the first failure instead. @@ -221,7 +334,6 @@ A model that fails is recorded with its error, and the run continues with the ne | Port already in use | `autodeep ui` picks the next free port automatically; `--port` forces one | | Very slow deep models on CPU | Set `max_epochs` (e.g. 30), fewer `max_evals`, or `max_rows` on the dataset | | TabICL fails to download its weights | It needs internet access once (Hugging Face Hub). Afterwards the weights are cached in `~/.cache/huggingface` | -| `ModuleNotFoundError: pkg_resources` | Your environment has setuptools ≥ 81: `pip install "setuptools<81"` (hyperopt needs it) | | Parquet / Excel files fail to load | `pip install -e ".[files]"` | --- @@ -234,14 +346,27 @@ uv run pytest # fast suite (~1 min); CI runs it on Python 3.10 and uv run pytest -m slow # trains every model on each problem type (a few minutes on CPU) ``` -Code map: `autodeep/automl.py` (AutoRunner), `datasets.py` (dataset specs and inference), `dataloaders/` (preprocessing and IGTD), `modelsdefinition/` (one trainer per model on a shared search loop), `modelutils/search.py` (hyperopt driver), `estimation.py`, `registry.py`, `cli.py`, `jobs.py`, `web/` (FastAPI server and single-page UI). +## Repository Structure -See [CHANGELOG.md](CHANGELOG.md) for what changed in 0.2.0. +The repository is organized as follows: + +- `autodeep/` – Core library: `automl.py` (AutoRunner), `datasets.py` (dataset specs and inference), `preprocessing.py` (fitted, replayable preprocessing), `predictor.py` (saved models), `autoplan.py` + `machine.py` (automatic plan and machine profile), `estimation.py`, `registry.py`, `cli.py`, `jobs.py`. +- `autodeep/modelsdefinition/` – One trainer per model on a shared hyperopt search loop (`autodeep/modelutils/search.py`); the deep tabular networks are in `tabular_nets/`. +- `autodeep/dataloaders/` – Data loading and IGTD images. +- `autodeep/configuration/` – Search spaces and default settings per model (`model_config.yml`, `model_config_XS.yml`). +- `autodeep/web/` – FastAPI server and single-page web app. +- `examples/` – A quickstart script, a walkthrough notebook and a commented experiment file. +- `benchmarks/` – Benchmark scripts and results. +- `tests/` – Test suite. + +See [CHANGELOG.md](CHANGELOG.md) for what changed in each release. ## License -MIT. See [LICENCE](LICENCE). +This project is licensed under the MIT License. See the [LICENCE](LICENCE) file for details. + +## Acknowledgments -## Acknowledgements +This library builds on top of several popular open-source projects, including [TabICL](https://github.com/soda-inria/tabicl), [pytabkit](https://github.com/dholzmueller/pytabkit), [Hyperopt](https://github.com/hyperopt/hyperopt), [XGBoost](https://xgboost.ai), [LightGBM](https://lightgbm.readthedocs.io), [CatBoost](https://catboost.ai), [PyTorch](https://pytorch.org) (obviously) and the [IGTD](https://github.com/zhuyitan/IGTD) algorithm. -Built on [PyTorch Tabular](https://github.com/manujosephv/pytorch_tabular), [TabICL](https://github.com/soda-inria/tabicl), [pytabkit](https://github.com/dholzmueller/pytabkit), [Hyperopt](https://github.com/hyperopt/hyperopt), [XGBoost](https://xgboost.ai), [CatBoost](https://catboost.ai), [PyTorch](https://pytorch.org) and the [IGTD](https://github.com/zhuyitan/IGTD) algorithm. Special thanks to PyTorch Tabular for its intuitive API for deep learning on tabular data. +Special thanks to [PyTorch Tabular](https://github.com/manujosephv/pytorch_tabular) (Manu Joseph, MIT licence), which provided a very intuitive API for deep learning models on tabular data: the deep tabular architectures in AutoDeep are adapted from it, and TabNet uses [pytorch-tabnet](https://github.com/dreamquark-ai/tabnet)'s network. If the owner ever sees this I would be honoured to try and integrate some of the AutoDeep functionalities in the project. diff --git a/autodeep/__init__.py b/autodeep/__init__.py index 0a1b2ff..b5a4633 100644 --- a/autodeep/__init__.py +++ b/autodeep/__init__.py @@ -7,9 +7,11 @@ runner = AutoRunner(datasets={"iris": {"path": "builtin:iris"}}, models="fast", max_evals=10) print(runner.estimate()) print(runner.run()) + model = runner.best_model("iris") # saved to output/models/iris/best + model.predict(new_rows) # later: autodeep.load_model("output/models/iris/best") """ -__version__ = "0.3.0" +__version__ = "0.5.0" from autodeep.datasets import BUILTIN_DATASETS, DatasetSpec, list_builtin_datasets # noqa: E402 from autodeep.registry import DEFAULT_MODELS, PRESETS, list_models # noqa: E402 @@ -21,6 +23,10 @@ def __getattr__(name): from autodeep.automl import AutoRunner return AutoRunner + if name in ("Predictor", "load_model"): + from autodeep import predictor + + return getattr(predictor, name) if name == "ResultsAnalyzer": from autodeep.outputhandler.resultanalyzer import ResultsAnalyzer @@ -28,4 +34,15 @@ def __getattr__(name): raise AttributeError(f"module 'autodeep' has no attribute '{name}'") -__all__ = ["AutoRunner", "DatasetSpec", "ResultsAnalyzer", "list_models", "list_builtin_datasets", "BUILTIN_DATASETS", "DEFAULT_MODELS", "PRESETS"] +__all__ = [ + "AutoRunner", + "DatasetSpec", + "Predictor", + "load_model", + "ResultsAnalyzer", + "list_models", + "list_builtin_datasets", + "BUILTIN_DATASETS", + "DEFAULT_MODELS", + "PRESETS", +] diff --git a/autodeep/automl.py b/autodeep/automl.py index bb68b3a..6b1e169 100755 --- a/autodeep/automl.py +++ b/autodeep/automl.py @@ -7,9 +7,10 @@ import json import time import traceback +from collections.abc import Callable from datetime import datetime from pathlib import Path -from typing import Any, Callable, Dict, List, Optional, Union +from typing import Any from uuid import uuid4 import numpy as np @@ -21,7 +22,7 @@ from autodeep.device import apply_device_policy, resolve_device, set_device from autodeep.evaluation.generalevaluator import METRICS, Evaluator from autodeep.logging_utils import get_logger, setup_logging -from autodeep.registry import DEFAULT_MODELS, resolve_models +from autodeep.registry import resolve_models CONFIG_DIR = Path(__file__).parent / "configuration" DEFAULT_MODEL_CONFIG_FILE = CONFIG_DIR / "model_config.yml" @@ -59,16 +60,16 @@ logger = get_logger() -def _load_yaml(path) -> Dict: - with open(path, "r") as f: +def _load_yaml(path) -> dict: + with open(path) as f: return yaml.safe_load(f) def _json(value) -> str: def default(o): - if isinstance(o, (np.integer,)): + if isinstance(o, np.integer): return int(o) - if isinstance(o, (np.floating,)): + if isinstance(o, np.floating): return float(o) if isinstance(o, np.ndarray): return o.tolist() @@ -90,16 +91,24 @@ class AutoRunner: runner = AutoRunner( datasets={"iris": {"path": "builtin:iris"}, "mine": {"path": "data.csv", "target": "label"}}, - models=["xgb", "catboost", "fttransformer"], # or a preset: "fast", "default", "modern", "deep", "all" - max_evals=20, + time_budget="20m", # models="auto" (default): pick what fits this machine in 20 minutes ) - print(runner.estimate()) # how long will it take? + print(runner.plan().describe()) # which models and why + print(runner.estimate()) # how long will it take? leaderboard = runner.run() + runner.best_model("mine").predict(new_rows) + + # or choose yourself: models=["xgb", "catboost", "fttransformer"] or a preset + # ("fast", "default", "modern", "deep", "all"), max_evals=20 Args: datasets / data_config: ``{name: {...}}`` dict, list of dicts or :class:`DatasetSpec` objects. - models / default_models: model names or a preset name. - max_evals: hyperparameter-search trials per (dataset, model). + models / default_models: ``"auto"`` (default: pick models that fit ``time_budget`` on this machine, + see :mod:`autodeep.autoplan`), model names or a preset name. + time_budget: total time for the run, in seconds or as text (``"20m"``, ``"1h"``). With ``models="auto"`` + it decides the models, trials and time limits (default 15 minutes); with explicit models it sets + ``timeout_per_model`` (budget / number of searches) unless that is given. + max_evals: hyperparameter-search trials per (dataset, model) (default: from the auto plan, else 25). timeout_per_model: optional time budget in seconds for each (dataset, model) search. max_epochs: optional cap on training epochs of every neural model (great for quick runs). model_config: path or dict overriding the bundled search spaces for every dataset. By default @@ -107,7 +116,12 @@ class AutoRunner: device: ``"auto"`` (GPU if available with enough free memory), ``"cpu"`` or ``"cuda"``. on_event: callback receiving progress events (dicts) - used by the CLI and the web UI. fail_fast: raise on the first failing model instead of recording the error and continuing. - save_models: also store the best model of every run under ``/models``. + save_best: save the best model of each dataset (highest validation score) to + ``/models//best``, ready for :func:`autodeep.load_model` / ``autodeep predict``. + save_models: also save every trained model to ``/models//``. + + After :meth:`run`, :meth:`best_model` returns the best model of a dataset as a + :class:`~autodeep.predictor.Predictor` (preprocessing + model): ``runner.best_model("churn").predict(new_rows)``. """ def __init__( @@ -118,32 +132,42 @@ def __init__( datasets=None, models=None, execution_mode: str = "hyperopt", - max_evals: int = 25, + max_evals: int | None = None, random_state: int = 42, - model_config: Union[str, Path, Dict, None] = None, - output_folder: Union[str, Path] = DEFAULT_OUTPUT_FOLDER, + model_config: str | Path | dict | None = None, + output_folder: str | Path = DEFAULT_OUTPUT_FOLDER, output_filename: str = "experiments", - igtd_path: Union[str, Path, None] = None, - igtd_config: Optional[Dict] = None, - timeout_per_model: Optional[float] = None, - max_epochs: Optional[int] = None, + igtd_path: str | Path | None = None, + igtd_config: dict | None = None, + timeout_per_model: float | None = None, + max_epochs: int | None = None, device: str = "auto", - on_event: Optional[Callable[[Dict], None]] = None, + on_event: Callable[[dict], None] | None = None, fail_fast: bool = False, save_models: bool = False, + save_best: bool = True, + time_budget: None | float | str = None, log_level: str = "INFO", ): if execution_mode != "hyperopt": raise ValueError("Only execution_mode='hyperopt' is implemented.") - self.datasets: List[DatasetSpec] = parse_datasets(datasets if datasets is not None else data_config) + self.datasets: list[DatasetSpec] = parse_datasets(datasets if datasets is not None else data_config) names = [d.name for d in self.datasets] if len(set(names)) != len(names): raise ValueError(f"Dataset names must be unique, got {names}") - self.models: List[str] = resolve_models(models if models is not None else (default_models if default_models is not None else DEFAULT_MODELS)) + from autodeep.autoplan import parse_duration + + requested = models if models is not None else default_models + self.auto = requested is None or (isinstance(requested, str) and requested.strip().lower() == "auto") + self.models: list[str] = [] if self.auto else resolve_models(requested) # auto: filled in by plan() self.execution_mode = execution_mode - self.max_evals = int(max_evals) + self.time_budget = parse_duration(time_budget) + self._user_max_evals = None if max_evals is None else int(max_evals) + self._user_timeout = timeout_per_model + self.max_evals = self._user_max_evals or 25 if self.max_evals < 1: raise ValueError("max_evals must be >= 1") + self.auto_plan = None self.random_state = random_state self.user_model_config = self._load_model_config(model_config) if model_config is not None else None self.output_folder = Path(output_folder) @@ -155,10 +179,13 @@ def __init__( self.device = device self.on_event = on_event self.fail_fast = fail_fast - self.save_models = save_models + self.save_models = bool(save_models) + self.save_best = bool(save_best) + self.best_models: dict[str, Any] = {} # dataset -> Predictor (best validation score) + self.best_model_paths: dict[str, Path] = {} self.log_level = log_level - self.results: List[Dict[str, Any]] = [] - self.trained_models: Dict[tuple, Any] = {} + self.results: list[dict[str, Any]] = [] + self.trained_models: dict[tuple, Any] = {} self.run_id = None # backwards-compatible attribute names @@ -171,7 +198,7 @@ def data_config(self): return {d.name: d.as_legacy_dict() for d in self.datasets} @classmethod - def from_yaml(cls, path, **overrides) -> "AutoRunner": + def from_yaml(cls, path, **overrides) -> AutoRunner: """Build a runner from an experiment YAML file (see ``examples/experiment.yaml``).""" cfg = _load_yaml(path) or {} base = Path(path).resolve().parent @@ -189,7 +216,7 @@ def from_yaml(cls, path, **overrides) -> "AutoRunner": # ------------------------------------------------------------------ config @staticmethod - def _load_model_config(cfg) -> Dict: + def _load_model_config(cfg) -> dict: if isinstance(cfg, dict): return copy.deepcopy(cfg) return _load_yaml(cfg) @@ -197,7 +224,7 @@ def _load_model_config(cfg) -> Dict: def _load_config(self, path): # backwards compatibility return _load_yaml(path) - def model_config_for(self, n_train_rows: int) -> Dict: + def model_config_for(self, n_train_rows: int) -> dict: if self.user_model_config is not None: return self.user_model_config path = XS_MODEL_CONFIG_FILE if n_train_rows <= XS_MAX_TRAIN_ROWS else DEFAULT_MODEL_CONFIG_FILE @@ -213,11 +240,45 @@ def estimate(self, as_dataframe: bool = True): df = spec.read() spec.resolve(df) shapes.append(shape_from_spec(spec, df)) + device = self._device() + self._plan_settings(shapes, device) plan = estimate_plan( - shapes, self.models, self.max_evals, timeout_per_model=self.timeout_per_model, max_epochs=self.max_epochs, device=self._device() + shapes, + self.models, + self.max_evals, + timeout_per_model=self.timeout_per_model, + max_epochs=self.max_epochs, + device=device, + speed_factor=self._speed_factor(), ) return plan.to_dataframe() if as_dataframe else plan + @staticmethod + def _speed_factor() -> float: + from autodeep.machine import current_speed_factor + + return current_speed_factor() + + def _plan_settings(self, shapes, device) -> None: + """Resolve ``models="auto"`` and ``time_budget`` into models, max_evals and timeout_per_model.""" + if self.auto: + from autodeep.autoplan import recommend + from autodeep.machine import machine_profile + + self.auto_plan = recommend( + shapes, self.time_budget, device=device, speed_factor=self._speed_factor(), max_epochs=self.max_epochs, machine=machine_profile() + ) + self.models = self.auto_plan.models + self.max_evals = self._user_max_evals or self.auto_plan.max_evals + self.timeout_per_model = self._user_timeout if self._user_timeout is not None else self.auto_plan.timeout_per_model + elif self.time_budget and self._user_timeout is None: + self.timeout_per_model = round(self.time_budget / max(len(shapes) * len(self.models), 1), 1) + + def plan(self): + """The automatic plan (models, trials, time limit and the reasons), for ``models="auto"``.""" + self.estimate(as_dataframe=False) + return self.auto_plan + def _device(self): set_device(self.device) return resolve_device() @@ -231,6 +292,9 @@ def run(self) -> pd.DataFrame: setup_logging(self.log_level, log_file=self.output_folder / "autodeep.log") set_device(self.device) device = apply_device_policy() # before anything initialises CUDA + # pin the device for the whole run: with "auto", every lookup would query nvidia-smi again and a run + # could switch to CPU halfway once its own GPU allocations shrink the free memory + set_device(device) self.run_id = datetime.now().strftime("%Y%m%d-%H%M%S-") + uuid4().hex[:6] from autodeep.factory import seed_everything @@ -243,7 +307,18 @@ def run(self) -> pd.DataFrame: spec.resolve(df) frames[spec.name] = df shapes = [shape_from_spec(s, frames[s.name]) for s in self.datasets] - plan = estimate_plan(shapes, self.models, self.max_evals, timeout_per_model=self.timeout_per_model, max_epochs=self.max_epochs, device=device) + self._plan_settings(shapes, device) + if self.auto_plan is not None: + logger.info("Automatic plan:\n" + self.auto_plan.describe()) + plan = estimate_plan( + shapes, + self.models, + self.max_evals, + timeout_per_model=self.timeout_per_model, + max_epochs=self.max_epochs, + device=device, + speed_factor=self._speed_factor(), + ) tracker = RunTracker(plan, device=device, max_epochs=self.max_epochs) def reporter(evt): @@ -258,6 +333,9 @@ def reporter(evt): f"Run {self.run_id}: {len(self.datasets)} dataset(s) x {len(self.models)} model(s), {self.max_evals} trial(s) each, " f"device={device}. Estimated time: {plan.human_total()}. Outputs -> {self.output_folder.resolve()}" ) + for job in plan.jobs: + if job.warning: + logger.warning(f"{job.model} on {job.dataset}: {job.warning}") progress.emit( "run_start", run_id=self.run_id, @@ -266,12 +344,13 @@ def reporter(evt): max_evals=self.max_evals, device=device, plan=plan.to_records(), + auto_plan=self.auto_plan.reasons if self.auto_plan is not None else None, ) cancelled = False try: for spec, shape in zip(self.datasets, shapes): model_cfg = self.model_config_for(shape.n_train) - cache: Dict[tuple, tuple] = {} + cache: dict[tuple, tuple] = {} for model_name in self.models: try: self._run_one(spec, frames[spec.name], model_name, model_cfg, cache, device) @@ -279,11 +358,14 @@ def reporter(evt): cancelled = True break frames[spec.name] = None + cache.clear() + self._save_best(spec.name) if cancelled: break finally: progress.emit("run_end", run_id=self.run_id, cancelled=cancelled, n_results=len(self.results)) progress.set_reporter(previous) + set_device(self.device) board = self.leaderboard() if not board.empty: logger.info("Leaderboard:\n" + board.to_string(index=False, max_colwidth=40)) @@ -311,14 +393,14 @@ def _get_data(self, spec, df, model_name, model_cfg, cache): ) if run_igtd: progress.emit("stage", stage="igtd", dataset=spec.name, model=model_name, message="Computing IGTD image layout") - cache[key] = loader.load_data() + cache[key] = (*loader.load_data(), loader.preprocessor) return cache[key] def _run_one(self, spec: DatasetSpec, df, model_name, model_cfg, cache, device): from autodeep.factory import create_model t0 = time.perf_counter() - row: Dict[str, Any] = { + row: dict[str, Any] = { "run_id": self.run_id, "timestamp": datetime.now().isoformat(timespec="seconds"), "dataset": spec.name, @@ -334,7 +416,7 @@ def _run_one(self, spec: DatasetSpec, df, model_name, model_cfg, cache, device): cfg = (model_cfg.get("model_configs", {}) or {}).get(model_name) if not cfg: raise ValueError(f"No configuration for model '{model_name}' in the model config file") - X_train, X_test, y_train, y_test, extra_info = self._get_data(spec, df, model_name, model_cfg, cache) + X_train, X_test, y_train, y_test, extra_info, preprocessor = self._get_data(spec, df, model_name, model_cfg, cache) row.update(n_train=len(X_train), n_test=len(X_test), n_features=X_train.shape[1]) trainer = create_model(model_name, problem_type=spec.problem_type, random_state=self.random_state) trainer.output_dir = self.output_folder / "tmp" @@ -371,8 +453,7 @@ def _run_one(self, spec: DatasetSpec, df, model_name, model_cfg, cache, device): n_failed_trials=sr.n_failed, ) self._write_trials(spec.name, model_name, sr.trials) - if self.save_models: - self._save_model(trainer, spec.name, model_name) + self._keep_model(spec, model_name, trainer, preprocessor, extra_info, row) self.trained_models[(spec.name, model_name)] = trainer if self.save_models else None logger.info(f"{model_name} on {spec.name}: validation {spec.metric}={best_score:.5f}, test {spec.metric}={row['test_score']:.5f}") except progress.RunCancelled: @@ -408,7 +489,7 @@ def results_path(self) -> Path: def _write_result(self, row): path = self.results_path - flat = {k: (_json(v) if isinstance(v, (dict, list)) else v) for k, v in row.items()} + flat = {k: (_json(v) if isinstance(v, dict | list) else v) for k, v in row.items()} new = pd.DataFrame([flat]).reindex(columns=RESULT_FIELDS) if path.exists() and path.stat().st_size > 0: header = pd.read_csv(path, nrows=0).columns.tolist() @@ -429,24 +510,90 @@ def _write_trials(self, dataset, model, trials): for t in trials: t = dict(t) params = t.pop("params", {}) or {} - rows.append({"run_id": self.run_id, **t, **{f"param_{k}": (_json(v) if isinstance(v, (dict, list)) else v) for k, v in params.items()}}) + rows.append({"run_id": self.run_id, **t, **{f"param_{k}": (_json(v) if isinstance(v, dict | list) else v) for k, v in params.items()}}) path = folder / f"{dataset}__{model}.csv" df = pd.DataFrame(rows) if path.exists(): df = pd.concat([pd.read_csv(path), df], ignore_index=True) df.to_csv(path, index=False) - def _save_model(self, trainer, dataset, model): - folder = self.output_folder / "models" / f"{dataset}__{model}" - folder.mkdir(parents=True, exist_ok=True) + # ------------------------------------------------------------------ trained models + @property + def models_folder(self) -> Path: + return self.output_folder / "models" + + def _keep_model(self, spec, model_name, trainer, preprocessor, extra_info, row): + """Wrap a finished model as a Predictor; keep it if it is the best so far, save it if asked.""" + from autodeep.evaluation.generalevaluator import is_better + from autodeep.predictor import Predictor + from autodeep.registry import MODELS + + if not (self.save_best or self.save_models): + return + info = { + "dataset": spec.name, + "model": model_name, + "model_display_name": MODELS[model_name].display_name if model_name in MODELS else model_name, + "problem_type": spec.problem_type, + "target": spec.target, + "classes": (extra_info or {}).get("classes"), + "metric": spec.metric, + "eval_metrics": list(spec.eval_metrics or []), + "val_score": row.get("best_score"), + "test_score": row.get("test_score"), + "test_metrics": row.get("test_metrics"), + "best_params": row.get("best_params"), + "n_train": row.get("n_train"), + "trained_on_device": row.get("device"), + "run_id": self.run_id, + } + predictor = Predictor(trainer, preprocessor, info) + if self.save_models: + try: + path = predictor.save(self.models_folder / spec.name / model_name) + logger.info(f"Saved {model_name} model to {path}") + except Exception as e: # saving must never lose the results + logger.warning(f"Could not save model {model_name}: {e}") + current = self.best_models.get(spec.name) + score = row.get("best_score") + if score is None or not np.isfinite(score): + return + if current is None or is_better(score, current.info["val_score"], spec.metric): + self.best_models[spec.name] = predictor + + def _save_best(self, dataset: str) -> None: + predictor = self.best_models.get(dataset) + if predictor is None or not self.save_best: + return try: - ext = {"xgb": "model.json", "catboost": "model.cbm", "mlp": "model.joblib", "resnet": "model.pt", "s1dcnn": "model.pt"}.get( - model, "model" + path = predictor.save(self.models_folder / dataset / "best") + self.best_model_paths[dataset] = path + logger.info( + f"Best model for {dataset}: {predictor.model_name} (validation {predictor.info['metric']}={predictor.info['val_score']:.5f}) -> {path}" ) - trainer.save_model(folder / ext) - logger.info(f"Saved best {model} model to {folder}") - except Exception as e: # saving must never lose the results - logger.warning(f"Could not save model {model}: {e}") + progress.emit("model_saved", dataset=dataset, model=predictor.model_name, path=str(path.resolve())) + except Exception as e: + logger.warning(f"Could not save the best model for {dataset}: {e}") + + def best_model(self, dataset: str | None = None): + """The best model of ``dataset`` (highest validation score) as a :class:`~autodeep.predictor.Predictor`. + + ``dataset`` may be omitted when the run has a single dataset. Falls back to the saved copy on disk. + """ + names = [d.name for d in self.datasets] + if dataset is None: + if len(names) != 1: + raise ValueError(f"Several datasets were run, pass one of {names}") + dataset = names[0] + if dataset in self.best_models: + return self.best_models[dataset] + path = self.models_folder / dataset / "best" + if path.exists(): + from autodeep.predictor import Predictor + + self.best_models[dataset] = Predictor.load(path) + return self.best_models[dataset] + raise ValueError(f"No trained model for dataset '{dataset}' (did run() finish at least one model?)") def leaderboard(self) -> pd.DataFrame: """One row per (dataset, model), best test score first within each dataset.""" @@ -457,7 +604,9 @@ def leaderboard(self) -> pd.DataFrame: if c not in df: df[c] = None df = df.rename(columns={"best_score": "val_score"}) - cols = ["dataset", "model", "status", "metric", "val_score", "test_score", "duration_sec", "n_trials", "error"] + best = {ds: p.model_name for ds, p in self.best_models.items()} + df["selected"] = [best.get(ds) == m for ds, m in zip(df["dataset"], df["model"])] + cols = ["dataset", "model", "status", "metric", "val_score", "test_score", "selected", "duration_sec", "n_trials", "error"] df = df[cols] parts = [] for _, g in df.groupby("dataset", sort=False): diff --git a/autodeep/autoplan.py b/autodeep/autoplan.py new file mode 100644 index 0000000..a63b565 --- /dev/null +++ b/autodeep/autoplan.py @@ -0,0 +1,202 @@ +"""Automatic experiment plan: which models, how many trials and what time limit, for *this* machine. + +``models="auto"`` (the default) asks this module for a plan. The idea is simple: + +1. **Time budget.** You give a total budget (default 15 minutes), split evenly over the datasets. +2. **Candidates in order of expected value**, different on CPU and GPU: gradient-boosted trees first, then + TabICLv2 (a pretrained model, one forward pass), RealMLP and TabM (the strongest trainable deep models on + TabArena), then classic deep tabular models. On a GPU the deep models move up. +3. **What fits.** The runtime estimator (built-in cost curves, scaled by this machine's measured CPU speed + or by its own timing history) says how long one trial of each model takes on your data. Models are + added in order while every chosen model still gets its minimum number of trials (1 for TabICL, 10 for + boosted trees, 3 for neural networks) within its share of the budget, and no model needs more than half + of it. A model that would not fit is skipped, and the plan says why. +4. **Settings.** ``max_evals`` is 30 and every model gets the same time limit ``T`` (``timeout_per_model``), + chosen so that ``sum(min(time for 30 trials, T))`` fills the budget: fast models finish all their trials in + seconds and leave the time to the slow ones, which stop at the limit. + +The result is an :class:`AutoPlan` with the chosen settings and plain-language reasons. +""" + +from __future__ import annotations + +import math +import re +from dataclasses import asdict, dataclass, field + +from autodeep.estimation import DatasetShape, TimingHistory, format_duration, seconds_per_trial, setup_seconds + +DEFAULT_TIME_BUDGET = 15 * 60 # seconds, whole run +MAX_TRIALS = 30 +MAX_MODELS = 8 +SLACK = 0.92 # plan for 92% of the budget: the last trial of a model runs past its time limit +MAX_SHARE = 0.5 # no single model may need more than half of a dataset's budget (keeps the comparison diverse) +MIN_TRIALS = {"xgb": 10, "lgbm": 10, "catboost": 10, "mlp": 5, "tabicl": 1} +DEFAULT_MIN_TRIALS = 3 + +# candidates in order of expected value (TabArena results for the modern models, practical experience for the rest) +CPU_ORDER = ["xgb", "catboost", "lgbm", "tabicl", "realmlp", "gandalf", "categoryembedding", "tabm", "fttransformer", "mlp"] +GPU_ORDER = ["tabicl", "xgb", "catboost", "lgbm", "realmlp", "tabm", "fttransformer", "gandalf", "categoryembedding", "mlp"] + + +def parse_duration(value: None | int | float | str) -> float | None: + """Seconds from ``90``, ``"90s"``, ``"15m"``, ``"1h30m"``, ``"1.5h"`` (``None`` stays ``None``).""" + if value is None or value == "": + return None + if isinstance(value, int | float): + return float(value) + text = str(value).strip().lower().replace(" ", "") + if re.fullmatch(r"\d+(\.\d+)?", text): + return float(text) + parts = re.findall(r"(\d+(?:\.\d+)?)(h|hours?|m|min|minutes?|s|sec|seconds?)", text) + if not parts or "".join(n + u for n, u in parts) != text: + raise ValueError(f"Cannot read the duration '{value}' (examples: 600, 90s, 15m, 1h30m)") + unit = {"h": 3600, "m": 60, "s": 1} + return float(sum(float(n) * unit[u[0]] for n, u in parts)) + + +def time_limit(full_seconds: list[float], budget: float, overrun: list[float] | None = None) -> float: + """Common per-model limit ``T`` with ``sum(min(full, T + overrun)) == budget`` (``inf`` when everything fits). + + ``overrun`` is how far a model typically runs past its limit (the running trial finishes: ~half a trial). + """ + overrun = overrun or [0.0] * len(full_seconds) + if sum(full_seconds) <= budget: + return math.inf + + def used(t): + return sum(min(f, t + o) for f, o in zip(full_seconds, overrun)) + + lo, hi = 0.0, max(full_seconds) + for _ in range(60): # bisection: used() is increasing in t + mid = (lo + hi) / 2 + lo, hi = (mid, hi) if used(mid) <= budget else (lo, mid) + return lo + + +@dataclass +class Candidate: + model: str + seconds_per_trial: float + min_trials: int + min_seconds: float # setup + min_trials x seconds_per_trial, on the largest dataset + full_seconds: float # setup + all trials (max_evals, or 1 for TabICL) + source: str + included: bool = False + note: str = "" + + +@dataclass +class AutoPlan: + models: list[str] + max_evals: int + timeout_per_model: float | None + budget_seconds: float + device: str + reasons: list[str] = field(default_factory=list) + candidates: list[Candidate] = field(default_factory=list) + + def settings(self) -> dict: + """The AutoRunner arguments this plan sets.""" + return {"models": list(self.models), "max_evals": self.max_evals, "timeout_per_model": self.timeout_per_model} + + def to_dict(self) -> dict: + d = asdict(self) + d["budget_human"] = format_duration(self.budget_seconds) + return d + + def describe(self) -> str: + return "\n".join(f" - {r}" for r in self.reasons) + + +def recommend( + shapes: list[DatasetShape], + budget_seconds: float | None = None, + device: str = "cpu", + speed_factor: float | None = None, + max_epochs: int | None = None, + history: TimingHistory | None = None, + machine=None, + max_models: int = MAX_MODELS, +) -> AutoPlan: + """Pick models, ``max_evals`` and ``timeout_per_model`` that fit ``budget_seconds`` on this machine.""" + if not shapes: + raise ValueError("recommend() needs at least one dataset") + budget = float(budget_seconds or DEFAULT_TIME_BUDGET) + history = history or TimingHistory() + per_dataset = SLACK * budget / len(shapes) + reasons = [] + if machine is not None: + reasons.append(f"Machine: {machine.describe()}.") + reasons.append( + f"Training on {'the GPU' if device == 'cuda' else 'the CPU'}. Budget {format_duration(budget)}" + + (f", ~{format_duration(budget / len(shapes))} per dataset ({len(shapes)} datasets)." if len(shapes) > 1 else ".") + ) + + largest = max(shapes, key=lambda s: s.n_train * max(s.n_features, 1)) + order = GPU_ORDER if device == "cuda" else CPU_ORDER + cands: list[Candidate] = [] + for model in order: + worst = max(shapes, key=lambda s: seconds_per_trial(model, s, device, max_epochs, history, speed_factor)[0]) + pt, _, _, source = seconds_per_trial(model, worst, device, max_epochs, history, speed_factor) + n_min = MIN_TRIALS.get(model, DEFAULT_MIN_TRIALS) + setup = setup_seconds(model, worst) + n_full = 1 if model == "tabicl" else MAX_TRIALS + cands.append(Candidate(model, round(pt, 2), n_min, round(setup + n_min * pt, 1), round(setup + n_full * pt, 1), source)) + + chosen: list[Candidate] = [] + for c in cands: + if len(chosen) >= max_models: + c.note = f"left out: the plan already has {max_models} models" + continue + trial = chosen + [c] + limit = time_limit([x.full_seconds for x in trial], per_dataset, [x.seconds_per_trial / 2 for x in trial]) + if c.min_seconds <= MAX_SHARE * per_dataset and all(x.min_seconds <= limit for x in trial): + chosen = trial + continue + what = "its single forward pass takes" if c.model == "tabicl" else f"{c.min_trials} trials take" + if c.min_seconds > per_dataset: + c.note = f"skipped: {what} ~{format_duration(c.min_seconds)} here, more than the whole budget" + elif c.min_seconds > MAX_SHARE * per_dataset: + c.note = f"skipped: {what} ~{format_duration(c.min_seconds)} here, more than half of the budget" + elif c.min_seconds > limit: + c.note = f"skipped: {what} ~{format_duration(c.min_seconds)} here, more than the ~{format_duration(limit)} each model would get" + else: + c.note = f"skipped: {what} ~{format_duration(c.min_seconds)} here, which would leave too little time for the models already chosen" + if not chosen: # the budget is too small for anything: run the cheapest model anyway + cheapest = min(cands, key=lambda x: x.min_seconds) + chosen = [cheapest] + reasons.append(f"The budget is very small: only {cheapest.model} fits (~{format_duration(cheapest.min_seconds)}).") + for c in chosen: + c.included, c.note = True, "" + + limit = time_limit([c.full_seconds for c in chosen], per_dataset, [c.seconds_per_trial / 2 for c in chosen]) + max_evals = MAX_TRIALS if any(c.model != "tabicl" for c in chosen) else 1 + timeout = None if math.isinf(limit) else round(max(limit, max(c.min_seconds for c in chosen))) + + names = [c.model for c in chosen] + reasons.append(f"Models: {', '.join(names)}.") + reasons.append( + f"Up to {max_evals} trials per model" + + ( + f"; a model stops after {format_duration(timeout)} (the running trial finishes), so fast models run all their trials and slow ones fewer." + if timeout + else f": everything fits in the budget (~{format_duration(sum(c.full_seconds for c in chosen))} per dataset)." + ) + ) + for c in cands: + if not c.included and c.note: + reasons.append(f"{c.model} {c.note}.") + if any(c.source.startswith("prior") for c in chosen): + reasons.append( + "Times are estimates from built-in cost curves" + + (" scaled by a quick CPU benchmark" if speed_factor else "") + + "; they adapt to this machine after the first run." + ) + if device == "cpu" and largest.n_train > 50_000: + reasons.append(f"{largest.name} has {largest.n_train:,} training rows: for a first look, consider max_rows: 20000.") + if machine is not None and machine.ram_available_gb: + need_gb = largest.n_rows * max(largest.n_onehot_features, largest.n_features) * 8 * 6 / 2**30 + if need_gb > 0.5 * machine.ram_available_gb: + reasons.append(f"{largest.name} may need ~{need_gb:.1f} GB of RAM ({machine.ram_available_gb:.0f} GB free): consider max_rows.") + return AutoPlan(names, max_evals, timeout, budget, device, reasons, cands) diff --git a/autodeep/cli.py b/autodeep/cli.py index 0743fc5..4e5b114 100644 --- a/autodeep/cli.py +++ b/autodeep/cli.py @@ -2,12 +2,15 @@ Commands: ui start the local web app - run run an experiment YAML file - estimate estimate how long an experiment YAML file will take + run run an experiment: a YAML file, or a data file with --target + estimate show the plan and how long it will take + system what AutoDeep sees on this machine (cores, RAM, GPU, speed) quickstart 30-second demo on built-in datasets models list available models datasets list built-in datasets profile summarise a dataset file (columns, types, inferred problem type) + predict predict new rows with a saved model (output/models//best) + info describe a saved model (inputs, scores, parameters) """ from __future__ import annotations @@ -59,6 +62,8 @@ def _confirm(prompt: str) -> bool: def _runner_from_args(args, **extra): + from pathlib import Path + from autodeep.automl import AutoRunner overrides = {} @@ -68,10 +73,36 @@ def _runner_from_args(args, **extra): overrides[key] = value if getattr(args, "models", None): overrides["models"] = args.models + if getattr(args, "budget", None): + overrides["time_budget"] = args.budget if getattr(args, "output", None): overrides["output_folder"] = args.output overrides.update(extra) - return AutoRunner.from_yaml(args.config, **overrides) + source = args.config + if str(source).lower().endswith((".yml", ".yaml")): + if getattr(args, "target", None): + raise ValueError("--target is for data files; set the target in the YAML file") + return AutoRunner.from_yaml(source, **overrides) + # a data file (or builtin:/openml:) instead of an experiment file + if not getattr(args, "target", None) and not str(source).startswith("builtin:"): + raise ValueError(f"'{source}' is not a YAML experiment file: pass the target column with --target") + name = Path(str(source).split(":", 1)[-1]).stem or "dataset" + dataset = {"path": str(source)} + if getattr(args, "target", None): + dataset["target"] = args.target + return AutoRunner(datasets={name: dataset}, **overrides) + + +def _print_plan(runner, plan): + if runner.auto_plan is not None: + print("Automatic plan (models: auto):") + print(runner.auto_plan.describe()) + print() + print(plan.to_dataframe().to_string(index=False)) + for job in plan.jobs: + if job.warning: + print(f"! {job.model} on {job.dataset}: {job.warning}") + print(f"\nEstimated total: {plan.human_total()} on {plan.device}") def cmd_run(args): @@ -79,22 +110,46 @@ def cmd_run(args): runner = _runner_from_args(args, on_event=_ConsoleProgress(), log_level="WARNING") plan = runner.estimate(as_dataframe=False) - print(plan.to_dataframe().to_string(index=False)) - print(f"\nEstimated total: {plan.human_total()} on {plan.device}") + _print_plan(runner, plan) if not args.yes and not _confirm("Start?"): return 1 board = runner.run() print("\nLeaderboard:") print(board.drop(columns=["error"]).to_string(index=False)) print(f"\nResults: {runner.results_path.resolve()} (took {format_duration(sum(r.get('duration_sec', 0) for r in runner.results))})") + _print_best_models(runner) return 0 +def _print_best_models(runner): + if not runner.best_model_paths: + return + print("\nBest model per dataset (chosen on the validation score), ready to use:") + for ds, path in runner.best_model_paths.items(): + p = runner.best_models[ds] + print(f" {ds}: {p.model_name} -> {path.resolve()}") + ds, path = next(iter(runner.best_model_paths.items())) + print(f"\n autodeep predict {path} new_rows.csv -o predictions.csv") + + def cmd_estimate(args): runner = _runner_from_args(args, log_level="WARNING") plan = runner.estimate(as_dataframe=False) - print(plan.to_dataframe().to_string(index=False)) - print(f"\nEstimated total: {plan.human_total()} on {plan.device}") + _print_plan(runner, plan) + return 0 + + +def cmd_system(args): + from autodeep.machine import machine_profile, measure_speed + + if args.benchmark: + m = machine_profile(benchmark=False) + measure_speed(m.cpu_name, m.logical_cores, refresh=True) + m = machine_profile() + print(m.describe()) + print(f" OS: {m.os}") + print(f" device='auto' trains on: {m.device}") + print(f" speed factor: {m.speed_factor:.2f} ({m.speed_source}; >1 = slower than the reference machine, used until timings are recorded)") return 0 @@ -115,6 +170,7 @@ def cmd_quickstart(args): print("\nLeaderboard:") print(board.drop(columns=["error"]).to_string(index=False)) print(f"\nResults written to {runner.results_path.resolve()}") + _print_best_models(runner) return 0 @@ -123,6 +179,7 @@ def cmd_models(args): _print_table(list_models(), ["name", "display_name", "family", "speed", "description"]) print("\nPresets: " + "; ".join(f"{k} = {', '.join(v)}" for k, v in PRESETS.items() if k != "all") + "; all = every model") + print("Default: auto = the models that fit your time budget on this machine (autodeep estimate shows the plan)") return 0 @@ -151,6 +208,45 @@ def cmd_profile(args): return 0 +def cmd_predict(args): + import pandas as pd + + from autodeep.datasets import read_table + from autodeep.predictor import load_model + + model = load_model(args.model, device=args.device or "auto") + df = read_table(args.data) + preds = model.predict_frame(df, proba=not args.no_proba) + out = preds if args.only_predictions else pd.concat([df, preds], axis=1) + if args.output: + out.to_csv(args.output, index=False) + print(f"{len(out)} predictions from {model.model_name} ({model.info.get('dataset')}) written to {args.output}", file=sys.stderr) + else: + out.to_csv(sys.stdout, index=False) + return 0 + + +def cmd_info(args): + import json + from pathlib import Path + + from autodeep.predictor import INFO_FILE + + path = Path(args.model) + info = json.loads((path / INFO_FILE if path.is_dir() else path.parent / INFO_FILE).read_text()) + print(f"{info.get('model_display_name', info.get('model'))} trained on '{info.get('dataset')}' ({info.get('problem_type')})") + print(f" target: {info.get('target')}" + (f" classes: {info.get('classes')}" if info.get("classes") else "")) + metric = info.get("metric") + fmt = lambda v: f"{v:.5f}" if isinstance(v, int | float) else "?" # noqa: E731 + print(f" {metric}: validation {fmt(info.get('val_score'))}, test {fmt(info.get('test_score'))}") + print(f" saved {info.get('saved_at')} with AutoDeep {info.get('autodeep_version')}, trained on {info.get('trained_on_device')}") + print("\nInput columns:") + _print_table(info.get("input_schema", []), ["name", "type"]) + if info.get("best_params"): + print("\nBest hyperparameters:", json.dumps(info["best_params"], default=str)) + return 0 + + def cmd_ui(args): from autodeep.web.server import serve @@ -170,8 +266,10 @@ def main(argv=None): p.set_defaults(func=cmd_ui) def add_run_options(p): - p.add_argument("config", help="experiment YAML file (see examples/experiment.yaml)") - p.add_argument("--models", help="comma separated model names or a preset (fast, default, modern, deep, all)") + p.add_argument("config", help="experiment YAML file (see examples/experiment.yaml), or a data file / builtin: / openml: with --target") + p.add_argument("--target", help="target column, when the first argument is a data file") + p.add_argument("--budget", help="total time budget, e.g. 10m, 1h (with models: auto it decides models and trials; default 15m)") + p.add_argument("--models", help="auto (default), comma separated model names, or a preset (fast, default, modern, deep, all)") p.add_argument("--max-evals", type=int) p.add_argument("--max-epochs", type=int) p.add_argument("--timeout-per-model", type=float, help="seconds") @@ -183,7 +281,7 @@ def add_run_options(p): p.add_argument("-y", "--yes", action="store_true", help="do not ask for confirmation after the estimate") p.set_defaults(func=cmd_run) - p = sub.add_parser("estimate", help="estimate the runtime of an experiment YAML file") + p = sub.add_parser("estimate", help="show the plan and estimated runtime of an experiment") add_run_options(p) p.set_defaults(func=cmd_estimate) @@ -194,6 +292,10 @@ def add_run_options(p): p.add_argument("--output") p.set_defaults(func=cmd_quickstart) + p = sub.add_parser("system", help="what AutoDeep sees on this machine") + p.add_argument("--benchmark", action="store_true", help="re-run the CPU speed benchmark") + p.set_defaults(func=cmd_system) + sub.add_parser("models", help="list available models").set_defaults(func=cmd_models) sub.add_parser("datasets", help="list built-in datasets").set_defaults(func=cmd_datasets) p = sub.add_parser("profile", help="summarise a dataset") @@ -201,6 +303,19 @@ def add_run_options(p): p.add_argument("--target") p.set_defaults(func=cmd_profile) + p = sub.add_parser("predict", help="predict new rows with a saved model") + p.add_argument("model", help="saved model folder, e.g. output/models//best") + p.add_argument("data", help="file with the rows to predict (same columns as the training data)") + p.add_argument("-o", "--output", help="CSV to write (default: print to stdout)") + p.add_argument("--only-predictions", action="store_true", help="write only the prediction columns, not the input columns") + p.add_argument("--no-proba", action="store_true", help="omit the class probability columns") + p.add_argument("--device", choices=["auto", "cpu", "cuda"]) + p.set_defaults(func=cmd_predict) + + p = sub.add_parser("info", help="describe a saved model") + p.add_argument("model", help="saved model folder") + p.set_defaults(func=cmd_info) + args = parser.parse_args(argv) try: return args.func(args) diff --git a/autodeep/configuration/model_config.yml b/autodeep/configuration/model_config.yml index 6f53d1f..1f60ee3 100755 --- a/autodeep/configuration/model_config.yml +++ b/autodeep/configuration/model_config.yml @@ -25,47 +25,40 @@ model_configs: return_extra_info: False default_params: - retrain: True val_size: 0.2 - early_stopping_rounds: 30 + early_stopping_rounds: 50 # on the validation split; n_estimators is only the cap verbose: false - learning_rate: 0.3 - max_depth: 6 - n_estimators: 100 - min_child_weight: 1 - subsample: 0.8 - colsample_bytree: 0.8 - gamma: 0.0 - early_stopping_rounds: 100 + # list of ints = integer range, list of floats = float range (log-uniform when > 0) param_grid: - learning_rate: - - 0.3 - - 0.01 - max_depth: - - 4 - - 6 - - 8 - n_estimators: - - 50 - - 100 - - 200 - min_child_weight: - - 1 - - 5 - - 10 - subsample: - - 0.6 - - 0.8 - - 1.0 - colsample_bytree: - - 0.6 - - 0.8 - - 1.0 - gamma: - - 0.0 - - 0.01 - - 0.2 + n_estimators: [2000] # constant: early stopping picks the number of trees + learning_rate: [0.01, 0.3] + max_depth: [3, 10] + min_child_weight: [1, 10] + subsample: [0.5, 1.0] + colsample_bytree: [0.5, 1.0] + reg_lambda: [0.001, 10.0] + gamma: [0.0, 0.5] + + lgbm: + data_params: + normalize_features: false + encode_categorical: False + return_extra_info: True + + default_params: + val_size: 0.2 + early_stopping_rounds: 100 # on the validation split; n_estimators is only the cap + + param_grid: + n_estimators: [2000] # constant: early stopping picks the number of trees + learning_rate: [0.01, 0.3] + num_leaves: [4, 128] + min_child_samples: [5, 200] + subsample: [0.5, 1.0] + subsample_freq: 1 + colsample_bytree: [0.4, 1.0] + reg_lambda: [0.001, 10.0] catboost: data_params: @@ -74,16 +67,15 @@ model_configs: return_extra_info: True # for dataloader default_params: - val_size: 0.2 - early_stopping_rounds: 100 + early_stopping_rounds: 100 # on the validation split; iterations is only the cap verbose: false - iterations: 500 param_grid: - iterations: - - 100 - - 500 + iterations: [2000] # constant: early stopping picks the number of trees + learning_rate: [0.02, 0.3] + depth: [4, 8] # symmetric trees: cost doubles with every level + l2_leaf_reg: [1.0, 10.0] categoryembedding: @@ -303,6 +295,9 @@ model_configs: shared_embedding_fraction: - 0.01 - 0.4 + deep_layers: # the layers / activation / dropout below only apply when this is true + - True + - False layers: - "64-32" - "128-64-32" @@ -1074,6 +1069,25 @@ model_configs: - 0.9 - 0.99 + resmlp: + data_params: + normalize_features: false + encode_categorical: False + return_extra_info: True + + default_params: + val_size: 0.2 + early_stopping_patience: 4 + + param_grid: + width: [64, 512] + n_layers: [1, 3] + dropout: [0.0, 0.3] + lr: [0.0003, 0.01] + weight_decay: [0.000001, 0.001] + batch_size: [null, 256, 1024, 4096] + max_epochs: [10, 60] + mlp: data_params: normalize_features: mean_std diff --git a/autodeep/configuration/model_config_XS.yml b/autodeep/configuration/model_config_XS.yml index a9429de..a7a4914 100755 --- a/autodeep/configuration/model_config_XS.yml +++ b/autodeep/configuration/model_config_XS.yml @@ -20,52 +20,45 @@ model_configs: xgb: data_params: - normalize_features: False + normalize_features: false encode_categorical: True return_extra_info: False default_params: - retrain: True val_size: 0.2 - early_stopping_rounds: 30 - verbose: False - learning_rate: 0.3 - max_depth: 6 - n_estimators: 100 - min_child_weight: 1 - subsample: 0.8 - colsample_bytree: 0.8 - gamma: 0.0 - early_stopping_rounds: 100 + early_stopping_rounds: 50 # on the validation split; n_estimators is only the cap + verbose: false + # list of ints = integer range, list of floats = float range (log-uniform when > 0) param_grid: - learning_rate: - - 0.3 - - 0.01 - max_depth: - - 4 - - 6 - - 8 - n_estimators: - - 50 - - 100 - - 200 - min_child_weight: - - 1 - - 5 - - 10 - subsample: - - 0.6 - - 0.8 - - 1.0 - colsample_bytree: - - 0.6 - - 0.8 - - 1.0 - gamma: - - 0.0 - - 0.01 - - 0.2 + n_estimators: [2000] # constant: early stopping picks the number of trees + learning_rate: [0.01, 0.3] + max_depth: [3, 10] + min_child_weight: [1, 10] + subsample: [0.5, 1.0] + colsample_bytree: [0.5, 1.0] + reg_lambda: [0.001, 10.0] + gamma: [0.0, 0.5] + + lgbm: + data_params: + normalize_features: false + encode_categorical: False + return_extra_info: True + + default_params: + val_size: 0.2 + early_stopping_rounds: 100 # on the validation split; n_estimators is only the cap + + param_grid: + n_estimators: [2000] # constant: early stopping picks the number of trees + learning_rate: [0.01, 0.3] + num_leaves: [4, 128] + min_child_samples: [5, 200] + subsample: [0.5, 1.0] + subsample_freq: 1 + colsample_bytree: [0.4, 1.0] + reg_lambda: [0.001, 10.0] catboost: data_params: @@ -74,16 +67,15 @@ model_configs: return_extra_info: True # for dataloader default_params: - val_size: 0.2 - early_stopping_rounds: 100 - verbose: False - iterations: 500 + early_stopping_rounds: 100 # on the validation split; iterations is only the cap + verbose: false param_grid: - iterations: - - 100 - - 500 + iterations: [2000] # constant: early stopping picks the number of trees + learning_rate: [0.02, 0.3] + depth: [4, 8] # symmetric trees: cost doubles with every level + l2_leaf_reg: [1.0, 10.0] categoryembedding: @@ -306,6 +298,9 @@ model_configs: shared_embedding_fraction: - 0.01 - 0.4 + deep_layers: # the layers / activation / dropout below only apply when this is true + - True + - False layers: - "64-32" - "128-64-32" @@ -1084,6 +1079,25 @@ model_configs: - 0.9 - 0.99 + resmlp: + data_params: + normalize_features: false + encode_categorical: False + return_extra_info: True + + default_params: + val_size: 0.2 + early_stopping_patience: 4 + + param_grid: + width: [64, 512] + n_layers: [1, 3] + dropout: [0.0, 0.3] + lr: [0.0003, 0.01] + weight_decay: [0.000001, 0.001] + batch_size: [null, 256, 1024, 4096] + max_epochs: [10, 60] + mlp: data_params: normalize_features: mean_std diff --git a/autodeep/dataloaders/dataloader.py b/autodeep/dataloaders/dataloader.py index add21a6..4ac842f 100755 --- a/autodeep/dataloaders/dataloader.py +++ b/autodeep/dataloaders/dataloader.py @@ -6,7 +6,7 @@ import hashlib import json from pathlib import Path -from typing import Any, Dict, List, Optional +from typing import Any import numpy as np import pandas as pd @@ -14,13 +14,13 @@ from sklearn.preprocessing import MinMaxScaler, StandardScaler from autodeep.logging_utils import get_logger +from autodeep.preprocessing import MAX_ONEHOT_CATEGORIES, TabularPreprocessor logger = get_logger("data") TARGET = "target" -MAX_ONEHOT_CATEGORIES = 30 -DEFAULT_IGTD_CONFIG: Dict[str, Any] = { +DEFAULT_IGTD_CONFIG: dict[str, Any] = { "img_size": "auto", "save_image_size": 3, "max_step": 30000, @@ -40,7 +40,7 @@ class IGTDPreprocessor: """Compute (and cache on disk) the IGTD feature -> pixel ordering used by the ResNet model.""" - def __init__(self, dataset_name: str = None, igtd_configs: Dict = None, base_result_dir: str = "IGTD", exclude_cols: Optional[List[str]] = None): + def __init__(self, dataset_name: str = None, igtd_configs: dict = None, base_result_dir: str = "IGTD", exclude_cols: list[str] | None = None): self.dataset_name = dataset_name or "dataset" cfg = copy.deepcopy(DEFAULT_IGTD_CONFIG) cfg.update(copy.deepcopy(igtd_configs or {})) @@ -67,7 +67,7 @@ def _cache_dir(self, X: pd.DataFrame) -> Path: key = hashlib.sha1(json.dumps([list(map(str, X.columns)), self.igtd_configs], sort_keys=True, default=str).encode()).hexdigest()[:10] return self.base_result_dir / f"{self.dataset_name}_{key}" - def run(self, X: pd.DataFrame) -> Dict[str, Any]: + def run(self, X: pd.DataFrame) -> dict[str, Any]: from autodeep.modelutils.igtdutilities import table_to_image if self.img_size == "auto": @@ -124,12 +124,12 @@ def run(self, X: pd.DataFrame) -> Dict[str, Any]: class ExtraInfoCreator: """Dataset statistics passed to the models (categorical columns, sizes, IGTD ordering...).""" - def __init__(self, dataset_name, run_igtd=False, igtd_preprocessor: Optional[IGTDPreprocessor] = None): + def __init__(self, dataset_name, run_igtd=False, igtd_preprocessor: IGTDPreprocessor | None = None): self.dataset_name = dataset_name self.run_igtd = run_igtd self.igtd_preprocessor = igtd_preprocessor - def create_extra_info(self, df: pd.DataFrame, dataset_name: str = None) -> Dict[str, Any]: + def create_extra_info(self, df: pd.DataFrame, dataset_name: str = None) -> dict[str, Any]: cat_cols = list(df.select_dtypes(include=["object", "category", "string"]).columns) num_cols = [c for c in df.columns if c not in cat_cols] info = { @@ -218,12 +218,12 @@ def __init__( return_extra_info=True, encode_categorical=False, run_igtd=False, - igtd_configs: Optional[Dict] = None, - igtd_result_base_dir: Optional[str] = "IGTD", - drop_columns: Optional[List[str]] = None, - dataframe: Optional[pd.DataFrame] = None, - sep: Optional[str] = None, - max_rows: Optional[int] = None, + igtd_configs: dict | None = None, + igtd_result_base_dir: str | None = "IGTD", + drop_columns: list[str] | None = None, + dataframe: pd.DataFrame | None = None, + sep: str | None = None, + max_rows: int | None = None, ): self.dataset_name = dataset_name self.dataset_path = dataset_path @@ -242,6 +242,8 @@ def __init__( self.dataframe = dataframe self.sep = sep self.max_rows = max_rows + self.preprocessor: TabularPreprocessor | None = None # fitted by load_data() + self.classes = None self.extra_info_creator = ExtraInfoCreator( dataset_name, run_igtd=run_igtd, @@ -306,7 +308,7 @@ def _impute(X_train, X_test): return X_train, X_test def load_data(self): - from autodeep.datasets import infer_problem_type, sanitize_columns + from autodeep.datasets import infer_problem_type df = self._read() if self.target_column not in df.columns: @@ -321,14 +323,9 @@ def load_data(self): if X.shape[1] == 0: raise ValueError(f"Dataset '{self.dataset_name}' has no feature columns left") - # column types: booleans and low-information types become categorical strings - for c in X.columns: - if pd.api.types.is_bool_dtype(X[c]) or isinstance(X[c].dtype, pd.CategoricalDtype) or pd.api.types.is_string_dtype(X[c]): - X[c] = X[c].astype(object).where(X[c].notna(), None) - X[c] = X[c].map(lambda v: v if v is None else str(v)) - elif pd.api.types.is_datetime64_any_dtype(X[c]): - X[c] = X[c].astype("int64") / 1e9 - X = X.rename(columns=sanitize_columns(X.columns)) + # column types (booleans and text -> categorical strings, datetimes -> seconds) and clean names + prep = TabularPreprocessor(normalize=self.normalize_features, encode_categorical=self.encode_categorical) + X = prep.fit_schema(X) classes = None if self.problem_type == "regression": @@ -339,17 +336,16 @@ def load_data(self): y = y.rename(TARGET) X_train, X_test, y_train, y_test = self._split(X, y, split_values) - X_train, X_test = self._impute(X_train, X_test) - if self.encode_categorical: - X_train, X_test = self.one_hot(X_train, X_test) - if self.normalize_features: - X_train, X_test = self.scale_features(X_train, X_test, mode=self.normalize_features) + prep.fit(X_train) # imputation values, categories and scaler come from the training rows only + X_train, X_test = prep.transform(X_train), prep.transform(X_test) + self.preprocessor = prep + self.classes = None if classes is None else [c.item() if hasattr(c, "item") else c for c in classes] extra_info = None if self.return_extra_info or self.run_igtd: extra_info = self.extra_info_creator.create_extra_info(X_train, self.dataset_name) extra_info["problem_type"] = self.problem_type if classes is not None: - extra_info["classes"] = [c.item() if hasattr(c, "item") else c for c in classes] + extra_info["classes"] = self.classes extra_info["num_classes"] = len(classes) return X_train, X_test, y_train, y_test, extra_info diff --git a/autodeep/datasets.py b/autodeep/datasets.py index 5527824..6f84412 100644 --- a/autodeep/datasets.py +++ b/autodeep/datasets.py @@ -17,7 +17,7 @@ import re from dataclasses import asdict, dataclass, field, fields from pathlib import Path -from typing import Any, Dict, List, Optional +from typing import Any import numpy as np import pandas as pd @@ -108,7 +108,7 @@ def _load_synthetic_mixed(n_samples=3000, random_state=0): return df -BUILTIN_DATASETS: Dict[str, Dict[str, Any]] = { +BUILTIN_DATASETS: dict[str, dict[str, Any]] = { "iris": { "loader": _load_iris, "target": "species", @@ -159,7 +159,7 @@ def _load_synthetic_mixed(n_samples=3000, random_state=0): SUPPORTED_EXTENSIONS = (".csv", ".tsv", ".txt", ".parquet", ".pq", ".feather", ".json", ".jsonl", ".xlsx", ".xls") -def list_builtin_datasets() -> List[Dict[str, Any]]: +def list_builtin_datasets() -> list[dict[str, Any]]: return [{"name": k, "path": f"builtin:{k}", **{kk: vv for kk, vv in v.items() if kk != "loader"}} for k, v in BUILTIN_DATASETS.items()] @@ -168,7 +168,7 @@ def list_builtin_datasets() -> List[Dict[str, Any]]: # -------------------------------------------------------------------------------------- -def read_table(path, sep: Optional[str] = None, nrows: Optional[int] = None) -> pd.DataFrame: +def read_table(path, sep: str | None = None, nrows: int | None = None) -> pd.DataFrame: """Read a dataset from a path or a ``builtin:``/``openml:`` reference into a DataFrame.""" path_str = str(path) if path_str.startswith("builtin:"): @@ -183,7 +183,12 @@ def read_table(path, sep: Optional[str] = None, nrows: Optional[int] = None) -> ref = path_str.split(":", 1)[1].strip() kwargs = {"data_id": int(ref)} if ref.isdigit() else {"name": ref, "version": "active"} - bunch = fetch_openml(as_frame=True, parser="auto", **kwargs) + try: + bunch = fetch_openml(as_frame=True, parser="auto", **kwargs) + except TypeError: + # scikit-learn <= 1.9's pandas ARFF parser expects string categories, which pandas 3 does not always + # give it ("expected string or bytes-like object, got 'int'"): use the pure-Python parser instead + bunch = fetch_openml(as_frame=True, parser="liac-arff", **kwargs) df = bunch.frame.copy() return df.head(nrows) if nrows else df @@ -211,7 +216,7 @@ def read_table(path, sep: Optional[str] = None, nrows: Optional[int] = None) -> def _sniff_separator(path: Path) -> str: import csv - with open(path, "r", newline="", errors="replace") as f: + with open(path, newline="", errors="replace") as f: sample = f.read(64 * 1024) try: return csv.Sniffer().sniff(sample, delimiters=",;\t|").delimiter @@ -251,7 +256,7 @@ def sanitize_column_name(name: Any) -> str: return s -def sanitize_columns(columns) -> Dict[Any, str]: +def sanitize_columns(columns) -> dict[Any, str]: mapping, seen = {}, set() for col in columns: base = sanitize_column_name(col) @@ -293,22 +298,22 @@ class DatasetSpec: name: str path: str - target: Optional[str] = None - problem_type: Optional[str] = None - metric: Optional[str] = None - eval_metrics: Optional[List[str]] = None + target: str | None = None + problem_type: str | None = None + metric: str | None = None + eval_metrics: list[str] | None = None test_size: float = 0.2 - split_col: Optional[str] = None + split_col: str | None = None train_value: Any = None test_value: Any = None - drop_columns: List[str] = field(default_factory=list) - sep: Optional[str] = None - max_rows: Optional[int] = None - igtd_configs: Optional[Dict[str, Any]] = None + drop_columns: list[str] = field(default_factory=list) + sep: str | None = None + max_rows: int | None = None + igtd_configs: dict[str, Any] | None = None # ---------------------------------------------------------------- construction @classmethod - def from_dict(cls, name: str, cfg: Dict[str, Any]) -> "DatasetSpec": + def from_dict(cls, name: str, cfg: dict[str, Any]) -> DatasetSpec: cfg = dict(cfg) for old, new in _LEGACY_KEYS.items(): if old in cfg: @@ -327,10 +332,10 @@ def from_dict(cls, name: str, cfg: Dict[str, Any]) -> "DatasetSpec": return cls(**cfg) @classmethod - def builtin(cls, name: str, **overrides) -> "DatasetSpec": + def builtin(cls, name: str, **overrides) -> DatasetSpec: return cls.from_dict(name, {"path": f"builtin:{name}", **overrides}) - def to_dict(self) -> Dict[str, Any]: + def to_dict(self) -> dict[str, Any]: return {k: v for k, v in asdict(self).items() if v not in (None, [], {})} # ---------------------------------------------------------------- resolution @@ -340,7 +345,7 @@ def read(self) -> pd.DataFrame: df = df.sample(n=int(self.max_rows), random_state=0).reset_index(drop=True) return df - def resolve(self, df: Optional[pd.DataFrame] = None) -> "DatasetSpec": + def resolve(self, df: pd.DataFrame | None = None) -> DatasetSpec: """Fill in target / problem type / metrics from the data and validate everything.""" if self.target is None and self.path.startswith("builtin:"): key = _BUILTIN_ALIASES.get(self.path.split(":", 1)[1], self.path.split(":", 1)[1]) @@ -380,7 +385,7 @@ def resolve(self, df: Optional[pd.DataFrame] = None) -> "DatasetSpec": self.eval_metrics = list(dict.fromkeys(evals)) return self - def as_legacy_dict(self) -> Dict[str, Any]: + def as_legacy_dict(self) -> dict[str, Any]: """The dictionary format used by the original AutoRunner ``data_config``.""" return { "dataset_path": self.path, @@ -395,7 +400,7 @@ def as_legacy_dict(self) -> Dict[str, Any]: } -def parse_datasets(data_config) -> List[DatasetSpec]: +def parse_datasets(data_config) -> list[DatasetSpec]: """Accept a dict ``{name: {...}}``, a list of dicts/specs or a single spec.""" if data_config is None: raise ValueError("No datasets given. Pass `datasets=` (or the legacy `data_config=`).") @@ -403,7 +408,7 @@ def parse_datasets(data_config) -> List[DatasetSpec]: return [data_config] if isinstance(data_config, dict): return [v if isinstance(v, DatasetSpec) else DatasetSpec.from_dict(k, v) for k, v in data_config.items()] - if isinstance(data_config, (list, tuple)): + if isinstance(data_config, list | tuple): specs = [] for i, item in enumerate(data_config): if isinstance(item, DatasetSpec): @@ -424,7 +429,7 @@ def parse_datasets(data_config) -> List[DatasetSpec]: # -------------------------------------------------------------------------------------- -def profile_dataframe(df: pd.DataFrame, target: Optional[str] = None, n_preview: int = 8) -> Dict[str, Any]: +def profile_dataframe(df: pd.DataFrame, target: str | None = None, n_preview: int = 8) -> dict[str, Any]: """Lightweight per-column summary of a dataset, with hints about likely problems.""" n = len(df) columns = [] diff --git a/autodeep/device.py b/autodeep/device.py index 05feda1..ea41832 100644 --- a/autodeep/device.py +++ b/autodeep/device.py @@ -21,13 +21,12 @@ import shutil import subprocess from functools import lru_cache -from typing import Dict, Optional MIN_FREE_GPU_MB = int(os.environ.get("AUTODEEP_MIN_FREE_GPU_MB", "2048")) -_override: Optional[str] = None +_override: str | None = None -def set_device(device: Optional[str]) -> None: +def set_device(device: str | None) -> None: """Choose the device for this process: ``"auto"`` (default), ``"cpu"`` or ``"cuda"``.""" global _override if device not in (None, "auto", "cpu", "cuda", "gpu"): @@ -119,7 +118,7 @@ def _nvidia_smi(): return gpus -def gpu_info() -> Dict: +def gpu_info() -> dict: """Information about the first visible GPU, without initialising CUDA when possible.""" if not _torch_built_with_cuda(): return {"available": False, "reason": "PyTorch was installed without CUDA support"} diff --git a/autodeep/ensemble.py b/autodeep/ensemble.py new file mode 100644 index 0000000..15a5c36 --- /dev/null +++ b/autodeep/ensemble.py @@ -0,0 +1,117 @@ +"""Stacking and blending of out-of-fold predictions (binary classification, rank metrics such as ROC AUC). + +Every member is a pair ``(oof, test)``: out-of-fold predictions for the training rows and predictions for the +test rows, on any scale (probabilities, log-odds, scores). Members can come from AutoDeep or from anywhere else +(other libraries, public prediction files), as long as their OOF predictions were made on the same folds as +the ones used here, or at least without seeing the row they predict. + +Two level-2 learners are available, both scored honestly with nested cross-validation (the weights are fitted +on four folds' OOF predictions and scored on the fifth): + +* ``hill``: Caruana greedy forward selection with replacement on logit-ranks; +* ``logreg``: L2 logistic regression on logit-ranks, with ``C`` chosen inside each outer fold. + +Inputs are turned into *logit ranks* ``logit((rank - 0.5) / n)``: ROC AUC only depends on the order, and this +puts members trained with different losses and calibrations on one scale. + + from autodeep.ensemble import Stacker + st = Stacker(method="logreg").fit(members, y, folds) # members: {name: (oof, test)} + st.nested_score_, st.weights_ + test_pred = st.predict() +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +import numpy as np +from scipy.special import logit +from scipy.stats import rankdata +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import roc_auc_score +from sklearn.model_selection import StratifiedKFold + + +def logit_rank(v: np.ndarray) -> np.ndarray: + v = np.asarray(v, dtype=np.float64).reshape(-1) + return logit((rankdata(v) - 0.5) / len(v)) + + +def hill_climb(Z: np.ndarray, y: np.ndarray, max_iter: int = 100, tol: float = 1e-7) -> np.ndarray: + """Greedy forward selection with replacement (Caruana et al., 2004). Returns weights summing to 1.""" + n = Z.shape[1] + scores = [roc_auc_score(y, Z[:, j]) for j in range(n)] + w = np.zeros(n) + j = int(np.argmax(scores)) + w[j] = 1 + cur, best = Z[:, j].copy(), scores[j] + for _ in range(max_iter): + k = w.sum() + cand = [roc_auc_score(y, (cur * k + Z[:, j]) / (k + 1)) for j in range(n)] + j = int(np.argmax(cand)) + if cand[j] - best < tol: + break + best, cur = cand[j], (cur * k + Z[:, j]) / (k + 1) + w[j] += 1 + return w / w.sum() + + +def _fit_logreg(Z, y, C): + m = LogisticRegression(C=C, max_iter=5000) + m.fit(Z, y) + return m + + +@dataclass +class Stacker: + """Level-2 model over member predictions. ``method`` is ``"hill"`` or ``"logreg"``.""" + + method: str = "logreg" + Cs: tuple[float, ...] = (0.001, 0.01, 0.1, 1.0) + inner_folds: int = 4 + random_state: int = 0 + names_: list[str] = field(default_factory=list) + weights_: dict[str, float] = field(default_factory=dict) + nested_score_: float | None = None + nested_oof_: np.ndarray | None = None + member_scores_: dict[str, float] = field(default_factory=dict) + + def _fit_level2(self, Z, y): + if self.method == "hill": + return ("hill", hill_climb(Z, y)) + if self.method != "logreg": + raise ValueError(f"unknown method {self.method!r}") + if len(self.Cs) == 1: + C = self.Cs[0] + else: + skf = StratifiedKFold(self.inner_folds, shuffle=True, random_state=self.random_state) + inner = list(skf.split(Z, y)) + C = max(self.Cs, key=lambda c: np.mean([roc_auc_score(y[b], _fit_logreg(Z[a], y[a], c).decision_function(Z[b])) for a, b in inner])) + return ("logreg", _fit_logreg(Z, y, C)) + + @staticmethod + def _apply(model, Z): + kind, m = model + return Z @ m if kind == "hill" else m.decision_function(Z) + + def fit(self, members: dict[str, tuple[np.ndarray, np.ndarray]], y, folds): + """``folds``: list of ``(train_idx, valid_idx)`` (the outer folds the OOF predictions were made on).""" + y = np.asarray(y).astype(int) + self.names_ = list(members) + self._Z = np.column_stack([logit_rank(members[n][0]) for n in self.names_]) + self._T = np.column_stack([logit_rank(members[n][1]) for n in self.names_]) + self.member_scores_ = {n: float(roc_auc_score(y, self._Z[:, j])) for j, n in enumerate(self.names_)} + oof = np.zeros(len(y)) + for a, b in folds: + oof[b] = self._apply(self._fit_level2(self._Z[a], y[a]), self._Z[b]) + self.nested_oof_ = oof + self.nested_score_ = float(roc_auc_score(y, oof)) + self.model_ = self._fit_level2(self._Z, y) + kind, m = self.model_ + w = m if kind == "hill" else m.coef_[0] + self.weights_ = {n: float(v) for n, v in zip(self.names_, w)} + return self + + def predict(self) -> np.ndarray: + """Level-2 score for the test rows (higher = more likely positive; only the order matters for AUC).""" + return self._apply(self.model_, self._T) diff --git a/autodeep/estimation.py b/autodeep/estimation.py index f62cb08..a166c48 100644 --- a/autodeep/estimation.py +++ b/autodeep/estimation.py @@ -4,6 +4,8 @@ 1. **Priors**: per-model cost curves ``seconds_per_trial = base + per_krow * (n_train/1000)^a * (n_features/20)^b`` measured on a 12-thread CPU. They capture how cost scales with data size. + Before there is any history, they are scaled by this machine's measured CPU speed + (:func:`autodeep.machine.measure_speed`, a ~0.5 s benchmark cached for 30 days). 2. **History**: every finished trial is appended to ``~/.cache/autodeep/timings.jsonl``. When a model has history on the current device, the prior is rescaled by the median ``actual / prior`` ratio, so estimates adapt to *your* machine after the first run. @@ -22,7 +24,6 @@ import time from dataclasses import asdict, dataclass, field from pathlib import Path -from typing import Dict, List, Optional import numpy as np import pandas as pd @@ -37,10 +38,15 @@ # Measured 2026-11 on a 12-thread CPU (Ryzen-class), median of random hyperparameter trials, at # ~2k rows (XS search space) and ~16k rows (default search space). node/danet/s1dcnn/resnet are # extrapolated from the 2k point. GPU factors are rough guesses: your history replaces them. -PRIORS: Dict[str, Dict[str, float]] = { - "xgb": dict(base=0.1, per_krow=0.012, a=1.0, b=0.8, gpu=1.0, epochs=False), - "catboost": dict(base=1.0, per_krow=0.06, a=1.0, b=0.7, gpu=1.0, epochs=False), - "mlp": dict(base=0.1, per_krow=0.11, a=1.0, b=0.4, gpu=1.0, epochs=False), +PRIORS: dict[str, dict[str, float]] = { + # xgb/catboost re-fitted 2026-11-12 for the 0.4.0 grids (up to 2000 trees + early stopping) on CPU at 16k-40k + # rows (medians of 5 trials on california_housing, adult, covertype_50k; multiclass costs ~3x more for xgb) + "xgb": dict(base=0.1, per_krow=0.11, a=1.0, b=0.8, gpu=1.0, epochs=False), + "lgbm": dict(base=0.1, per_krow=0.11, a=1.0, b=0.8, gpu=1.0, epochs=False), # assumed ~xgb until timed + "catboost": dict(base=1.0, per_krow=0.28, a=1.0, b=0.7, gpu=1.0, epochs=False), + # mlp re-measured 2026-11-12 at 16k rows (default search space, sgd trials ~30 s): steeper than linear + "resmlp": dict(base=0.2, per_krow=0.5, a=1.0, b=0.3, gpu=4.0, epochs=False), # assumed, until timed + "mlp": dict(base=0.1, per_krow=0.55, a=1.5, b=0.4, gpu=1.0, epochs=False), "categoryembedding": dict(base=0.6, per_krow=0.75, a=1.0, b=0.2, gpu=2.0, epochs=True), "tabnet": dict(base=0.3, per_krow=4.7, a=1.0, b=0.4, gpu=2.5, epochs=True), "fttransformer": dict(base=0.6, per_krow=63.0, a=1.0, b=1.0, gpu=6.0, epochs=True), @@ -54,11 +60,16 @@ "resnet": dict(base=1.0, per_krow=95.0, a=1.0, b=0.3, gpu=10.0, epochs=True), # added 2026-11 (same machine). tabicl: one forward pass, cost ~ rows x context (2k: 38 s, 16k: 497 s on CPU). # realmlp: fixed 256 epochs (2k: 17 s, 16k: 110 s). tabm: early stopping (2k: 109 s; 16k extrapolated). - "tabicl": dict(base=3.0, per_krow=16.0, a=1.23, b=0.5, gpu=15.0, epochs=False), - "realmlp": dict(base=0.5, per_krow=9.4, a=0.89, b=0.5, gpu=5.0, epochs=True, typical_epochs=256), - "tabm": dict(base=1.0, per_krow=60.0, a=0.85, b=0.5, gpu=10.0, epochs=True, typical_epochs=100), + # GPU factors of these three measured 2026-11-12 on an RTX 3060 (benchmarks/larger_datasets.py, 16k-40k rows): + # tabicl 54-78x, tabm 10-43x (median 13x), realmlp 0.9-2.1x (batch 256 x 256 epochs is launch-bound). + "tabicl": dict(base=3.0, per_krow=16.0, a=1.23, b=0.5, gpu=50.0, epochs=False), + "realmlp": dict(base=0.5, per_krow=9.4, a=0.89, b=0.5, gpu=1.5, epochs=True, typical_epochs=256), + "tabm": dict(base=1.0, per_krow=60.0, a=0.85, b=0.5, gpu=12.0, epochs=True, typical_epochs=100), } DEFAULT_PRIOR = dict(base=5.0, per_krow=5.0, a=1.0, b=0.5, gpu=3.0, epochs=True) +# models with a GPU factor of at least GPU_HUNGRY get a warning when their CPU estimate exceeds SLOW_ON_CPU_SECONDS +GPU_HUNGRY = 10.0 +SLOW_ON_CPU_SECONDS = 300 @dataclass @@ -95,7 +106,7 @@ def _effective_features(model: str, shape: DatasetShape) -> int: return shape.n_onehot_features if model in ("xgb", "mlp", "resnet", "s1dcnn") else shape.n_features -def prior_seconds_per_trial(model: str, n_train: int, n_features: int, device: str = "cpu", max_epochs: Optional[int] = None) -> float: +def prior_seconds_per_trial(model: str, n_train: int, n_features: int, device: str = "cpu", max_epochs: int | None = None) -> float: p = PRIORS.get(model, DEFAULT_PRIOR) # hyperopt's internal validation split: models train on ~80% of the training rows krows = max(n_train * 0.8, 1) / 1000.0 @@ -115,9 +126,9 @@ def igtd_seconds(n_features: int) -> float: class TimingHistory: def __init__(self, path: Path = HISTORY_FILE): self.path = Path(path) - self._records: Optional[List[Dict]] = None + self._records: list[dict] | None = None - def records(self) -> List[Dict]: + def records(self) -> list[dict]: if self._records is None: self._records = [] if self.path.exists(): @@ -128,7 +139,7 @@ def records(self) -> List[Dict]: continue return self._records - def add(self, record: Dict) -> None: + def add(self, record: dict) -> None: try: self.path.parent.mkdir(parents=True, exist_ok=True) with open(self.path, "a") as f: @@ -173,12 +184,12 @@ class JobEstimate: high_seconds: float source: str # "prior" | "history (n)" capped_by_timeout: bool = False - warning: Optional[str] = None + warning: str | None = None @dataclass class Plan: - jobs: List[JobEstimate] = field(default_factory=list) + jobs: list[JobEstimate] = field(default_factory=list) device: str = "cpu" @property @@ -196,7 +207,7 @@ def high_seconds(self) -> float: def human_total(self) -> str: return f"~{format_duration(self.total_seconds)} (range {format_duration(self.low_seconds)} - {format_duration(self.high_seconds)})" - def to_records(self) -> List[Dict]: + def to_records(self) -> list[dict]: return [asdict(j) for j in self.jobs] def to_dataframe(self) -> pd.DataFrame: @@ -207,7 +218,7 @@ def to_dataframe(self) -> pd.DataFrame: df["range"] = [f"{format_duration(lo)} - {format_duration(hi)}" for lo, hi in zip(df.low_seconds, df.high_seconds)] return df[["dataset", "model", "n_train", "n_features", "trials", "seconds_per_trial", "estimate", "range", "source"]] - def summary(self) -> Dict: + def summary(self) -> dict: return { "device": self.device, "total_seconds": self.total_seconds, @@ -218,6 +229,30 @@ def summary(self) -> Dict: } +def seconds_per_trial( + model: str, + shape: DatasetShape, + device: str = "cpu", + max_epochs: int | None = None, + history: TimingHistory | None = None, + speed_factor: float | None = None, +): + """``(seconds, low_factor, high_factor, source)`` for one search trial of ``model`` on ``shape``.""" + history = history or TimingHistory() + per_trial = prior_seconds_per_trial(model, shape.n_train, _effective_features(model, shape), device, max_epochs) + ratio, n_hist = history.calibration(model, device) + if ratio is not None: + lo_f, hi_f = (0.6, 1.6) if n_hist >= 5 else (0.4, 2.0) + return per_trial * ratio, lo_f, hi_f, f"history ({n_hist} trials)" + if device == "cpu" and speed_factor and abs(speed_factor - 1.0) > 0.05: # the benchmark measures the CPU only + return per_trial * speed_factor, 0.35, 2.5, f"prior x{speed_factor:.2f} (CPU benchmark)" + return per_trial, 0.35, 2.5, "prior" + + +def setup_seconds(model: str, shape: DatasetShape) -> float: + return igtd_seconds(_effective_features(model, shape)) if model == "resnet" else 0.0 + + def _trials_for(model: str, max_evals: int) -> int: """Number of trials a search will run (models without hyperparameters run one).""" from autodeep.registry import MODELS @@ -228,29 +263,23 @@ def _trials_for(model: str, max_evals: int) -> int: def estimate_plan( - shapes: List[DatasetShape], - models: List[str], + shapes: list[DatasetShape], + models: list[str], max_evals: int, - timeout_per_model: Optional[float] = None, - max_epochs: Optional[int] = None, + timeout_per_model: float | None = None, + max_epochs: int | None = None, device: str = "cpu", - history: Optional[TimingHistory] = None, + history: TimingHistory | None = None, + speed_factor: float | None = None, ) -> Plan: + """Estimate every (dataset, model) search. ``speed_factor`` scales the built-in priors (see :mod:`autodeep.machine`).""" history = history or TimingHistory() plan = Plan(device=device) for shape in shapes: for model in models: n_feat = _effective_features(model, shape) - per_trial = prior_seconds_per_trial(model, shape.n_train, n_feat, device, max_epochs) - ratio, n_hist = history.calibration(model, device) - if ratio is not None: - per_trial *= ratio - lo_f, hi_f = (0.6, 1.6) if n_hist >= 5 else (0.4, 2.0) - source = f"history ({n_hist} trials)" - else: - lo_f, hi_f = (0.35, 2.5) - source = "prior" - setup = igtd_seconds(n_feat) if model == "resnet" else 0.0 + per_trial, lo_f, hi_f, source = seconds_per_trial(model, shape, device, max_epochs, history, speed_factor) + setup = setup_seconds(model, shape) trials = _trials_for(model, max_evals) total = per_trial * trials + setup capped, warning = False, None @@ -259,6 +288,9 @@ def estimate_plan( total, capped = setup + max(per_trial, float(timeout_per_model) + per_trial / 2), True if per_trial > timeout_per_model: warning = f"one trial (~{format_duration(per_trial)}) is longer than the time budget: only 1 trial will run" + gpu_factor = PRIORS.get(model, DEFAULT_PRIOR)["gpu"] + if warning is None and device == "cpu" and gpu_factor >= GPU_HUNGRY and total > SLOW_ON_CPU_SECONDS: + warning = f"~{format_duration(total)} on CPU; this model is much faster on a GPU (or use models: auto to fit a time budget)" plan.jobs.append( JobEstimate( dataset=shape.name, @@ -300,7 +332,7 @@ def format_duration(seconds: float) -> str: class RunTracker: """Consumes progress events, records timings and maintains a live ETA.""" - def __init__(self, plan: Plan, device: str = "cpu", max_epochs: Optional[int] = None, history: Optional[TimingHistory] = None): + def __init__(self, plan: Plan, device: str = "cpu", max_epochs: int | None = None, history: TimingHistory | None = None): self.plan = plan self.device = device self.max_epochs = max_epochs @@ -309,7 +341,7 @@ def __init__(self, plan: Plan, device: str = "cpu", max_epochs: Optional[int] = self.order = [(j.dataset, j.model) for j in plan.jobs] self.done_jobs = set() self.current = None - self.current_durations: List[float] = [] + self.current_durations: list[float] = [] self.current_started = None self.started = time.time() self.trials_done = 0 @@ -320,7 +352,7 @@ def __init__(self, plan: Plan, device: str = "cpu", max_epochs: Optional[int] = def total_trials(self) -> int: return sum(j.trials for j in self.plan.jobs) - def observe(self, evt: Dict) -> None: + def observe(self, evt: dict) -> None: kind = evt.get("event") if kind == "model_start": self.current = (evt["dataset"], evt["model"]) @@ -371,7 +403,7 @@ def eta_seconds(self) -> float: remaining += job.total_seconds * calib return remaining - def snapshot(self) -> Dict: + def snapshot(self) -> dict: eta = self.eta_seconds() elapsed = time.time() - self.started total_jobs = len(self.order) diff --git a/autodeep/evaluation/generalevaluator.py b/autodeep/evaluation/generalevaluator.py index 562c57c..677d834 100755 --- a/autodeep/evaluation/generalevaluator.py +++ b/autodeep/evaluation/generalevaluator.py @@ -2,8 +2,8 @@ from __future__ import annotations +from collections.abc import Callable from dataclasses import dataclass -from typing import Callable, Dict, FrozenSet, List import numpy as np from sklearn.metrics import ( @@ -30,7 +30,7 @@ class MetricInfo: name: str maximize: bool best: float - problem_types: FrozenSet[str] + problem_types: frozenset[str] needs_proba: bool description: str @@ -66,8 +66,8 @@ def _log_loss(y_true, y_pred, y_prob, problem_type): return log_loss(y_true, np.clip(y_prob, 1e-15, 1 - 1e-15), labels=np.arange(y_prob.shape[1])) -METRICS: Dict[str, MetricInfo] = {} -_FUNCS: Dict[str, Callable] = {} +METRICS: dict[str, MetricInfo] = {} +_FUNCS: dict[str, Callable] = {} def _register(name, maximize, best, problem_types, needs_proba, description, fn): @@ -146,7 +146,7 @@ def validate_metric(name: str, problem_type: str) -> None: raise ValueError(f"Metric '{name}' is not valid for {problem_type}. Valid metrics: {valid}") -def metrics_for_problem(problem_type: str) -> List[Dict]: +def metrics_for_problem(problem_type: str) -> list[dict]: return [ {"name": m.name, "maximize": m.maximize, "needs_proba": m.needs_proba, "description": m.description} for m in METRICS.values() @@ -191,7 +191,7 @@ def evaluate_metric(self, metric_name: str) -> float: raise ValueError(f"Metric '{name}' needs predicted probabilities but none were provided.") return float(_FUNCS[name](y_true, y_pred, self.y_prob, self.problem_type)) - def evaluate_model(self) -> Dict[str, float]: + def evaluate_model(self) -> dict[str, float]: if self.problem_type not in PROBLEM_TYPES: raise ValueError(f"Invalid problem type: {self.problem_type}") names = [normalize_metric_name(m) for m in self.run_metrics] diff --git a/autodeep/jobs.py b/autodeep/jobs.py index ed7b4e6..abe5aa6 100644 --- a/autodeep/jobs.py +++ b/autodeep/jobs.py @@ -15,7 +15,7 @@ import time import traceback from pathlib import Path -from typing import Any, Dict +from typing import Any JOB_FILE = "job.json" EVENTS_FILE = "events.jsonl" @@ -23,10 +23,10 @@ LOG_FILE = "run.log" # keys of job.json forwarded to AutoRunner -RUNNER_KEYS = {"max_evals", "random_state", "timeout_per_model", "max_epochs", "device", "save_models", "model_config"} +RUNNER_KEYS = {"max_evals", "random_state", "timeout_per_model", "max_epochs", "device", "save_models", "save_best", "model_config"} -def _write_json(path: Path, data: Dict[str, Any]) -> None: +def _write_json(path: Path, data: dict[str, Any]) -> None: tmp = path.with_suffix(".tmp") tmp.write_text(json.dumps(data, default=str)) os.replace(tmp, path) diff --git a/autodeep/logging_utils.py b/autodeep/logging_utils.py index 5a4c173..7762ba9 100644 --- a/autodeep/logging_utils.py +++ b/autodeep/logging_utils.py @@ -7,17 +7,16 @@ import sys import warnings from pathlib import Path -from typing import Optional LOGGER_NAME = "autodeep" _FMT = "%(asctime)s | %(levelname)-7s | %(name)s | %(message)s" -def get_logger(name: Optional[str] = None) -> logging.Logger: +def get_logger(name: str | None = None) -> logging.Logger: return logging.getLogger(LOGGER_NAME if not name else f"{LOGGER_NAME}.{name}") -def setup_logging(level: str = "INFO", log_file: Optional[Path] = None, quiet_libraries: bool = True) -> logging.Logger: +def setup_logging(level: str = "INFO", log_file: Path | None = None, quiet_libraries: bool = True) -> logging.Logger: """Configure the ``autodeep`` logger (idempotent).""" logger = logging.getLogger(LOGGER_NAME) logger.setLevel(logging.DEBUG) @@ -54,7 +53,7 @@ def setup_logging(level: str = "INFO", log_file: Optional[Path] = None, quiet_li def quiet_third_party() -> None: os.environ.setdefault("PT_LOGLEVEL", "ERROR") - for name in ("pytorch_lightning", "lightning", "lightning.pytorch", "lightning_fabric", "pytorch_tabular", "hyperopt", "matplotlib"): + for name in ("pytorch_lightning", "lightning", "lightning.pytorch", "lightning_fabric", "hyperopt", "matplotlib"): logging.getLogger(name).setLevel(logging.ERROR) warnings.filterwarnings("ignore", category=FutureWarning) warnings.filterwarnings("ignore", category=DeprecationWarning) diff --git a/autodeep/machine.py b/autodeep/machine.py new file mode 100644 index 0000000..642b72d --- /dev/null +++ b/autodeep/machine.py @@ -0,0 +1,277 @@ +"""What is this machine capable of? CPU cores, RAM, GPU and a quick speed measurement. + +Used by the automatic plan (:mod:`autodeep.autoplan`) and to scale the runtime estimates before any run +history exists on this machine. Nothing here imports torch. + +The speed factor comes from a ~0.2 s micro-benchmark (BLAS matrix products, sorting, a Python loop) +compared with the machine the built-in cost curves were measured on (a 6-core / 12-thread Ryzen 5 3600). +A factor of 2 means "about twice as slow". It is cached in ``~/.cache/autodeep/machine.json`` for 30 days. +""" + +from __future__ import annotations + +import json +import os +import platform +import socket +import subprocess +import sys +import time +from dataclasses import asdict, dataclass, field +from pathlib import Path + +# best-of-5 timings of _benchmark() on the reference machine (AMD Ryzen 5 3600, 6 cores / 12 threads) +REFERENCE_TIMES = {"matmul": 0.0100, "sort": 0.0220, "python": 0.0217} +BENCHMARK_WEIGHTS = {"matmul": 0.4, "sort": 0.3, "python": 0.3} +REFERENCE_PHYSICAL_CORES = 6 +CACHE_DAYS = 30 + + +def _cache_file() -> Path: + return Path(os.environ.get("AUTODEEP_CACHE", Path.home() / ".cache" / "autodeep")) / "machine.json" + + +@dataclass +class MachineProfile: + os: str + cpu_name: str + logical_cores: int + physical_cores: int + ram_total_gb: float | None + ram_available_gb: float | None + gpu: dict = field(default_factory=dict) + device: str = "cpu" # what device="auto" resolves to right now + speed_factor: float = 1.0 # > 1: slower than the reference machine + speed_source: str = "default" + + def to_dict(self) -> dict: + return asdict(self) + + def describe(self) -> str: + ram = f", {self.ram_total_gb:.0f} GB RAM ({self.ram_available_gb:.0f} GB free)" if self.ram_total_gb else "" + gpu = self.gpu or {} + if gpu.get("available"): + g = f"GPU {gpu.get('name', '?')} with {gpu.get('free_mb', 0) / 1024:.1f} of {gpu.get('total_mb', 0) / 1024:.0f} GB free" + g += "" if self.device == "cuda" else " (too little free memory: training on CPU)" + else: + g = "no usable GPU" + speed = f"CPU speed x{1 / self.speed_factor:.2f} of the reference machine" if self.speed_source == "benchmark" else "" + return f"{self.cpu_name}: {self.physical_cores} cores / {self.logical_cores} threads{ram}; {g}" + (f"; {speed}" if speed else "") + + +# -------------------------------------------------------------------------------------- +# probes +# -------------------------------------------------------------------------------------- + + +def _cpu_name() -> str: + try: + if sys.platform.startswith("linux"): + for line in Path("/proc/cpuinfo").read_text().splitlines(): + if line.lower().startswith("model name"): + return line.split(":", 1)[1].strip() + if sys.platform == "darwin": + return subprocess.run(["sysctl", "-n", "machdep.cpu.brand_string"], capture_output=True, text=True, timeout=5).stdout.strip() or "CPU" + except (OSError, subprocess.SubprocessError): + pass + return platform.processor() or platform.machine() or "CPU" + + +def _physical_cores(logical: int) -> int: + try: + import psutil # optional + + n = psutil.cpu_count(logical=False) + if n: + return int(n) + except ImportError: + pass + if sys.platform.startswith("linux"): + try: + cores = set() + phys = core = None + for line in Path("/proc/cpuinfo").read_text().splitlines(): + if line.startswith("physical id"): + phys = line.split(":")[1].strip() + elif line.startswith("core id"): + core = line.split(":")[1].strip() + cores.add((phys, core)) + if cores: + return len(cores) + except OSError: + pass + return max(1, logical // 2) + + +def _ram_gb(): + """``(total, available)`` in GB, or ``(None, None)``.""" + try: + import psutil # optional + + vm = psutil.virtual_memory() + return vm.total / 2**30, vm.available / 2**30 + except ImportError: + pass + try: + if sys.platform.startswith("linux"): + info = {} + for line in Path("/proc/meminfo").read_text().splitlines(): + key, value = line.split(":", 1) + info[key] = int(value.strip().split()[0]) / 2**20 # kB -> GB + return info.get("MemTotal"), info.get("MemAvailable", info.get("MemFree")) + if sys.platform == "darwin": + total = int(subprocess.run(["sysctl", "-n", "hw.memsize"], capture_output=True, text=True, timeout=5).stdout.strip()) / 2**30 + return total, None + if sys.platform == "win32": + import ctypes + + class MEMORYSTATUSEX(ctypes.Structure): + _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong)] + [ + (name, ctypes.c_ulonglong) + for name in ( + "ullTotalPhys", + "ullAvailPhys", + "ullTotalPageFile", + "ullAvailPageFile", + "ullTotalVirtual", + "ullAvailVirtual", + "ullExtended", + ) + ] + + st = MEMORYSTATUSEX() + st.dwLength = ctypes.sizeof(MEMORYSTATUSEX) + ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(st)) + return st.ullTotalPhys / 2**30, st.ullAvailPhys / 2**30 + except (OSError, ValueError, subprocess.SubprocessError, AttributeError): + pass + return None, None + + +def _benchmark() -> dict[str, float]: + """Best-of-5 timings of three small workloads (~0.3 s in total on the reference machine).""" + import numpy as np + + rng = np.random.default_rng(0) + a = rng.standard_normal((400, 400)) + x = rng.standard_normal(300_000) + + def matmul(): + for _ in range(15): + a @ a + + def sort(): + for _ in range(6): + np.sort(x) + + def python(): + s = 0 + for i in range(400_000): + s += i * i + + # warm up (BLAS thread pool, CPU clock ramping up from idle) for ~0.25 s + t_end = time.perf_counter() + 0.25 + while time.perf_counter() < t_end: + matmul() + python() + out = {} + for name, fn in (("matmul", matmul), ("sort", sort), ("python", python)): + best = float("inf") + for _ in range(5): + t = time.perf_counter() + fn() + best = min(best, time.perf_counter() - t) + out[name] = best + return out + + +def speed_factor_from(times: dict[str, float]) -> float: + """Weighted geometric mean of ``time / reference_time`` (clipped to 0.25 - 8).""" + import math + + log = sum(w * math.log(max(times[k], 1e-6) / REFERENCE_TIMES[k]) for k, w in BENCHMARK_WEIGHTS.items()) + return float(min(max(math.exp(log), 0.25), 8.0)) + + +def _machine_key(cpu: str, logical: int) -> str: + return f"{socket.gethostname()}|{cpu}|{logical}" + + +_SPEED_MEMO: dict[str, tuple] = {} + + +def measure_speed(cpu: str, logical: int, refresh: bool = False): + """``(factor, source)``: cached benchmark result for this machine, measured if missing or stale.""" + key = _machine_key(cpu, logical) + if not refresh and key in _SPEED_MEMO: + return _SPEED_MEMO[key] + _SPEED_MEMO[key] = result = _measure_speed(cpu, logical, refresh) + return result + + +def _measure_speed(cpu: str, logical: int, refresh: bool): + env = os.environ.get("AUTODEEP_SPEED_FACTOR") + if env: + try: + return float(env), "AUTODEEP_SPEED_FACTOR" + except ValueError: + pass + path, key = _cache_file(), _machine_key(cpu, logical) + if not refresh: + try: + cached = json.loads(path.read_text()) + if cached.get("key") == key and time.time() - cached.get("time", 0) < CACHE_DAYS * 86400: + return float(cached["speed_factor"]), "benchmark" + except (OSError, ValueError, KeyError): + pass + try: + times = _benchmark() + if speed_factor_from(times) > 1.25: # a cold start or a busy moment: measure again, keep the faster times + again = _benchmark() + times = {k: min(v, again[k]) for k, v in times.items()} + except Exception: # pragma: no cover - numpy issues + return 1.0, "default" + factor = speed_factor_from(times) + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps({"key": key, "time": time.time(), "speed_factor": factor, "times": times})) + except OSError: + pass + return factor, "benchmark" + + +def _logical_cores() -> int: + try: + return len(os.sched_getaffinity(0)) # respects taskset / container CPU limits + except (AttributeError, OSError): + return os.cpu_count() or 1 + + +def current_speed_factor() -> float: + """This machine's speed factor (benchmark cached on disk; 1.0 if it cannot be measured).""" + try: + return measure_speed(_cpu_name(), _logical_cores())[0] + except Exception: # pragma: no cover - estimation is best effort + return 1.0 + + +def machine_profile(benchmark: bool = True) -> MachineProfile: + """Profile of this machine. Free RAM / GPU memory are read on every call; the speed benchmark is cached.""" + from autodeep.device import gpu_info, resolve_device + + logical = _logical_cores() + cpu = _cpu_name() + total, avail = _ram_gb() + factor, source = measure_speed(cpu, logical) if benchmark else (1.0, "default") + return MachineProfile( + os=f"{platform.system()} {platform.release()}", + cpu_name=cpu, + logical_cores=logical, + physical_cores=min(_physical_cores(logical), logical), + ram_total_gb=None if total is None else round(total, 1), + ram_available_gb=None if avail is None else round(avail, 1), + gpu=gpu_info(), + device=resolve_device(), + speed_factor=round(factor, 3), + speed_source=source, + ) diff --git a/autodeep/modelsdefinition/CommonStructure.py b/autodeep/modelsdefinition/CommonStructure.py index 5837403..42eb550 100755 --- a/autodeep/modelsdefinition/CommonStructure.py +++ b/autodeep/modelsdefinition/CommonStructure.py @@ -15,7 +15,7 @@ import copy from pathlib import Path -from typing import Any, Dict, Optional, Tuple +from typing import Any import numpy as np import pandas as pd @@ -23,16 +23,10 @@ from sklearn.utils.class_weight import compute_class_weight from autodeep.device import resolve_device -from autodeep.evaluation.generalevaluator import Evaluator +from autodeep.evaluation.generalevaluator import Evaluator, normalize_metric_name from autodeep.logging_utils import get_logger from autodeep.modelutils.search import TrialOutcome, run_hyperopt -from autodeep.modelutils.trainingutilities import ( - handle_rogue_batch_size, - infer_hyperopt_space, - infer_hyperopt_space_pytorch_tabular, - prepare_optimizer, - prepare_scheduler, -) +from autodeep.modelutils.trainingutilities import infer_hyperopt_space MAX_ROWS_FOR_TRAIN_METRICS = 50_000 @@ -60,48 +54,61 @@ class BaseTrainer: model_name = "base" space_fn = staticmethod(infer_hyperopt_space) #: upper bound on the number of search trials (1 for models with nothing to tune, e.g. TabICL) - max_trials: Optional[int] = None + max_trials: int | None = None #: allow running with an empty ``param_grid`` (defaults only) allow_empty_grid = False #: first trial uses the first option of every ``param_grid`` choice (``null`` = the library's tuned default) first_trial_defaults = False #: train metrics are computed on a subsample of at most this many rows max_rows_for_train_metrics = MAX_ROWS_FOR_TRAIN_METRICS + #: False for models whose train metrics mean nothing (TabICL scores its own context rows) + compute_train_metrics = True + #: after the search, refit the best configuration on all training rows (train + validation split). + #: Only for models where that is cheap and needs no early stopping, e.g. in-context learners. + refit_on_full_train = False - def __init__(self, problem_type: str = "binary_classification", random_state: int = 42, num_workers: Optional[int] = None): + def __init__(self, problem_type: str = "binary_classification", random_state: int = 42, num_workers: int | None = None): self.problem_type = problem_type self.random_state = random_state self.task = "regression" if problem_type == "regression" else "classification" self.logger = get_logger(self.model_name) self.model = None - self.extra_info: Optional[Dict[str, Any]] = None - self.default_params: Dict[str, Any] = {} + self.extra_info: dict[str, Any] | None = None + self.default_params: dict[str, Any] = {} self.num_workers = num_workers - self.output_dir: Optional[Path] = None # set by AutoRunner; where per-trial files go - self.max_epochs: Optional[int] = None # global override, e.g. for quick runs - self.timeout: Optional[float] = None # seconds for the whole search + self.output_dir: Path | None = None # set by AutoRunner; where per-trial files go + self.max_epochs: int | None = None # global override, e.g. for quick runs + self.timeout: float | None = None # seconds for the whole search self.search_result = None - self.num_classes: Optional[int] = None + self.num_classes: int | None = None # ------------------------------------------------------------------ hooks - def prepare(self, X: pd.DataFrame, y: pd.Series, extra_info: Optional[Dict]) -> None: + def prepare(self, X: pd.DataFrame, y: pd.Series, extra_info: dict | None) -> None: """Called once before the search (e.g. compute class weights).""" def transform_X(self, X: pd.DataFrame) -> pd.DataFrame: """Applied to every feature matrix before fitting / predicting.""" return X - def fit_trial(self, params: Dict[str, Any], X_train, y_train, X_val, y_val): + def fit_trial(self, params: dict[str, Any], X_train, y_train, X_val, y_val): raise NotImplementedError - def predict_with(self, model, X: pd.DataFrame) -> Tuple[np.ndarray, Optional[np.ndarray]]: + def predict_with(self, model, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray | None]: """Return ``(predictions, probabilities)``; probabilities are 1-D (binary), 2-D (multiclass) or ``None``.""" raise NotImplementedError # ------------------------------------------------------------------ helpers @property def device(self) -> str: - return resolve_device() + return getattr(self, "_device_override", None) or resolve_device() + + def to_device(self, device: str) -> None: + """Run predictions of the trained model on ``device`` (``"cpu"`` or ``"cuda"``), e.g. after loading it elsewhere.""" + self._device_override = device + + def strip_for_saving(self) -> None: + """Drop search bookkeeping that a saved predictor does not need.""" + self.search_result = None def _setting(self, name, default=None): """Read a value from ``default_params`` honouring global overrides.""" @@ -115,7 +122,7 @@ def cpu_torch_threads(self, n_rows: int) -> int: return torch_threads(n_rows) - def class_weights(self, y: pd.Series) -> Optional[np.ndarray]: + def class_weights(self, y: pd.Series) -> np.ndarray | None: if self.problem_type == "regression": return None classes = np.arange(self.num_classes) @@ -128,7 +135,7 @@ def _split(self, X, y, val_size): stratify = y if self.problem_type != "regression" and y.value_counts().min() >= 2 else None return train_test_split(X, y, test_size=val_size, random_state=self.random_state, stratify=stratify) - def _metrics(self, evaluator: Evaluator, model, X, y) -> Dict[str, float]: + def _metrics(self, evaluator: Evaluator, model, X, y) -> dict[str, float]: if len(X) > self.max_rows_for_train_metrics: idx = np.random.default_rng(0).choice(len(X), self.max_rows_for_train_metrics, replace=False) X, y = X.iloc[idx], y.iloc[idx] @@ -164,12 +171,34 @@ def hyperopt_search(self, X, y, model_config, metric, eval_metrics, max_evals=16 X_tr, X_val, y_tr, y_val = self._split(X, y, val_size) evaluator = Evaluator(problem_type=self.problem_type, run_metrics=eval_metrics, metric=metric) + # search_folds > 1: score every trial on K stratified folds of the training data (mean of the validation + # metrics) instead of one split. K times the cost, much less noise when candidates differ by little. + # The model kept for prediction is the one of the first split (the usual train/validation split). + n_search_folds = int(self.default_params.get("search_folds", 1) or 1) + extra_splits = [] + if n_search_folds > 1: + from sklearn.model_selection import KFold, StratifiedKFold + + cv_cls = KFold if self.problem_type == "regression" else StratifiedKFold + splits = list(cv_cls(n_search_folds, shuffle=True, random_state=self.random_state).split(X, y)) + extra_splits = [(X.iloc[a], X.iloc[b], y.iloc[a], y.iloc[b]) for a, b in splits[1:]] + def objective(params): params = {k: v for k, v in params.items() if k != _NO_PARAMS} model = self.fit_trial(params, X_tr, y_tr, X_val, y_val) + val = self._metrics(evaluator, model, X_val, y_val) + if extra_splits: + folds = [val] + for Xa, Xb, ya, yb in extra_splits: + m = self.fit_trial(params, Xa, ya, Xb, yb) + folds.append(self._metrics(evaluator, m, Xb, yb)) + del m + val = {k: float(np.mean([f[k] for f in folds])) for k in val} + key = normalize_metric_name(metric) + val[f"{key}_folds"] = [f.get(key) for f in folds] return TrialOutcome( - validation_metrics=self._metrics(evaluator, model, X_val, y_val), - train_metrics=self._metrics(evaluator, model, X_tr, y_tr), + validation_metrics=val, + train_metrics=self._metrics(evaluator, model, X_tr, y_tr) if self.compute_train_metrics else {}, model=model, ) @@ -196,6 +225,10 @@ def objective(params): torch.set_num_threads(previous_threads) self.search_result = result self.model = result.best_model + if self.refit_on_full_train: + raw = {k: v for k, v in (result.best_raw_params or {}).items() if k != _NO_PARAMS} + self.logger.info(f"{self.model_name}: refitting the best configuration on all {len(X)} training rows") + self.model = self.fit_trial(raw, X, y, X_val, y_val) self.best_model = self.model self.on_search_end() best_params = {k: v for k, v in result.best_params.items() if k != _NO_PARAMS} @@ -206,7 +239,7 @@ def _default_start_point(self, param_grid): """Hyperopt point selecting option 0 of every choice, if every parameter is a choice starting with ``None``.""" if not (self.first_trial_defaults and param_grid): return None - if all(isinstance(v, (list, tuple)) and len(v) > 1 and v[0] is None for v in param_grid.values()): + if all(isinstance(v, list | tuple) and len(v) > 1 and v[0] is None for v in param_grid.values()): return [{name: 0 for name in param_grid}] self.logger.debug(f"{self.model_name}: param_grid is not all null-first choices, first trial is random") return None @@ -246,155 +279,3 @@ def save_model(self, path): Path(path).parent.mkdir(parents=True, exist_ok=True) joblib.dump(self.model, path) - - -def _redirect_pt_tmp(): - """PyTorch Tabular writes ``./.pt_tmp/exp_version_manager.yml`` in the working directory; keep it in AutoDeep's cache.""" - import os - - import pytorch_tabular.tabular_model as ptm - - if getattr(ptm.ExperimentRunManager, "_autodeep", False): - return - cache = Path(os.environ.get("AUTODEEP_CACHE", Path.home() / ".cache" / "autodeep")) - path = str(cache / "pytorch_tabular" / "exp_version_manager.yml") - base = ptm.ExperimentRunManager - - class _ExperimentRunManager(base): - _autodeep = True - - def __init__(self, exp_version_manager: str = path): - super().__init__(exp_version_manager) - - ptm.ExperimentRunManager = _ExperimentRunManager - - -class PytorchTabularTrainer(BaseTrainer): - """Generic wrapper around any PyTorch Tabular model config class.""" - - config_class = None - space_fn = staticmethod(infer_hyperopt_space_pytorch_tabular) - - def __init__(self, problem_type="binary_classification", random_state=42, num_workers=None): - super().__init__(problem_type, random_state=random_state, num_workers=num_workers) - self.loss_fn = None - - # -- hooks - def adjust_params(self, params: Dict[str, Any]) -> Dict[str, Any]: - """Model specific parameter fix-ups (override in subclasses).""" - return params - - def prepare(self, X, y, extra_info): - import torch - import torch.nn as nn - - if self.problem_type == "regression": - self.loss_fn = nn.MSELoss() - else: - self.loss_fn = nn.CrossEntropyLoss(weight=torch.tensor(self.class_weights(y), dtype=torch.float32)) - cat_cols = [c for c in self.extra_info.get("cat_col_names", []) if c in X.columns] - self.categorical_cols = cat_cols - self.continuous_cols = [c for c in X.columns if c not in cat_cols] - - def _configs(self, params): - from pytorch_tabular.config import DataConfig, OptimizerConfig, TrainerConfig - - dp = self.default_params - data_config = DataConfig( - target=[TARGET], - continuous_cols=self.continuous_cols, - categorical_cols=self.categorical_cols, - num_workers=self.num_workers if self.num_workers is not None else 0, - pin_memory=self.device == "cuda", - ) - trainer_config = TrainerConfig( - batch_size=int(params.get("batch_size", dp.get("batch_size", 256))), - max_epochs=int(self._setting("max_epochs", 100)), - accelerator="gpu" if self.device == "cuda" else "cpu", - devices=1, - auto_lr_find=bool(dp.get("auto_lr_find", False)), - early_stopping="valid_loss", - early_stopping_mode="min", - early_stopping_patience=int(dp.get("early_stopping_patience", 10)), - early_stopping_min_delta=float(dp.get("tol", 0.0)), - checkpoints=None, # best weights are kept in memory by BestWeights (no torch.load of pickled configs) - load_best=False, - progress_bar="none", - precision=dp.get("precision", 32), - seed=self.random_state, - trainer_kwargs={"enable_model_summary": False}, - ) - optimizer_name, optimizer_params, learning_rate = prepare_optimizer(params.get("optimizer_fn")) - scheduler_name, scheduler_params = prepare_scheduler(params.get("scheduler_fn")) - optimizer_config = OptimizerConfig( - optimizer=optimizer_name, - optimizer_params=optimizer_params, - lr_scheduler=scheduler_name, - lr_scheduler_params=scheduler_params, - lr_scheduler_monitor_metric="valid_loss", - ) - return data_config, trainer_config, optimizer_config, learning_rate - - def prepare_tabular_model(self, params, default_params=None, default=False): - import inspect - - from pytorch_tabular import TabularModel - - _redirect_pt_tmp() - params = self.adjust_params(dict(params)) - data_config, trainer_config, optimizer_config, learning_rate = self._configs(params) - valid = inspect.signature(self.config_class).parameters - model_kwargs = {k: v for k, v in params.items() if k in valid and k not in ("task", "learning_rate")} - ignored = sorted(k for k in params if k not in valid and k not in ("batch_size", "optimizer_fn", "scheduler_fn")) - if ignored: - self.logger.debug(f"{self.model_name}: ignoring parameters not accepted by {self.config_class.__name__}: {ignored}") - model_config = self.config_class(task=self.task, learning_rate=learning_rate, **model_kwargs) - tabular_model = TabularModel( - data_config=data_config, - model_config=model_config, - optimizer_config=optimizer_config, - trainer_config=trainer_config, - verbose=False, - suppress_lightning_logger=True, - ) - tabular_model.logger = False # otherwise Lightning writes ./lightning_logs/version_N for every trial - return tabular_model - - def fit_trial(self, params, X_train, y_train, X_val, y_val): - from sklearn.preprocessing import StandardScaler - - batch_size = int(params.get("batch_size", self.default_params.get("batch_size", 256))) - X_train, y_train, X_val, y_val = handle_rogue_batch_size(X_train, y_train, X_val, y_val, batch_size) - model = self.prepare_tabular_model(params) - fit_kwargs = {} - if self.problem_type == "regression": - fit_kwargs["target_transform"] = StandardScaler() - from autodeep.modelsdefinition.lightning_callbacks import BestWeights - - best = BestWeights() - model.fit( - train=pd.concat([X_train, y_train.rename(TARGET)], axis=1), - validation=pd.concat([X_val, y_val.rename(TARGET)], axis=1), - loss=self.loss_fn, - seed=self.random_state, - callbacks=[best], - **fit_kwargs, - ) - if best.state is not None: - model.model.load_state_dict(best.state) - return model - - def predict_with(self, model, X): - pred_df = model.predict(X, progress_bar="none") - if self.problem_type == "regression": - return pred_df[f"{TARGET}_prediction"].to_numpy(dtype=float), None - prob_cols = [f"{TARGET}_{k}_probability" for k in range(self.num_classes)] - proba = np.column_stack([pred_df[c].to_numpy(dtype=float) if c in pred_df else np.zeros(len(pred_df)) for c in prob_cols]) - proba = np.nan_to_num(proba, nan=0.0) - pred = proba.argmax(axis=1) - if self.problem_type == "binary_classification": - return pred, proba[:, 1] - return pred, proba - - def save_model(self, path): - self.model.save_model(str(path)) diff --git a/autodeep/modelsdefinition/LightGBMTrainer.py b/autodeep/modelsdefinition/LightGBMTrainer.py new file mode 100644 index 0000000..dbdb0a7 --- /dev/null +++ b/autodeep/modelsdefinition/LightGBMTrainer.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +import numpy as np + +from autodeep.device import cpu_threads +from autodeep.modelsdefinition.CommonStructure import SklearnLikeTrainer + + +class LightGBMTrainer(SklearnLikeTrainer): + """LightGBM (leaf-wise histogram GBDT) on CPU, with native pandas categorical columns.""" + + model_name = "lgbm" + + def fit_trial(self, params, X_train, y_train, X_val, y_val): + import lightgbm as lgb + + params = dict(params) + for k in ("num_leaves", "min_child_samples", "max_bin", "n_estimators", "max_cat_to_onehot", "bagging_freq"): + if k in params: + params[k] = int(params[k]) + es = int(self.default_params.get("early_stopping_rounds", 100)) + common = dict(random_state=self.random_state, n_jobs=cpu_threads(len(X_train)), verbosity=-1) + if self.problem_type == "regression": + model = lgb.LGBMRegressor(**common, **params) + elif self.problem_type == "multiclass_classification": + model = lgb.LGBMClassifier(objective="multiclass", num_class=self.num_classes, **common, **params) + else: + model = lgb.LGBMClassifier(objective="binary", **common, **params) + X_train, off_tr = split_offset(_categories(X_train), self.default_params) + X_val, off_val = split_offset(_categories(X_val), self.default_params) + fit_kw = {} if off_tr is None else dict(init_score=off_tr, eval_init_score=[off_val]) + model.fit(X_train, y_train, eval_set=[(X_val, y_val)], callbacks=[lgb.early_stopping(es, verbose=False)], **fit_kw) + return model + + def predict_with(self, model, X): + X, offset = split_offset(_categories(X), self.default_params) + if offset is None: + return super().predict_with(model, X) + if self.problem_type != "binary_classification": + raise NotImplementedError("offset columns are supported for binary classification only") + prob = 1.0 / (1.0 + np.exp(-(model.predict(X, raw_score=True) + offset))) + return (prob >= 0.5).astype(int), prob + + def save_model(self, path): + self.model.booster_.save_model(str(path)) + + +def _categories(X): + obj_cols = X.select_dtypes(include=["object", "string", "bool"]).columns + if len(obj_cols) == 0: + return X + X = X.copy() + for c in obj_cols: + X[c] = X[c].astype("category") + return X + + +def split_offset(X, default_params): + """Remove the offset column (``default_params["offset_column"]``) from ``X``. + + An offset is a column of log-odds from another model (e.g. a GLM): boosting starts from it instead of from a + constant (``init_score`` / ``base_margin``) and predictions add it back. Rows of the training set must get + out-of-fold offsets, or the trees learn nothing. + """ + col = (default_params or {}).get("offset_column") + if not col or col not in X.columns: + return X, None + return X.drop(columns=[col]), X[col].to_numpy(dtype=float) diff --git a/autodeep/modelsdefinition/ResNetModel.py b/autodeep/modelsdefinition/ResNetModel.py index 69d04d0..d544030 100644 --- a/autodeep/modelsdefinition/ResNetModel.py +++ b/autodeep/modelsdefinition/ResNetModel.py @@ -58,7 +58,7 @@ def to_tensor(self, X): import torch arr = X.to_numpy(dtype=np.float32).reshape(-1, 1, self.img_rows, self.img_columns) - return torch.as_tensor(arr).expand(-1, 3, -1, -1).contiguous() + return torch.tensor(arr).expand(-1, 3, -1, -1).contiguous() # torch.tensor copies (to_numpy can be read-only) def build_network(self, params, n_features, n_outputs): return build_resnet(params.get("resnet_depth", "resnet18"), params.get("weights"), n_outputs) diff --git a/autodeep/modelsdefinition/ResidualMLP.py b/autodeep/modelsdefinition/ResidualMLP.py new file mode 100644 index 0000000..4ec18d2 --- /dev/null +++ b/autodeep/modelsdefinition/ResidualMLP.py @@ -0,0 +1,168 @@ +"""Residual MLP: a plain PyTorch MLP that can start from another model's prediction (``offset_column``). + +With an offset (log-odds of e.g. an out-of-fold GLM) the output is ``offset + net(x)`` and the last layer is +initialised at zero, so training starts exactly at the offset model and the network only learns what it misses +(the neural counterpart of GLM-boosted trees). Without an offset it is an ordinary MLP. + +Inputs: numeric columns are standardised (quantile-clipped), categorical columns one-hot encoded (levels seen in +training). Early stopping on the validation metric (AUC for binary classification, loss otherwise); the best +epoch's weights are kept. +""" + +from __future__ import annotations + +import copy +import math + +import numpy as np +import pandas as pd + +from autodeep.modelsdefinition.CommonStructure import BaseTrainer +from autodeep.modelsdefinition.LightGBMTrainer import split_offset + + +class ResidualMLPTrainer(BaseTrainer): + model_name = "resmlp" + predict_batch_size = 16384 + + # ------------------------------------------------------------------ inputs + def prepare(self, X, y, extra_info): + X, _ = split_offset(X, self.default_params) + self.cat_cols_ = [c for c in X.columns if not pd.api.types.is_numeric_dtype(X[c]) or isinstance(X[c].dtype, pd.CategoricalDtype)] + self.num_cols_ = [c for c in X.columns if c not in self.cat_cols_] + self.levels_ = {c: list(pd.Series(X[c].astype(str).unique()).sort_values()) for c in self.cat_cols_} + num = X[self.num_cols_].to_numpy(dtype=np.float64) + self.lo_, self.hi_ = np.nanquantile(num, 0.001, axis=0), np.nanquantile(num, 0.999, axis=0) + clipped = np.clip(num, self.lo_, self.hi_) + self.mu_, self.sd_ = np.nanmean(clipped, axis=0), np.nanstd(clipped, axis=0) + 1e-6 + if self.problem_type == "regression": + self.y_mean, self.y_std = float(y.mean()), float(y.std() or 1.0) + + def _matrix(self, X): + X, offset = split_offset(X, self.default_params) + num = (np.clip(X[self.num_cols_].to_numpy(dtype=np.float64), self.lo_, self.hi_) - self.mu_) / self.sd_ + blocks = [np.nan_to_num(num)] + for c in self.cat_cols_: + v = X[c].astype(str).to_numpy() + blocks.append(np.column_stack([(v == lev) for lev in self.levels_[c]]).astype(np.float64)) + return np.hstack(blocks).astype(np.float32), offset + + @property + def n_outputs(self): + return self.num_classes if self.problem_type == "multiclass_classification" else 1 + + # ------------------------------------------------------------------ model + def _build(self, params, d_in): + import torch.nn as nn + + width, depth = int(params.get("width", 256)), int(params.get("n_layers", 2)) + drop = float(params.get("dropout", 0.1)) + layers, d = [], d_in + for i in range(depth): + w = max(16, width // (2**i)) + layers += [nn.Linear(d, w), nn.SiLU(), nn.Dropout(drop)] + d = w + head = nn.Linear(d, self.n_outputs) + nn.init.zeros_(head.weight) + nn.init.zeros_(head.bias) + return nn.Sequential(*layers, head) + + def fit_trial(self, params, X_train, y_train, X_val, y_val): + import torch + import torch.nn.functional as Fn + from sklearn.metrics import roc_auc_score + + torch.manual_seed(self.random_state) + dev = self.device + Xa, oa = self._matrix(X_train) + Xb, ob = self._matrix(X_val) + oa = np.zeros(len(Xa), np.float32) if oa is None else oa.astype(np.float32) + ob = np.zeros(len(Xb), np.float32) if ob is None else ob.astype(np.float32) + ya, yb = np.asarray(y_train), np.asarray(y_val) + if self.problem_type == "regression": + ya = (ya - self.y_mean) / self.y_std + net = self._build(params, Xa.shape[1]).to(dev) + net._autodeep_build = (dict(params), int(Xa.shape[1])) + if self.problem_type != "multiclass_classification" and not self.default_params.get("offset_column"): + with torch.no_grad(): # start at the base rate (or mean) when there is no offset + net[-1].bias.fill_(float(np.log(ya.mean() / (1 - ya.mean()))) if self.problem_type == "binary_classification" else 0.0) + lr, wd = float(params.get("lr", 1e-3)), float(params.get("weight_decay", 1e-5)) + opt = torch.optim.AdamW(net.parameters(), lr=lr, weight_decay=wd) + epochs = int(self._setting("max_epochs", params.get("max_epochs", 30))) + bs = int(min(int(params.get("batch_size") or 1024), len(Xa))) + steps = epochs * math.ceil(len(Xa) / bs) + sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=steps, pct_start=0.1) + Ta, Toa = torch.tensor(Xa, device=dev), torch.tensor(oa, device=dev) + ytype = torch.long if self.problem_type == "multiclass_classification" else torch.float32 + Tya = torch.tensor(ya, device=dev, dtype=ytype) + patience = int(self.default_params.get("early_stopping_patience", 4)) + best, best_state, bad = -math.inf, None, 0 + g = torch.Generator(device=dev).manual_seed(self.random_state) + for _ in range(epochs): + net.train() + perm = torch.randperm(len(Ta), device=dev, generator=g) + for i in range(0, len(Ta), bs): + idx = perm[i : i + bs] + out = net(Ta[idx]) + if self.problem_type == "multiclass_classification": + loss = Fn.cross_entropy(out, Tya[idx]) + elif self.problem_type == "binary_classification": + loss = Fn.binary_cross_entropy_with_logits(out.reshape(-1) + Toa[idx], Tya[idx]) + else: + loss = Fn.mse_loss(out.reshape(-1) + Toa[idx], Tya[idx]) + opt.zero_grad(set_to_none=True) + loss.backward() + opt.step() + sched.step() + raw = self._raw(net, Xb, ob) + if self.problem_type == "binary_classification": + score = roc_auc_score(yb, raw) if len(np.unique(yb)) > 1 else -float(np.mean(np.logaddexp(0, raw) - yb * raw)) + elif self.problem_type == "multiclass_classification": + score = -float(Fn.cross_entropy(torch.tensor(raw), torch.tensor(yb, dtype=torch.long))) + else: + score = -float(np.mean((raw - (yb - self.y_mean) / self.y_std) ** 2)) + if score > best: + best, bad, best_state = score, 0, copy.deepcopy(net.state_dict()) + else: + bad += 1 + if bad >= patience: + break + net.load_state_dict(best_state) + net.eval() + return net + + def _raw(self, net, X, offset): + import torch + + net.eval() + outs = [] + with torch.no_grad(): + for i in range(0, len(X), self.predict_batch_size): + outs.append(net(torch.tensor(X[i : i + self.predict_batch_size], device=self.device)).float().cpu().numpy()) + out = np.concatenate(outs) if outs else np.zeros((0, self.n_outputs)) + if self.n_outputs == 1: + out = out.reshape(-1) + (0 if offset is None else offset) + return out + + def predict_with(self, net, X): + net = net.to(self.device) + Xm, offset = self._matrix(X) + raw = self._raw(net, Xm, offset) + if self.problem_type == "regression": + return raw * self.y_std + self.y_mean, None + if self.problem_type == "binary_classification": + prob = 1.0 / (1.0 + np.exp(-raw)) + return (prob >= 0.5).astype(int), prob + e = np.exp(raw - raw.max(axis=1, keepdims=True)) + prob = e / e.sum(axis=1, keepdims=True) + return prob.argmax(axis=1), prob + + def to_device(self, device): + super().to_device(device) + if self.model is not None: + self.model.to("cuda" if device == "cuda" else "cpu") + + def save_model(self, path): + import torch + + torch.save(self.model.state_dict(), path) diff --git a/autodeep/modelsdefinition/XGBoostTrainer.py b/autodeep/modelsdefinition/XGBoostTrainer.py index 479f31b..3d800aa 100755 --- a/autodeep/modelsdefinition/XGBoostTrainer.py +++ b/autodeep/modelsdefinition/XGBoostTrainer.py @@ -1,7 +1,10 @@ from __future__ import annotations +import numpy as np + from autodeep.device import cpu_threads, xgboost_device from autodeep.modelsdefinition.CommonStructure import SklearnLikeTrainer +from autodeep.modelsdefinition.LightGBMTrainer import split_offset class XGBoostTrainer(SklearnLikeTrainer): @@ -25,12 +28,30 @@ def fit_trial(self, params, X_train, y_train, X_val, y_val): model = xgb.XGBClassifier(objective="multi:softprob", num_class=self.num_classes, **common, **params) else: model = xgb.XGBClassifier(objective="binary:logistic", **common, **params) - X_train, X_val = _categories_to_pandas(X_train), _categories_to_pandas(X_val) - model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=bool(self.default_params.get("verbose", False))) + X_train, off_tr = split_offset(_categories_to_pandas(X_train), self.default_params) + X_val, off_val = split_offset(_categories_to_pandas(X_val), self.default_params) + fit_kw = {} if off_tr is None else dict(base_margin=off_tr, base_margin_eval_set=[off_val]) + model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=bool(self.default_params.get("verbose", False)), **fit_kw) return model def predict_with(self, model, X): - return super().predict_with(model, _categories_to_pandas(X)) + import warnings + + with warnings.catch_warnings(): + # a GPU booster given CPU data falls back to a DMatrix (still on the GPU) and warns on every call + warnings.filterwarnings("ignore", message=".*mismatched devices.*") + X, offset = split_offset(_categories_to_pandas(X), self.default_params) + if offset is None: + return super().predict_with(model, X) + if self.problem_type != "binary_classification": + raise NotImplementedError("offset columns are supported for binary classification only") + prob = np.asarray(model.predict_proba(X, base_margin=offset))[:, 1] + return (prob >= 0.5).astype(int), prob + + def to_device(self, device): + super().to_device(device) + if self.model is not None: + self.model.set_params(device="cuda" if device == "cuda" else "cpu") def save_model(self, path): self.model.save_model(str(path)) diff --git a/autodeep/modelsdefinition/deep_tabular_models.py b/autodeep/modelsdefinition/deep_tabular_models.py new file mode 100644 index 0000000..d087464 --- /dev/null +++ b/autodeep/modelsdefinition/deep_tabular_models.py @@ -0,0 +1,148 @@ +"""Deep tabular models with learned categorical embeddings: CategoryEmbedding, TabNet, FT-Transformer, +TabTransformer, AutoInt, GANDALF, GATE, NODE and DANet. + +The architectures were ported from pytorch-tabular (see ``tabular_nets/``) and are trained with AutoDeep's +own loop (:class:`~autodeep.modelsdefinition.torch_base.TorchTrainer`): early stopping on validation loss +with the best weights kept in memory, AutoDeep's optimizers and schedulers, and the regression target +standardised during training. Hyperparameter names are the same as in pytorch-tabular's model configs. +""" + +from __future__ import annotations + +from typing import Any + +import numpy as np +import pandas as pd + +from autodeep.modelsdefinition.torch_base import TorchTrainer + + +class EmbeddingTorchTrainer(TorchTrainer): + """Continuous columns as floats, categorical columns ordinal-encoded (unseen values and NaN map to 0).""" + + arch: str = "" + + # ------------------------------------------------------------------ hooks + def adjust_params(self, params: dict[str, Any]) -> dict[str, Any]: + """Model specific parameter fix-ups (override in subclasses).""" + return params + + def prepare(self, X, y, extra_info): + super().prepare(X, y, extra_info) + declared = [c for c in (extra_info or {}).get("cat_col_names", []) if c in X.columns] + undeclared = [c for c in X.columns if c not in declared and not pd.api.types.is_numeric_dtype(X[c])] + self.categorical_cols = declared + undeclared + self.continuous_cols = [c for c in X.columns if c not in self.categorical_cols] + # code 0 is reserved for unknown values, as in pytorch-tabular's OrdinalEncoder + self.category_maps = {c: {v: i + 1 for i, v in enumerate(sorted(X[c].dropna().astype(str).unique()))} for c in self.categorical_cols} + self.cat_cardinalities = [len(self.category_maps[c]) + 1 for c in self.categorical_cols] + + def to_tensor(self, X: pd.DataFrame): + import torch + + parts = [X[self.continuous_cols].to_numpy(dtype=np.float32)] + for c in self.categorical_cols: + codes = X[c].astype(str).where(X[c].notna(), None).map(self.category_maps[c]) + parts.append(codes.fillna(0).to_numpy(dtype=np.float32).reshape(-1, 1)) + return torch.as_tensor(np.concatenate(parts, axis=1) if parts else np.empty((len(X), 0), np.float32)) + + def _split_input(self, xb): + n = len(self.continuous_cols) + return xb[:, :n], xb[:, n:].long() + + def _forward(self, net, xb): + out = net(*self._split_input(xb)) + return out.reshape(-1) if self.n_outputs == 1 else out + + def build_network(self, params, n_features, n_outputs): + from autodeep.modelsdefinition.tabular_nets.architectures import build_network + + params = self.adjust_params(dict(params)) + params.setdefault("batch_size", self.default_params.get("batch_size", 256)) + return build_network(self.arch, params, len(self.continuous_cols), self.cat_cardinalities, n_outputs, self.task) + + def init_network(self, net, X_train_t, y_train_t): + """pytorch-tabular's data-aware initialisation: NODE thresholds and the GANDALF/GATE regression bias.""" + import torch + + n = int(getattr(net.hparams, "data_aware_init_batch_size", 2000)) + g = torch.Generator().manual_seed(self.random_state) + idx = torch.randperm(len(X_train_t), generator=g)[:n] + x_cont, x_cat = self._split_input(X_train_t[idx].to(self.device)) + net.data_aware_init(x_cont, x_cat, y_train_t[idx].to(self.device)) + + +def _embed_dim_from_heads(params, multiplier="input_embed_dim_multiplier", target="input_embed_dim"): + """The embedding size must be a multiple of ``num_heads``: the grid samples a multiplier instead.""" + mult, heads = params.pop(multiplier, None), params.get("num_heads") + if mult is not None and heads is not None: + params[target] = int(mult) * int(heads) + return params + + +class CategoryEmbeddingTrainer(EmbeddingTorchTrainer): + model_name = "categoryembedding" + arch = "categoryembedding" + + +class TabNetTrainer(EmbeddingTorchTrainer): + model_name = "tabnet" + arch = "tabnet" + + +class FTTransformerTrainer(EmbeddingTorchTrainer): + model_name = "fttransformer" + arch = "fttransformer" + + def adjust_params(self, params): + return _embed_dim_from_heads(params) + + +class TabTransformerTrainer(EmbeddingTorchTrainer): + model_name = "tabtransformer" + arch = "tabtransformer" + + #: the old pytorch-tabular ``out_ff_*`` options configure the MLP head (pytorch-tabular 1.x ignored them) + _HEAD_KEYS = { + "out_ff_layers": "layers", + "out_ff_activation": "activation", + "out_ff_dropout": "dropout", + "out_ff_initialization": "initialization", + } + + def adjust_params(self, params): + head = dict(params.pop("head_config", None) or {}) + for old, new in self._HEAD_KEYS.items(): + if old in params: + head[new] = params.pop(old) + if head: + params["head_config"] = head + return _embed_dim_from_heads(params) + + +class AutoIntTrainer(EmbeddingTorchTrainer): + model_name = "autoint" + arch = "autoint" + + def adjust_params(self, params): + return _embed_dim_from_heads(params, "attn_embed_dim_multiplier", "attn_embed_dim") + + +class GandalfTrainer(EmbeddingTorchTrainer): + model_name = "gandalf" + arch = "gandalf" + + +class GateTrainer(EmbeddingTorchTrainer): + model_name = "gate" + arch = "gate" + + +class NodeTrainer(EmbeddingTorchTrainer): + model_name = "node" + arch = "node" + + +class DANetTrainer(EmbeddingTorchTrainer): + model_name = "danet" + arch = "danet" diff --git a/autodeep/modelsdefinition/foundation_models.py b/autodeep/modelsdefinition/foundation_models.py index e44dac5..97c940a 100644 --- a/autodeep/modelsdefinition/foundation_models.py +++ b/autodeep/modelsdefinition/foundation_models.py @@ -12,6 +12,8 @@ from __future__ import annotations +import copy + import numpy as np import pandas as pd @@ -62,11 +64,36 @@ def predict_with(self, model, X): class TabICLTrainer(_RawFeaturesTrainer): """TabICLv2 tabular foundation model (no training, no hyperparameters).""" + def __getstate__(self): + # TabICL re-creates its torch state when unpickled, on the device it was given: always CPU first, so a model + # trained on a GPU also loads on a machine without one. Predictor.load() then moves it with to_device(). + state, light = self.__dict__.copy(), {} + for key in ("model", "best_model"): + est = state.get(key) + if est is not None and getattr(est, "device", None) != "cpu": + if id(est) not in light: + light[id(est)] = copy.copy(est) + light[id(est)].device = "cpu" + state[key] = light[id(est)] + return state + + def to_device(self, device): + super().to_device(device) + target = self._torch_device() + if self.model is not None and str(getattr(self.model, "device_", "cpu")) != target: + state = self.model.__getstate__() + state["device"] = target + self.model.__setstate__(state) # reloads the (cached) weights on the new device + self.best_model = self.model + model_name = "tabicl" max_trials = 1 allow_empty_grid = True - # predicting costs O(rows x context): don't spend minutes scoring the context rows on themselves - max_rows_for_train_metrics = 1000 + # scoring the context rows against themselves says nothing (and costs O(rows x context)) + compute_train_metrics = False + # "fitting" only stores the context: validation scores come from the 80% split, test predictions + # use every training row as context + refit_on_full_train = True def cpu_torch_threads(self, n_rows: int) -> int: return _physical_cores() @@ -102,7 +129,52 @@ def fit_trial(self, params, X_train, y_train, X_val, y_val): return model +def _move_torch_state(obj, device, _seen=None, _depth=0): + """Move every module / tensor / ``torch.device`` attribute inside a pytabkit model to ``device``. + + pytabkit only implements ``.to()`` for RealMLP; TabM keeps its network, fitted transforms and a ``device_`` + attribute in nested interface objects. Only pytabkit objects and plain containers are traversed. + """ + import torch + + _seen = set() if _seen is None else _seen + if isinstance(obj, torch.nn.Module): + obj.to(device) # in place; some pytabkit modules override .to() and return None + return obj + if isinstance(obj, torch.Tensor): + return obj.to(device) + if isinstance(obj, torch.device): + return torch.device(device) + if _depth > 12 or id(obj) in _seen: + return obj + _seen.add(id(obj)) + if isinstance(obj, dict): + for k in list(obj): + obj[k] = _move_torch_state(obj[k], device, _seen, _depth + 1) + elif isinstance(obj, list): + for i, v in enumerate(obj): + obj[i] = _move_torch_state(v, device, _seen, _depth + 1) + elif isinstance(obj, tuple): + return type(obj)(_move_torch_state(v, device, _seen, _depth + 1) for v in obj) if not hasattr(obj, "_fields") else obj + elif type(obj).__module__.startswith("pytabkit") and hasattr(obj, "__dict__"): + for k, v in list(vars(obj).items()): + setattr(obj, k, _move_torch_state(v, device, _seen, _depth + 1)) + return obj + + class _PytabkitTrainer(_RawFeaturesTrainer): + def to_device(self, device): + super().to_device(device) + if self.model is not None: + target = self._torch_device() + try: + self.model.to(target) # RealMLP (also updates its own device setting) + except (AttributeError, NotImplementedError): + pass + _move_torch_state(self.model, target) + if hasattr(self.model, "device"): + self.model.device = target + first_trial_defaults = True # trial 1 = the published tuned defaults (TD / D), then search around them classifier = "" regressor = "" diff --git a/autodeep/modelsdefinition/lightning_callbacks.py b/autodeep/modelsdefinition/lightning_callbacks.py deleted file mode 100644 index bdb6c91..0000000 --- a/autodeep/modelsdefinition/lightning_callbacks.py +++ /dev/null @@ -1,26 +0,0 @@ -"""Lightning callbacks (module level so that saved PyTorch Tabular models can be pickled).""" - -import pytorch_lightning as pl - - -class BestWeights(pl.Callback): - """Keep an in-memory copy of the weights with the lowest validation loss. - - Replaces PyTorch Tabular's checkpoint reload, which fails with ``torch.load(weights_only=True)`` - (the default since PyTorch 2.6) because checkpoints contain omegaconf objects. - """ - - def __init__(self): - self.best = float("inf") - self.state = None - - def on_validation_epoch_end(self, trainer, pl_module): - if trainer.sanity_checking: - return - value = trainer.callback_metrics.get("valid_loss") - if value is not None and float(value) < self.best: - self.best = float(value) - self.state = {k: t.detach().clone() for k, t in pl_module.state_dict().items()} - - def state_dict(self): # nothing worth persisting with a saved model - return {} diff --git a/autodeep/modelsdefinition/pytorch_tabular_models.py b/autodeep/modelsdefinition/pytorch_tabular_models.py index 73af1e6..aac502c 100644 --- a/autodeep/modelsdefinition/pytorch_tabular_models.py +++ b/autodeep/modelsdefinition/pytorch_tabular_models.py @@ -1,94 +1,14 @@ -"""All PyTorch Tabular based models. Each is a thin subclass of :class:`PytorchTabularTrainer`.""" - -from __future__ import annotations - -from autodeep.modelsdefinition.CommonStructure import PytorchTabularTrainer - - -def _cfg(name): - import pytorch_tabular.models as m - - return getattr(m, name) - - -class _Lazy(PytorchTabularTrainer): - """Resolve the config class lazily so importing AutoDeep stays fast.""" - - config_name = None - - @property - def config_class(self): - return _cfg(self.config_name) - - -class CategoryEmbeddingTrainer(_Lazy): - model_name = "categoryembedding" - config_name = "CategoryEmbeddingModelConfig" - - -class TabNetTrainer(_Lazy): - model_name = "tabnet" - config_name = "TabNetModelConfig" - - def prepare(self, X, y, extra_info): - try: - import pytorch_tabnet # noqa: F401 - except ImportError as e: # otherwise pytorch-tabular fails with "create_group_matrix() takes no arguments" - raise ImportError("TabNet needs the 'pytorch-tabnet' package: pip install 'pytorch-tabnet<4.2'") from e - super().prepare(X, y, extra_info) - - -def _embed_dim_from_heads(params): - """``input_embed_dim`` must be a multiple of ``num_heads``: the grid samples a multiplier instead.""" - mult, heads = params.pop("input_embed_dim_multiplier", None), params.get("num_heads") - if mult is not None and heads is not None: - params["input_embed_dim"] = int(mult) * int(heads) - return params - - -class FTTransformerTrainer(_Lazy): - model_name = "fttransformer" - config_name = "FTTransformerConfig" - - def adjust_params(self, params): - return _embed_dim_from_heads(params) - - -class TabTransformerTrainer(_Lazy): - model_name = "tabtransformer" - config_name = "TabTransformerConfig" - - def adjust_params(self, params): - return _embed_dim_from_heads(params) - - -class AutoIntTrainer(_Lazy): - model_name = "autoint" - config_name = "AutoIntConfig" - - def adjust_params(self, params): - # attention embedding must be divisible by the number of heads - mult, heads = params.pop("attn_embed_dim_multiplier", None), params.get("num_heads") - if mult is not None and heads is not None: - params["attn_embed_dim"] = int(mult) * int(heads) - return params - - -class GandalfTrainer(_Lazy): - model_name = "gandalf" - config_name = "GANDALFConfig" - - -class GateTrainer(_Lazy): - model_name = "gate" - config_name = "GatedAdditiveTreeEnsembleConfig" - - -class NodeTrainer(_Lazy): - model_name = "node" - config_name = "NodeConfig" - - -class DANetTrainer(_Lazy): - model_name = "danet" - config_name = "DANetConfig" +"""Backwards-compatible import path: the models now live in :mod:`autodeep.modelsdefinition.deep_tabular_models`.""" + +from autodeep.modelsdefinition.deep_tabular_models import ( # noqa: F401 + AutoIntTrainer, + CategoryEmbeddingTrainer, + DANetTrainer, + EmbeddingTorchTrainer, + FTTransformerTrainer, + GandalfTrainer, + GateTrainer, + NodeTrainer, + TabNetTrainer, + TabTransformerTrainer, +) diff --git a/autodeep/modelsdefinition/tabular_nets/LICENSE b/autodeep/modelsdefinition/tabular_nets/LICENSE new file mode 100644 index 0000000..db30df8 --- /dev/null +++ b/autodeep/modelsdefinition/tabular_nets/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020, Manu Joseph + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/autodeep/modelsdefinition/tabular_nets/__init__.py b/autodeep/modelsdefinition/tabular_nets/__init__.py new file mode 100644 index 0000000..290ca9c --- /dev/null +++ b/autodeep/modelsdefinition/tabular_nets/__init__.py @@ -0,0 +1,11 @@ +"""Deep tabular architectures adapted from pytorch-tabular 1.2.0 as plain PyTorch modules. + +pytorch-tabular: Copyright (c) 2020, Manu Joseph, MIT licence (full text in ``LICENSE`` in this folder). +Parts of it were themselves adapted from pytorch-widedeep, AutoGluon, NODE (Popov et al.), DANet, +entmax (Peters, Niculae) and LabML annotated papers; their notices are kept in the individual files. + +Changes from the original: no Lightning / omegaconf / einops, hyperparameters from a plain namespace, +no feature-importance bookkeeping, ``torch.jit.script`` dropped (deprecated in torch 2.15). +""" + +from autodeep.modelsdefinition.tabular_nets.architectures import BUILDERS, DEFAULTS, build_network # noqa: F401 diff --git a/autodeep/modelsdefinition/tabular_nets/activations.py b/autodeep/modelsdefinition/tabular_nets/activations.py new file mode 100644 index 0000000..e7bec09 --- /dev/null +++ b/autodeep/modelsdefinition/tabular_nets/activations.py @@ -0,0 +1,411 @@ +# W605 +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor +from torch.autograd import Function + + +class Entmoid15(Function): + """A highly optimized equivalent of labda x: Entmax15([x, 0])""" + + @staticmethod + def forward(ctx, input): + output = Entmoid15._forward(input) + ctx.save_for_backward(output) + return output + + @staticmethod + def _forward(input): + input, is_pos = abs(input), input >= 0 + tau = (input + torch.sqrt(F.relu(8 - input**2))) / 2 + tau.masked_fill_(tau <= input, 2.0) + y_neg = 0.25 * F.relu(tau - input, inplace=True) ** 2 + return torch.where(is_pos, 1 - y_neg, y_neg) + + @staticmethod + def backward(ctx, grad_output): + return Entmoid15._backward(ctx.saved_tensors[0], grad_output) + + @staticmethod + def _backward(output, grad_output): + gppr0, gppr1 = output.sqrt(), (1 - output).sqrt() + grad_input = grad_output * gppr0 + q = grad_input / (gppr0 + gppr1) + grad_input -= q * gppr0 + return grad_input + + +def sparsemoid(input): + return (0.5 * input + 0.5).clamp_(0, 1) + + +def t_softmax(input: Tensor, t: Tensor = None, dim: int = -1) -> Tensor: + if t is None: + t = torch.tensor(0.5, device=input.device) + assert (t >= 0.0).all() + maxes = torch.max(input, dim=dim, keepdim=True).values + input_minus_maxes = input - maxes + + w = torch.relu(input_minus_maxes + t) + 1e-8 + return torch.softmax(input_minus_maxes + torch.log(w), dim=dim) + + +class TSoftmax(torch.nn.Module): + def __init__(self, dim: int = -1): + super().__init__() + self.dim = dim + + def forward(self, input: Tensor, t: Tensor) -> Tensor: + return t_softmax(input, t, self.dim) + + +class RSoftmax(torch.nn.Module): + def __init__(self, dim: int = -1, eps: float = 1e-8): + super().__init__() + self.dim = dim + self.eps = eps + self.tsoftmax = TSoftmax(dim=dim) + + @classmethod + def calculate_t(cls, input: Tensor, r: Tensor, dim: int = -1, eps: float = 1e-8): + # r represents what is the fraction of zero values that we want to have + assert ((0.0 <= r) & (r <= 1.0)).all() + + maxes = torch.max(input, dim=dim, keepdim=True).values + input_minus_maxes = input - maxes + + zeros_mask = torch.exp(input_minus_maxes) == 0.0 + zeros_frac = zeros_mask.sum(dim=dim, keepdim=True).float() / input_minus_maxes.shape[dim] + + q = torch.clamp((r - zeros_frac) / (1 - zeros_frac), min=0.0, max=1.0) + x_minus_maxes = input_minus_maxes * (~zeros_mask).float() + if q.ndim > 1: + t = -torch.quantile(x_minus_maxes, q.view(-1), dim=dim, keepdim=True).detach() + t = t.squeeze(dim).diagonal(dim1=-2, dim2=-1).unsqueeze(-1) + eps + else: + t = -torch.quantile(x_minus_maxes, q, dim=dim).detach() + eps + return t + + def forward(self, input: Tensor, r: Tensor): + t = RSoftmax.calculate_t(input, r, self.dim, self.eps) + return self.tsoftmax(input, t) + + +# """ +# An implementation of entmax (Peters et al., 2019). See +# https://arxiv.org/pdf/1905.05702 for detailed description. + +# This builds on previous work with sparsemax (Martins & Astudillo, 2016). +# See https://arxiv.org/pdf/1602.02068. +# """ + +# Author: Ben Peters +# Author: Vlad Niculae +# License: MIT +# Including here for conda compatibility + + +def _make_ix_like(X, dim): + d = X.size(dim) + rho = torch.arange(1, d + 1, device=X.device, dtype=X.dtype) + view = [1] * X.dim() + view[0] = -1 + return rho.view(view).transpose(0, dim) + + +def _roll_last(X, dim): + if dim == -1: + return X + elif dim < 0: + dim = X.dim() - dim + + perm = [i for i in range(X.dim()) if i != dim] + [dim] + return X.permute(perm) + + +def _sparsemax_threshold_and_support(X, dim=-1, k=None): + """Core computation for sparsemax: optimal threshold and support size. + + Parameters + ---------- + X : torch.Tensor + The input tensor to compute thresholds over. + + dim : int + The dimension along which to apply sparsemax. + + k : int or None + number of largest elements to partial-sort over. For optimal + performance, should be slightly bigger than the expected number of + nonzeros in the solution. If the solution is more than k-sparse, + this function is recursively called with a 2*k schedule. + If `None`, full sorting is performed from the beginning. + + Returns + ------- + tau : torch.Tensor like `X`, with all but the `dim` dimension intact + the threshold value for each vector + support_size : torch LongTensor, shape like `tau` + the number of nonzeros in each vector. + """ + + if k is None or k >= X.shape[dim]: # do full sort + topk, _ = torch.sort(X, dim=dim, descending=True) + else: + topk, _ = torch.topk(X, k=k, dim=dim) + + topk_cumsum = topk.cumsum(dim) - 1 + rhos = _make_ix_like(topk, dim) + support = rhos * topk > topk_cumsum + + support_size = support.sum(dim=dim).unsqueeze(dim) + tau = topk_cumsum.gather(dim, support_size - 1) + tau /= support_size.to(X.dtype) + + if k is not None and k < X.shape[dim]: + unsolved = (support_size == k).squeeze(dim) + + if torch.any(unsolved): + in_ = _roll_last(X, dim)[unsolved] + tau_, ss_ = _sparsemax_threshold_and_support(in_, dim=-1, k=2 * k) + _roll_last(tau, dim)[unsolved] = tau_ + _roll_last(support_size, dim)[unsolved] = ss_ + + return tau, support_size + + +def _entmax_threshold_and_support(X, dim=-1, k=None): + """Core computation for 1.5-entmax: optimal threshold and support size. + + Parameters + ---------- + X : torch.Tensor + The input tensor to compute thresholds over. + + dim : int + The dimension along which to apply 1.5-entmax. + + k : int or None + number of largest elements to partial-sort over. For optimal + performance, should be slightly bigger than the expected number of + nonzeros in the solution. If the solution is more than k-sparse, + this function is recursively called with a 2*k schedule. + If `None`, full sorting is performed from the beginning. + + Returns + ------- + tau : torch.Tensor like `X`, with all but the `dim` dimension intact + the threshold value for each vector + support_size : torch LongTensor, shape like `tau` + the number of nonzeros in each vector. + + """ + + if k is None or k >= X.shape[dim]: # do full sort + Xsrt, _ = torch.sort(X, dim=dim, descending=True) + else: + Xsrt, _ = torch.topk(X, k=k, dim=dim) + + rho = _make_ix_like(Xsrt, dim) + mean = Xsrt.cumsum(dim) / rho + mean_sq = (Xsrt**2).cumsum(dim) / rho + ss = rho * (mean_sq - mean**2) + delta = (1 - ss) / rho + + # NOTE this is not exactly the same as in reference algo + # Fortunately it seems the clamped values never wrongly + # get selected by tau <= sorted_z. Prove this! + delta_nz = torch.clamp(delta, 0) + tau = mean - torch.sqrt(delta_nz) + + support_size = (tau <= Xsrt).sum(dim).unsqueeze(dim) + tau_star = tau.gather(dim, support_size - 1) + + if k is not None and k < X.shape[dim]: + unsolved = (support_size == k).squeeze(dim) + + if torch.any(unsolved): + X_ = _roll_last(X, dim)[unsolved] + tau_, ss_ = _entmax_threshold_and_support(X_, dim=-1, k=2 * k) + _roll_last(tau_star, dim)[unsolved] = tau_ + _roll_last(support_size, dim)[unsolved] = ss_ + + return tau_star, support_size + + +class SparsemaxFunction(Function): + @classmethod + def forward(cls, ctx, X, dim=-1, k=None): + ctx.dim = dim + max_val, _ = X.max(dim=dim, keepdim=True) + X = X - max_val # same numerical stability trick as softmax + tau, supp_size = _sparsemax_threshold_and_support(X, dim=dim, k=k) + output = torch.clamp(X - tau, min=0) + ctx.save_for_backward(supp_size, output) + return output + + @classmethod + def backward(cls, ctx, grad_output): + supp_size, output = ctx.saved_tensors + dim = ctx.dim + grad_input = grad_output.clone() + grad_input[output == 0] = 0 + + v_hat = grad_input.sum(dim=dim) / supp_size.to(output.dtype).squeeze(dim) + v_hat = v_hat.unsqueeze(dim) + grad_input = torch.where(output != 0, grad_input - v_hat, grad_input) + return grad_input, None, None + + +class Entmax15Function(Function): + @classmethod + def forward(cls, ctx, X, dim=0, k=None): + ctx.dim = dim + + max_val, _ = X.max(dim=dim, keepdim=True) + X = X - max_val # same numerical stability trick as for softmax + X = X / 2 # divide by 2 to solve actual Entmax + + tau_star, _ = _entmax_threshold_and_support(X, dim=dim, k=k) + + Y = torch.clamp(X - tau_star, min=0) ** 2 + ctx.save_for_backward(Y) + return Y + + @classmethod + def backward(cls, ctx, dY): + (Y,) = ctx.saved_tensors + gppr = Y.sqrt() # = 1 / g'' (Y) + dX = dY * gppr + q = dX.sum(ctx.dim) / gppr.sum(ctx.dim) + q = q.unsqueeze(ctx.dim) + dX -= q * gppr + return dX, None, None + + +def sparsemax(X, dim=-1, k=None): + """sparsemax: normalizing sparse transform (a la softmax). + + Solves the projection: + + min_p ||x - p||_2 s.t. p >= 0, sum(p) == 1. + + Parameters + ---------- + X : torch.Tensor + The input tensor. + + dim : int + The dimension along which to apply sparsemax. + + k : int or None + number of largest elements to partial-sort over. For optimal + performance, should be slightly bigger than the expected number of + nonzeros in the solution. If the solution is more than k-sparse, + this function is recursively called with a 2*k schedule. + If `None`, full sorting is performed from the beginning. + + Returns + ------- + P : torch tensor, same shape as X + The projection result, such that P.sum(dim=dim) == 1 elementwise. + """ + + return SparsemaxFunction.apply(X, dim, k) + + +def entmax15(X, dim=-1, k=None): + """1.5-entmax: normalizing sparse transform (a la softmax). + + Solves the optimization problem: + + max_p - H_1.5(p) s.t. p >= 0, sum(p) == 1. + + where H_1.5(p) is the Tsallis alpha-entropy with alpha=1.5. + + Parameters + ---------- + X : torch.Tensor + The input tensor. + + dim : int + The dimension along which to apply 1.5-entmax. + + k : int or None + number of largest elements to partial-sort over. For optimal + performance, should be slightly bigger than the expected number of + nonzeros in the solution. If the solution is more than k-sparse, + this function is recursively called with a 2*k schedule. + If `None`, full sorting is performed from the beginning. + + Returns + ------- + P : torch tensor, same shape as X + The projection result, such that P.sum(dim=dim) == 1 elementwise. + """ + + return Entmax15Function.apply(X, dim, k) + + +class Sparsemax(nn.Module): + def __init__(self, dim=-1, k=None): + """sparsemax: normalizing sparse transform (a la softmax). + + Solves the projection: + + min_p ||x - p||_2 s.t. p >= 0, sum(p) == 1. + + Parameters + ---------- + dim : int + The dimension along which to apply sparsemax. + + k : int or None + number of largest elements to partial-sort over. For optimal + performance, should be slightly bigger than the expected number of + nonzeros in the solution. If the solution is more than k-sparse, + this function is recursively called with a 2*k schedule. + If `None`, full sorting is performed from the beginning. + """ + self.dim = dim + self.k = k + super().__init__() + + def forward(self, X): + return sparsemax(X, dim=self.dim, k=self.k) + + +class Entmax15(nn.Module): + def __init__(self, dim=-1, k=None): + """1.5-entmax: normalizing sparse transform (a la softmax). + + Solves the optimization problem: + + max_p - H_1.5(p) s.t. p >= 0, sum(p) == 1. + + where H_1.5(p) is the Tsallis alpha-entropy with alpha=1.5. + + Parameters + ---------- + dim : int + The dimension along which to apply 1.5-entmax. + + k : int or None + number of largest elements to partial-sort over. For optimal + performance, should be slightly bigger than the expected number of + nonzeros in the solution. If the solution is more than k-sparse, + this function is recursively called with a 2*k schedule. + If `None`, full sorting is performed from the beginning. + """ + self.dim = dim + self.k = k + super().__init__() + + def forward(self, X): + return entmax15(X, dim=self.dim, k=self.k) + + +entmoid15 = Entmoid15.apply +entmax15 = entmax15 +sparsemax = sparsemax diff --git a/autodeep/modelsdefinition/tabular_nets/architectures.py b/autodeep/modelsdefinition/tabular_nets/architectures.py new file mode 100644 index 0000000..c65302f --- /dev/null +++ b/autodeep/modelsdefinition/tabular_nets/architectures.py @@ -0,0 +1,679 @@ +"""The nine pytorch-tabular architectures as plain ``nn.Module``s (no Lightning, omegaconf or einops). + +Backbones are copied from pytorch-tabular 1.2.0 (Manu Joseph, MIT licence, see LICENSE in this folder) with +only these changes: hyperparameters come from a ``SimpleNamespace`` instead of a ``DictConfig``, the +feature-importance bookkeeping is gone, and every network takes ``(x_cont, x_cat)`` and returns logits. + +:func:`build_network` merges the user's hyperparameters over pytorch-tabular's defaults (``DEFAULTS``) and +over the data schema (number of continuous columns, categorical cardinalities, output size), the same +"inferred config" pytorch-tabular derives from the training data. +""" + +from __future__ import annotations + +import logging +from collections import OrderedDict +from types import SimpleNamespace + +import torch +import torch.nn as nn + +from . import activations +from .activations import entmax15, entmoid15, sparsemax, sparsemoid, t_softmax +from .batch_norm import BatchNorm1d +from .danet_blocks import BasicBlock +from .embeddings import Embedding1dLayer, Embedding2dLayer +from .gated_units import GatedFeatureLearningUnit +from .misc import Add +from .node_blocks import DenseODSTBlock +from .soft_trees import NeuralDecisionTree +from .transformers import AppendCLSToken, TransformerEncoderBlock +from .utils import LinearHead, _initialize_layers, _linear_dropout_bn + +logger = logging.getLogger(__name__) + +# consumed by the training loop, not by the architectures +_TRAINER_KEYS = {"batch_size", "optimizer_fn", "scheduler_fn", "weights"} + +# Shared by every pytorch-tabular ModelConfig +_COMMON = { + "embedding_dropout": 0.0, + "batch_norm_continuous_input": True, + "virtual_batch_size": None, + "head_config": {"layers": ""}, + "data_aware_init_batch_size": 2000, +} + +#: pytorch-tabular 1.2.0 defaults of the model config classes (fields used by the architectures) +DEFAULTS: dict[str, dict] = { + "categoryembedding": { + "layers": "128-64-32", + "activation": "ReLU", + "use_batch_norm": False, + "initialization": "kaiming", + "dropout": 0.0, + }, + "tabnet": { + "virtual_batch_size": 128, + "n_d": 8, + "n_a": 8, + "n_steps": 3, + "gamma": 1.3, + "n_independent": 2, + "n_shared": 2, + "mask_type": "sparsemax", + }, + "fttransformer": { + "input_embed_dim": 32, + "embedding_initialization": "kaiming_uniform", + "embedding_bias": True, + "share_embedding_strategy": "fraction", + "shared_embedding_fraction": 0.25, + "num_heads": 8, + "num_attn_blocks": 6, + "transformer_head_dim": None, + "attn_dropout": 0.1, + "add_norm_dropout": 0.1, + "ff_dropout": 0.1, + "ff_hidden_multiplier": 4, + "transformer_activation": "GEGLU", + }, + "tabtransformer": { + "input_embed_dim": 32, + "embedding_initialization": "kaiming_uniform", + "embedding_bias": False, + "share_embedding_strategy": "fraction", + "shared_embedding_fraction": 0.25, + "num_heads": 8, + "num_attn_blocks": 6, + "transformer_head_dim": None, + "attn_dropout": 0.1, + "add_norm_dropout": 0.1, + "ff_dropout": 0.1, + "ff_hidden_multiplier": 4, + "transformer_activation": "GEGLU", + }, + "autoint": { + "attn_embed_dim": 32, + "num_heads": 2, + "num_attn_blocks": 3, + "attn_dropouts": 0.0, + "has_residuals": True, + "embedding_dim": 16, + "embedding_initialization": "kaiming_uniform", + "embedding_bias": True, + "share_embedding_strategy": "fraction", + "shared_embedding_fraction": 0.25, + "deep_layers": False, + "layers": "128-64-32", + "activation": "ReLU", + "use_batch_norm": False, + "initialization": "kaiming", + "dropout": 0.0, + "attention_pooling": False, + }, + "gandalf": { + "gflu_stages": 6, + "gflu_dropout": 0.0, + "gflu_feature_init_sparsity": 0.3, + "learnable_sparsity": True, + }, + "gate": { + "gflu_stages": 6, + "gflu_dropout": 0.0, + "tree_depth": 4, + "num_trees": 10, + "binning_activation": "sparsemoid", + "feature_mask_function": "t-softmax", + "gflu_feature_init_sparsity": 0.3, + "tree_feature_init_sparsity": 0.8, + "learnable_sparsity": True, + "tree_dropout": 0.0, + "chain_trees": True, + "tree_wise_attention": True, + "tree_wise_attention_dropout": 0.0, + "share_head_weights": True, + }, + "node": { + "num_layers": 1, + "num_trees": 2048, + "additional_tree_output_dim": 3, + "depth": 6, + "choice_function": "entmax15", + "bin_function": "entmoid15", + "max_features": None, + "input_dropout": 0.0, + "initialize_response": "normal", + "initialize_selection_logits": "uniform", + "threshold_init_beta": 1.0, + "threshold_init_cutoff": 1.0, + }, + "danet": { + "virtual_batch_size": 256, + "n_layers": 8, + "abstlay_dim_1": 32, + "abstlay_dim_2": None, + "k": 5, + "dropout_rate": 0.1, + "block_activation": "LeakyReLU", + }, +} + + +def embedding_dims(categorical_cardinality: list[int]): + """pytorch-tabular's rule for the 1-D categorical embeddings.""" + return [(c, min(50, (c + 1) // 2)) for c in categorical_cardinality] + + +def make_hparams(model: str, params: dict, continuous_dim: int, categorical_cardinality: list[int], output_dim: int, task: str): + hp = {**_COMMON, **DEFAULTS[model]} + ignored = sorted(k for k in params if k not in hp and k not in _TRAINER_KEYS) + if ignored: + logger.debug(f"{model}: ignoring parameters the architecture does not use: {ignored}") + hp.update({k: v for k, v in params.items() if k in hp or k == "batch_size"}) + hp["head_config"] = {**_COMMON["head_config"], **(hp.get("head_config") or {})} + hp.update( + continuous_dim=int(continuous_dim), + categorical_dim=len(categorical_cardinality), + categorical_cardinality=list(categorical_cardinality), + embedding_dims=embedding_dims(categorical_cardinality), + output_dim=int(output_dim), + task=task, + ) + hp["embedded_cat_dim"] = sum(d for _, d in hp["embedding_dims"]) + return SimpleNamespace(**hp) + + +def _head(hp, in_units): + return LinearHead(in_units, hp.output_dim, **hp.head_config) + + +# ---------------------------------------------------------------------------------------------- networks +class TabularNet(nn.Module): + """``head(backbone(embedding(x)))``, the forward pass of pytorch-tabular's ``BaseModel``.""" + + def __init__(self, hp, embedding: nn.Module, backbone: nn.Module, head: nn.Module): + super().__init__() + self.hparams = hp + self.embedding_layer, self.backbone, self.head = embedding, backbone, head + + def forward(self, x_cont, x_cat): + x = self.embedding_layer({"continuous": x_cont, "categorical": x_cat}) + return self.head(self.backbone(x)) + + def data_aware_init(self, x_cont, x_cat, y): + """Called once with a training batch before the first epoch (pytorch-tabular's ``data_aware_initialization``).""" + + +class _T0Mixin: + """GANDALF and GATE start their regression bias ``T0`` at the target mean.""" + + def _t0(self): + return self.T0 + + def data_aware_init(self, x_cont, x_cat, y): + if self.hparams.task == "regression": + self._t0().data = torch.mean(y.reshape(len(y), -1).float(), dim=0).to(self._t0().device) + + +# -- CategoryEmbedding ---------------------------------------------------------------------- +class CategoryEmbeddingBackbone(nn.Module): + def __init__(self, hp): + super().__init__() + self.hparams = hp + layers = [] + _curr_units = hp.embedded_cat_dim + hp.continuous_dim + for units in hp.layers.split("-"): + layers.extend(_linear_dropout_bn(hp.activation, hp.initialization, hp.use_batch_norm, _curr_units, int(units), hp.dropout)) + _curr_units = int(units) + self.linear_layers = nn.Sequential(*layers) + _initialize_layers(hp.activation, hp.initialization, self.linear_layers) + self.output_dim = _curr_units + + def forward(self, x): + return self.linear_layers(x) + + +def _embedding_1d(hp): + return Embedding1dLayer( + continuous_dim=hp.continuous_dim, + categorical_embedding_dims=hp.embedding_dims, + embedding_dropout=hp.embedding_dropout, + batch_norm_continuous_input=hp.batch_norm_continuous_input, + virtual_batch_size=hp.virtual_batch_size, + ) + + +def _build_categoryembedding(hp): + backbone = CategoryEmbeddingBackbone(hp) + return TabularNet(hp, _embedding_1d(hp), backbone, _head(hp, backbone.output_dim)) + + +# -- GANDALF -------------------------------------------------------------------------------- +class GANDALFBackbone(nn.Module): + def __init__(self, hp): + super().__init__() + n_features = hp.embedded_cat_dim + hp.continuous_dim + self.gflus = GatedFeatureLearningUnit( + n_features_in=n_features, + n_stages=hp.gflu_stages, + feature_mask_function=t_softmax, + dropout=hp.gflu_dropout, + feature_sparsity=hp.gflu_feature_init_sparsity, + learnable_sparsity=hp.learnable_sparsity, + ) + self.output_dim = n_features + + def forward(self, x): + return self.gflus(x) + + +class GANDALFNet(_T0Mixin, TabularNet): + pass + + +def _build_gandalf(hp): + assert hp.gflu_stages > 0, "gflu_stages should be greater than 0" + backbone = GANDALFBackbone(hp) + net = GANDALFNet(hp, _embedding_1d(hp), backbone, nn.Identity()) + net.T0 = nn.Parameter(torch.rand(hp.output_dim), requires_grad=True) + net.head = nn.Sequential(_head(hp, backbone.output_dim), Add(net.T0)) + return net + + +# -- GATE ----------------------------------------------------------------------------------- +class GatedAdditiveTreesBackbone(nn.Module): + ACTIVATION_MAP = {"entmax": entmax15, "sparsemax": sparsemax, "softmax": nn.functional.softmax, "t-softmax": t_softmax} + BINARY_ACTIVATION_MAP = {"entmoid": entmoid15, "sparsemoid": sparsemoid, "sigmoid": nn.functional.sigmoid} + + def __init__(self, hp): + super().__init__() + assert hp.binning_activation in self.BINARY_ACTIVATION_MAP, f"`binning_activation should be one of {list(self.BINARY_ACTIVATION_MAP)}" + assert hp.feature_mask_function in self.ACTIVATION_MAP, f"`feature_mask_function should be one of {list(self.ACTIVATION_MAP)}" + assert hp.tree_depth > 0 and hp.num_trees > 0, "GATE needs tree_depth > 0 and num_trees > 0" + self.gflu_stages = hp.gflu_stages + self.num_trees = hp.num_trees + self.tree_depth = hp.tree_depth + self.chain_trees = hp.chain_trees + self.tree_wise_attention = hp.tree_wise_attention + self.n_features = hp.embedded_cat_dim + hp.continuous_dim + self.output_dim = 2**self.tree_depth + feature_mask_function = self.ACTIVATION_MAP[hp.feature_mask_function] + if self.gflu_stages > 0: + self.gflus = GatedFeatureLearningUnit( + n_features_in=self.n_features, + n_stages=self.gflu_stages, + feature_mask_function=feature_mask_function, + dropout=hp.gflu_dropout, + feature_sparsity=hp.gflu_feature_init_sparsity, + learnable_sparsity=hp.learnable_sparsity, + ) + self.trees = nn.ModuleList( + [ + NeuralDecisionTree( + depth=self.tree_depth, + n_features=self.n_features + 2**self.tree_depth * t if self.chain_trees else self.n_features, + dropout=hp.tree_dropout, + binning_activation=self.BINARY_ACTIVATION_MAP[hp.binning_activation], + feature_mask_function=feature_mask_function, + feature_sparsity=hp.tree_feature_init_sparsity, + learnable_sparsity=hp.learnable_sparsity, + ) + for t in range(self.num_trees) + ] + ) + if self.tree_wise_attention: + self.tree_attention = nn.MultiheadAttention( + embed_dim=self.output_dim, num_heads=1, batch_first=False, dropout=hp.tree_wise_attention_dropout + ) + + def forward(self, x): + if self.gflu_stages > 0: + x = self.gflus(x) + tree_outputs = [] + tree_input = x + for i in range(self.num_trees): + tree_output, _ = self.trees[i](tree_input) + tree_outputs.append(tree_output.unsqueeze(-1)) + if self.chain_trees: + tree_input = torch.cat([tree_input, tree_output], 1) + tree_outputs = torch.cat(tree_outputs, dim=-1) + if self.tree_wise_attention: + tree_outputs = tree_outputs.permute(2, 0, 1) + tree_outputs, _ = self.tree_attention(tree_outputs, tree_outputs, tree_outputs) + tree_outputs = tree_outputs.permute(1, 2, 0) + return tree_outputs + + +class GATEHead(nn.Module): + """pytorch-tabular's ``CustomHead`` for GATE: a weighted sum of per-tree heads (+ ``T0`` for regression).""" + + def __init__(self, input_dim: int, hp): + super().__init__() + self.share_head_weights, self.task = hp.share_head_weights, hp.task + if self.share_head_weights: + self.head = _head(hp, input_dim) + else: + self.head = nn.ModuleList([_head(hp, input_dim) for _ in range(hp.num_trees)]) + self.eta = nn.Parameter(torch.rand(hp.num_trees, requires_grad=True)) + if self.task == "regression": + self.T0 = nn.Parameter(torch.rand(hp.output_dim), requires_grad=True) + + def forward(self, backbone_features): + if not self.share_head_weights: + y_hat = torch.cat([h(backbone_features[:, :, i]).unsqueeze(1) for i, h in enumerate(self.head)], dim=1) + else: + y_hat = self.head(backbone_features.transpose(2, 1)) + y_hat = (y_hat * self.eta.reshape(1, -1, 1)).sum(dim=1) + if self.task == "regression": + y_hat = y_hat + self.T0 + return y_hat + + +class GATENet(_T0Mixin, TabularNet): + def _t0(self): + return self.head.T0 + + +def _build_gate(hp): + backbone = GatedAdditiveTreesBackbone(hp) + return GATENet(hp, _embedding_1d(hp), backbone, GATEHead(backbone.output_dim, hp)) + + +# -- NODE ----------------------------------------------------------------------------------- +class NODEBackbone(nn.Module): + def __init__(self, hp): + super().__init__() + self.dense_block = DenseODSTBlock( + input_dim=hp.continuous_dim + hp.embedded_cat_dim, + num_trees=hp.num_trees, + num_layers=hp.num_layers, + tree_output_dim=hp.output_dim + hp.additional_tree_output_dim, + max_features=hp.max_features, + input_dropout=hp.input_dropout, + depth=hp.depth, + choice_function=getattr(activations, hp.choice_function), + bin_function=getattr(activations, hp.bin_function), + initialize_response_=getattr(nn.init, hp.initialize_response + "_"), + initialize_selection_logits_=getattr(nn.init, hp.initialize_selection_logits + "_"), + threshold_init_beta=hp.threshold_init_beta, + threshold_init_cutoff=hp.threshold_init_cutoff, + ) + self.output_dim = hp.output_dim + hp.additional_tree_output_dim + + def forward(self, x): + return self.dense_block(x) + + +class NODEHead(nn.Module): + """NODE averages the first ``output_dim`` outputs of every tree (pytorch-tabular's ``Lambda(self.subset)``).""" + + def __init__(self, output_dim: int): + super().__init__() + self.output_dim = output_dim + + def forward(self, x): + return x[..., : self.output_dim].mean(dim=-2) + + +class NODENet(TabularNet): + def data_aware_init(self, x_cont, x_cat, y): + # ODST layers initialise their thresholds from the first batch they see (ModuleWithInit) + with torch.no_grad(): + self(x_cont, x_cat) + + +def _build_node(hp): + return NODENet(hp, _embedding_1d(hp), NODEBackbone(hp), NODEHead(hp.output_dim)) + + +# -- DANet ---------------------------------------------------------------------------------- +class DANetBackbone(nn.Module): + def __init__(self, hp): + super().__init__() + abstlay_dim_2 = hp.abstlay_dim_2 if hp.abstlay_dim_2 is not None else hp.abstlay_dim_1 * 2 + input_dim = hp.continuous_dim + hp.embedded_cat_dim + params = { + "fix_input_dim": input_dim, + "k": hp.k, + "virtual_batch_size": hp.virtual_batch_size, + "abstlay_dim_1": hp.abstlay_dim_1, + "abstlay_dim_2": abstlay_dim_2, + "drop_rate": hp.dropout_rate, + "block_activation": getattr(nn, hp.block_activation)(), + } + self.init_layer = BasicBlock(input_dim, **params) + self.layers = nn.ModuleList([BasicBlock(abstlay_dim_2, **params) for _ in range(hp.n_layers - 1)]) + self.output_dim = abstlay_dim_2 + + def forward(self, x): + out = self.init_layer(x) + for layer in self.layers: + out = layer(x, pre_out=out) + return out + + +def _build_danet(hp): + batch_size = getattr(hp, "batch_size", None) + if batch_size is not None and hp.virtual_batch_size > int(batch_size): + hp.virtual_batch_size = int(batch_size) # as pytorch-tabular does + backbone = DANetBackbone(hp) + return TabularNet(hp, _embedding_1d(hp), backbone, _head(hp, backbone.output_dim)) + + +# -- FT-Transformer ------------------------------------------------------------------------- +def _embedding_2d(hp, embedding_dim, continuous_dim=None, batch_norm=True): + return Embedding2dLayer( + continuous_dim=hp.continuous_dim if continuous_dim is None else continuous_dim, + categorical_cardinality=hp.categorical_cardinality, + embedding_dim=embedding_dim, + shared_embedding_strategy=hp.share_embedding_strategy, + frac_shared_embed=hp.shared_embedding_fraction, + embedding_bias=hp.embedding_bias, + batch_norm_continuous_input=hp.batch_norm_continuous_input and batch_norm, + embedding_dropout=hp.embedding_dropout, + initialization=hp.embedding_initialization, + virtual_batch_size=hp.virtual_batch_size, + ) + + +def _transformer_blocks(hp, keep_attn): + blocks = OrderedDict() + for i in range(hp.num_attn_blocks): + blocks[f"mha_block_{i}"] = TransformerEncoderBlock( + input_embed_dim=hp.input_embed_dim, + num_heads=hp.num_heads, + ff_hidden_multiplier=hp.ff_hidden_multiplier, + ff_activation=hp.transformer_activation, + attn_dropout=hp.attn_dropout, + ff_dropout=hp.ff_dropout, + add_norm_dropout=hp.add_norm_dropout, + keep_attn=keep_attn, + transformer_head_dim=hp.transformer_head_dim, + ) + return nn.Sequential(blocks) + + +def _check_share_strategy(hp): + assert hp.share_embedding_strategy in ( + "add", + "fraction", + ), f"`share_embedding_strategy` should be one of `add` or `fraction`, not {hp.share_embedding_strategy}" + + +class FTTransformerBackbone(nn.Module): + def __init__(self, hp): + super().__init__() + _check_share_strategy(hp) + self.add_cls = AppendCLSToken(d_token=hp.input_embed_dim, initialization=hp.embedding_initialization) + self.transformer_blocks = _transformer_blocks(hp, keep_attn=False) + self.output_dim = hp.input_embed_dim + + def forward(self, x): + x = self.add_cls(x) + for block in self.transformer_blocks: + x = block(x) + return x[:, -1] + + +def _build_fttransformer(hp): + backbone = FTTransformerBackbone(hp) + return TabularNet(hp, _embedding_2d(hp, hp.input_embed_dim), backbone, _head(hp, backbone.output_dim)) + + +# -- TabTransformer ------------------------------------------------------------------------- +class TabTransformerBackbone(nn.Module): + def __init__(self, hp): + super().__init__() + _check_share_strategy(hp) + self.categorical_dim, self.continuous_dim = hp.categorical_dim, hp.continuous_dim + self.batch_norm_continuous_input = hp.batch_norm_continuous_input + self.transformer_blocks = _transformer_blocks(hp, keep_attn=False) + if hp.batch_norm_continuous_input: + self.normalizing_batch_norm = BatchNorm1d(hp.continuous_dim, hp.virtual_batch_size) + self.output_dim = hp.input_embed_dim * hp.categorical_dim + hp.continuous_dim + + def forward(self, x_cat: torch.Tensor | None, x_cont: torch.Tensor) -> torch.Tensor: + x = None + if self.categorical_dim > 0: + for block in self.transformer_blocks: + x_cat = block(x_cat) + x = x_cat.reshape(x_cat.shape[0], -1) # b n h -> b (n h) + if self.continuous_dim > 0: + if self.batch_norm_continuous_input: + x_cont = self.normalizing_batch_norm(x_cont) + x = x_cont if x is None else torch.cat([x, x_cont], 1) + return x + + +class TabTransformerNet(TabularNet): + """Only the categorical columns go through the transformer; continuous columns join before the head.""" + + def forward(self, x_cont, x_cat): + x_cat_emb = self.embedding_layer({"continuous": x_cont[:, :0], "categorical": x_cat}) if x_cat.shape[1] > 0 else None + return self.head(self.backbone(x_cat_emb, x_cont)) + + +def _build_tabtransformer(hp): + backbone = TabTransformerBackbone(hp) + embedding = _embedding_2d(hp, hp.input_embed_dim, continuous_dim=0, batch_norm=False) + return TabTransformerNet(hp, embedding, backbone, _head(hp, backbone.output_dim)) + + +# -- AutoInt -------------------------------------------------------------------------------- +class AutoIntBackbone(nn.Module): + def __init__(self, hp): + super().__init__() + self.hparams = hp + _curr_units = hp.embedding_dim + if hp.deep_layers: + layers = [] + for units in hp.layers.split("-"): + layers.extend(_linear_dropout_bn(hp.activation, hp.initialization, hp.use_batch_norm, _curr_units, int(units), hp.dropout)) + _curr_units = int(units) + self.linear_layers = nn.Sequential(*layers) + self.attn_proj = nn.Linear(_curr_units, hp.attn_embed_dim) + _initialize_layers(hp.activation, hp.initialization, self.attn_proj) + self.self_attns = nn.ModuleList( + [nn.MultiheadAttention(hp.attn_embed_dim, hp.num_heads, dropout=hp.attn_dropouts) for _ in range(hp.num_attn_blocks)] + ) + if hp.has_residuals: + self.V_res_embedding = torch.nn.Linear(_curr_units, hp.attn_embed_dim * hp.num_attn_blocks if hp.attention_pooling else hp.attn_embed_dim) + self.output_dim = (hp.continuous_dim + hp.categorical_dim) * hp.attn_embed_dim + if hp.attention_pooling: + self.output_dim = self.output_dim * hp.num_attn_blocks + + def forward(self, x): + hp = self.hparams + if hp.deep_layers: + x = self.linear_layers(x) + cross_term = self.attn_proj(x).transpose(0, 1) + attention_ops = [] + for self_attn in self.self_attns: + cross_term, _ = self_attn(cross_term, cross_term, cross_term) + if hp.attention_pooling: + attention_ops.append(cross_term) + if hp.attention_pooling: + cross_term = torch.cat(attention_ops, dim=-1) + cross_term = cross_term.transpose(0, 1) + if hp.has_residuals: + cross_term = cross_term + self.V_res_embedding(x) + return nn.functional.relu(cross_term).reshape(-1, self.output_dim) + + +def _build_autoint(hp): + backbone = AutoIntBackbone(hp) + embedding = Embedding2dLayer( + continuous_dim=hp.continuous_dim, + categorical_cardinality=hp.categorical_cardinality, + embedding_dim=hp.embedding_dim, + shared_embedding_strategy=hp.share_embedding_strategy, + frac_shared_embed=hp.shared_embedding_fraction, + embedding_bias=hp.embedding_bias, + batch_norm_continuous_input=hp.batch_norm_continuous_input, + embedding_dropout=hp.embedding_dropout, + initialization=hp.embedding_initialization, + ) + return TabularNet(hp, embedding, backbone, _head(hp, backbone.output_dim)) + + +# -- TabNet --------------------------------------------------------------------------------- +class TabNetNet(TabularNet): + """pytorch-tabnet's ``TabNet`` network; categorical columns go first, as pytorch-tabular passes them.""" + + def __init__(self, hp): + from pytorch_tabnet.tab_network import TabNet + from pytorch_tabnet.utils import create_group_matrix + + n_in = hp.continuous_dim + hp.categorical_dim + tabnet = TabNet( + input_dim=n_in, + output_dim=hp.output_dim, + n_d=hp.n_d, + n_a=hp.n_a, + n_steps=hp.n_steps, + gamma=hp.gamma, + cat_idxs=list(range(hp.categorical_dim)), + cat_dims=[cardinality for cardinality, _ in hp.embedding_dims], + cat_emb_dim=[embed_dim for _, embed_dim in hp.embedding_dims], + n_independent=hp.n_independent, + n_shared=hp.n_shared, + epsilon=1e-15, + virtual_batch_size=hp.virtual_batch_size, + momentum=0.02, + mask_type=hp.mask_type, + group_attention_matrix=create_group_matrix([[i] for i in range(n_in)], n_in), + ) + super().__init__(hp, nn.Identity(), tabnet, nn.Identity()) + + def forward(self, x_cont, x_cat): + x = torch.cat([x_cat.to(x_cont.dtype), x_cont], dim=1) if x_cat.shape[1] > 0 else x_cont + tabnet = self.backbone + # plain tensor attributes in pytorch-tabnet, so Module.to() does not move them + tabnet.embedder.embedding_group_matrix = tabnet.embedder.embedding_group_matrix.to(x.device) + tabnet.tabnet.encoder.group_attention_matrix = tabnet.tabnet.encoder.group_attention_matrix.to(x.device) + out, _ = tabnet(x) # pytorch-tabular ignores TabNet's sparsity loss as well + return out + + +def _build_tabnet(hp): + return TabNetNet(hp) + + +BUILDERS = { + "categoryembedding": _build_categoryembedding, + "gandalf": _build_gandalf, + "gate": _build_gate, + "node": _build_node, + "danet": _build_danet, + "fttransformer": _build_fttransformer, + "tabtransformer": _build_tabtransformer, + "autoint": _build_autoint, + "tabnet": _build_tabnet, +} + + +def build_network(model: str, params: dict, continuous_dim: int, categorical_cardinality: list[int], output_dim: int, task: str) -> TabularNet: + """Build one of the nine architectures for the given data schema.""" + hp = make_hparams(model, params, continuous_dim, categorical_cardinality, output_dim, task) + return BUILDERS[model](hp) diff --git a/autodeep/modelsdefinition/tabular_nets/batch_norm.py b/autodeep/modelsdefinition/tabular_nets/batch_norm.py new file mode 100644 index 0000000..6c90b1c --- /dev/null +++ b/autodeep/modelsdefinition/tabular_nets/batch_norm.py @@ -0,0 +1,40 @@ +import numpy as np +import torch +from torch import nn + + +class GBN(nn.Module): + """ + Ghost Batch Normalization + https://arxiv.org/abs/1705.08741 + """ + + def __init__(self, input_dim, virtual_batch_size=512): + super().__init__() + self.input_dim = input_dim + self.virtual_batch_size = virtual_batch_size + self.bn = nn.BatchNorm1d(self.input_dim) + + def forward(self, x): + if self.training: + chunks = x.chunk(int(np.ceil(x.shape[0] / self.virtual_batch_size)), 0) + res = [self.bn(x_) for x_ in chunks] + return torch.cat(res, dim=0) + else: + return self.bn(x) + + +class BatchNorm1d(nn.Module): + """BatchNorm1d with Ghost Batch Normalization.""" + + def __init__(self, num_features, virtual_batch_size=None): + super().__init__() + self.num_features = num_features + self.virtual_batch_size = virtual_batch_size + if self.virtual_batch_size is None: + self.bn = nn.BatchNorm1d(self.num_features) + else: + self.bn = GBN(self.num_features, self.virtual_batch_size) + + def forward(self, x): + return self.bn(x) diff --git a/autodeep/modelsdefinition/tabular_nets/danet_blocks.py b/autodeep/modelsdefinition/tabular_nets/danet_blocks.py new file mode 100644 index 0000000..8c7d6bc --- /dev/null +++ b/autodeep/modelsdefinition/tabular_nets/danet_blocks.py @@ -0,0 +1,87 @@ +from functools import partial + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .activations import entmax15 +from .batch_norm import GBN + + +def initialize_glu(module, input_dim, output_dim): + gain_value = np.sqrt((input_dim + output_dim) / np.sqrt(input_dim)) + torch.nn.init.xavier_normal_(module.weight, gain=gain_value) + return + + +class LearnableLocality(nn.Module): + def __init__(self, input_dim, k): + super().__init__() + self.register_parameter("weight", nn.Parameter(torch.rand(k, input_dim))) + self.smax = partial(entmax15, dim=-1) + + def forward(self, x): + mask = self.smax(self.weight) + masked_x = torch.einsum("nd,bd->bnd", mask, x) # [B, k, D] + return masked_x + + +class AbstractLayer(nn.Module): + def __init__(self, base_input_dim, base_output_dim, k, virtual_batch_size, bias=True): + super().__init__() + self.masker = LearnableLocality(input_dim=base_input_dim, k=k) + self.fc = nn.Conv1d( + base_input_dim * k, + 2 * k * base_output_dim, + kernel_size=1, + groups=k, + bias=bias, + ) + initialize_glu(self.fc, input_dim=base_input_dim * k, output_dim=2 * k * base_output_dim) + self.bn = GBN(2 * base_output_dim * k, virtual_batch_size) + self.k = k + self.base_output_dim = base_output_dim + + def forward(self, x): + b = x.size(0) + x = self.masker(x) # [B, D] -> [B, k, D] + x = self.fc(x.reshape(b, -1, 1)) # [B, k, D] -> [B, k * D, 1] -> [B, k * (2 * D'), 1] + x = self.bn(x) + chunks = x.chunk(self.k, 1) # k * [B, 2 * D', 1] + x = sum( + [F.relu(torch.sigmoid(x_[:, : self.base_output_dim, :]) * x_[:, self.base_output_dim :, :]) for x_ in chunks] + ) # k * [B, D', 1] -> [B, D', 1] + return x.squeeze(-1) + + +class BasicBlock(nn.Module): + def __init__( + self, + input_dim, + abstlay_dim_1, + abstlay_dim_2, + k, + virtual_batch_size, + fix_input_dim, + drop_rate, + block_activation, + ): + super().__init__() + self.conv1 = AbstractLayer(input_dim, abstlay_dim_1, k, virtual_batch_size) + self.conv2 = AbstractLayer(abstlay_dim_1, abstlay_dim_2, k, virtual_batch_size) + + self.downsample = nn.Sequential( + nn.Dropout(drop_rate), + AbstractLayer(fix_input_dim, abstlay_dim_2, k, virtual_batch_size), + ) + self.block_activation = block_activation + + def forward(self, x, pre_out=None): + if pre_out is None: + pre_out = x + out = self.conv1(pre_out) + out = self.conv2(out) + identity = self.downsample(x) + out += identity + return self.block_activation(out) diff --git a/autodeep/modelsdefinition/tabular_nets/embeddings.py b/autodeep/modelsdefinition/tabular_nets/embeddings.py new file mode 100644 index 0000000..fbd5aba --- /dev/null +++ b/autodeep/modelsdefinition/tabular_nets/embeddings.py @@ -0,0 +1,295 @@ +# W605 +import math +from functools import partial +from typing import Any + +import torch +from torch import nn + +from .batch_norm import BatchNorm1d +from .utils import _initialize_kaiming + + +# Slight adaptation from https://github.com/jrzaurin/pytorch-widedeep which in turn adapted from AutoGluon +class SharedEmbeddings(nn.Module): + """Enables different values in a categorical feature to share some embeddings across.""" + + def __init__( + self, + num_embed: int, + embed_dim: int, + add_shared_embed: bool = False, + frac_shared_embed: float = 0.25, + ): + super().__init__() + assert frac_shared_embed < 1, "'frac_shared_embed' must be less than 1" + + self.add_shared_embed = add_shared_embed + self.embed = nn.Embedding(num_embed, embed_dim, padding_idx=0) + self.embed.weight.data.clamp_(-2, 2) + if add_shared_embed: + col_embed_dim = embed_dim + else: + col_embed_dim = int(embed_dim * frac_shared_embed) + self.shared_embed = nn.Parameter(torch.empty(1, col_embed_dim).uniform_(-1, 1)) + + def forward(self, X: torch.Tensor) -> torch.Tensor: + out = self.embed(X) + shared_embed = self.shared_embed.expand(out.shape[0], -1) + if self.add_shared_embed: + out += shared_embed + else: + out[:, : shared_embed.shape[1]] = shared_embed + return out + + @property + def weight(self): + w = self.embed.weight.detach() + if self.add_shared_embed: + w += self.shared_embed + else: + w[:, : self.shared_embed.shape[1]] = self.shared_embed + return w + + +class PreEncoded1dLayer(nn.Module): + """Takes in pre-encoded categorical variables and just concatenates with continuous variables No learnable + component.""" + + def __init__( + self, + continuous_dim: int, + categorical_dim: tuple[int, int], + embedding_dropout: float = 0.0, + batch_norm_continuous_input: bool = False, + virtual_batch_size: int | None = None, + ): + super().__init__() + self.continuous_dim = continuous_dim + self.categorical_dim = categorical_dim + self.batch_norm_continuous_input = batch_norm_continuous_input + + if embedding_dropout > 0: + self.embd_dropout = nn.Dropout(embedding_dropout) + else: + self.embd_dropout = None + # Continuous Layers + if batch_norm_continuous_input: + self.normalizing_batch_norm = BatchNorm1d(continuous_dim, virtual_batch_size) + + def forward(self, x: dict[str, Any]) -> torch.Tensor: + assert "continuous" in x or "categorical" in x, "x must contain either continuous and categorical features" + # (B, N) + continuous_data, categorical_data = ( + x.get("continuous", torch.empty(0, 0)), + x.get("categorical", torch.empty(0, 0)), + ) + assert categorical_data.shape[1] == self.categorical_dim, "categorical_data must have same number of columns as categorical embedding layers" + assert continuous_data.shape[1] == self.continuous_dim, "continuous_data must have same number of columns as continuous dim" + embed = None + if continuous_data.shape[1] > 0: + if self.batch_norm_continuous_input: + embed = self.normalizing_batch_norm(continuous_data) + else: + embed = continuous_data + # (B, N, C) + if categorical_data.shape[1] > 0: + # (B, N, C) + if embed is None: + embed = categorical_data + else: + embed = torch.cat([embed, categorical_data], dim=1) + if self.embd_dropout is not None: + embed = self.embd_dropout(embed) + return embed + + +class Embedding1dLayer(nn.Module): + """Enables different values in a categorical features to have different embeddings.""" + + def __init__( + self, + continuous_dim: int, + categorical_embedding_dims: tuple[int, int], + embedding_dropout: float = 0.0, + batch_norm_continuous_input: bool = False, + virtual_batch_size: int | None = None, + ): + super().__init__() + self.continuous_dim = continuous_dim + self.categorical_embedding_dims = categorical_embedding_dims + self.batch_norm_continuous_input = batch_norm_continuous_input + + # Embedding layers + self.cat_embedding_layers = nn.ModuleList([nn.Embedding(x, y) for x, y in categorical_embedding_dims]) + if embedding_dropout > 0: + self.embd_dropout = nn.Dropout(embedding_dropout) + else: + self.embd_dropout = None + # Continuous Layers + if batch_norm_continuous_input: + self.normalizing_batch_norm = BatchNorm1d(continuous_dim, virtual_batch_size) + + def forward(self, x: dict[str, Any]) -> torch.Tensor: + assert "continuous" in x or "categorical" in x, "x must contain either continuous and categorical features" + # (B, N) + continuous_data, categorical_data = ( + x.get("continuous", torch.empty(0, 0)), + x.get("categorical", torch.empty(0, 0)), + ) + assert categorical_data.shape[1] == len( + self.cat_embedding_layers + ), "categorical_data must have same number of columns as categorical embedding layers" + assert continuous_data.shape[1] == self.continuous_dim, "continuous_data must have same number of columns as continuous dim" + embed = None + if continuous_data.shape[1] > 0: + if self.batch_norm_continuous_input: + embed = self.normalizing_batch_norm(continuous_data) + else: + embed = continuous_data + # (B, N, C) + if categorical_data.shape[1] > 0: + categorical_embed = torch.cat( + [embedding_layer(categorical_data[:, i]) for i, embedding_layer in enumerate(self.cat_embedding_layers)], + dim=1, + ) + # (B, N, C + C) + if embed is None: + embed = categorical_embed + else: + embed = torch.cat([embed, categorical_embed], dim=1) + if self.embd_dropout is not None: + embed = self.embd_dropout(embed) + return embed + + +class Embedding2dLayer(nn.Module): + """Embeds categorical and continuous features into a 2D tensor.""" + + def __init__( + self, + continuous_dim: int, + categorical_cardinality: list[int], + embedding_dim: int, + shared_embedding_strategy: str | None = None, + frac_shared_embed: float = 0.25, + embedding_bias: bool = False, + batch_norm_continuous_input: bool = False, + virtual_batch_size: int | None = None, + embedding_dropout: float = 0.0, + initialization: str | None = None, + ): + """ + Args: + continuous_dim: number of continuous features + categorical_cardinality: list of cardinalities of categorical features + embedding_dim: embedding dimension + shared_embedding_strategy: strategy to use for shared embeddings + frac_shared_embed: fraction of embeddings to share + embedding_bias: whether to use bias in embedding layers + batch_norm_continuous_input: whether to use batch norm on continuous features + embedding_dropout: dropout to apply to embeddings + initialization: initialization strategy to use for embedding layers""" + super().__init__() + self.continuous_dim = continuous_dim + self.categorical_cardinality = categorical_cardinality + self.embedding_dim = embedding_dim + self.batch_norm_continuous_input = batch_norm_continuous_input + self.shared_embedding_strategy = shared_embedding_strategy + self.frac_shared_embed = frac_shared_embed + self.embedding_bias = embedding_bias + self.initialization = initialization + d_sqrt_inv = 1 / math.sqrt(embedding_dim) + if initialization is not None: + assert initialization in [ + "kaiming_uniform", + "kaiming_normal", + ], "initialization should be either of `kaiming` or `uniform`" + self._do_kaiming_initialization = True + self._initialize_kaiming = partial( + _initialize_kaiming, + initialization=initialization, + d_sqrt_inv=d_sqrt_inv, + ) + else: + self._do_kaiming_initialization = False + + # cat Embedding layers + if self.shared_embedding_strategy is not None: + self.cat_embedding_layers = nn.ModuleList( + [ + SharedEmbeddings( + c, + self.embedding_dim, + add_shared_embed=(self.shared_embedding_strategy == "add"), + frac_shared_embed=self.frac_shared_embed, + ) + for c in categorical_cardinality + ] + ) + if self._do_kaiming_initialization: + for embedding_layer in self.cat_embedding_layers: + self._initialize_kaiming(embedding_layer.embed.weight) + self._initialize_kaiming(embedding_layer.shared_embed) + else: + self.cat_embedding_layers = nn.ModuleList([nn.Embedding(c, self.embedding_dim) for c in categorical_cardinality]) + if self._do_kaiming_initialization: + for embedding_layer in self.cat_embedding_layers: + self._initialize_kaiming(embedding_layer.weight) + if embedding_bias: + self.cat_embedding_bias = nn.Parameter(torch.Tensor(len(self.categorical_cardinality), self.embedding_dim)) + if self._do_kaiming_initialization: + self._initialize_kaiming(self.cat_embedding_bias) + # Continuous Embedding Layer + self.cont_embedding_layer = nn.Embedding(self.continuous_dim, self.embedding_dim) + if self._do_kaiming_initialization: + self._initialize_kaiming(self.cont_embedding_layer.weight) + if embedding_bias: + self.cont_embedding_bias = nn.Parameter(torch.Tensor(self.continuous_dim, self.embedding_dim)) + if self._do_kaiming_initialization: + self._initialize_kaiming(self.cont_embedding_bias) + if batch_norm_continuous_input: + self.normalizing_batch_norm = BatchNorm1d(continuous_dim, virtual_batch_size) + if embedding_dropout > 0: + self.embd_dropout = nn.Dropout(embedding_dropout) + else: + self.embd_dropout = None + + def forward(self, x: dict[str, Any]) -> torch.Tensor: + assert "continuous" in x or "categorical" in x, "x must contain either continuous and categorical features" + # (B, N) + continuous_data, categorical_data = ( + x.get("continuous", torch.empty(0, 0)), + x.get("categorical", torch.empty(0, 0)), + ) + assert categorical_data.shape[1] == len( + self.cat_embedding_layers + ), "categorical_data must have same number of columns as categorical embedding layers" + assert continuous_data.shape[1] == self.continuous_dim, "continuous_data must have same number of columns as continuous dim" + embed = None + if continuous_data.shape[1] > 0: + cont_idx = torch.arange(self.continuous_dim, device=continuous_data.device).expand(continuous_data.size(0), -1) + if self.batch_norm_continuous_input: + continuous_data = self.normalizing_batch_norm(continuous_data) + embed = torch.mul( + continuous_data.unsqueeze(2), + self.cont_embedding_layer(cont_idx), + ) + if self.embedding_bias: + embed += self.cont_embedding_bias + # (B, N, C) + if categorical_data.shape[1] > 0: + categorical_embed = torch.cat( + [embedding_layer(categorical_data[:, i]).unsqueeze(1) for i, embedding_layer in enumerate(self.cat_embedding_layers)], + dim=1, + ) + if self.embedding_bias: + categorical_embed += self.cat_embedding_bias + # (B, N, C + C) + if embed is None: + embed = categorical_embed + else: + embed = torch.cat([embed, categorical_embed], dim=1) + if self.embd_dropout is not None: + embed = self.embd_dropout(embed) + return embed diff --git a/autodeep/modelsdefinition/tabular_nets/gated_units.py b/autodeep/modelsdefinition/tabular_nets/gated_units.py new file mode 100644 index 0000000..de79d3c --- /dev/null +++ b/autodeep/modelsdefinition/tabular_nets/gated_units.py @@ -0,0 +1,213 @@ +# Pytorch Tabular +# Author: Manu Joseph +# For license information, see LICENSE.TXT +import random +from collections.abc import Callable + +import torch +import torch.nn as nn + +from .activations import RSoftmax, entmax15 + + +class GatedFeatureLearningUnit(nn.Module): + def __init__( + self, + n_features_in: int, + n_stages: int, + feature_mask_function: Callable = entmax15, + feature_sparsity: float = 0.3, + learnable_sparsity: bool = True, + dropout: float = 0.0, + ): + super().__init__() + self.n_features_in = n_features_in + self.n_features_out = n_features_in + self.feature_mask_function = feature_mask_function + self._dropout = dropout + self.n_stages = n_stages + self.feature_sparsity = feature_sparsity + self.learnable_sparsity = learnable_sparsity + self._build_network() + + def _create_feature_mask(self): + feature_masks = torch.cat( + [ + torch.distributions.Beta( + torch.tensor([random.uniform(0.5, 10.0)]), + torch.tensor([random.uniform(0.5, 10.0)]), + ) + .sample((self.n_features_in,)) + .squeeze(-1) + for _ in range(self.n_stages) + ] + ).reshape(self.n_stages, self.n_features_in) + return nn.Parameter( + feature_masks, + requires_grad=True, + ) + + def _build_network(self): + self.W_in = nn.ModuleList([nn.Linear(2 * self.n_features_in, 2 * self.n_features_in) for _ in range(self.n_stages)]) + self.W_out = nn.ModuleList([nn.Linear(2 * self.n_features_in, self.n_features_in) for _ in range(self.n_stages)]) + + self.feature_masks = self._create_feature_mask() + if self.feature_mask_function.__name__ == "t_softmax": + t = RSoftmax.calculate_t(self.feature_masks, r=torch.tensor([self.feature_sparsity]), dim=-1) + self.t = nn.Parameter(t, requires_grad=self.learnable_sparsity) + self.dropout = nn.Dropout(self._dropout) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + h = x + t = torch.relu(self.t) if self.feature_mask_function.__name__ == "t_softmax" else None + for d in range(self.n_stages): + if self.feature_mask_function.__name__ == "t_softmax": + feature = self.feature_mask_function(self.feature_masks[d], t[d]) * x + else: + feature = self.feature_mask_function(self.feature_masks[d]) * x + h_in = self.W_in[d](torch.cat([feature, h], dim=-1)) + z = torch.sigmoid(h_in[:, : self.n_features_in]) + r = torch.sigmoid(h_in[:, self.n_features_in :]) + h_out = torch.tanh(self.W_out[d](torch.cat([r * h, x], dim=-1))) + h = self.dropout((1 - z) * h + z * h_out) + return h + + +# https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/transformers/feed_forward.py +class PositionWiseFeedForward(nn.Module): + r""" + title: Position-wise Feed-Forward Network (FFN) + summary: Documented reusable implementation of the position wise feedforward network. + + # Position-wise Feed-Forward Network (FFN) + This is a [PyTorch](https://pytorch.org) implementation + of position-wise feedforward network used in transformer. + FFN consists of two fully connected layers. + Number of dimensions in the hidden layer $d_{ff}$, is generally set to around + four times that of the token embedding $d_{model}$. + So it is sometime also called the expand-and-contract network. + There is an activation at the hidden layer, which is + usually set to ReLU (Rectified Linear Unit) activation, $$\\max(0, x)$$ + That is, the FFN function is, + $$FFN(x, W_1, W_2, b_1, b_2) = \\max(0, x W_1 + b_1) W_2 + b_2$$ + where $W_1$, $W_2$, $b_1$ and $b_2$ are learnable parameters. + Sometimes the + GELU (Gaussian Error Linear Unit) activation is also used instead of ReLU. + $$x \\Phi(x)$$ where $\\Phi(x) = P(X \\le x), X \\sim \\mathcal{N}(0,1)$ + ### Gated Linear Units + This is a generic implementation that supports different variants including + [Gated Linear Units](https://arxiv.org/abs/2002.05202) (GLU). + """ + + def __init__( + self, + d_model: int, + d_ff: int, + dropout: float = 0.1, + activation=nn.ReLU(), + is_gated: bool = False, + bias1: bool = True, + bias2: bool = True, + bias_gate: bool = True, + ): + """ + * `d_model` is the number of features in a token embedding + * `d_ff` is the number of features in the hidden layer of the FFN + * `dropout` is dropout probability for the hidden layer + * `is_gated` specifies whether the hidden layer is gated + * `bias1` specified whether the first fully connected layer should have a learnable bias + * `bias2` specified whether the second fully connected layer should have a learnable bias + * `bias_gate` specified whether the fully connected layer for the gate should have a learnable bias + """ + super().__init__() + # Layer one parameterized by weight $W_1$ and bias $b_1$ + self.layer1 = nn.Linear(d_model, d_ff, bias=bias1) + # Layer one parameterized by weight $W_1$ and bias $b_1$ + self.layer2 = nn.Linear(d_ff, d_model, bias=bias2) + # Hidden layer dropout + self.dropout = nn.Dropout(dropout) + # Activation function $f$ + self.activation = activation + # Whether there is a gate + self.is_gated = is_gated + if is_gated: + # If there is a gate the linear layer to transform inputs to + # be multiplied by the gate, parameterized by weight $V$ and bias $c$ + self.linear_v = nn.Linear(d_model, d_ff, bias=bias_gate) + + def forward(self, x: torch.Tensor): + # $f(x W_1 + b_1)$ + g = self.activation(self.layer1(x)) + # If gated, $f(x W_1 + b_1) \otimes (x V + b) $ + if self.is_gated: + x = g * self.linear_v(x) + # Otherwise + else: + x = g + # Apply dropout + x = self.dropout(x) + # $(f(x W_1 + b_1) \otimes (x V + b)) W_2 + b_2$ or $f(x W_1 + b_1) W_2 + b_2$ + # depending on whether it is gated + return self.layer2(x) + + +# Inspired by implementations +# 1. lucidrains - https://github.com/lucidrains/tab-transformer-pytorch/ +# If you are interested in Transformers, you should definitely check out his repositories. +# 2. PyTorch Wide and Deep - https://github.com/jrzaurin/pytorch-widedeep/ +# It is another library for tabular data, which supports multi modal problems. +# Check out the library if you haven't already. +# 3. AutoGluon - https://github.com/awslabs/autogluon +# AutoGluon is an AuttoML library which supports Tabular data as well. it is from Amazon Research and is in MXNet +# 4. LabML Annotated Deep Learning Papers - The position-wise FF was shamelessly copied from +# https://github.com/labmlai/annotated_deep_learning_paper_implementations/tree/master/labml_nn/transformers + + +# GLU Variants Improve Transformer https://arxiv.org/pdf/2002.05202.pdf +class GEGLU(nn.Module): + """Gated Exponential Linear Unit (GEGLU)""" + + def __init__(self, d_model: int, d_ff: int, dropout: float = 0.1): + """ + Args: + d_model: dimension of the model + d_ff: dimension of the feedforward layer + dropout: dropout probability + """ + super().__init__() + self.ffn = PositionWiseFeedForward(d_model, d_ff, dropout, nn.GELU(), True, False, False, False) + + def forward(self, x: torch.Tensor): + return self.ffn(x) + + +class ReGLU(nn.Module): + """ReGLU.""" + + def __init__(self, d_model: int, d_ff: int, dropout: float = 0.1): + """ + Args: + d_model: dimension of the model + d_ff: dimension of the feedforward layer + dropout: dropout probability + """ + super().__init__() + self.ffn = PositionWiseFeedForward(d_model, d_ff, dropout, nn.ReLU(), True, False, False, False) + + def forward(self, x: torch.Tensor): + return self.ffn(x) + + +class SwiGLU(nn.Module): + def __init__(self, d_model: int, d_ff: int, dropout: float = 0.1): + """ + Args: + d_model: dimension of the model + d_ff: dimension of the feedforward layer + dropout: dropout probability + """ + super().__init__() + self.ffn = PositionWiseFeedForward(d_model, d_ff, dropout, nn.SiLU(), True, False, False, False) + + def forward(self, x: torch.Tensor): + return self.ffn(x) diff --git a/autodeep/modelsdefinition/tabular_nets/misc.py b/autodeep/modelsdefinition/tabular_nets/misc.py new file mode 100644 index 0000000..a4214ec --- /dev/null +++ b/autodeep/modelsdefinition/tabular_nets/misc.py @@ -0,0 +1,72 @@ +# W605 +from collections.abc import Callable + +import torch +from torch import nn + + +class Residual(nn.Module): + def __init__(self, fn): + super().__init__() + self.fn = fn + + def forward(self, x, **kwargs): + return self.fn(x, **kwargs) + x + + +class Lambda(nn.Module): + """A wrapper for a lambda function as a pytorch module.""" + + def __init__(self, func: Callable): + """Initialize lambda module + Args: + func: any function/callable + """ + super().__init__() + self.func = func + + def forward(self, *args, **kwargs): + return self.func(*args, **kwargs) + + +class ModuleWithInit(nn.Module): + """Base class for pytorch module with data-aware initializer on first batch.""" + + def __init__(self): + super().__init__() + self._is_initialized_tensor = nn.Parameter(torch.tensor(0, dtype=torch.uint8), requires_grad=False) + self._is_initialized_bool = None + # Note: this module uses a separate flag self._is_initialized so as to achieve both + # * persistence: is_initialized is saved alongside model in state_dict + # * speed: model doesn't need to cache + # please DO NOT use these flags in child modules + + def initialize(self, *args, **kwargs): + """Initialize module tensors using first batch of data.""" + raise NotImplementedError("Please implement ") + + def __call__(self, *args, **kwargs): + if self._is_initialized_bool is None: + self._is_initialized_bool = bool(self._is_initialized_tensor.item()) + if not self._is_initialized_bool: + self.initialize(*args, **kwargs) + self._is_initialized_tensor.data[...] = 1 + self._is_initialized_bool = True + return super().__call__(*args, **kwargs) + + +class Add(nn.Module): + """A module that adds a constant/parameter value to the input.""" + + def __init__(self, add_value: float | torch.Tensor): + """Initialize the module. + + Args: + add_value: The value to add to the input + + """ + super().__init__() + self.add_value = add_value + + def forward(self, x): + return x + self.add_value diff --git a/autodeep/modelsdefinition/tabular_nets/node_blocks.py b/autodeep/modelsdefinition/tabular_nets/node_blocks.py new file mode 100644 index 0000000..fd64dd6 --- /dev/null +++ b/autodeep/modelsdefinition/tabular_nets/node_blocks.py @@ -0,0 +1,64 @@ +# Neural Oblivious Decision Ensembles +# Author: Sergey Popov, Julian Qian +# https://github.com/Qwicen/node +# For license information, see https://github.com/Qwicen/node/blob/master/LICENSE.md +"""Dense ODST Block.""" + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .soft_trees import ODST + + +class DenseODSTBlock(nn.Sequential): + def __init__( + self, + input_dim, + num_trees, + num_layers, + tree_output_dim=1, + max_features=None, + input_dropout=0.0, + flatten_output=False, + Module=ODST, + **kwargs, + ): + layers = [] + for _ in range(num_layers): + oddt = Module(input_dim, num_trees, tree_output_dim=tree_output_dim, flatten_output=True, **kwargs) + input_dim = min(input_dim + num_trees * tree_output_dim, max_features or float("inf")) + layers.append(oddt) + + super().__init__(*layers) + self.num_layers, self.layer_dim, self.tree_dim = ( + num_layers, + num_trees, + tree_output_dim, + ) + self.max_features, self.flatten_output = max_features, flatten_output + self.input_dropout = input_dropout + + def forward(self, x): + initial_features = x.shape[-1] + for layer in self: + layer_inp = x + if self.max_features is not None: + tail_features = min(self.max_features, layer_inp.shape[-1]) - initial_features + if tail_features != 0: + layer_inp = torch.cat( + [ + layer_inp[..., :initial_features], + layer_inp[..., -tail_features:], + ], + dim=-1, + ) + if self.training and self.input_dropout: + layer_inp = F.dropout(layer_inp, self.input_dropout) + h = layer(layer_inp) + x = torch.cat([x, h], dim=-1) + + outputs = x[..., initial_features:] + if not self.flatten_output: + outputs = outputs.reshape(*outputs.shape[:-1], self.num_layers * self.layer_dim, self.tree_dim) + return outputs diff --git a/autodeep/modelsdefinition/tabular_nets/soft_trees.py b/autodeep/modelsdefinition/tabular_nets/soft_trees.py new file mode 100644 index 0000000..2582d8d --- /dev/null +++ b/autodeep/modelsdefinition/tabular_nets/soft_trees.py @@ -0,0 +1,297 @@ +import logging +import random +from collections.abc import Callable + +import numpy as np +import torch +import torch.nn as nn + +from .activations import RSoftmax, entmax15, sparsemax, sparsemoid +from .misc import ModuleWithInit +from .utils import check_numpy + +logger = logging.getLogger(__name__) + +# Neural Oblivious Decision Ensembles +# Author: Sergey Popov, Julian Qian +# https://github.com/Qwicen/node +# For license information, see https://github.com/Qwicen/node/blob/master/LICENSE.md + + +class ODST(ModuleWithInit): + def __init__( + self, + in_features, + num_trees, + depth=6, + tree_output_dim=1, + flatten_output=True, + choice_function=sparsemax, + bin_function=sparsemoid, + initialize_response_=nn.init.normal_, + initialize_selection_logits_=nn.init.uniform_, + threshold_init_beta=1.0, + threshold_init_cutoff=1.0, + ): + """Oblivious Differentiable Sparsemax Trees. http://tinyurl.com/odst-readmore One can drop (sic!) this module + anywhere instead of nn.Linear. + + :param in_features: number of features in the input tensor + :param num_trees: number of trees in this layer + :param tree_dim: number of response channels in the response of individual tree + :param depth: number of splits in every tree + :param flatten_output: if False, returns [..., num_trees, tree_dim], + by default returns [..., num_trees * tree_dim] + :param choice_function: f(tensor, dim) -> R_simplex computes feature weights s.t. f(tensor, dim).sum(dim) == 1 + :param bin_function: f(tensor) -> R[0, 1], computes tree leaf weights + + :param initialize_response_: in-place initializer for tree output tensor + :param initialize_selection_logits_: in-place initializer for logits that select features for the tree + both thresholds and scales are initialized with data-aware init (or .load_state_dict) + :param threshold_init_beta: initializes threshold to a q-th quantile of data points + where q ~ Beta(:threshold_init_beta:, :threshold_init_beta:) + If this param is set to 1, initial thresholds will have the same distribution as data points + If greater than 1 (e.g. 10), thresholds will be closer to median data value + If less than 1 (e.g. 0.1), thresholds will approach min/max data values. + + :param threshold_init_cutoff: threshold log-temperatures initializer, in (0, inf) + By default(1.0), log-remperatures are initialized in such a way that all bin selectors + end up in the linear region of sparse-sigmoid. The temperatures are then scaled by this parameter. + Setting this value > 1.0 will result in some margin between data points and sparse-sigmoid cutoff value + Setting this value < 1.0 will cause (1 - value) part of data points to end up in flat sparse-sigmoid region + For instance, threshold_init_cutoff = 0.9 will set 10% points equal to 0.0 or 1.0 + Setting this value > 1.0 will result in a margin between data points and sparse-sigmoid cutoff value + All points will be between (0.5 - 0.5 / threshold_init_cutoff) and (0.5 + 0.5 / threshold_init_cutoff) + """ + super().__init__() + self.depth, self.num_trees, self.tree_dim, self.flatten_output = ( + depth, + num_trees, + tree_output_dim, + flatten_output, + ) + self.choice_function, self.bin_function = choice_function, bin_function + self.threshold_init_beta, self.threshold_init_cutoff = ( + threshold_init_beta, + threshold_init_cutoff, + ) + + self.response = nn.Parameter(torch.zeros([num_trees, tree_output_dim, 2**depth]), requires_grad=True) + initialize_response_(self.response) + + self.feature_selection_logits = nn.Parameter(torch.zeros([in_features, num_trees, depth]), requires_grad=True) + initialize_selection_logits_(self.feature_selection_logits) + + self.feature_thresholds = nn.Parameter( + torch.full([num_trees, depth], float("nan"), dtype=torch.float32), + requires_grad=True, + ) # nan values will be initialized on first batch (data-aware init) + self.log_temperatures = nn.Parameter( + torch.full([num_trees, depth], float("nan"), dtype=torch.float32), + requires_grad=True, + ) + + # binary codes for mapping between 1-hot vectors and bin indices + with torch.no_grad(): + indices = torch.arange(2**self.depth) + offsets = 2 ** torch.arange(self.depth) + bin_codes = (indices.view(1, -1) // offsets.view(-1, 1) % 2).to(torch.float32) + bin_codes_1hot = torch.stack([bin_codes, 1.0 - bin_codes], dim=-1) + self.bin_codes_1hot = nn.Parameter(bin_codes_1hot, requires_grad=False) + # ^-- [depth, 2 ** depth, 2] + + def forward(self, input): + assert len(input.shape) >= 2 + if len(input.shape) > 2: + return self.forward(input.reshape(-1, input.shape[-1])).reshape(*input.shape[:-1], -1) + # new input shape: [batch_size, in_features] + + feature_logits = self.feature_selection_logits + feature_selectors = self.choice_function(feature_logits, dim=0) + # ^--[in_features, num_trees, depth] + + feature_values = torch.einsum("bi,ind->bnd", input, feature_selectors) + # ^--[batch_size, num_trees, depth] + + threshold_logits = (feature_values - self.feature_thresholds) * torch.exp(-self.log_temperatures) + + threshold_logits = torch.stack([-threshold_logits, threshold_logits], dim=-1) + # ^--[batch_size, num_trees, depth, 2] + + bins = self.bin_function(threshold_logits) + # ^--[batch_size, num_trees, depth, 2], approximately binary + + bin_matches = torch.einsum("btds,dcs->btdc", bins, self.bin_codes_1hot) + # ^--[batch_size, num_trees, depth, 2 ** depth] + + response_weights = torch.prod(bin_matches, dim=-2) + # ^-- [batch_size, num_trees, 2 ** depth] + + response = torch.einsum("bnd,ncd->bnc", response_weights, self.response) + # ^-- [batch_size, num_trees, tree_dim] + + return response.flatten(1, 2) if self.flatten_output else response + + def initialize(self, input, eps=1e-6): + # data-aware initializer + assert len(input.shape) == 2 + if input.shape[0] < 1000: + # AutoDeep: logged instead of warned, the batch is already as large as the training set allows + logger.debug(f"ODST data-aware initialisation on {input.shape[0]} rows (fewer than 1000 may be less stable)") + with torch.no_grad(): + feature_selectors = self.choice_function(self.feature_selection_logits, dim=0) + # ^--[in_features, num_trees, depth] + + feature_values = torch.einsum("bi,ind->bnd", input, feature_selectors) + # ^--[batch_size, num_trees, depth] + + # initialize thresholds: sample random percentiles of data + percentiles_q = 100 * np.random.beta( + self.threshold_init_beta, + self.threshold_init_beta, + size=[self.num_trees, self.depth], + ) + self.feature_thresholds.data[...] = torch.as_tensor( + list( + map( + np.percentile, + check_numpy(feature_values.flatten(1, 2).t()), + percentiles_q.flatten(), + ) + ), + dtype=feature_values.dtype, + device=feature_values.device, + ).view(self.num_trees, self.depth) + + # init temperatures: make sure enough data points are in the linear region of sparse-sigmoid + temperatures = np.percentile( + check_numpy(abs(feature_values - self.feature_thresholds)), + q=100 * min(1.0, self.threshold_init_cutoff), + axis=0, + ) + + # if threshold_init_cutoff > 1, scale everything down by it + temperatures /= max(1.0, self.threshold_init_cutoff) + self.log_temperatures.data[...] = torch.log(torch.as_tensor(temperatures) + eps) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(in_features={self.feature_selection_logits.shape[0]}," + f" num_trees={self.num_trees}," + f" depth={self.depth}," + f" tree_dim={self.tree_dim}," + f" flatten_output={self.flatten_output})" + ) + + +class NeuralDecisionStump(nn.Module): + def __init__( + self, + n_features: int, + binning_activation: Callable = entmax15, + feature_mask_function: Callable = entmax15, + feature_sparsity: float = 0.8, + learnable_sparsity: bool = True, + ): + super().__init__() + self._num_cutpoints = 1 + self._num_leaf = 2 + self.n_features = n_features + self.binning_activation = binning_activation + self.feature_mask_function = feature_mask_function + self.feature_sparsity = feature_sparsity + self.learnable_sparsity = learnable_sparsity + self._build_network() + + def _build_network(self): + # sampling a random beta distribution + # random distribution helps with diversity in trees and feature splits + alpha = random.uniform(0.5, 10.0) + beta = random.uniform(0.5, 10.0) + # with torch.no_grad(): + feature_mask = torch.distributions.Beta(torch.tensor([alpha]), torch.tensor([beta])).sample((self.n_features,)).squeeze(-1) + self.feature_mask = nn.Parameter(feature_mask, requires_grad=True) + if self.feature_mask_function.__name__ == "t_softmax": + t = RSoftmax.calculate_t(self.feature_mask, r=torch.tensor([self.feature_sparsity])) + self.t = nn.Parameter(t, requires_grad=self.learnable_sparsity) + W = torch.linspace( + 1.0, + self._num_cutpoints + 1.0, + self._num_cutpoints + 1, + requires_grad=False, + ).reshape(1, 1, -1) + self.register_buffer("W", W) + + cutpoints = torch.rand([self.n_features, self._num_cutpoints]) + # Append zeros to the beginning of each row + cutpoints = torch.cat([torch.zeros([self.n_features, 1], device=cutpoints.device), cutpoints], 1) + self.cut_points = nn.Parameter(cutpoints, requires_grad=True) + self.leaf_responses = nn.Parameter(torch.rand(self.n_features, self._num_leaf), requires_grad=True) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if self.feature_mask_function.__name__ == "t_softmax": + t = torch.relu(self.t) + feature_mask = self.feature_mask_function(self.feature_mask, t) + else: + feature_mask = self.feature_mask_function(self.feature_mask) + # Repeat W for each batch size using broadcasting + W = torch.ones(x.size(0), 1, 1, device=x.device) * self.W + # Binning features + x = torch.bmm(x.unsqueeze(-1), W) - self.cut_points.unsqueeze(0) + x = self.binning_activation(x) # , dim=-1) + x = x * self.leaf_responses.unsqueeze(0) + x = (x * feature_mask.reshape(1, -1, 1)).sum(dim=1) + return x, feature_mask + + +class NeuralDecisionTree(nn.Module): + def __init__( + self, + depth: int, + n_features: int, + dropout: float = 0, + binning_activation: Callable = entmax15, + feature_mask_function: Callable = entmax15, + feature_sparsity: float = 0.8, + learnable_sparsity: bool = True, + ): + super().__init__() + self.depth = depth + self._num_cutpoints = 1 + self.n_features = n_features + self._dropout = dropout + self.binning_activation = binning_activation + self.feature_mask_function = feature_mask_function + self.feature_sparsity = feature_sparsity + self.learnable_sparsity = learnable_sparsity + self._build_network() + + def _build_network(self): + for d in range(self.depth): + for n in range(max(2 ** (d), 1)): + self.add_module( + f"decision_stump_{d}_{n}", + NeuralDecisionStump( + self.n_features + (2 ** (d) if d > 0 else 0), + self.binning_activation, + self.feature_mask_function, + self.feature_sparsity, + self.learnable_sparsity, + ), + ) + self.dropout = nn.Dropout(self._dropout) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + tree_input = x + feature_masks = [] + for d in range(self.depth): + layer_nodes = [] + layer_feature_masks = [] + for n in range(max(2 ** (d), 1)): + leaf_nodes, feature_mask = self._modules[f"decision_stump_{d}_{n}"](tree_input) + layer_nodes.append(leaf_nodes) + layer_feature_masks.append(feature_mask) + layer_nodes = torch.cat(layer_nodes, dim=1) + tree_input = torch.cat([x, layer_nodes], dim=1) + feature_masks.append(layer_feature_masks) + return self.dropout(layer_nodes), feature_masks diff --git a/autodeep/modelsdefinition/tabular_nets/transformers.py b/autodeep/modelsdefinition/tabular_nets/transformers.py new file mode 100644 index 0000000..4b7c52b --- /dev/null +++ b/autodeep/modelsdefinition/tabular_nets/transformers.py @@ -0,0 +1,143 @@ +# W605 +import math + +import torch +from torch import einsum, nn + +from .gated_units import GEGLU, PositionWiseFeedForward, ReGLU, SwiGLU +from .utils import _initialize_kaiming + +# from . import activations + + +GATED_UNITS = {"GEGLU": GEGLU, "ReGLU": ReGLU, "SwiGLU": SwiGLU} + + +class AddNorm(nn.Module): + """Applies LayerNorm, Dropout and adds to input. + + Standard AddNorm operations in Transformers + + """ + + def __init__(self, input_dim: int, dropout: float): + super().__init__() + self.dropout = nn.Dropout(dropout) + self.ln = nn.LayerNorm(input_dim) + + def forward(self, X: torch.Tensor, Y: torch.Tensor) -> torch.Tensor: + return self.ln(self.dropout(Y) + X) + + +class MultiHeadedAttention(nn.Module): + """Multi Headed Attention Block in Transformers.""" + + def __init__( + self, + input_dim: int, + num_heads: int = 8, + head_dim: int = 16, + dropout: int = 0.1, + keep_attn: bool = True, + ): + super().__init__() + assert input_dim % num_heads == 0, "'input_dim' must be multiples of 'num_heads'" + inner_dim = head_dim * num_heads + self.n_heads = num_heads + self.scale = head_dim**-0.5 + self.keep_attn = keep_attn + + self.to_qkv = nn.Linear(input_dim, inner_dim * 3, bias=False) + self.to_out = nn.Linear(inner_dim, input_dim) + + self.dropout = nn.Dropout(dropout) + + def forward(self, x): + h = self.n_heads + q, k, v = self.to_qkv(x).chunk(3, dim=-1) + b, n = x.shape[0], x.shape[1] + q, k, v = (t.reshape(b, n, h, -1).transpose(1, 2) for t in (q, k, v)) # b n (h d) -> b h n d + sim = einsum("b h i d, b h j d -> b h i j", q, k) * self.scale + + attn = sim.softmax(dim=-1) + attn = self.dropout(attn) + if self.keep_attn: + self.attn_weights = attn + out = einsum("b h i j, b h j d -> b h i d", attn, v) + out = out.transpose(1, 2).reshape(b, n, -1) # b h n d -> b n (h d) + return self.to_out(out) + + +class TransformerEncoderBlock(nn.Module): + """A single Transformer Encoder Block.""" + + def __init__( + self, + input_embed_dim: int, + num_heads: int = 8, + ff_hidden_multiplier: int = 4, + ff_activation: str = "GEGLU", + attn_dropout: float = 0.1, + keep_attn: bool = True, + ff_dropout: float = 0.1, + add_norm_dropout: float = 0.1, + transformer_head_dim: int | None = None, + ): + """ + Args: + input_embed_dim: The input embedding dimension + num_heads: The number of attention heads + ff_hidden_multiplier: The hidden dimension multiplier for the position-wise feed-forward layer + ff_activation: The activation function for the position-wise feed-forward layer + attn_dropout: The dropout probability for the attention layer + keep_attn: Whether to keep the attention weights + ff_dropout: The dropout probability for the position-wise feed-forward layer + add_norm_dropout: The dropout probability for the residual connections + transformer_head_dim: The dimension of the attention heads. If None, will default to input_embed_dim + """ + super().__init__() + self.mha = MultiHeadedAttention( + input_embed_dim, + num_heads, + head_dim=input_embed_dim if transformer_head_dim is None else transformer_head_dim, + dropout=attn_dropout, + keep_attn=keep_attn, + ) + + try: + self.pos_wise_ff = GATED_UNITS[ff_activation]( + d_model=input_embed_dim, + d_ff=input_embed_dim * ff_hidden_multiplier, + dropout=ff_dropout, + ) + except (AttributeError, KeyError): + self.pos_wise_ff = PositionWiseFeedForward( + d_model=input_embed_dim, + d_ff=input_embed_dim * ff_hidden_multiplier, + dropout=ff_dropout, + activation=getattr(nn, ff_activation)(), + ) + self.attn_add_norm = AddNorm(input_embed_dim, add_norm_dropout) + self.ff_add_norm = AddNorm(input_embed_dim, add_norm_dropout) + + def forward(self, x): + y = self.mha(x) + x = self.attn_add_norm(x, y) + y = self.pos_wise_ff(y) + return self.ff_add_norm(x, y) + + +class AppendCLSToken(nn.Module): + """Appends the [CLS] token for BERT-like inference.""" + + def __init__(self, d_token: int, initialization: str) -> None: + """Initialize self.""" + super().__init__() + self.weight = nn.Parameter(torch.Tensor(d_token)) + d_sqrt_inv = 1 / math.sqrt(d_token) + _initialize_kaiming(self.weight, initialization, d_sqrt_inv) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Perform the forward pass.""" + assert x.ndim == 3 + return torch.cat([x, self.weight.view(1, 1, -1).repeat(len(x), 1, 1)], dim=1) diff --git a/autodeep/modelsdefinition/tabular_nets/utils.py b/autodeep/modelsdefinition/tabular_nets/utils.py new file mode 100644 index 0000000..decd646 --- /dev/null +++ b/autodeep/modelsdefinition/tabular_nets/utils.py @@ -0,0 +1,107 @@ +"""Small helpers from ``pytorch_tabular.utils`` and the ``LinearHead`` from ``pytorch_tabular.models.common.heads``. + +Pytorch Tabular, Author: Manu Joseph , MIT licence (see LICENSE in this folder). +""" + +import logging + +import numpy as np +import torch +import torch.nn as nn + +from .batch_norm import BatchNorm1d + +logger = logging.getLogger(__name__) + + +def _initialize_layers(activation, initialization, layers): + if type(layers) is nn.Sequential: + for layer in layers: + if hasattr(layer, "weight"): + _initialize_layers(activation, initialization, layer) + else: + if activation == "ReLU": + nonlinearity = "relu" + elif activation == "LeakyReLU": + nonlinearity = "leaky_relu" + else: + if initialization == "kaiming": + logger.debug("Kaiming initialization is only recommended for ReLU and LeakyReLU.") + nonlinearity = "leaky_relu" + else: + nonlinearity = "relu" + + if initialization == "kaiming": + nn.init.kaiming_normal_(layers.weight, nonlinearity=nonlinearity) + elif initialization == "xavier": + nn.init.xavier_normal_( + layers.weight, + gain=(nn.init.calculate_gain(nonlinearity) if activation in ["ReLU", "LeakyReLU"] else 1), + ) + elif initialization == "random": + nn.init.normal_(layers.weight) + + +def _linear_dropout_bn(activation, initialization, use_batch_norm, in_units, out_units, dropout): + _activation = getattr(nn, activation) if isinstance(activation, str) else activation + layers = [] + if use_batch_norm: + layers.append(BatchNorm1d(num_features=in_units)) + linear = nn.Linear(in_units, out_units) + _initialize_layers(activation, initialization, linear) + layers.extend([linear, _activation()]) + if dropout != 0: + layers.append(nn.Dropout(dropout)) + return layers + + +def _initialize_kaiming(x, initialization, d_sqrt_inv): + if initialization == "kaiming_uniform": + nn.init.uniform_(x, a=-d_sqrt_inv, b=d_sqrt_inv) + elif initialization == "kaiming_normal": + nn.init.normal_(x, std=d_sqrt_inv) + elif initialization is None: + pass + else: + raise NotImplementedError("initialization should be either of `kaiming_normal`, `kaiming_uniform`, `None`") + + +def check_numpy(x): + """Makes sure x is a numpy array.""" + if isinstance(x, torch.Tensor): + x = x.detach().cpu().numpy() + x = np.asarray(x) + assert isinstance(x, np.ndarray) + return x + + +class LinearHead(nn.Module): + """Optional hidden layers followed by the output ``Linear`` (pytorch-tabular's ``LinearHead``). + + pytorch-tabular's default head config is ``{"layers": ""}``: a single ``Linear``. + """ + + def __init__( + self, + in_units: int, + output_dim: int, + layers: str = "", + activation: str = "ReLU", + dropout: float = 0.0, + use_batch_norm: bool = False, + initialization: str = "kaiming", + ): + super().__init__() + _layers = [] + _curr_units = in_units + for units in str(layers or "").split("-"): + if units == "": + continue + _layers.extend(_linear_dropout_bn(activation, initialization, use_batch_norm, _curr_units, int(units), dropout)) + _curr_units = int(units) + _layers.append(nn.Linear(_curr_units, output_dim)) + self.layers = nn.Sequential(*_layers) + _initialize_layers(activation, initialization, self.layers) + + def forward(self, x): + return self.layers(x) diff --git a/autodeep/modelsdefinition/torch_base.py b/autodeep/modelsdefinition/torch_base.py index 96f1b72..d8911fa 100644 --- a/autodeep/modelsdefinition/torch_base.py +++ b/autodeep/modelsdefinition/torch_base.py @@ -1,10 +1,10 @@ -"""Training loop shared by the custom PyTorch models (ResNet on IGTD images, Soft-Ordering 1D-CNN).""" +"""Training loop shared by AutoDeep's own PyTorch models (embedding-based tabular nets, ResNet on IGTD images, 1D-CNN).""" from __future__ import annotations import copy import math -from typing import Optional +import random import numpy as np import pandas as pd @@ -29,7 +29,7 @@ def build_network(self, params, n_features: int, n_outputs: int): def to_tensor(self, X: pd.DataFrame): import torch - return torch.as_tensor(X.to_numpy(dtype=np.float32)) + return torch.tensor(X.to_numpy(dtype=np.float32)) # a copy: with pandas 3 copy-on-write, to_numpy() can be read-only # ------------------------------------------------------------------ setup @property @@ -56,7 +56,7 @@ def _loss_fn(self, y_train): def _target_tensor(self, y): import torch - y = np.asarray(y) + y = np.array(y) # a copy: with pandas 3 copy-on-write, np.asarray(series) is read-only if self.problem_type == "multiclass_classification": return torch.as_tensor(y, dtype=torch.long) if self.problem_type == "regression": @@ -87,6 +87,9 @@ def _loader(self, X_t, y_t, batch_size, shuffle): pin_memory=self.device == "cuda", ) + def init_network(self, net, X_train_t, y_train_t) -> None: + """Hook called once per trial before the first epoch, e.g. for data-aware initialisation.""" + def _forward(self, net, xb): out = net(xb) return out.reshape(-1) if self.n_outputs == 1 else out @@ -96,16 +99,21 @@ def fit_trial(self, params, X_train, y_train, X_val, y_val): import torch torch.manual_seed(self.random_state) + random.seed(self.random_state) # some architectures draw their initial masks with random / numpy + np.random.seed(self.random_state % 2**32) device = self.device - batch_size = int(min(int(params.get("batch_size", 256)), len(X_train))) + batch_size = int(min(int(params.get("batch_size", self.default_params.get("batch_size", 256))), len(X_train))) max_epochs = max(1, int(self._setting("max_epochs", 100))) patience = int(self.default_params.get("early_stopping_patience", 10)) tol = float(self.default_params.get("tol", 0.0)) net = self.build_network(params, X_train.shape[1], self.n_outputs).to(device) + net._autodeep_build = (dict(params), int(X_train.shape[1]), int(self.n_outputs)) # to rebuild the net after unpickling opt, sched = self._optimizer(params, net) loss_fn = self._loss_fn(y_train) - train_loader = self._loader(self.to_tensor(X_train), self._target_tensor(y_train), batch_size, shuffle=True) + X_train_t, y_train_t = self.to_tensor(X_train), self._target_tensor(y_train) + self.init_network(net, X_train_t, y_train_t) + train_loader = self._loader(X_train_t, y_train_t, batch_size, shuffle=True) val_loader = self._loader(self.to_tensor(X_val), self._target_tensor(y_val), max(batch_size, 1024), shuffle=False) best_loss, best_state, best_epoch, bad_epochs = math.inf, None, 0, 0 @@ -151,6 +159,7 @@ def _evaluate_loss(self, net, loader, loss_fn) -> float: def predict_with(self, net, X): import torch + net = self._on_own_device(net) net.eval() X_t = self.to_tensor(X) outs = [] @@ -166,12 +175,60 @@ def predict_with(self, net, X): prob = torch.softmax(out, dim=1).numpy() return prob.argmax(axis=1), prob + # Networks are pickled as (build arguments, weights): some layers (weight_norm parametrizations, + # locally defined classes) cannot be pickled as modules. + def __getstate__(self): + state, packed = self.__dict__.copy(), {} + for key in ("model", "best_model"): + net = state.get(key) + if net is not None and hasattr(net, "_autodeep_build"): + if id(net) not in packed: + packed[id(net)] = { + "_autodeep_net": True, + "build": net._autodeep_build, + "weights": {k: v.cpu() for k, v in net.state_dict().items()}, + } + state[key] = packed[id(net)] + return state + + def __setstate__(self, state): + self.__dict__.update(state) + rebuilt = {} + for key in ("model", "best_model"): + saved = state.get(key) + if isinstance(saved, dict) and saved.get("_autodeep_net"): + if id(saved) not in rebuilt: + params, n_features, n_outputs = saved["build"] + params = {**params, "weights": None} # no pretrained download: the weights come from the file + net = self.build_network(params, n_features, n_outputs) + net.load_state_dict(saved["weights"]) + net._autodeep_build = saved["build"] + rebuilt[id(saved)] = net.eval() # on CPU; predict_with() moves it to the trainer's device + setattr(self, key, rebuilt[id(saved)]) + + def _on_own_device(self, net): + """Move ``net`` where :attr:`device` sends the inputs, e.g. after unpickling (CPU if that fails).""" + device = self.device + param = next(net.parameters(), None) + if param is None or param.device.type == device: + return net + try: + return net.to(device) + except Exception: # e.g. no usable GPU after all + self._device_override = "cpu" + return net.to("cpu") + + def to_device(self, device: str) -> None: + super().to_device(device) + if self.model is not None: + self.model.to(device) + def save_model(self, path): import torch torch.save(self.model.state_dict(), str(path)) - def _load_model(self, path, params: Optional[dict] = None): # pragma: no cover - convenience + def _load_model(self, path, params: dict | None = None): # pragma: no cover - convenience import torch self.model.load_state_dict(torch.load(str(path), map_location=self.device)) diff --git a/autodeep/modelutils/search.py b/autodeep/modelutils/search.py index 918d497..47754c5 100644 --- a/autodeep/modelutils/search.py +++ b/autodeep/modelutils/search.py @@ -5,8 +5,10 @@ import math import time import traceback +from collections.abc import Callable from dataclasses import dataclass, field -from typing import Any, Callable, Dict, List, Optional +from functools import partial +from typing import Any import numpy as np from hyperopt import STATUS_FAIL, STATUS_OK, Trials, fmin, tpe @@ -20,26 +22,36 @@ logger = get_logger("search") +def n_startup_trials(max_evals: int) -> int: + """Random trials before TPE starts modelling the space. + + hyperopt's default is 20, which turns a 25-trial search into 20 random trials and 5 guided ones. + A third of the budget, between 5 and 10 (Optuna uses 10), leaves most of the trials to TPE. + """ + return max(5, min(10, int(max_evals) // 3)) + + @dataclass class TrialOutcome: """What a model's ``objective`` must return for one hyperparameter set.""" - validation_metrics: Dict[str, float] - train_metrics: Dict[str, float] + validation_metrics: dict[str, float] + train_metrics: dict[str, float] model: Any = None - extra: Dict[str, Any] = field(default_factory=dict) + extra: dict[str, Any] = field(default_factory=dict) @dataclass class SearchResult: - best_params: Dict[str, Any] + best_params: dict[str, Any] best_score: float - train_metrics: Dict[str, float] - validation_metrics: Dict[str, float] + train_metrics: dict[str, float] + validation_metrics: dict[str, float] best_model: Any - trials: List[Dict[str, Any]] + trials: list[dict[str, Any]] n_failed: int duration: float + best_raw_params: dict[str, Any] | None = None # as passed to the objective (before JSON cleaning) def short_error(e: BaseException, limit: int = 300) -> str: @@ -53,7 +65,7 @@ def make_serializable(value): """Turn hyperopt-sampled params (which may contain classes / numpy types) into plain JSON-able values.""" if isinstance(value, dict): return {str(k): make_serializable(v) for k, v in value.items()} - if isinstance(value, (list, tuple)): + if isinstance(value, list | tuple): return [make_serializable(v) for v in value] if isinstance(value, type): return value.__name__ @@ -65,15 +77,15 @@ def make_serializable(value): def run_hyperopt( - objective: Callable[[Dict[str, Any]], TrialOutcome], - space: Dict[str, Any], + objective: Callable[[dict[str, Any]], TrialOutcome], + space: dict[str, Any], metric: str, max_evals: int, random_state: int = 42, - timeout: Optional[float] = None, + timeout: float | None = None, model_name: str = "model", stop_on_perfect_score: bool = True, - points_to_evaluate: Optional[List[Dict[str, Any]]] = None, + points_to_evaluate: list[dict[str, Any]] | None = None, ) -> SearchResult: """Run a TPE search, keeping only the best model in memory. @@ -85,7 +97,7 @@ def run_hyperopt( metric = normalize_metric_name(metric) info = METRICS[metric] state = {"best_loss": math.inf, "best": None, "n_done": 0, "n_failed": 0, "last_error": None} - records: List[Dict[str, Any]] = [] + records: list[dict[str, Any]] = [] t_start = time.perf_counter() def wrapped(params): @@ -171,7 +183,7 @@ def early_stop(trials, *args): fmin( wrapped, space=space, - algo=tpe.suggest, + algo=partial(tpe.suggest, n_startup_jobs=n_startup_trials(max_evals)), max_evals=int(max_evals), trials=trials, rstate=np.random.default_rng(random_state), @@ -194,4 +206,5 @@ def early_stop(trials, *args): trials=records, n_failed=state["n_failed"], duration=time.perf_counter() - t_start, + best_raw_params=best["raw_params"], ) diff --git a/autodeep/modelutils/trainingutilities.py b/autodeep/modelutils/trainingutilities.py index 2ffffef..aa2ea4d 100644 --- a/autodeep/modelutils/trainingutilities.py +++ b/autodeep/modelutils/trainingutilities.py @@ -12,8 +12,6 @@ from __future__ import annotations -from typing import Dict - import numpy as np import pandas as pd from hyperopt import hp @@ -37,7 +35,7 @@ def map_scheduler_str_to_class(scheduler_str): def _ensure_min_max(values): - if isinstance(values[0], (float, int)) and not isinstance(values[0], bool): + if isinstance(values[0], float | int) and not isinstance(values[0], bool): return min(values), max(values) return values @@ -58,13 +56,13 @@ def _is_categorical(name, values): return ( name in CATEGORICAL_NUMERIC_PARAMS or any(v is None for v in values) - or isinstance(values[0], (str, bool, list, tuple)) - or not all(isinstance(v, (int, float)) for v in values) + or isinstance(values[0], str | bool | list | tuple) + or not all(isinstance(v, int | float) for v in values) ) def _param_space(name, values, int_step=1): - if not isinstance(values, (list, tuple)): + if not isinstance(values, list | tuple): return values # constant if len(values) == 0: raise ValueError(f"Empty value list for hyperparameter '{name}'") @@ -73,14 +71,14 @@ def _param_space(name, values, int_step=1): return _numeric_space(name, values, int_step=int_step) -def infer_hyperopt_space(param_grid: Dict): +def infer_hyperopt_space(param_grid: dict): """Search space for plain (non-torch) models such as XGBoost, CatBoost and scikit-learn MLP.""" param_grid = dict(param_grid) param_grid.pop("default_params", None) return {name: _param_space(name, values) for name, values in param_grid.items()} -def _conditional_choice(param_name, options: Dict, key, mapping): +def _conditional_choice(param_name, options: dict, key, mapping): branches = [] for option_name, sub_params in options.items(): branch = {key: mapping[option_name]} @@ -90,7 +88,7 @@ def _conditional_choice(param_name, options: Dict, key, mapping): return hp.choice(param_name, branches) -def infer_hyperopt_space_pytorch_tabular(param_grid: Dict): +def infer_hyperopt_space_pytorch_tabular(param_grid: dict): """Search space for torch models: also understands ``optimizer_fn`` / ``scheduler_fn`` blocks.""" param_grid = dict(param_grid) param_grid.pop("default_params", None) @@ -108,7 +106,7 @@ def infer_hyperopt_space_pytorch_tabular(param_grid: Dict): space[new_name] = _param_space(new_name, subsub_values) else: step = 1 - if name == "batch_size" and isinstance(values, (list, tuple)) and not _is_categorical(name, values): + if name == "batch_size" and isinstance(values, list | tuple) and not _is_categorical(name, values): step = max(1, min(32, int(min(values)))) # quniform may round down to 0 if step > lower bound space[name] = _param_space(name, values, int_step=step) return space diff --git a/autodeep/outputhandler/outputwriter.py b/autodeep/outputhandler/outputwriter.py index 40ab221..2abbdae 100644 --- a/autodeep/outputhandler/outputwriter.py +++ b/autodeep/outputhandler/outputwriter.py @@ -52,7 +52,7 @@ def write_row(self, **kwargs): row = {} for field in self.fields: value = kwargs.get(field) - if isinstance(value, (list, dict)): + if isinstance(value, list | dict): value = str(value) row[field] = value writer.writerow(row) diff --git a/autodeep/predictor.py b/autodeep/predictor.py new file mode 100644 index 0000000..4ba05a3 --- /dev/null +++ b/autodeep/predictor.py @@ -0,0 +1,227 @@ +"""A trained model you can use: preprocessing + model + original labels, saved as one folder. + +Every AutoDeep run keeps the best model of each dataset (chosen on the validation score) as a +:class:`Predictor`:: + + leaderboard = runner.run() + model = runner.best_model("churn") # or: autodeep.load_model("output/models/churn/best") + model.predict(new_rows) # original labels / values + model.predict_proba(new_rows) # DataFrame, one column per class + +``new_rows`` is a DataFrame (or a file path, a dict or a list of dicts) with the same columns as the +training data; the target and any extra columns are ignored. Missing values are filled exactly as during +training, and unseen categories are handled. + +From the command line: ``autodeep predict output/models/churn/best new.csv -o predictions.csv``. + +A saved predictor is a folder with ``predictor.pt`` (a pickle: only load files you trust) and a readable +``info.json``. Loading needs the same AutoDeep version (or a compatible one) and the model's libraries. +""" + +from __future__ import annotations + +import json +import platform +from datetime import datetime +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + +from autodeep.logging_utils import get_logger + +logger = get_logger("predictor") + +FORMAT_VERSION = 1 +PICKLE_FILE = "predictor.pt" +INFO_FILE = "info.json" + +DataLike = pd.DataFrame | str | Path | dict[str, Any] | list[dict[str, Any]] + + +def _jsonable(value): + if isinstance(value, dict): + return {str(k): _jsonable(v) for k, v in value.items()} + if isinstance(value, list | tuple): + return [_jsonable(v) for v in value] + if isinstance(value, np.generic): + return value.item() + if isinstance(value, str | int | float | bool) or value is None: + return value + return str(value) + + +class Predictor: + """Preprocessing + trained model for one (dataset, model) pair.""" + + def __init__(self, trainer, preprocessor, info: dict[str, Any]): + self.trainer = trainer + self.preprocessor = preprocessor + self.info = dict(info) + + # ------------------------------------------------------------------ properties + @property + def problem_type(self) -> str: + return self.info["problem_type"] + + @property + def model_name(self) -> str: + return self.info["model"] + + @property + def classes(self) -> list[Any] | None: + """Original class labels (classification), in the order of the probability columns.""" + return self.info.get("classes") + + @property + def input_columns(self) -> list[str]: + return list(self.preprocessor.input_columns) + + def __repr__(self) -> str: + i = self.info + score = f", test {i.get('metric')}={i['test_score']:.4f}" if isinstance(i.get("test_score"), int | float) else "" + return f"Predictor({i.get('model')} on {i.get('dataset')!r}, {i.get('problem_type')}{score}, {len(self.input_columns)} input columns)" + + # ------------------------------------------------------------------ prediction + def _frame(self, data: DataLike) -> pd.DataFrame: + if isinstance(data, pd.DataFrame): + return data + if isinstance(data, str | Path): + from autodeep.datasets import read_table + + return read_table(data) + if isinstance(data, dict): + return pd.DataFrame([data]) + if isinstance(data, list): + return pd.DataFrame(data) + raise TypeError(f"Expected a DataFrame, a file path, a dict or a list of dicts, got {type(data).__name__}") + + def _raw_predict(self, data: DataLike): + df = self._frame(data) + if len(df) == 0: + raise ValueError("No rows to predict") + X = self.preprocessor.transform_raw(df) + pred, prob = self.trainer.predict(X, predict_proba=True) + return df.index, np.asarray(pred), None if prob is None else np.asarray(prob) + + def _labels(self, pred: np.ndarray) -> np.ndarray: + if self.problem_type == "regression": + return pred.astype(float).reshape(-1) + classes = np.asarray(self.classes, dtype=object) + out = classes[pred.astype(int).reshape(-1)] + try: # keep a numeric dtype for numeric labels + return out.astype(np.asarray(self.classes).dtype) + except (TypeError, ValueError): + return out + + def _proba_frame(self, prob: np.ndarray, index) -> pd.DataFrame: + if prob.ndim == 1: # binary: probability of the second class + prob = np.column_stack([1.0 - prob, prob]) + return pd.DataFrame(prob, index=index, columns=list(self.classes)) + + def predict(self, data: DataLike) -> np.ndarray: + """Predicted labels (classification, original values) or values (regression).""" + _, pred, _ = self._raw_predict(data) + return self._labels(pred) + + def predict_proba(self, data: DataLike) -> pd.DataFrame: + """Class probabilities, one column per original class label (classification only).""" + if self.problem_type == "regression": + raise ValueError("predict_proba() is only available for classification models") + index, _, prob = self._raw_predict(data) + if prob is None: + raise ValueError(f"Model '{self.model_name}' does not provide probabilities") + return self._proba_frame(prob, index) + + def predict_frame(self, data: DataLike, proba: bool = True) -> pd.DataFrame: + """A DataFrame with a ``prediction`` column (and ``proba_`` columns), aligned with the input rows.""" + index, pred, prob = self._raw_predict(data) + out = pd.DataFrame({"prediction": self._labels(pred)}, index=index) + if proba and prob is not None: + probs = self._proba_frame(prob, index) + probs.columns = [f"proba_{c}" for c in probs.columns] + out = pd.concat([out, probs], axis=1) + return out + + def evaluate(self, data: DataLike, target: str | None = None, metrics: list[str] | None = None) -> dict[str, float]: + """Score the model on labelled rows (the target column must be present).""" + from autodeep.evaluation.generalevaluator import Evaluator + + df = self._frame(data) + target = target or self.info.get("target") + if target not in df.columns: + raise ValueError(f"Target column '{target}' not found") + df = df[df[target].notna()] + _, pred, prob = self._raw_predict(df.drop(columns=[target])) + y = df[target] + if self.problem_type != "regression": + lookup = {str(c): i for i, c in enumerate(self.classes)} + unknown = sorted({str(v) for v in y} - set(lookup)) + if unknown: + raise ValueError(f"Labels {unknown[:5]} were not seen during training (known: {self.classes})") + y = y.map(lambda v: lookup[str(v)]) + return Evaluator( + y_true=np.asarray(y), + y_pred=pred, + y_prob=prob, + run_metrics=metrics or self.info.get("eval_metrics"), + metric=self.info.get("metric"), + problem_type=self.problem_type, + ).evaluate_model() + + # ------------------------------------------------------------------ persistence + def save(self, path: str | Path) -> Path: + """Write the predictor to the folder ``path`` (created if needed).""" + import torch + + import autodeep + + path = Path(path) + path.mkdir(parents=True, exist_ok=True) + self.trainer.strip_for_saving() + self.info.update( + format_version=FORMAT_VERSION, + autodeep_version=autodeep.__version__, + saved_at=datetime.now().isoformat(timespec="seconds"), + python_version=platform.python_version(), + torch_version=torch.__version__, + input_schema=self.preprocessor.schema(), + ) + torch.save(self, path / PICKLE_FILE) + (path / INFO_FILE).write_text(json.dumps(_jsonable(self.info), indent=2)) + return path + + @classmethod + def load(cls, path: str | Path, device: str = "auto") -> Predictor: + """Load a predictor saved with :meth:`save`. ``device``: ``"auto"``, ``"cpu"`` or ``"cuda"``.""" + import torch + + path = Path(path) + file = path / PICKLE_FILE if path.is_dir() else path + if not file.exists(): + raise FileNotFoundError(f"No saved AutoDeep model at {path} (expected {PICKLE_FILE})") + obj = torch.load(file, map_location="cpu", weights_only=False) + if not isinstance(obj, cls): + raise TypeError(f"{file} does not contain an AutoDeep Predictor") + version = obj.info.get("format_version", 0) + if version > FORMAT_VERSION: + raise ValueError(f"{file} was saved by a newer AutoDeep (format {version}); upgrade AutoDeep to load it") + obj.to(device) + return obj + + def to(self, device: str = "auto") -> Predictor: + """Run predictions on ``device`` (``"auto"`` picks the GPU only if it has enough free memory).""" + if device in (None, "auto"): + from autodeep.device import resolve_device + + device = resolve_device() + if device == "gpu": + device = "cuda" + self.trainer.to_device(device) + return self + + +def load_model(path: str | Path, device: str = "auto") -> Predictor: + """Load a model saved by AutoDeep (a folder such as ``output/models//best``).""" + return Predictor.load(path, device=device) diff --git a/autodeep/preprocessing.py b/autodeep/preprocessing.py new file mode 100644 index 0000000..6c70d44 --- /dev/null +++ b/autodeep/preprocessing.py @@ -0,0 +1,192 @@ +"""Feature preprocessing that is fitted once and can be replayed on new data. + +:class:`TabularPreprocessor` holds every decision made while preparing the training data: the input +columns and their types, the sanitised column names, the imputation values, the one-hot categories and the +fitted scaler. The data loader uses it to build ``X_train`` / ``X_test``, and a saved +:class:`~autodeep.predictor.Predictor` uses the same object to turn raw rows into model input. +""" + +from __future__ import annotations + +from typing import Any + +import numpy as np +import pandas as pd + +from autodeep.logging_utils import get_logger + +logger = get_logger("data") + +MAX_ONEHOT_CATEGORIES = 30 +_EPOCH = pd.Timestamp("1970-01-01") + + +def _to_str_or_none(s: pd.Series) -> pd.Series: + s = s.astype(object).where(s.notna(), None) + return s.map(lambda v: v if v is None else str(v)) + + +def _datetime_seconds(s: pd.Series) -> pd.Series: + s = pd.to_datetime(s, errors="coerce") + if getattr(s.dt, "tz", None) is not None: + s = s.dt.tz_convert("UTC").dt.tz_localize(None) + return (s - _EPOCH).dt.total_seconds() + + +class TabularPreprocessor: + """Column typing, imputation, optional one-hot encoding and optional scaling. + + Usage:: + + prep = TabularPreprocessor(normalize="mean_std", encode_categorical=False) + X = prep.fit_schema(raw_features) # types + clean column names (whole dataset) + prep.fit(X.loc[train_idx]) # statistics from the training rows only + X_train, X_test = prep.transform(X.loc[train_idx]), prep.transform(X.loc[test_idx]) + X_new = prep.transform_raw(new_rows) # later, on raw data with the original column names + """ + + def __init__(self, normalize: Any = "mean_std", encode_categorical: bool = False, max_categories: int = MAX_ONEHOT_CATEGORIES): + if normalize in (None, False, "false", "none", "None", ""): + normalize = None + if normalize not in (None, "mean_std", "min_max"): + raise ValueError(f"Invalid normalization method '{normalize}' (use mean_std, min_max or false)") + self.normalize = normalize + self.encode_categorical = bool(encode_categorical) + self.max_categories = int(max_categories) + # schema + self.input_columns: list[str] = [] + self.rename: dict[Any, str] = {} + self.categorical: list[str] = [] # sanitised names + self.datetime: list[str] = [] + self.numeric: list[str] = [] + # fitted state + self.fill_values: dict[str, Any] = {} + self.onehot_top: dict[str, list[str]] = {} + self.onehot_columns: list[str] = [] + self.onehot_rename: dict[str, str] = {} + self.scale_columns: list[str] = [] + self.scaler = None + self.output_columns: list[str] = [] + self.fitted = False + + # ------------------------------------------------------------------ schema + def fit_schema(self, X: pd.DataFrame) -> pd.DataFrame: + """Decide the type of every column, clean the names and return the typed frame. + + Booleans, categoricals and text become categorical strings; datetimes become seconds since 1970; + everything else is numeric. + """ + from autodeep.datasets import sanitize_columns + + self.input_columns = list(X.columns) + self.rename = sanitize_columns(X.columns) + self.categorical, self.datetime, self.numeric = [], [], [] + for c in X.columns: + s = X[c] + name = self.rename[c] + if pd.api.types.is_datetime64_any_dtype(s): + self.datetime.append(name) + elif pd.api.types.is_bool_dtype(s) or not pd.api.types.is_numeric_dtype(s): + self.categorical.append(name) + else: + self.numeric.append(name) + return self._apply_schema(X) + + def _apply_schema(self, X: pd.DataFrame) -> pd.DataFrame: + X = X[self.input_columns].rename(columns=self.rename) + out = {} + for c in X.columns: + s = X[c] + if c in self.categorical: + out[c] = _to_str_or_none(s) + elif c in self.datetime: + out[c] = _datetime_seconds(s) + elif not pd.api.types.is_numeric_dtype(s) or pd.api.types.is_bool_dtype(s): # e.g. numbers read as text + converted = pd.to_numeric(s.map(lambda v: v if not isinstance(v, bool | np.bool_) else int(v)), errors="coerce") + bad = int(converted.isna().sum() - s.isna().sum()) + if bad > 0: + logger.warning(f"Column '{c}': {bad} value(s) are not numbers and are treated as missing") + out[c] = converted + else: + out[c] = s + return pd.DataFrame(out, index=X.index) + + # ------------------------------------------------------------------ fit / transform + def fit(self, X_train: pd.DataFrame) -> TabularPreprocessor: + """Learn imputation values, one-hot categories and the scaler from typed training rows.""" + self.fill_values = {} + for c in X_train.columns: + s = X_train[c] + if c not in self.categorical: + fill = s.median() + self.fill_values[c] = 0.0 if pd.isna(fill) else fill + else: + mode = s.mode(dropna=True) + self.fill_values[c] = mode.iloc[0] if not mode.empty else "missing" + X = self._impute(X_train) + + self.onehot_top, self.onehot_columns, self.onehot_rename = {}, [], {} + if self.encode_categorical and self.categorical: + for c in self.categorical: + counts = X[c].value_counts() + if len(counts) > self.max_categories: + logger.info(f"Column '{c}' has {len(counts)} categories: keeping the {self.max_categories} most frequent, the rest -> 'other'") + self.onehot_top[c] = list(counts.index[: self.max_categories]) + dummies = pd.get_dummies(self._grouped(X), prefix=self.categorical, dtype=float) + self.onehot_columns = list(dummies.columns) + from autodeep.datasets import sanitize_columns + + kept = [c for c in X.columns if c not in self.categorical] + self.onehot_rename = sanitize_columns(kept + self.onehot_columns) + X = self._encode(X) + + self.scaler, self.scale_columns = None, [] + if self.normalize: + from sklearn.preprocessing import MinMaxScaler, StandardScaler + + self.scale_columns = list(X.select_dtypes(include=[np.number, "bool"]).columns) + if self.scale_columns: + self.scaler = (StandardScaler() if self.normalize == "mean_std" else MinMaxScaler()).fit(X[self.scale_columns].astype(float)) + self.output_columns = list(X.columns) + self.fitted = True + return self + + def _impute(self, X: pd.DataFrame) -> pd.DataFrame: + X = X.copy() + for c, fill in self.fill_values.items(): + if c in X and X[c].isna().any(): + X[c] = X[c].fillna(fill) + return X + + def _grouped(self, X: pd.DataFrame) -> pd.DataFrame: + return pd.DataFrame({c: X[c].where(X[c].isin(self.onehot_top[c]), "other").astype(str) for c in self.categorical}, index=X.index) + + def _encode(self, X: pd.DataFrame) -> pd.DataFrame: + if not self.onehot_columns: + return X + dummies = pd.get_dummies(self._grouped(X), prefix=self.categorical, dtype=float).reindex(columns=self.onehot_columns, fill_value=0.0) + X = pd.concat([X.drop(columns=self.categorical), dummies], axis=1) + return X.rename(columns=self.onehot_rename) + + def transform(self, X: pd.DataFrame) -> pd.DataFrame: + """Typed frame (output of :meth:`fit_schema` / :meth:`transform_raw` schema step) -> model input.""" + if not self.fitted: + raise RuntimeError("TabularPreprocessor is not fitted") + X = self._encode(self._impute(X)) + if self.scaler is not None: + X = X.copy() + X[self.scale_columns] = self.scaler.transform(X[self.scale_columns].astype(float)) + return X + + def transform_raw(self, X: pd.DataFrame) -> pd.DataFrame: + """Raw rows with the original column names (extra columns are ignored) -> model input.""" + missing = [c for c in self.input_columns if c not in X.columns] + if missing: + raise ValueError(f"Missing column(s) {missing}. The model was trained on: {self.input_columns}") + return self.transform(self._apply_schema(X)) + + # ------------------------------------------------------------------ info + def schema(self) -> list[dict[str, Any]]: + """``[{"name", "type"}]`` of the expected input columns (original names).""" + kind = {**{c: "categorical" for c in self.categorical}, **{c: "datetime" for c in self.datetime}} + return [{"name": str(c), "type": kind.get(self.rename[c], "numeric")} for c in self.input_columns] diff --git a/autodeep/progress.py b/autodeep/progress.py index 933ceba..feb35cc 100644 --- a/autodeep/progress.py +++ b/autodeep/progress.py @@ -8,7 +8,7 @@ import threading import time -from typing import Callable, Optional +from collections.abc import Callable _local = threading.local() @@ -17,11 +17,11 @@ class RunCancelled(Exception): """Raised to abort a run (e.g. the user pressed *Stop* in the web UI).""" -def set_reporter(fn: Optional[Callable[[dict], None]]) -> None: +def set_reporter(fn: Callable[[dict], None] | None) -> None: _local.reporter = fn -def get_reporter() -> Optional[Callable[[dict], None]]: +def get_reporter() -> Callable[[dict], None] | None: return getattr(_local, "reporter", None) diff --git a/autodeep/registry.py b/autodeep/registry.py index aa1e819..a462c08 100644 --- a/autodeep/registry.py +++ b/autodeep/registry.py @@ -7,7 +7,6 @@ import importlib from dataclasses import asdict, dataclass, field -from typing import Dict, List, Optional, Tuple @dataclass(frozen=True) @@ -18,15 +17,15 @@ class ModelInfo: target: str # "module:Class" description: str uses_gpu: bool = False - aliases: Tuple[str, ...] = field(default_factory=tuple) + aliases: tuple[str, ...] = field(default_factory=tuple) speed: str = "medium" # "fast" | "medium" | "slow" (rough guide for the UI) - max_trials: Optional[int] = None # e.g. 1 for models without hyperparameters + max_trials: int | None = None # e.g. 1 for models without hyperparameters def load(self): module, cls = self.target.split(":") return getattr(importlib.import_module(module), cls) - def to_dict(self) -> Dict: + def to_dict(self) -> dict: d = asdict(self) d.pop("target") d["aliases"] = list(self.aliases) @@ -34,10 +33,10 @@ def to_dict(self) -> Dict: _P = "autodeep.modelsdefinition" -_PT = f"{_P}.pytorch_tabular_models" +_PT = f"{_P}.deep_tabular_models" _FM = f"{_P}.foundation_models" -MODELS: Dict[str, ModelInfo] = { +MODELS: dict[str, ModelInfo] = { m.name: m for m in [ ModelInfo( @@ -50,6 +49,16 @@ def to_dict(self) -> Dict: ("xgboost",), "fast", ), + ModelInfo( + "lgbm", + "LightGBM", + "gbdt", + f"{_P}.LightGBMTrainer:LightGBMTrainer", + "Leaf-wise gradient boosting (CPU) with native categorical handling.", + False, + ("lightgbm", "lgb"), + "fast", + ), ModelInfo( "catboost", "CatBoost", @@ -70,6 +79,16 @@ def to_dict(self) -> Dict: (), "fast", ), + ModelInfo( + "resmlp", + "Residual MLP", + "neural", + f"{_P}.ResidualMLP:ResidualMLPTrainer", + "PyTorch MLP; with an offset column it starts from another model's prediction and learns the residual.", + True, + ("residualmlp",), + "fast", + ), ModelInfo( "categoryembedding", "Category Embedding MLP", @@ -174,7 +193,7 @@ def to_dict(self) -> Dict: #: A sensible default selection: fast, robust models first. DEFAULT_MODELS = ["xgb", "catboost", "mlp", "tabicl", "realmlp", "categoryembedding", "fttransformer", "gandalf"] PRESETS = { - "fast": ["xgb", "catboost", "mlp"], + "fast": ["xgb", "lgbm", "catboost", "mlp"], "default": DEFAULT_MODELS, "modern": ["tabicl", "realmlp", "tabm"], "deep": ["realmlp", "tabm", "categoryembedding", "fttransformer", "tabtransformer", "tabnet", "gandalf", "autoint", "node", "gate", "danet"], @@ -190,7 +209,7 @@ def canonical_name(name: str) -> str: return key -def resolve_models(models) -> List[str]: +def resolve_models(models) -> list[str]: """Accept a list of names, a preset name (``"fast"``, ``"default"``, ``"modern"``, ``"deep"``, ``"all"``) or ``None``.""" if models is None: return list(DEFAULT_MODELS) @@ -207,7 +226,7 @@ def resolve_models(models) -> List[str]: return list(dict.fromkeys(out)) -def list_models() -> List[Dict]: +def list_models() -> list[dict]: return [m.to_dict() for m in MODELS.values()] diff --git a/autodeep/web/server.py b/autodeep/web/server.py index 9449c01..229b97a 100644 --- a/autodeep/web/server.py +++ b/autodeep/web/server.py @@ -23,7 +23,7 @@ import time import uuid from pathlib import Path -from typing import Any, Dict, List, Optional +from typing import Any import pandas as pd from fastapi import FastAPI, File, Form, HTTPException, UploadFile @@ -48,33 +48,41 @@ class DatasetIn(BaseModel): name: str path: str - target: Optional[str] = None - problem_type: Optional[str] = None - metric: Optional[str] = None - eval_metrics: Optional[List[str]] = None + target: str | None = None + problem_type: str | None = None + metric: str | None = None + eval_metrics: list[str] | None = None test_size: float = 0.2 - split_col: Optional[str] = None - train_value: Optional[Any] = None - test_value: Optional[Any] = None - drop_columns: List[str] = Field(default_factory=list) - max_rows: Optional[int] = None + split_col: str | None = None + train_value: Any | None = None + test_value: Any | None = None + drop_columns: list[str] = Field(default_factory=list) + max_rows: int | None = None class JobIn(BaseModel): - name: Optional[str] = None - datasets: List[DatasetIn] - models: List[str] + name: str | None = None + datasets: list[DatasetIn] + models: list[str] max_evals: int = 20 - max_epochs: Optional[int] = None - timeout_per_model: Optional[float] = None + max_epochs: int | None = None + timeout_per_model: float | None = None device: str = "auto" random_state: int = 42 save_models: bool = False + save_best: bool = True + + +class PlanIn(BaseModel): + datasets: list[DatasetIn] + time_budget: float = 15 * 60 # seconds, whole run + device: str = "auto" + max_epochs: int | None = None class ProfileIn(BaseModel): path: str - target: Optional[str] = None + target: str | None = None # -------------------------------------------------------------------------------------- @@ -91,11 +99,11 @@ def __init__(self, root: Path): for d in (self.datasets_dir, self.runs_dir): d.mkdir(parents=True, exist_ok=True) self.lock = threading.Lock() - self.procs: Dict[str, subprocess.Popen] = {} - self._profile_cache: Dict[str, Any] = {} + self.procs: dict[str, subprocess.Popen] = {} + self._profile_cache: dict[str, Any] = {} # datasets ---------------------------------------------------------------- - def registered(self) -> List[Dict]: + def registered(self) -> list[dict]: if not self.registry_file.exists(): return [] try: @@ -103,7 +111,7 @@ def registered(self) -> List[Dict]: except json.JSONDecodeError: return [] - def save_registered(self, items: List[Dict]) -> None: + def save_registered(self, items: list[dict]) -> None: with self.lock: self.registry_file.write_text(json.dumps(items, indent=2, default=str)) @@ -126,7 +134,7 @@ def job_dir(self, job_id: str) -> Path: raise HTTPException(404, f"job {job_id} not found") return d - def job_status(self, job_id: str) -> Dict: + def job_status(self, job_id: str) -> dict: d = self.job_dir(job_id) job = json.loads((d / JOB_FILE).read_text()) status = {} @@ -162,7 +170,7 @@ def _safe_filename(name: str) -> str: return f"{stem}{ext.lower()}" -def _read_events(path: Path, since: int = 0, limit: int = 500) -> List[Dict]: +def _read_events(path: Path, since: int = 0, limit: int = 500) -> list[dict]: if not path.exists(): return [] out = [] @@ -181,7 +189,20 @@ def _read_events(path: Path, since: int = 0, limit: int = 500) -> List[Dict]: return out -def _results(job_dir: Path) -> List[Dict]: +def _best_models(job_dir: Path) -> list[dict]: + """Saved best model per dataset (read from info.json; the server never unpickles models).""" + out = [] + for info_file in sorted((job_dir / "output" / "models").glob("*/best/info.json")): + try: + info = json.loads(info_file.read_text()) + except (OSError, json.JSONDecodeError): + continue + keys = ("dataset", "model", "model_display_name", "problem_type", "target", "classes", "metric", "val_score", "test_score", "input_schema") + out.append({**{k: info.get(k) for k in keys}, "path": str(info_file.parent.resolve())}) + return out + + +def _results(job_dir: Path) -> list[dict]: path = job_dir / "output" / "experiments.csv" if not path.exists(): return [] @@ -202,7 +223,7 @@ def _results(job_dir: Path) -> List[Dict]: # -------------------------------------------------------------------------------------- -def create_app(workspace: Optional[str] = None) -> FastAPI: +def create_app(workspace: str | None = None) -> FastAPI: ws = Workspace(Path(workspace or os.environ.get("AUTODEEP_WORKSPACE", "autodeep_workspace"))) app = FastAPI(title="AutoDeep", version=__version__) app.state.workspace = ws @@ -242,7 +263,7 @@ def datasets(): return {"builtin": list_builtin_datasets(), "registered": ws.registered(), "supported_extensions": list(SUPPORTED_EXTENSIONS)} @app.post("/api/datasets/upload") - async def upload(file: UploadFile = File(...), name: Optional[str] = Form(None)): + async def upload(file: UploadFile = File(...), name: str | None = Form(None)): filename = _safe_filename(file.filename) if not filename.lower().endswith(SUPPORTED_EXTENSIONS): raise HTTPException(400, f"Unsupported file type. Use one of {', '.join(SUPPORTED_EXTENSIONS)}") @@ -323,11 +344,39 @@ def estimate(job: JobIn): except Exception as e: raise HTTPException(400, str(e)) set_device(job.device) + from autodeep.machine import current_speed_factor + plan = estimate_plan( - shapes, models, job.max_evals, timeout_per_model=job.timeout_per_model, max_epochs=job.max_epochs, device=resolve_device() + shapes, + models, + job.max_evals, + timeout_per_model=job.timeout_per_model, + max_epochs=job.max_epochs, + device=resolve_device(), + speed_factor=current_speed_factor(), ) return {**plan.summary(), "datasets": [s.to_dict() for s in specs]} + @app.post("/api/plan") + def auto_plan(req: PlanIn): + """Recommended models / trials / time limit for these datasets on this machine (models: auto).""" + from autodeep.autoplan import recommend + from autodeep.device import resolve_device, set_device + from autodeep.machine import machine_profile + + if not req.datasets: + raise HTTPException(400, "Add at least one dataset") + try: + _, shapes = _specs(JobIn(datasets=req.datasets, models=["xgb"])) + except Exception as e: + raise HTTPException(400, str(e)) + set_device(req.device) + machine = machine_profile() + plan = recommend( + shapes, req.time_budget, device=resolve_device(), speed_factor=machine.speed_factor, max_epochs=req.max_epochs, machine=machine + ) + return plan.to_dict() + @app.post("/api/jobs") def create_job(job: JobIn): if not job.datasets or not job.models: @@ -377,6 +426,7 @@ def job(job_id: str, since: int = 0): d = ws.job_dir(job_id) info["events"] = _read_events(d / EVENTS_FILE, since=since) info["results"] = _results(d) + info["best_models"] = _best_models(d) return info @app.post("/api/jobs/{job_id}/cancel") @@ -438,6 +488,49 @@ def results_csv(job_id: str): raise HTTPException(404, "no results yet") return FileResponse(path, media_type="text/csv", filename=f"autodeep_{job_id}.csv") + def _model_dir(job_id: str, dataset: str) -> Path: + base = (ws.job_dir(job_id) / "output" / "models").resolve() + d = (base / dataset / "best").resolve() + if base not in d.parents or not (d / "info.json").exists(): + raise HTTPException(404, f"No saved model for dataset '{dataset}'") + return d + + @app.get("/api/jobs/{job_id}/models/{dataset}/download") + def download_model(job_id: str, dataset: str): + import io + import zipfile + + from fastapi.responses import Response + + d = _model_dir(job_id, dataset) + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z: + for f in d.rglob("*"): + if f.is_file(): + z.write(f, Path(f"{dataset}_model") / f.relative_to(d)) + name = _safe_filename(f"autodeep_{dataset}_model.zip") + return Response(buf.getvalue(), media_type="application/zip", headers={"Content-Disposition": f'attachment; filename="{name}"'}) + + @app.post("/api/jobs/{job_id}/models/{dataset}/predict") + async def predict(job_id: str, dataset: str, file: UploadFile = File(...)): + d = _model_dir(job_id, dataset) + suffix = Path(file.filename or "rows.csv").suffix.lower() or ".csv" + if suffix not in SUPPORTED_EXTENSIONS: + raise HTTPException(400, f"Unsupported file type '{suffix}'") + work = ws.job_dir(job_id) / "predictions" + work.mkdir(exist_ok=True) + stem = time.strftime("%Y%m%d-%H%M%S-") + uuid.uuid4().hex[:4] + src, dst = work / f"{stem}_input{suffix}", work / f"{stem}_{_safe_filename(dataset)}_predictions.csv" + src.write_bytes(await file.read()) + # prediction loads torch: run it in a subprocess so the server stays light + proc = subprocess.run( + [sys.executable, "-m", "autodeep.cli", "predict", str(d), str(src), "-o", str(dst)], capture_output=True, text=True, timeout=1800 + ) + if proc.returncode != 0 or not dst.exists(): + lines = [ln for ln in (proc.stderr or "").strip().splitlines() if ln.strip()] + raise HTTPException(400, lines[-1] if lines else "prediction failed") + return FileResponse(dst, media_type="text/csv", filename=f"{_safe_filename(dataset)}_predictions.csv") + return app @@ -455,7 +548,7 @@ def _port_free(host: str, port: int) -> bool: return False -def serve(host: str = "127.0.0.1", port: Optional[int] = None, workspace: Optional[str] = None, open_browser: bool = True): +def serve(host: str = "127.0.0.1", port: int | None = None, workspace: str | None = None, open_browser: bool = True): import uvicorn if port is None: # default port busy (another app?) -> take the next free one diff --git a/autodeep/web/static/index.html b/autodeep/web/static/index.html index 01b565c..54ba7e2 100644 --- a/autodeep/web/static/index.html +++ b/autodeep/web/static/index.html @@ -76,6 +76,15 @@ .ds .body { padding: 12px; } .ds .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 10px; } .hint { font-size: 12px; color: var(--muted); } +.bestmodel { display: flex; flex-wrap: wrap; gap: 10px 16px; align-items: center; padding: 10px 0; border-bottom: 1px solid var(--border); } +.bestmodel:last-child { border-bottom: 0; } +.bestmodel code { font-family: var(--mono); font-size: 12px; background: var(--surface-2); padding: 2px 6px; border-radius: 6px; overflow-wrap: anywhere; } +.tag.saved { background: var(--accent-soft); color: var(--text); } +.autobox { border: 1px solid var(--border); background: var(--surface-2); border-radius: 8px; padding: 10px 12px; margin-bottom: 14px; } +.autobox input { font: inherit; padding: 3px 6px; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); color: var(--text); } +.autoreasons { margin: 8px 0 0; padding-left: 18px; font-size: 12.5px; color: var(--text-2); } +.autoreasons:empty { display: none; } +.autoreasons li { margin: 2px 0; } .warnline { font-size: 12.5px; color: var(--text-2); margin-top: 8px; } .warnline::before { content: "\26A0 "; color: var(--warning); } .err { color: var(--critical); font-size: 13px; margin-top: 8px; white-space: pre-wrap; } @@ -90,6 +99,7 @@ .model.on { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); } .model .t { font-weight: 600; font-size: 13.5px; } .model .d { color: var(--muted); font-size: 12px; } +.model input[type=checkbox] { flex: none; margin-top: 3px; } /* long descriptions must not squeeze the box */ .fam { font-size: 11px; text-transform: uppercase; letter-spacing: .05em; color: var(--muted); margin: 14px 0 6px; font-weight: 600; } .estimate { display: flex; gap: 24px; align-items: center; flex-wrap: wrap; padding: 14px 16px; border-top: 1px solid var(--border); } .hero { font-size: 30px; font-weight: 650; letter-spacing: -.02em; } @@ -168,7 +178,17 @@

AutoDeep

2

Models

-
+
+
+
+ + + +
+
    +
    +
    +
    @@ -180,10 +200,10 @@

    AutoDeep

    - +
    -

    Tip: for a first look use 5-10 trials and max epochs 30. A time budget stops a model's search after the running trial finishes.

    +

    Auto (in Models) fills these in for your time budget. A time limit stops a model's search after the running trial finishes; max epochs caps the training length of the neural models.

    Estimated time
    –
    @@ -212,6 +232,7 @@

    AutoDeep

    +

    Leaderboard

    Best hyperparameters per model, scored on the held-out test set
    Results appear here as models finish.

    Activity

    Log

    @@ -221,7 +242,7 @@

    AutoDeep