From 5125c9dd944b434b9604eb70f559711d3c6384d1 Mon Sep 17 00:00:00 2001 From: mdicio Date: Thu, 12 Nov 2026 01:34:45 +0100 Subject: [PATCH 01/15] CI: bump actions to checkout@v5, setup-python@v6, cache@v5 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013EC637XcrFPHFykZKx7pbm --- .github/workflows/ci.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 From 1aed0d1581bd2723ad0fad6f815fcaa214983937 Mon Sep 17 00:00:00 2001 From: mdicio Date: Thu, 12 Nov 2026 00:56:04 +0100 Subject: [PATCH 02/15] Saved predictors: best model per dataset with its preprocessing, autodeep predict - TabularPreprocessor: the data loader's typing/imputation/one-hot/scaling as one fitted object that replays on raw rows (output identical to the previous loader on 24 cases) - Predictor (preprocessing + model + original labels): predict, predict_proba, predict_frame, evaluate, save/load as a folder (predictor.pt + info.json) - AutoRunner keeps the best model per dataset by validation score, saves it to models//best (save_best=True); save_models=True saves every model; runner.best_model(); leaderboard 'selected' column - All 17 models pickle: PyTorch Tabular without training data / Lightning trainer, torch nets as build args + weights, TabICL/pytabkit/XGBoost device moves, so GPU-trained models load on CPU-only machines - CLI: autodeep predict, autodeep info; web UI: download model, predict a file Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013EC637XcrFPHFykZKx7pbm --- autodeep/__init__.py | 19 +- autodeep/automl.py | 110 +++++++-- autodeep/cli.py | 67 ++++++ autodeep/dataloaders/dataloader.py | 28 +-- autodeep/jobs.py | 2 +- autodeep/modelsdefinition/CommonStructure.py | 48 ++-- autodeep/modelsdefinition/XGBoostTrainer.py | 5 + .../modelsdefinition/foundation_models.py | 69 ++++++ autodeep/modelsdefinition/torch_base.py | 37 +++ autodeep/predictor.py | 227 ++++++++++++++++++ autodeep/preprocessing.py | 192 +++++++++++++++ autodeep/web/server.py | 58 +++++ autodeep/web/static/index.html | 45 +++- tests/test_predictor.py | 95 ++++++++ tests/test_web.py | 9 + 15 files changed, 958 insertions(+), 53 deletions(-) create mode 100644 autodeep/predictor.py create mode 100644 autodeep/preprocessing.py create mode 100644 tests/test_predictor.py diff --git a/autodeep/__init__.py b/autodeep/__init__.py index 0a1b2ff..aa86b72 100644 --- a/autodeep/__init__.py +++ b/autodeep/__init__.py @@ -7,6 +7,8 @@ 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" @@ -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..d4ff0e6 100755 --- a/autodeep/automl.py +++ b/autodeep/automl.py @@ -107,7 +107,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__( @@ -131,6 +136,7 @@ def __init__( on_event: Optional[Callable[[Dict], None]] = None, fail_fast: bool = False, save_models: bool = False, + save_best: bool = True, log_level: str = "INFO", ): if execution_mode != "hyperopt": @@ -155,7 +161,10 @@ 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] = {} @@ -279,6 +288,8 @@ def reporter(evt): cancelled = True break frames[spec.name] = None + cache.clear() + self._save_best(spec.name) if cancelled: break finally: @@ -311,7 +322,7 @@ 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): @@ -334,7 +345,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 +382,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: @@ -436,17 +446,83 @@ def _write_trials(self, dataset, model, trials): 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: Optional[str] = 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 +533,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/cli.py b/autodeep/cli.py index 0743fc5..62c8685 100644 --- a/autodeep/cli.py +++ b/autodeep/cli.py @@ -8,6 +8,8 @@ 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 @@ -87,9 +89,21 @@ def cmd_run(args): 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) @@ -115,6 +129,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 @@ -151,6 +166,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 @@ -201,6 +255,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/dataloaders/dataloader.py b/autodeep/dataloaders/dataloader.py index add21a6..8e37bc7 100755 --- a/autodeep/dataloaders/dataloader.py +++ b/autodeep/dataloaders/dataloader.py @@ -14,11 +14,11 @@ 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] = { "img_size": "auto", @@ -242,6 +242,8 @@ def __init__( self.dataframe = dataframe self.sep = sep self.max_rows = max_rows + self.preprocessor: Optional[TabularPreprocessor] = 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/jobs.py b/autodeep/jobs.py index ed7b4e6..4d830dd 100644 --- a/autodeep/jobs.py +++ b/autodeep/jobs.py @@ -23,7 +23,7 @@ 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: diff --git a/autodeep/modelsdefinition/CommonStructure.py b/autodeep/modelsdefinition/CommonStructure.py index 5837403..40cc24a 100755 --- a/autodeep/modelsdefinition/CommonStructure.py +++ b/autodeep/modelsdefinition/CommonStructure.py @@ -101,7 +101,15 @@ def predict_with(self, model, X: pd.DataFrame) -> Tuple[np.ndarray, Optional[np. # ------------------------------------------------------------------ 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.""" @@ -249,24 +257,16 @@ def save_model(self, path): def _redirect_pt_tmp(): - """PyTorch Tabular writes ``./.pt_tmp/exp_version_manager.yml`` in the working directory; keep it in AutoDeep's cache.""" + """PyTorch Tabular writes ``./.pt_tmp/exp_version_manager.yml`` in the working directory; keep it in AutoDeep's cache. + + Only the default argument is changed (no subclass), so trained models stay picklable. + """ 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 + ptm.ExperimentRunManager.__init__.__defaults__ = (str(cache / "pytorch_tabular" / "exp_version_manager.yml"),) class PytorchTabularTrainer(BaseTrainer): @@ -382,6 +382,7 @@ def fit_trial(self, params, X_train, y_train, X_val, y_val): ) if best.state is not None: model.model.load_state_dict(best.state) + best.state = None # free the copy (the callback stays referenced by the model) return model def predict_with(self, model, X): @@ -396,5 +397,24 @@ def predict_with(self, model, X): return pred, proba[:, 1] return pred, proba + def to_device(self, device): + super().to_device(device) + if self.model is not None: + self.model.model.to(device) + + def __getstate__(self): + """Pickle only what prediction needs (no training data, Lightning trainer or callbacks).""" + state = self.__dict__.copy() + model = state.get("model") + if model is not None and getattr(getattr(model, "datamodule", None), "_fitted", False): + light = copy.copy(model) + light.datamodule = model.datamodule.inference_only_copy() + light.trainer = None # the Lightning trainer and callbacks are only needed for fitting + light.callbacks = [] + state["model"] = light + if state.get("best_model") is model: + state["best_model"] = light + return state + def save_model(self, path): self.model.save_model(str(path)) diff --git a/autodeep/modelsdefinition/XGBoostTrainer.py b/autodeep/modelsdefinition/XGBoostTrainer.py index 479f31b..70d78a7 100755 --- a/autodeep/modelsdefinition/XGBoostTrainer.py +++ b/autodeep/modelsdefinition/XGBoostTrainer.py @@ -32,6 +32,11 @@ def fit_trial(self, params, X_train, y_train, X_val, y_val): def predict_with(self, model, X): return super().predict_with(model, _categories_to_pandas(X)) + 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/foundation_models.py b/autodeep/modelsdefinition/foundation_models.py index e44dac5..f1f960f 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,6 +64,28 @@ 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 @@ -102,7 +126,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/torch_base.py b/autodeep/modelsdefinition/torch_base.py index 96f1b72..ed4f3e8 100644 --- a/autodeep/modelsdefinition/torch_base.py +++ b/autodeep/modelsdefinition/torch_base.py @@ -103,6 +103,7 @@ def fit_trial(self, params, X_train, y_train, X_val, y_val): 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) @@ -166,6 +167,42 @@ 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() + setattr(self, key, rebuilt[id(saved)]) + + 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 diff --git a/autodeep/predictor.py b/autodeep/predictor.py new file mode 100644 index 0000000..b2d0449 --- /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, Dict, List, Optional, Union + +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 = Union[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) -> Optional[List[Any]]: + """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: Optional[str] = None, metrics: Optional[List[str]] = 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: Union[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: Union[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: Union[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..88d2175 --- /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, Dict, List + +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/web/server.py b/autodeep/web/server.py index 9449c01..166f80e 100644 --- a/autodeep/web/server.py +++ b/autodeep/web/server.py @@ -70,6 +70,7 @@ class JobIn(BaseModel): device: str = "auto" random_state: int = 42 save_models: bool = False + save_best: bool = True class ProfileIn(BaseModel): @@ -181,6 +182,19 @@ def _read_events(path: Path, since: int = 0, limit: int = 500) -> List[Dict]: return out +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(): @@ -377,6 +391,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 +453,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 diff --git a/autodeep/web/static/index.html b/autodeep/web/static/index.html index 01b565c..8d984a2 100644 --- a/autodeep/web/static/index.html +++ b/autodeep/web/static/index.html @@ -76,6 +76,10 @@ .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); } .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; } @@ -180,7 +184,7 @@

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.

