#foundation-model #python #tabular #learning #port #rlx #safetensors #checkpoint #hugging-face

tabicl

TabICL — a tabular in-context learning foundation model (Rust port). Top-level prelude crate.

1 stable release

Uses new Rust 2024

2.1.1 May 29, 2026

#1496 in Artificial intelligence

BSD-3-Clause

430KB
9K SLoC

tabicl-rs

A Rust port of TabICL, the state-of-the-art tabular in-context learning foundation model, built on rlx.

Status: numerically verified against PyTorch on real HuggingFace weights. Production checkpoint loads, runs forward, and matches Python output within fp32 ULP precision (~5e-6 max diff) across the full 27.5M-parameter, 18-transformer-block model.

        ┌─────────────────────────────────────────────────────┐
        │  tabicl-rs ↔ Python tabicl: 5.2e-6 max diff          │
        │  on HuggingFace tabicl-classifier-v2 (391 params).   │
        │  Verified on Apple M-series and NVIDIA RTX 4090.     │
        └─────────────────────────────────────────────────────┘

Quick start

use tabicl::{TabICLClassifier, TabICLRegressor};
use tabicl_model::tabicl::TabICLConfig;

let mut clf = TabICLClassifier::new();
clf.fit(x_train.view(), &y_train)?;
clf.load_checkpoint(TabICLConfig::default(), "weights.safetensors")?;
let predictions = clf.predict(x_test.view())?;

To load a real HuggingFace checkpoint, convert it once via the included script:

python3 scripts/convert_python_checkpoint.py \
    ~/.cache/huggingface/hub/models--jingang--TabICL/.../tabicl-classifier-v2-20260212.ckpt \
    /path/to/weights.safetensors

Crates: inference core vs optional

The workspace has 11 internal crates, but only five are published to crates.io for inference. Everything else stays in the repo with publish = false (training, forecasting, SHAP, CLI, Python bindings).

Published for inference (depend on these)

Crate Role
tabicl Prelude — use tabicl::TabICLClassifier
tabicl-model Transformer + safetensors loader + rlx backends
tabicl-sklearn TabICLClassifier / TabICLRegressor API
tabicl-preprocess Scalers, pipelines, label encoding
tabicl-quantile Regression quantile head

Typical Cargo.toml for inference:

[dependencies]
tabicl = "2.1"
# tabicl pulls tabicl-model, tabicl-sklearn, tabicl-preprocess, tabicl-quantile

Enable GPU backends on tabicl-model via features (metal, mlx, cuda, gpu).

Workspace-only (not on crates.io)

Crate Why it stays internal
tabicl-prior Synthetic pretraining data
tabicl-train Pretraining loop demo
tabicl-finetune Fine-tuning experiments
tabicl-forecast Time-series wrapper (Apache-2.0)
tabicl-unsupervised Density / outlier scoring
tabicl-shap Feature attributions
tabicl-cli CSV CLI binary
pytabicl Python bindings (maturin)

When building from this repository, depend on the workspace-only crates directly (e.g. tabicl-finetune, tabicl-shap). The crates.io tabicl package is inference-only (classifier/regressor + preprocess + model).

Architecture

Each published crate mirrors one Python sub-package. The prelude re-exports the user-facing surface so use tabicl::TabICLClassifier; works out of the box.

