tabsil 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tabsil/__init__.py +72 -0
- tabsil/hub/__init__.py +169 -0
- tabsil/inference/__init__.py +12 -0
- tabsil/inference/ensemble.py +455 -0
- tabsil/inference/preprocessing.py +249 -0
- tabsil/inference/subsample.py +94 -0
- tabsil/models/__init__.py +165 -0
- tabsil/models/bar_distribution.py +194 -0
- tabsil/models/column_row_transformer.py +1535 -0
- tabsil/models/quantile_distribution.py +86 -0
- tabsil/py.typed +0 -0
- tabsil/recipe.py +190 -0
- tabsil/utils.py +27 -0
- tabsil-0.1.0.dist-info/METADATA +179 -0
- tabsil-0.1.0.dist-info/RECORD +19 -0
- tabsil-0.1.0.dist-info/WHEEL +4 -0
- tabsil-0.1.0.dist-info/licenses/LICENSE +202 -0
- tabsil-0.1.0.dist-info/licenses/LICENSES/TabICL-BSD-3-Clause.txt +28 -0
- tabsil-0.1.0.dist-info/licenses/NOTICE +23 -0
tabsil/__init__.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""TabSil: a tabular foundation model (classification and regression in one model).
|
|
2
|
+
|
|
3
|
+
This package is inference: loading the weights and predicting. Modules on an axis are named after
|
|
4
|
+
the part they implement (generic nouns); TabSil's numbers and the combination of the parts are in
|
|
5
|
+
`recipe`.
|
|
6
|
+
|
|
7
|
+
- `models`: the model and its registry (column-row transformer, bar and quantile distributions,
|
|
8
|
+
checkpoint save and load)
|
|
9
|
+
- `inference`: sklearn-style inference (preprocessing member ensembles)
|
|
10
|
+
- `hub`: save to and load from the Hugging Face Hub format (`save_pretrained`, `from_pretrained`)
|
|
11
|
+
- `recipe`: TabSil's structure and inference defaults (`TabSilClassifier`, `TabSilRegressor`)
|
|
12
|
+
- `utils`: device and seed helpers
|
|
13
|
+
|
|
14
|
+
Training (priors, training loop, curriculum), evaluation (AMLB/CTR23, TabArena, BeyondArena,
|
|
15
|
+
uncertainty metrics) and the Hub upload scripts are in the `tabsil-train` package (`training/` in
|
|
16
|
+
the repository, imported as `tabsil_train`).
|
|
17
|
+
|
|
18
|
+
The inference entry points are importable from here and loaded on first use (so `import tabsil`
|
|
19
|
+
does not import the Hub and inference code).
|
|
20
|
+
|
|
21
|
+
from tabsil import TabSilClassifier
|
|
22
|
+
|
|
23
|
+
clf = TabSilClassifier("path/to/folder").fit(x_train, y_train) # a save_pretrained folder
|
|
24
|
+
# without a model: the default Hub repo (`tabsil.recipe.HUB_REPO`) at the tag `HUB_REVISION`
|
|
25
|
+
# (the v1 weights)
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from typing import TYPE_CHECKING
|
|
29
|
+
|
|
30
|
+
from tabsil.models.bar_distribution import (
|
|
31
|
+
BarDistribution,
|
|
32
|
+
FullSupportBarDistribution,
|
|
33
|
+
get_bucket_borders,
|
|
34
|
+
)
|
|
35
|
+
from tabsil.utils import get_device, set_seed
|
|
36
|
+
|
|
37
|
+
if TYPE_CHECKING:
|
|
38
|
+
from tabsil.hub import from_pretrained
|
|
39
|
+
from tabsil.recipe import TabSilClassifier, TabSilRegressor
|
|
40
|
+
|
|
41
|
+
# Names loaded on first use -> the module defining them
|
|
42
|
+
_LAZY = {
|
|
43
|
+
"from_pretrained": "tabsil.hub",
|
|
44
|
+
"TabSilClassifier": "tabsil.recipe",
|
|
45
|
+
"TabSilRegressor": "tabsil.recipe",
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def __getattr__(name: str):
|
|
50
|
+
if name in _LAZY:
|
|
51
|
+
import importlib
|
|
52
|
+
|
|
53
|
+
value = getattr(importlib.import_module(_LAZY[name]), name)
|
|
54
|
+
globals()[name] = value
|
|
55
|
+
return value
|
|
56
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def __dir__() -> list[str]:
|
|
60
|
+
return sorted(set(globals()) | set(_LAZY))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
__all__ = [
|
|
64
|
+
"get_device",
|
|
65
|
+
"set_seed",
|
|
66
|
+
"BarDistribution",
|
|
67
|
+
"FullSupportBarDistribution",
|
|
68
|
+
"get_bucket_borders",
|
|
69
|
+
"from_pretrained",
|
|
70
|
+
"TabSilClassifier",
|
|
71
|
+
"TabSilRegressor",
|
|
72
|
+
]
|
tabsil/hub/__init__.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Upload trained models (`tabsil.models` registry models) to the Hugging Face Hub and download
|
|
2
|
+
them (`tabsil.from_pretrained` is `from_pretrained` here).
|
|
3
|
+
|
|
4
|
+
On the Hub the weights are in `model.safetensors` and the config in `config.json`, so loading
|
|
5
|
+
needs no pickle.
|
|
6
|
+
The regression borders (the buckets the quantile outputs are turned into) go into
|
|
7
|
+
`model.safetensors` too, under the name `borders`.
|
|
8
|
+
|
|
9
|
+
from tabsil import from_pretrained
|
|
10
|
+
model, borders = from_pretrained("aiden-jeon/tabsil")
|
|
11
|
+
model, borders = from_pretrained("aiden-jeon/tabsil@stage2-10k")
|
|
12
|
+
|
|
13
|
+
For inference alone this function is not needed: `TabSilClassifier()`·`TabSilRegressor()`
|
|
14
|
+
(`tabsil.recipe`) download from the default Hub repo (`HUB_REPO` at the tag `HUB_REVISION`)
|
|
15
|
+
(`model_or_pretrained`).
|
|
16
|
+
|
|
17
|
+
`load_model` reads a Hub repo, a local `save_pretrained` folder or a checkpoint file the same way
|
|
18
|
+
(the evaluation and upload scripts use it through `tabsil_train.hub.load_model`, which also reads
|
|
19
|
+
MLflow run artifacts, `runs:/...`). Hub repos are written as `hf://owner/name`, so a mistyped local
|
|
20
|
+
path is not sent to the Hub. Intermediate checkpoints live on branches of the same repo
|
|
21
|
+
(`stage1-150k`, `stage2-10k`) and are loaded as `hf://owner/name@stage2-10k`.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import json
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
|
|
29
|
+
import torch
|
|
30
|
+
from huggingface_hub import hf_hub_download
|
|
31
|
+
from safetensors.torch import load_file, save_file
|
|
32
|
+
from torch import nn
|
|
33
|
+
|
|
34
|
+
from tabsil.models import (
|
|
35
|
+
DEFAULT_MODEL_TYPE,
|
|
36
|
+
build_model,
|
|
37
|
+
config_dict,
|
|
38
|
+
model_from_state,
|
|
39
|
+
state_config,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
WEIGHTS_NAME = "model.safetensors"
|
|
43
|
+
CONFIG_NAME = "config.json"
|
|
44
|
+
BORDERS_KEY = "borders"
|
|
45
|
+
HUB_PREFIX = "hf://"
|
|
46
|
+
# MLflow run artifacts, read by `tabsil_train.hub.load_model`
|
|
47
|
+
RUNS_PREFIX = "runs:/"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _is_local_path(repo_id_or_path: str | Path) -> bool:
|
|
51
|
+
"""Whether the argument is a local path rather than a Hub repo id (`owner/name`)."""
|
|
52
|
+
if isinstance(repo_id_or_path, Path) or Path(repo_id_or_path).exists():
|
|
53
|
+
return True
|
|
54
|
+
s = str(repo_id_or_path)
|
|
55
|
+
return s.count("/") != 1 or s.startswith((".", "/", "~")) or s.endswith((".pt", ".json"))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def save_pretrained(
|
|
59
|
+
model: nn.Module, borders: torch.Tensor | None, out_dir: str | Path, **extra
|
|
60
|
+
) -> Path:
|
|
61
|
+
"""Write `model.safetensors` and `config.json` to `out_dir`. `extra` adds keys to config.json
|
|
62
|
+
(`inference`: the inference settings for these weights)."""
|
|
63
|
+
out_dir = Path(out_dir)
|
|
64
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
65
|
+
tensors = {k: v.detach().cpu().contiguous() for k, v in model.state_dict().items()}
|
|
66
|
+
if borders is not None:
|
|
67
|
+
tensors[BORDERS_KEY] = borders.detach().cpu().contiguous()
|
|
68
|
+
save_file(tensors, out_dir / WEIGHTS_NAME)
|
|
69
|
+
# the model serves both tasks with one set of weights
|
|
70
|
+
config = {
|
|
71
|
+
"task": "multitask",
|
|
72
|
+
"model_type": model.model_type,
|
|
73
|
+
"model": config_dict(model.config),
|
|
74
|
+
**extra,
|
|
75
|
+
}
|
|
76
|
+
(out_dir / CONFIG_NAME).write_text(json.dumps(config, indent=2) + "\n")
|
|
77
|
+
return out_dir
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def from_pretrained(
|
|
81
|
+
repo_id_or_path: str | Path, revision: str | None = None
|
|
82
|
+
) -> tuple[nn.Module, torch.Tensor | None]:
|
|
83
|
+
"""Load (model, regression borders) from a Hub repo id or a local `save_pretrained` folder.
|
|
84
|
+
Pass an intermediate checkpoint branch as `revision` or as `owner/name@stage2-10k`."""
|
|
85
|
+
if _is_local_path(repo_id_or_path):
|
|
86
|
+
local = Path(repo_id_or_path).expanduser()
|
|
87
|
+
weights_path, config_path = local / WEIGHTS_NAME, local / CONFIG_NAME
|
|
88
|
+
else:
|
|
89
|
+
repo_id, _, at = str(repo_id_or_path).partition("@")
|
|
90
|
+
if at:
|
|
91
|
+
if revision is not None and revision != at:
|
|
92
|
+
raise ValueError(f"revision given twice: {repo_id_or_path}, {revision}")
|
|
93
|
+
revision = at
|
|
94
|
+
weights_path = hf_hub_download(repo_id, WEIGHTS_NAME, revision=revision)
|
|
95
|
+
config_path = hf_hub_download(repo_id, CONFIG_NAME, revision=revision)
|
|
96
|
+
config = json.loads(Path(config_path).read_text())
|
|
97
|
+
tensors = load_file(weights_path)
|
|
98
|
+
borders = tensors.pop(BORDERS_KEY, None)
|
|
99
|
+
model = build_model(config.get("model_type", DEFAULT_MODEL_TYPE), config["model"])
|
|
100
|
+
model.load_state_dict(tensors)
|
|
101
|
+
if "inference" in config:
|
|
102
|
+
# inference settings for these weights (number of members, member preprocessing kinds);
|
|
103
|
+
# the recipe's inference classes read them as defaults (`tabsil.recipe.default_inference`)
|
|
104
|
+
model.inference_config = config["inference"]
|
|
105
|
+
return model.eval(), borders
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def model_or_pretrained(
|
|
109
|
+
model: nn.Module | str | Path | None, default_repo: str, task: str
|
|
110
|
+
) -> tuple[nn.Module, torch.Tensor | None]:
|
|
111
|
+
"""Resolve the `model` an inference class receives into (model, regression borders).
|
|
112
|
+
|
|
113
|
+
A module gives (that module, None); a Hub repo id (`owner/name`, `owner/name@branch`) or a
|
|
114
|
+
local folder is loaded from there; None loads `default_repo` (the default Hub repo).
|
|
115
|
+
ValueError if the loaded model does not serve `task`."""
|
|
116
|
+
if isinstance(model, nn.Module):
|
|
117
|
+
return model, None
|
|
118
|
+
spec = default_repo if model is None else model
|
|
119
|
+
loaded = from_pretrained(spec)
|
|
120
|
+
if task not in (served := served_tasks(*loaded)):
|
|
121
|
+
raise ValueError(f"{spec} is a {'·'.join(served)} model (needs a {task} model)")
|
|
122
|
+
return loaded
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def served_tasks(model: nn.Module, borders: torch.Tensor | None) -> tuple[str, ...]:
|
|
126
|
+
"""The tasks the model serves (`model.tasks`; regression only with the regression borders)."""
|
|
127
|
+
return tuple(t for t in model.tasks if t != "regression" or borders is not None)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def load_model(
|
|
131
|
+
spec: str | Path, task: str, dst: str | Path | None = None, *, name: str | None = None
|
|
132
|
+
) -> tuple[nn.Module, torch.Tensor | None]:
|
|
133
|
+
"""Load a checkpoint onto the CPU. `spec` is one of:
|
|
134
|
+
|
|
135
|
+
- `hf://owner/name`: a Hub repo (uploaded with `save_pretrained`). Append `@<revision>` to
|
|
136
|
+
load a branch, tag or commit (e.g. `hf://owner/name@step-100k`)
|
|
137
|
+
- a local `save_pretrained` folder, or a file saved with `tabsil.models.save_checkpoint`
|
|
138
|
+
|
|
139
|
+
Checkpoints written during training (`checkpoints/step_XXXXXXX.pt`, `latest.pt`) build the
|
|
140
|
+
model from the model type and config stored in them. MLflow run artifacts (`runs:/...`) are
|
|
141
|
+
read by `tabsil_train.hub.load_model` (the `tabsil-train` package). Messages name the
|
|
142
|
+
checkpoint `name` (default: `spec`). `dst` (the download folder of MLflow artifacts) is not used
|
|
143
|
+
here; it is kept so that calls written for the earlier `load_model(spec, task, dst)` still work.
|
|
144
|
+
"""
|
|
145
|
+
spec = str(spec)
|
|
146
|
+
name = spec if name is None else name
|
|
147
|
+
if spec.startswith(HUB_PREFIX):
|
|
148
|
+
repo_id, _, revision = spec.removeprefix(HUB_PREFIX).partition("@")
|
|
149
|
+
return _check_task(from_pretrained(repo_id, revision=revision or None), task, name)
|
|
150
|
+
if spec.startswith(RUNS_PREFIX):
|
|
151
|
+
raise SystemExit(
|
|
152
|
+
f"{name} is an MLflow run artifact: load it with `tabsil_train.hub.load_model`"
|
|
153
|
+
" (the tabsil-train package)."
|
|
154
|
+
)
|
|
155
|
+
path = Path(spec)
|
|
156
|
+
if not path.exists():
|
|
157
|
+
raise SystemExit(f"{name} does not exist (pass a Hub repo as {HUB_PREFIX}owner/name).")
|
|
158
|
+
if path.is_dir():
|
|
159
|
+
return _check_task(from_pretrained(path), task, name)
|
|
160
|
+
state = torch.load(path, map_location="cpu", weights_only=True)
|
|
161
|
+
if state_config(state) is None:
|
|
162
|
+
raise SystemExit(f"{name} has no model config (saved before checkpoints recorded one).")
|
|
163
|
+
return _check_task(model_from_state(state), task, name)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _check_task(loaded: tuple[nn.Module, torch.Tensor | None], task: str, spec: str):
|
|
167
|
+
if task not in (served := served_tasks(*loaded)):
|
|
168
|
+
raise SystemExit(f"{spec} is a {'·'.join(served)} model (needs a {task} model).")
|
|
169
|
+
return loaded
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Inference: use a trained model in sklearn style (preprocessing members, ensembles).
|
|
2
|
+
|
|
3
|
+
- `preprocessing`: preprocessing of one ensemble member (outlier clipping, one-hot, column
|
|
4
|
+
subsets)
|
|
5
|
+
- `ensemble`: preprocessing-member ensembles `EnsembleClassifier` and `EnsembleRegressor`. They
|
|
6
|
+
work with any model class that has `forward(x, y_train, task)` (`tabsil.recipe.TabSilClassifier`,
|
|
7
|
+
`TabSilRegressor`)
|
|
8
|
+
- `subsample`: `SubsampledEstimator`, which reduces the rows passed to fit to N (class-stratified
|
|
9
|
+
for classification; for context-length experiments)
|
|
10
|
+
|
|
11
|
+
The classes with TabSil's default inference settings are in `tabsil.recipe`.
|
|
12
|
+
"""
|