@@ -212,6 +216,7 @@

AutoDeep

+

Leaderboard

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

Activity

Log

@@ -416,7 +421,7 @@

AutoDeep

$("runs").innerHTML = r.jobs.length ? r.jobs.map(j => { const s = j.status || {}; return `
${esc(j.name || j.id)}
${statusBadge(s.state)}
${new Date((j.created_at || 0) * 1000).toLocaleString()} · ${s.jobs_done ?? 0}/${s.jobs_total ?? "?"} models${s.state === "running" ? ` · ETA ${esc(s.eta_human || "?")}` : ""}
${s.elapsed_seconds ? fmtDur(s.elapsed_seconds) : ""}
`; }).join("") : `
No runs yet. Configure an experiment and press Start experiment.
`; } function openRun(id) { - S.run = id; S.seq = 0; S.feed = []; $("rdFeed").innerHTML = ""; $("rdLog").textContent = ""; + S.run = id; S.seq = 0; S.feed = []; S.modelsKey = null; $("rdFeed").innerHTML = ""; $("rdLog").textContent = ""; $("runsList").classList.add("hidden"); $("runDetail").classList.remove("hidden"); $("rdCsv").onclick = () => location.href = `/api/jobs/${id}/results.csv`; $("rdCancel").onclick = async () => { await api(`/api/jobs/${id}/cancel`, { method: "POST" }); toast("Stopping after the current trial…"); }; @@ -445,7 +450,8 @@

AutoDeep

const feed = $("rdFeed"); const atBottom = feed.scrollHeight - feed.scrollTop - feed.clientHeight < 30; feed.innerHTML = S.feed.map(l => `
${esc(l)}
`).join("") || `
waiting for the first events…
`; if (atBottom) feed.scrollTop = feed.scrollHeight; - renderBoard(info.results); + renderBestModels(info.best_models || []); + renderBoard(info.results, info.best_models || []); S.polls = (S.polls || 0) + 1; if (live) { if (S.polls % 4 === 0) loadLog(); S.runTimer = setTimeout(pollRun, 1500); } else loadLog(); } @@ -462,7 +468,36 @@