Crate Mirrors tabicl. Lines What it does
tabicl-model _model/ 4.2k Transformer: ColEmbedding (ISAB), RowInteraction, ICLearning, KV cache, RoPE, SSMax (incl. QASSMax-MLP), state-dict loader, manual-backward autodiff, rlx multi-backend dispatch.
tabicl-quantile _model/quantile_dist.py 0.7k Quantile-distribution head with spline body + exponential/GPD tails, PAVA isotonic regression, CRPS + pinball losses.
tabicl-preprocess _sklearn/preprocessing.py 1.5k CustomStandardScaler, OutlierRemover, QuantileTransformer, PowerTransformer (Yeo-Johnson), RobustScaler, RTDLQuantileTransformer, Pipeline (4 modes), LabelEncoder, Shuffler (Latin/shift/random), sklearn_utils, NaN imputation.
tabicl-sklearn _sklearn/{classifier,regressor}.py 1.1k scikit-learn-style TabICLClassifier / TabICLRegressor with fit/predict/predict_proba, ensembling, hierarchical many-class decoder, NaN handling, checkpoint loading.
tabicl-prior prior/ 1.5k MLPSCM + TreeSCM synthetic data generators (decision_tree / extra_trees / random_forest / xgboost-via-GBM backends), PriorDataset batched loader, activations, hp_sampling, reg2cls.
tabicl-finetune _finetune/ 0.8k Head-only fine-tuning with closed-form gradients, full-backbone MlpBlock::sgd_step, rlx-autodiff demo.
tabicl-train train/ 0.2k Pretraining loop using rlx-autodiff (verified to reduce loss).
tabicl-forecast forecast/ 0.6k TimeSeriesDataFrame, calendar/seasonality transforms, lag-feature forecaster.
tabicl-unsupervised _unsupervised/ 0.5k TabICLUnsupervised with both Gaussian-KDE and per-column TabICL-conditional density paths.
tabicl-shap shap/ 0.4k Kernel-SHAP + permutation-importance feature attributions.
tabicl top-level tabicl prelude 0.1k Re-exports the user-facing surface.

Total: ~17 kLOC of Rust + tests, validated against ~24 kLOC of Python.

Cross-stack parity verification

Six numerical parity tests confirm Rust output matches Python TabICL within fp32 noise:

Test Config Max diff
python_checkpoint_parity Simplest (no target-aware / grouping / SSMax) 7.5e-8
python_checkpoint_parity_default Target-aware + feature_group="same" 4.5e-8
python_checkpoint_parity_regression Regression head (5 quantiles) 1.5e-8
python_checkpoint_parity_ssmax SSMax qassmax-mlp-elementwise 6.0e-8
full_config_small_parity All production features at depth=1 2.7e-7
hf_checkpoint_parity Real HF production checkpoint (27.5M params) 5.2e-6

Plus 10 layer-level Python-formula tests (LayerNorm, RoPE, attention, GELU, softmax, cross-entropy, etc.) confirming each primitive matches PyTorch bit-for-bit.

Plus 2 gradient-parity tests: linear3d_backward and layer_norm_backward match PyTorch autograd at ~5e-7.

Multi-backend support

tabicl-model builds against all rlx backends behind feature gates. The attention kernel — the dominant compute — is benchmarked and parity-tested across every backend.

Backend Feature flag Status Apple M-series perf RTX 4090 perf
CPU (default) ✅ reference 850 µs/iter 912 µs/iter
MLX mlx ✅ verified 325 µs (2.6×) n/a
Metal metal ✅ verified 1972 µs n/a
WGPU gpu ✅ verified 6000 µs 3832 µs
CUDA cuda ✅ verified on RTX 4090 n/a 477 µs (1.9×)
ROCm rocm compiles (no AMD hardware tested) —

Cross-backend numerical parity:

metal vs cpu: max_diff = 1.8e-7
mlx   vs cpu: max_diff = 1.2e-7
wgpu  vs cpu: max_diff = 2.4e-7
cuda  vs cpu: max_diff = 1.8e-7

All within 1 ULP of fp32 — every backend produces bit-equivalent output.

Run the bench yourself:

# Apple Silicon
cargo bench -p tabicl-model --bench backends --features=metal,mlx,gpu

# NVIDIA
cargo bench -p tabicl-model --bench backends --features=cuda

Model weights

The tabicl crate on crates.io does not ship checkpoints. Download weights.safetensors from HuggingFace (tabicl-classifier-v2-rs, tabicl-regressor-v2-rs) or convert a Python .ckpt with scripts/convert_python_checkpoint.py. Legacy .json + .bin checkpoints still load but are deprecated.

Building

rlx-* dependencies are pulled from crates.io (no local checkout required).

# Default (CPU only)
cargo build --workspace

# With backends
cargo build --workspace --features=metal,mlx     # macOS
cargo build --workspace --features=cuda,gpu      # NVIDIA + cross-platform

Testing

cargo test --workspace                # 318 tests, runs in ~3 s
cargo test --workspace --release      # release-mode (slightly faster)