AutoDeep

} return null; } -function renderBoard(results) { +function renderBestModels(list) { + $("rdModelsCard").classList.toggle("hidden", !list.length); + if (!list.length) return; + const key = JSON.stringify(list.map(m => [m.dataset, m.model, m.path])); + if (key === S.modelsKey) return; // keep file inputs intact between polls + S.modelsKey = key; + $("rdModels").innerHTML = list.map((m, i) => `
+
${esc(m.dataset)}: ${esc(m.model_display_name || m.model)} +
validation ${esc(m.metric)} ${fmtNum(m.val_score)} · test ${fmtNum(m.test_score)} · needs ${(m.input_schema || []).length} input columns${m.classes ? " · predicts " + esc(m.classes.slice(0, 6).join(", ")) + (m.classes.length > 6 ? "…" : "") : ""}
+
Python: autodeep.load_model("${esc(m.path)}").predict(df)
+ + +
`).join(""); + S.bestModels = list; +} +async function predictFile(i, input) { + const m = S.bestModels[i], file = input.files[0]; if (!file) return; + toast(`Predicting ${file.name} with ${m.model}…`); + const fd = new FormData(); fd.append("file", file); + try { + const r = await fetch(`/api/jobs/${S.run}/models/${encodeURIComponent(m.dataset)}/predict`, { method: "POST", body: fd }); + if (!r.ok) { let msg = r.statusText; try { msg = (await r.json()).detail || msg; } catch {} throw new Error(msg); } + const blob = await r.blob(), a = document.createElement("a"); + a.href = URL.createObjectURL(blob); a.download = `${m.dataset}_predictions.csv`; a.click(); URL.revokeObjectURL(a.href); + toast("Predictions downloaded"); + } catch (e) { toast("Prediction failed: " + e.message); } + input.value = ""; +} +function renderBoard(results, best = []) { + const saved = Object.fromEntries(best.map(m => [m.dataset, m.model])); if (!results || !results.length) { $("rdBoard").innerHTML = `
Results appear here as models finish.
`; return; } const byDs = {}; for (const r of results) (byDs[r.dataset] ||= []).push(r); $("rdBoard").innerHTML = Object.entries(byDs).map(([ds, rows]) => { @@ -474,7 +509,7 @@

AutoDeep

const evalKeys = [...new Set(ok.flatMap(r => Object.keys(r.test_metrics || {})))].filter(k => k !== metric); return `

${esc(ds)} · ${esc(PT_LABEL[rows[0].problem_type] || "")} · ranked by test ${esc(metric)} (${info.maximize ? "higher" : "lower"} is better)

${evalKeys.map(k => ``).join("")} - ${ok.map((r, i) => `${evalKeys.map(k => ``).join("")}`).join("")} + ${ok.map((r, i) => `${evalKeys.map(k => ``).join("")}`).join("")} ${others.map(r => ``).join("")}
#ModelStatusTest ${esc(metric)}Val ${esc(metric)}test ${esc(k)}TrialsTimeBest parameters
${i + 1}${esc(r.model)}${statusBadge("ok")}
${fmtNum(r.test_score)}
${fmtNum(r.best_score)}${fmtNum(r.test_metrics?.[k])}${r.n_trials ?? ""}${r.n_failed_trials ? ` (${r.n_failed_trials} failed)` : ""}${fmtDur(r.duration_sec)}
show
${esc(JSON.stringify(r.best_params, null, 1))}
${i + 1}${esc(r.model)}${saved[ds] === r.model ? ` saved` : ""}${statusBadge("ok")}
${fmtNum(r.test_score)}
${fmtNum(r.best_score)}${fmtNum(r.test_metrics?.[k])}${r.n_trials ?? ""}${r.n_failed_trials ? ` (${r.n_failed_trials} failed)` : ""}${fmtDur(r.duration_sec)}
show
${esc(JSON.stringify(r.best_params, null, 1))}
${esc(r.model)}${statusBadge(r.status)}${esc(r.error || "")}${fmtDur(r.duration_sec)}
`; }).join(""); diff --git a/tests/test_predictor.py b/tests/test_predictor.py new file mode 100644 index 0000000..e20d4d8 --- /dev/null +++ b/tests/test_predictor.py @@ -0,0 +1,95 @@ +"""Saved models: preprocessing replay, save/load round trip, predict CLI.""" + +import numpy as np +import pandas as pd +import pytest + +from autodeep import AutoRunner, load_model +from autodeep.cli import main +from autodeep.dataloaders.dataloader import DynamicDataLoader +from autodeep.datasets import parse_datasets, read_table +from autodeep.preprocessing import TabularPreprocessor + + +@pytest.mark.parametrize("normalize,encode", [("mean_std", False), ("min_max", True), (False, True)]) +def test_preprocessor_replays_training_transform(mixed_csv, normalize, encode): + spec = parse_datasets({"m": {"path": str(mixed_csv), "target": "label", "drop_columns": ["id", "split"]}})[0] + df = spec.read() + spec.resolve(df) + loader = DynamicDataLoader.from_spec(spec, dataframe=df, normalize_features=normalize, encode_categorical=encode) + X_train, X_test, *_ = loader.load_data() + raw = df.drop(columns=["label"]).loc[X_test.index] # extra columns (id, split) are ignored + pd.testing.assert_frame_equal(loader.preprocessor.transform_raw(raw), X_test, check_dtype=False) + + +def test_preprocessor_handles_unseen_values_and_types(): + train = pd.DataFrame({"a b": [1.0, 2.0, None, 4.0], "c": ["x", "y", "x", None], "flag": [True, False, True, True]}) + prep = TabularPreprocessor(normalize="mean_std", encode_categorical=True) + prep.fit(prep.fit_schema(train)) + new = pd.DataFrame({"a b": ["3", "oops"], "c": ["z", None], "flag": [False, True], "extra": [0, 0]}) # numbers as text, unseen category + out = prep.transform_raw(new) + assert list(out.columns) == prep.output_columns and not out.isna().any().any() + with pytest.raises(ValueError, match="Missing column"): + prep.transform_raw(new.drop(columns=["c"])) + assert [c["type"] for c in prep.schema()] == ["numeric", "categorical", "categorical"] + + +def test_best_model_save_load_predict(tmp_path, mixed_csv): + runner = AutoRunner( + datasets={ + "mixed": {"path": str(mixed_csv), "target": "label", "drop_columns": ["id", "split"]}, + "iris": {"path": "builtin:iris"}, + "diabetes": {"path": "builtin:diabetes"}, + }, + models=["xgb", "mlp"], + max_evals=1, + output_folder=tmp_path / "out", + log_level="WARNING", + ) + board = runner.run() + assert board.groupby("dataset")["selected"].sum().eq(1).all() + raw = pd.read_csv(mixed_csv).head(25) + for name, data in [("mixed", raw), ("iris", read_table("builtin:iris").head(25)), ("diabetes", read_table("builtin:diabetes").head(25))]: + mem = runner.best_model(name) + path = tmp_path / "out" / "models" / name / "best" + assert (path / "info.json").exists() and runner.best_model_paths[name] == path + disk = load_model(path, device="cpu") + assert disk.model_name == mem.model_name + np.testing.assert_array_equal(np.asarray(disk.predict(data), dtype=str), np.asarray(mem.predict(data), dtype=str)) + if disk.problem_type != "regression": + proba = disk.predict_proba(data) + assert list(proba.columns) == disk.classes and np.allclose(proba.sum(axis=1), 1.0) + assert set(disk.predict(data)) <= set(disk.classes) + scores = disk.evaluate(data) + assert disk.info["metric"] in scores + assert set(runner.best_model("mixed").predict(raw)) <= {"yes", "no"} # original labels, not 0/1 + + +def test_save_models_and_predict_cli(tmp_path, mixed_csv, capsys): + runner = AutoRunner( + datasets={"m": {"path": str(mixed_csv), "target": "label", "drop_columns": ["id", "split"]}}, + models=["xgb", "catboost"], + max_evals=1, + output_folder=tmp_path / "out", + save_models=True, + log_level="WARNING", + ) + runner.run() + models = tmp_path / "out" / "models" / "m" + assert {p.name for p in models.iterdir()} == {"xgb", "catboost", "best"} + rows = pd.read_csv(mixed_csv).drop(columns=["label"]).head(10) + rows.loc[0, "city"] = "paris" # unseen category + rows.to_csv(tmp_path / "new.csv", index=False) + out = tmp_path / "pred.csv" + assert main(["predict", str(models / "best"), str(tmp_path / "new.csv"), "-o", str(out)]) == 0 + pred = pd.read_csv(out) + assert len(pred) == 10 and {"prediction", "proba_no", "proba_yes", "city"} <= set(pred.columns) + assert main(["info", str(models / "catboost")]) == 0 + assert "Input columns" in capsys.readouterr().out + assert main(["predict", str(models / "best"), "builtin:iris"]) == 2 # wrong columns -> clean error + + +def test_no_saving_when_disabled(tmp_path): + runner = AutoRunner(datasets={"iris": {"path": "builtin:iris"}}, models=["xgb"], max_evals=1, output_folder=tmp_path / "o", save_best=False) + runner.run() + assert not (tmp_path / "o" / "models").exists() diff --git a/tests/test_web.py b/tests/test_web.py index 378f9e7..e56ff94 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -45,5 +45,14 @@ def test_job_lifecycle(client): assert info["status"]["state"] == "finished", client.get(f"/api/jobs/{job_id}/log").text assert info["results"][0]["status"] == "ok" assert client.get(f"/api/jobs/{job_id}/results.csv").status_code == 200 + best = info["best_models"] + assert len(best) == 1 and best[0]["dataset"] == "iris" and best[0]["model"] == "xgb" + z = client.get(f"/api/jobs/{job_id}/models/iris/download") + assert z.status_code == 200 and z.content[:2] == b"PK" + rows = "sepal length (cm),sepal width (cm),petal length (cm),petal width (cm)\n5.1,3.5,1.4,0.2\n6.7,3.0,5.2,2.3\n" + pred = client.post(f"/api/jobs/{job_id}/models/iris/predict", files={"file": ("rows.csv", rows.encode(), "text/csv")}) + assert pred.status_code == 200, pred.text + assert pred.text.splitlines()[0].startswith("sepal length") and "prediction" in pred.text.splitlines()[0] + assert client.get(f"/api/jobs/{job_id}/models/..%2F..%2Fx/download").status_code == 404 assert any(j["id"] == job_id for j in client.get("/api/jobs").json()["jobs"]) assert client.delete(f"/api/jobs/{job_id}").json()["ok"] From c199be5d3bd05f880b29b87ad65d334454346045 Mon Sep 17 00:00:00 2001 From: mdicio Date: Thu, 12 Nov 2026 01:28:56 +0100 Subject: [PATCH 03/15] models: auto with a time budget, machine profile, docs for 0.4.0 - autoplan: picks models (CPU/GPU priority order), max_evals and a water-filled per-model time limit that fit time_budget (default 15m), with reasons for every skipped model; no model may need more than half the budget; 8% slack for overrun - machine: cores, RAM, GPU and a ~0.5 s CPU benchmark (warm-up for powersave governors, cached 30 days) that scales the cost-curve priors until history exists - AutoRunner: models=None/'auto' is the default, time_budget, plan(); explicit max_evals/timeout_per_model win; a budget with explicit models sets the timeout - CLI: run/estimate accept a data file + --target, --budget, autodeep system - Web UI: Auto mode with budget and plan explanation, /api/plan - sklearn MLP prior re-measured (was ~15x optimistic above 10k rows) - README/CHANGELOG/examples; version 0.4.0 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013EC637XcrFPHFykZKx7pbm --- CHANGELOG.md | 16 ++ README.md | 66 ++++++-- autodeep/__init__.py | 2 +- autodeep/automl.py | 85 ++++++++-- autodeep/autoplan.py | 203 ++++++++++++++++++++++++ autodeep/cli.py | 65 ++++++-- autodeep/estimation.py | 43 +++-- autodeep/machine.py | 278 +++++++++++++++++++++++++++++++++ autodeep/web/server.py | 37 ++++- autodeep/web/static/index.html | 61 ++++++-- examples/experiment.yaml | 16 +- examples/quickstart.py | 13 +- pyproject.toml | 2 +- tests/conftest.py | 1 + tests/test_autoplan.py | 94 +++++++++++ tests/test_web.py | 2 + 16 files changed, 915 insertions(+), 69 deletions(-) create mode 100644 autodeep/autoplan.py create mode 100644 autodeep/machine.py create mode 100644 tests/test_autoplan.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 30e2055..0ce8d89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## 0.4.0 (unreleased): 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, PyTorch Tabular, RealMLP, TabM, the 1D-CNN and TabICL). +- **`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. + +### Changed +- `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. +- Saved PyTorch Tabular models no longer carry the training data or the Lightning trainer; the 1D-CNN and ResNet are saved as weights plus build arguments. +- The scikit-learn MLP's runtime prior was re-measured (it was ~15x too optimistic above 10,000 rows). + ## 0.3.0: modern tabular models ### New diff --git a/README.md b/README.md index 16c06a7..c82a9f2 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,12 @@ **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 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. 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. You can drive it from a browser, from the command line, or from Python. + +```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 +``` --- @@ -51,9 +56,10 @@ 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. @@ -63,9 +69,13 @@ Uploaded files and runs are stored in `./autodeep_workspace` (change it with `-- 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,9 +88,8 @@ 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 ``` @@ -94,13 +103,18 @@ runner = AutoRunner( "iris": {"path": "builtin:iris"}, "churn": {"path": "data/churn.csv", "target": "churned", "drop_columns": ["customer_id"]}, }, - models=["xgb", "catboost", "fttransformer"], - max_evals=20, + 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", ) +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 + analyzer = ResultsAnalyzer(runner.results_path) analyzer.view_performance(dataset_name="churn") analyzer.view_parameters(model_name="xgb") @@ -110,6 +124,27 @@ See [`examples/quickstart.py`](examples/quickstart.py) and the notebook [`exampl --- +## 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. @@ -162,6 +197,8 @@ Only `path` and `target` are required; everything else is inferred or has a defa | `danet` | DANet | PyTorch Tabular | | `resnet` | ResNet-18/34/50 on [IGTD](https://doi.org/10.1038/s41598-021-90923-y) images | tabular-as-image | +**Auto (default):** AutoDeep picks models in order of expected value for the device (on CPU: xgb, catboost, 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, catboost, mlp · `default` = fast + tabicl, realmlp, categoryembedding, fttransformer, gandalf · `modern` = tabicl, realmlp, tabm · `deep` = realmlp, tabm and all PyTorch 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 PyTorch Tabular architectures (which TabArena does not include). @@ -184,7 +221,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 +238,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. @@ -234,9 +272,9 @@ 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). +Code map: `autodeep/automl.py` (AutoRunner), `datasets.py` (dataset specs and inference), `dataloaders/` (data loading and IGTD), `preprocessing.py` (fitted, replayable preprocessing), `predictor.py` (saved models), `autoplan.py` + `machine.py` (automatic plan and machine profile), `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). -See [CHANGELOG.md](CHANGELOG.md) for what changed in 0.2.0. +See [CHANGELOG.md](CHANGELOG.md) for what changed in each release. ## License diff --git a/autodeep/__init__.py b/autodeep/__init__.py index aa86b72..4e10361 100644 --- a/autodeep/__init__.py +++ b/autodeep/__init__.py @@ -11,7 +11,7 @@ model.predict(new_rows) # later: autodeep.load_model("output/models/iris/best") """ -__version__ = "0.3.0" +__version__ = "0.4.0" from autodeep.datasets import BUILTIN_DATASETS, DatasetSpec, list_builtin_datasets # noqa: E402 from autodeep.registry import DEFAULT_MODELS, PRESETS, list_models # noqa: E402 diff --git a/autodeep/automl.py b/autodeep/automl.py index d4ff0e6..a948d8f 100755 --- a/autodeep/automl.py +++ b/autodeep/automl.py @@ -21,7 +21,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" @@ -90,16 +90,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 @@ -123,7 +131,7 @@ def __init__( datasets=None, models=None, execution_mode: str = "hyperopt", - max_evals: int = 25, + max_evals: Optional[int] = None, random_state: int = 42, model_config: Union[str, Path, Dict, None] = None, output_folder: Union[str, Path] = DEFAULT_OUTPUT_FOLDER, @@ -137,6 +145,7 @@ def __init__( fail_fast: bool = False, save_models: bool = False, save_best: bool = True, + time_budget: Union[None, float, str] = None, log_level: str = "INFO", ): if execution_mode != "hyperopt": @@ -145,11 +154,19 @@ def __init__( 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) @@ -222,11 +239,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() @@ -252,7 +303,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): @@ -275,6 +337,7 @@ 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: diff --git a/autodeep/autoplan.py b/autodeep/autoplan.py new file mode 100644 index 0000000..7c9ed77 --- /dev/null +++ b/autodeep/autoplan.py @@ -0,0 +1,203 @@ +"""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 typing import Dict, List, Optional, Union + +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, "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", "tabicl", "realmlp", "gandalf", "categoryembedding", "tabm", "fttransformer", "mlp"] +GPU_ORDER = ["tabicl", "xgb", "catboost", "realmlp", "tabm", "fttransformer", "gandalf", "categoryembedding", "mlp"] + + +def parse_duration(value: Union[None, int, float, str]) -> Optional[float]: + """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: Optional[List[float]] = 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: Optional[float] + 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: Optional[float] = None, + device: str = "cpu", + speed_factor: Optional[float] = None, + max_epochs: Optional[int] = None, + history: Optional[TimingHistory] = 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 62c8685..bb63b25 100644 --- a/autodeep/cli.py +++ b/autodeep/cli.py @@ -2,8 +2,9 @@ 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 @@ -61,6 +62,8 @@ def _confirm(prompt: str) -> bool: def _runner_from_args(args, **extra): + from pathlib import Path + from autodeep.automl import AutoRunner overrides = {} @@ -70,10 +73,33 @@ 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)) + print(f"\nEstimated total: {plan.human_total()} on {plan.device}") def cmd_run(args): @@ -81,8 +107,7 @@ 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() @@ -107,8 +132,21 @@ def _print_best_models(runner): 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 @@ -138,6 +176,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 @@ -224,8 +263,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") @@ -237,7 +278,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) @@ -248,6 +289,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") diff --git a/autodeep/estimation.py b/autodeep/estimation.py index f62cb08..4070ad8 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. @@ -40,7 +42,8 @@ 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), + # mlp re-measured 2026-11-12 at 16k rows (default search space, sgd trials ~30 s): steeper than linear + "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), @@ -218,6 +221,30 @@ def summary(self) -> Dict: } +def seconds_per_trial( + model: str, + shape: DatasetShape, + device: str = "cpu", + max_epochs: Optional[int] = None, + history: Optional[TimingHistory] = None, + speed_factor: Optional[float] = 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 @@ -235,22 +262,16 @@ def estimate_plan( max_epochs: Optional[int] = None, device: str = "cpu", history: Optional[TimingHistory] = None, + speed_factor: Optional[float] = 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 diff --git a/autodeep/machine.py b/autodeep/machine.py new file mode 100644 index 0000000..5e80c37 --- /dev/null +++ b/autodeep/machine.py @@ -0,0 +1,278 @@ +"""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 +from typing import Dict, Optional + +# 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: Optional[float] + ram_available_gb: Optional[float] + 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/web/server.py b/autodeep/web/server.py index 166f80e..01814e7 100644 --- a/autodeep/web/server.py +++ b/autodeep/web/server.py @@ -73,6 +73,13 @@ class JobIn(BaseModel): save_best: bool = True +class PlanIn(BaseModel): + datasets: List[DatasetIn] + time_budget: float = 15 * 60 # seconds, whole run + device: str = "auto" + max_epochs: Optional[int] = None + + class ProfileIn(BaseModel): path: str target: Optional[str] = None @@ -337,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: diff --git a/autodeep/web/static/index.html b/autodeep/web/static/index.html index 8d984a2..490b559 100644 --- a/autodeep/web/static/index.html +++ b/autodeep/web/static/index.html @@ -80,6 +80,11 @@ .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; } @@ -172,7 +177,17 @@

AutoDeep

2

Models

-
+
+
+
+ + + +
+
    +
    +
    +
    @@ -187,7 +202,7 @@

    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
    –
    @@ -226,7 +241,7 @@

    AutoDeep