To regenerate cross-stack parity fixtures (requires Python tabicl):

python3 scripts/generate_parity_fixtures.py   # creates /tmp/tabicl_*_parity/*
cargo test --workspace --test python_checkpoint_parity

Loading a HuggingFace checkpoint

# 1. Download + convert (requires Python + huggingface_hub + torch)
python3 scripts/convert_python_checkpoint.py \
    ~/.cache/huggingface/hub/models--jingang--TabICL/.../tabicl-classifier-v2-20260212.ckpt \
    out.json
// 2. Load in Rust
use tabicl_model::tabicl::TabICLConfig;
use tabicl::TabICLClassifier;

let mut clf = TabICLClassifier::new();
clf.fit(x_train.view(), &y_train)?;
clf.load_checkpoint(TabICLConfig::default(), "weights.safetensors")?;
let preds = clf.predict(x_test.view())?;

The conversion script writes standard safetensors; the loader accepts .safetensors (preferred) or legacy .json + .bin. 391 parameters from the production checkpoint round-trip through Rust with bit-identical forward output.

Training and fine-tuning

Three paths are wired:

  1. Head-only fine-tuning (closed-form gradients, fastest):

    use tabicl_finetune::{FinetunedTabICLClassifier, FineTuneConfig};
    let mut clf = FinetunedTabICLClassifier::new(FineTuneConfig::default());
    clf.fit(features.view(), labels.view())?;
    
  2. Manual full-backbone backward via tabicl_model::autodiff:

    use tabicl_model::autodiff::MlpBlock;
    let mut block = MlpBlock::new(in_dim, hidden, out_dim);
    let loss = block.sgd_step(x.view(), target.view(), lr);  // updates all 6 param groups
    
  3. rlx-autodiff driven pretraining via tabicl-train::run:

    use tabicl_train::{run, TrainConfig};
    let stats = run(&TrainConfig::default())?;  // SGD with verified loss decrease
    

Each train_step uses rlx_autodiff::grad_with_loss and verified to match PyTorch autograd gradients at ~5e-7.

Inference example

use ndarray::array;
use tabicl_model::tabicl::TabICLConfig;
use tabicl::TabICLClassifier;

let x_train = array![[0.0_f32, 1.0], [1.0, 2.0], [2.0, 3.0], [3.0, 4.0]];
let y_train = ["a", "b", "a", "b"];

let mut clf = TabICLClassifier::new();
clf.fit(x_train.view(), &y_train)?;
clf.init_model(TabICLConfig::default());  // or .load_checkpoint(..., "path.json")?

let x_test = array![[0.5_f32, 1.5], [2.5, 3.5]];
let preds = clf.predict(x_test.view())?;       // ["a", "b"]
let probs = clf.predict_proba(x_test.view())?; // softmax over classes

Examples

Inference (published tabicl crate) — tabicl/examples/:

Example Command What it shows
classifier_basic cargo run -p tabicl --example classifier_basic --release TabICLClassifier::{new, fit, init_model, predict, predict_proba}
regressor_basic cargo run -p tabicl --example regressor_basic --release TabICLRegressor with Mean / Median / RawQuantiles
load_checkpoint cargo run -p tabicl --example load_checkpoint --release -- path/to/weights.safetensors load_checkpoint from .safetensors

Workspace-only crates (build from the repo; not on crates.io):

Example Crate Command
backend_dispatch tabicl-model cargo run -p tabicl-model --example backend_dispatch --release
forecast_timeseries tabicl-forecast cargo run -p tabicl-forecast --example forecast_timeseries --release
unsupervised_density tabicl-unsupervised cargo run -p tabicl-unsupervised --example unsupervised_density --release
finetune_head tabicl-finetune cargo run -p tabicl-finetune --example finetune_head --release
shap_explanation tabicl-shap cargo run -p tabicl-shap --example shap_explanation --release

load_checkpoint takes an optional path and falls back to zero-init weights.

Command-line interface

The tabicl-cli crate ships a tabicl binary for one-shot predictions from CSV files. Build with cargo build -p tabicl-cli --release; the binary lands in target/release/tabicl:

# classification — last column of train.csv is the label
tabicl predict-classify --train train.csv --test test.csv [--ckpt weights.safetensors]

# regression — last column is a numeric target
tabicl predict-regress --train train.csv --test test.csv [--ckpt weights.safetensors]

Predictions are written to stdout, one per line. Without --ckpt, weights are zero-init (useful only for testing the plumbing).

Python bindings

pytabicl/ is a pyo3 + maturin extension module. Build with:

pip install maturin numpy
cd pytabicl
maturin develop --release

Then in Python:

import numpy as np
from pytabicl import TabICLClassifier

X = np.random.randn(100, 8).astype("float32")
y = ["a" if x[0] > 0 else "b" for x in X]
clf = TabICLClassifier()
clf.fit(X, y)
clf.load_checkpoint("/path/to/weights.safetensors")  # from HuggingFace, not in the crate
print(clf.predict(X[:5]))

The bindings use abi3-py39, so a single wheel works on Python 3.9+.

Inference pipeline (what forward actually does)

  1. ColEmbedding — pad CLS slots, group features (same/valid mode), project per-column via SkippableLinear, optionally add target-aware y-embedding, run SetTransformer (3 ISAB blocks with QASSMax-MLP SSMax) with train_size-masked inducing-point attention.
  2. RowInteraction — overwrite CLS slots with learnable tokens, encode each row through 3 MAB blocks with RoPE, slice CLS outputs, apply final LayerNorm.
  3. ICLearning — embed y_train (OneHotAndLinear or Linear), add into first train_size positions of row representations, run 12-MAB transformer with QASSMax SSMax + train-size-sliced cross-attention, final LN + 2-layer GELU decoder MLP.
  4. Output decoding — classification: softmax over class logits with temperature; regression: quantile-distribution mean() over spline body + exponential/GPD tails.

Every step has a Rust → PyTorch parity test in tests/.

Performance

On NVIDIA RTX 4090 vs CPU (production attention, 64×64):

        ┌─────────┬──────────┬──────────┐
        │ backend │ per-iter │ speedup  │
        ├─────────┼──────────┼──────────┤
        │ CUDA    │   477 µs │   1.9×   │
        │ CPU     │   912 µs │   1.0×   │
        │ WGPU    │  3832 µs │   0.24×  │
        └─────────┴──────────┴──────────┘

For long sequences (128×128), CUDA's advantage grows to 5.8× as the fused attention kernel (rlx-cuda/src/kernels/attention.cu) amortizes launch overhead.

On Apple Silicon, MLX is fastest (325 µs) at production shape — its Compiled lazy-graph mode reuses kernels across calls.

Limitations and notes

  • Per-element fp32 ULP gap vs PyTorch is ~5e-6 on the full HF checkpoint. This is f32 numerical drift through 18 transformer blocks; exact bit-equivalence would require either f64 throughout or matching PyTorch's BLAS accumulation order. The 5e-6 diff does not affect classification accuracy (argmax stable) and is below the noise floor of any practical prediction.
  • Training loops are simple SGD. Python tabicl ships a full cosine-warmup + gradient-checkpointing + W&B + distributed setup. The rlx-autodiff demo + manual-backward primitives compose into a working training loop, but tabicl-rs's train::run is intentionally small for clarity.
  • TreeSCM xgboost backend is a pure-Rust gradient-boosted regressor (tabicl-prior::gbm), not real XGBoost. Output distributions differ but synthesizing tabular data from random Gaussian targets is the intent.
  • Forecasting is a lag-feature + rolling-forward approach. Python's forecaster has a deeper pandas/GluonTS integration we don't reproduce.
  • Session::compile gradient path requires a d_output input seeded with [1.0] for scalar loss — the rlx-autodiff convention. Documented in tabicl_finetune::head_grad_via_rlx.

File layout

tabicl-rs/
├── tabicl/                 # prelude crate
├── tabicl-model/           # transformer + autodiff + multi-backend
│   ├── src/
│   │   ├── attention.rs    # MHA forward, SSMax integration
│   │   ├── autodiff.rs     # manual backward + MlpBlock
│   │   ├── embedding.rs    # ColEmbedding + feature grouping + target-aware
│   │   ├── encoders.rs     # MAB + ISAB + SetTransformer + EncoderStack
│   │   ├── gpu_attention.rs # rlx graph dispatch
│   │   ├── inference.rs    # InferenceManager batching
│   │   ├── interaction.rs  # RowInteraction
│   │   ├── kv_cache.rs     # KV cache types
│   │   ├── layers.rs       # Linear, LayerNorm, OneHotAndLinear, SkippableLinear
│   │   ├── learning.rs     # ICLearning
│   │   ├── rope.rs         # RoPE (interleaved + non-interleaved)
│   │   ├── ssmax.rs        # SSMax variants + QASSMax-MLP
│   │   ├── state_dict.rs   # safetensors + legacy loader
│   │   └── tabicl.rs       # top-level model
│   ├── benches/backends.rs # multi-backend bench harness
│   └── tests/              # 8 cross-stack + parity test files
├── tabicl-quantile/        # quantile head
├── tabicl-preprocess/      # all preprocessing
├── tabicl-sklearn/         # user-facing API
├── tabicl-prior/           # synthetic data
├── tabicl-finetune/        # fine-tuning
├── tabicl-train/           # pretraining
├── tabicl-forecast/        # time-series
├── tabicl-unsupervised/    # density / generation
├── tabicl-shap/            # SHAP attributions
├── tabicl-cli/             # `tabicl` command-line binary
├── pytabicl/               # pyo3 Python bindings (built via maturin)
├── data/                   # HF publish staging (model cards only; weights not in git/crates.io)
│   ├── tabicl-classifier-v2/   # → MIT-RLX/tabicl-classifier-v2-rs on HuggingFace
│   └── tabicl-regressor-v2/    # → MIT-RLX/tabicl-regressor-v2-rs on HuggingFace
├── scripts/
│   └── convert_python_checkpoint.py
├── .github/workflows/ci.yml
├── deny.toml               # cargo-deny policy
└── README.md

API stability

tabicl-rs tracks the upstream Python tabicl major+minor version (currently 2.1). Within a 2.1.x line we follow SemVer:

  • Public surface — everything re-exported from the prelude (tabicl::*) and every pub item not marked #[doc(hidden)]. Breaking changes here require a major-version bump.
  • #[non_exhaustive] enums — FeatureShuffle, OutputType, Activation, ColFeatureGroup, Offload, NormalizationMethod, OutputDistribution, ShapMethod, MaskingStrategy, PointEstimate, SsmaxKind, TailMode, PriorKind, TreeModelKind, ActivationKind, ShuffleMethod. New variants can be added in minor releases.
  • Numerical outputs — bit-exact reproducibility is not guaranteed across point releases (kernel fusion, summation order, BLAS choice can shift the last few ULP). Cross-stack parity to PyTorch is verified at ≤ 1e-5 max abs diff on fp32 logits and is regression-tested in CI.
  • Internal modules named _* (matching the Python _model, _sklearn, _unsupervised convention) and items marked #[doc(hidden)] carry no stability guarantee.

The MSRV is Rust 1.87 and is verified in CI; bumps will be called out in CHANGELOG.md.

License

Matches the upstream Python TabICL dual licensing (see LICENSE):

  • BSD-3-Clause — main code (everything except tabicl-forecast). Tracks the BSD-3-Clause license of soda-inria/tabicl.
  • Apache-2.0 — tabicl-forecast crate. Mirrors the upstream src/tabicl/forecast/ directory, which is derived from TabPFN-TS.

Citation

If you use this Rust port in research, please cite the original TabICL paper:

@inproceedings{qu2025tabicl,
  title={TabICL: A Tabular Foundation Model for In-Context Learning on Large Data},
  author={Qu, Jingang and Holzmüller, David and Le Morvan, Marine and Varoquaux, Gaël},
  booktitle={ICML 2025},
  year={2025}
}

And the rlx framework if you use the backend layer:

@software{rlx,
  title={RLX: ML compiler + runtime for transformer inference and training},
  author={Hauptmann, Eugene and Kosmyna, Nataliya},
  year={2026},
  url={https://github.com/MIT-RLX/rlx}
}

Dependencies

~24MB
~382K SLoC