"""TabPFNClassifier class. !!! example ```python import sklearn.datasets from tabpfn import TabPFNClassifier model = TabPFNClassifier() X, y = sklearn.datasets.load_iris(return_X_y=True) model.fit(X, y) predictions = model.predict(X) ``` """ # Copyright (c) Prior Labs GmbH 2026. from __future__ import annotations import copy import dataclasses import logging import warnings from collections.abc import Callable, Sequence from pathlib import Path from typing import TYPE_CHECKING, Annotated, Any, Literal from typing_extensions import Self, deprecated import numpy as np import torch from sklearn import config_context from sklearn.base import BaseEstimator, ClassifierMixin, check_is_fitted, clone from tqdm.auto import tqdm from tabpfn.base import ( GROUPED_PRESET, ModelSpecs, clean_predict_input, create_inference_engine, determine_precision, estimator_to_device, expand_dates_and_text, get_embeddings, initialize_model_variables_helper, reject_categoricals_for_differentiable_input, resolve_categorical_features_indices, resolve_presets, resolved_average_before_softmax, resolved_n_estimators, resolved_softmax_temperature, transform_columns, validate_additional_model_input, validate_and_clean_fit_input, ) from tabpfn.constants import ( PROBABILITY_EPSILON_ROUND_ZERO, SKLEARN_16_DECIMAL_PRECISION, ModelVersion, XType, YType, ) from tabpfn.downsample_correction import ( apply_class_weights, context_class_prior, downsample_class_weights, ) from tabpfn.errors import TabPFNValidationError, handle_oom_errors from tabpfn.inference import ( InferenceEngine, InferenceEngineBatchedNoPreprocessing, InferenceEngineCachePreprocessing, _maybe_run_gpu_preprocessing, ) from tabpfn.inference_tuning import ( ClassifierEvalMetrics, ClassifierTuningConfig, find_optimal_classification_thresholds, find_optimal_temperature, get_tuning_split_indices, resolve_tuning_config, ) from tabpfn.model_loading import ( ModelSource, load_fitted_tabpfn_model, prepend_cache_path, save_fitted_tabpfn_model, ) from tabpfn.preprocessing import ( ClassifierEnsembleConfig, EnsembleConfig, FeatureSubsamplingMethod, PreprocessorConfig, SampleSubsamplingMethod, generate_classification_ensemble_configs, ) from tabpfn.preprocessing.datamodel import Feature, FeatureModality, FeatureSchema from tabpfn.preprocessing.datetimes import DateTransformer from tabpfn.preprocessing.ensemble import ( TabPFNEnsemblePreprocessor, scale_n_estimators_for_feature_coverage, ) from tabpfn.preprocessing.group_aggregates import GroupAggregator, pool_rows from tabpfn.preprocessing.group_ids import ( GroupIdEncoder, reject_group_col, ) from tabpfn.preprocessing.label_encoder import TabPFNLabelEncoder from tabpfn.preprocessing.row_weights import ( classes_with_zero_weight, resolve_sample_weight_mode, tuning_metric_row_weights, validate_row_weights, ) from tabpfn.preprocessing.text import TextTransformer from tabpfn.utils import ( DevicesSpecification, as_tensor_to_read, balance_probas_by_class_counts, convert_batch_of_cat_ix_to_schema, infer_random_state, ) from tabpfn.validation import ( check_input_shape_matches, extract_input_shape, validate_dataset_size, validate_num_classes, ) logger = logging.getLogger(__name__) if TYPE_CHECKING: import numpy.typing as npt from torch.types import _dtype from tabpfn.architectures.interface import ( Architecture, ArchitectureConfig, PerformanceOptions, ) from tabpfn.constants import MemorySavingMode from tabpfn.inference_config import InferenceConfig from tabpfn.preprocessing.clean import ColumnRangeEncoders from tabpfn.preprocessing.row_weights import SampleWeightMode from tabpfn.preprocessing.source_decisions import SourceDecisions from tabpfn.preprocessing.steps.preprocessing_helpers import ( OrderPreservingColumnTransformer, ) try: from sklearn.base import Tags except ImportError: Tags = Any DEFAULT_CLASSIFICATION_EVAL_METRIC = ClassifierEvalMetrics.ACCURACY CLASSIFICATION_PRESETS: dict[str, dict[str, Any]] = {"grouped": GROUPED_PRESET} """The named bundles of `inference_config` values that `presets` selects.""" class TabPFNClassifier(ClassifierMixin, BaseEstimator): """TabPFN classifier with a scikit-learn-compatible interface. Usage guidance: - TabPFN-3 and later versions support up to 1,000,000 rows, subject to feature count, checkpoint limits, and memory. - For large datasets or limited memory, use per-estimator subsampling, e.g. ``inference_config={"SUBSAMPLE_SAMPLES": 50_000}``. - Pass raw pandas DataFrames to ``fit`` and ``predict``. Categorical strings/categories and missing feature values are handled automatically; no manual integer/one-hot encoding, imputation, scaling, or outlier removal is needed. """ configs_: list[ArchitectureConfig] """The configurations of the loaded models to be used for inference. The concrete type of these configs is defined by the architectures in use and should be inspected at runtime, but they will be subclasses of ArchitectureConfig. """ models_: list[Architecture] """The loaded models to be used for inference. The models can be different PyTorch modules, but will be subclasses of Architecture. """ inference_config_: InferenceConfig """Additional configuration of the interface for expert users.""" devices_: tuple[torch.device, ...] """The devices determined to be used. The devices are determined based on the `device` argument to the constructor, and the devices available on the system. See the constructor documentation for details. """ feature_names_in_: npt.NDArray[Any] """The feature names of the input data. May not be set if the input data does not have feature names, such as with a numpy array. """ n_features_in_: int """The number of features in the input data used during `fit()`.""" n_train_samples_: int """The number of training samples used during `fit()`.""" inferred_feature_schema_: FeatureSchema """The inferred feature schema. This contains the feature modalities per column, using heuristics and user-provided indices for categorical features.""" classes_: npt.NDArray[Any] """The unique classes found in the target data during `fit()`.""" n_classes_: int """The number of classes found in the target data during `fit()`.""" class_counts_: npt.NDArray[Any] """The number of classes per class found in the target data during `fit()`.""" n_outputs_: Literal[1] """The number of outputs the model has. Only 1 for now""" use_autocast_: bool """Whether torch's autocast should be used.""" forced_inference_dtype_: _dtype | None """The forced inference dtype for the model based on `inference_precision`.""" executor_: InferenceEngine """The inference engine used to make predictions.""" label_encoder_: TabPFNLabelEncoder """The label encoder used to encode the target variable.""" ordinal_encoder_: OrderPreservingColumnTransformer | ColumnRangeEncoders """The fitted cleaning that makes categorical data numeric. `clean_data_transform` applies it to predict input.""" date_transformer_: DateTransformer """The transformer that converted every temporal column before validation.""" text_transformer_: TextTransformer """The transformer that expanded every text column before validation.""" group_encoder_: GroupIdEncoder """The encoder that replaced the `group_col` columns with one categorical feature, holding the key-to-code mapping fitted on the training rows.""" group_aggregator_: GroupAggregator """Appends the per-group aggregates (`APPEND_GROUP_AGGREGATES`) and decides whether predictions are pooled per group (`POOL_GROUP_PREDICTIONS`).""" group_feature_index_: int | None """Where the encoded group feature sits in the cleaned input, or `None` without `group_col`.""" categorical_features_indices_: list[int] | None """Declared categorical column positions after date/text expansion, including columns declared through pandas `category` dtype. Expanded source columns are removed and their generated features appended, so these positions can differ from those in the original fit input.""" tuned_classification_thresholds_: npt.NDArray[Any] | None """The tuned classification thresholds for each class or None if no tuning is specified.""" eval_metric_: ClassifierEvalMetrics """The validated evaluation metric to optimize for during prediction.""" softmax_temperature_: float """The softmax temperature used for prediction. This is the resolved `softmax_temperature`, i.e. the one the checkpoint declares when no temperature tuning is done.""" average_before_softmax_: bool """The resolved `average_before_softmax`, i.e. the one the checkpoint declares unless it was overridden.""" ensemble_configs_: list[ClassifierEnsembleConfig] """The ensemble configurations used during fit. Stored for reuse in prompt tuning.""" downsample_correction_weights_: np.ndarray | None """Per-class weights that undo the prior shift of `SAMPLE_SUBSAMPLING_METHOD="majority_downsample"`, applied to the averaged probabilities. `None` when that sampler is not in effect.""" def __init__( # noqa: PLR0913 self, *, n_estimators: int | Literal["auto"] = "auto", auto_scale_n_estimators: bool = True, categorical_features_indices: Sequence[int] | None = None, group_col: str | list[str] | None = None, softmax_temperature: float | Literal["auto"] = "auto", balance_probabilities: bool = False, average_before_softmax: bool | Literal["auto"] = "auto", model_path: str | Path | list[str] | list[Path] | Literal["auto"] | ModelSpecs | list[ModelSpecs] = "auto", device: DevicesSpecification = "auto", ignore_pretraining_limits: bool = False, inference_precision: _dtype | Literal["autocast", "auto"] = "auto", fit_mode: Literal[ "low_memory", "fit_preprocessors", "fit_with_cache", "batched", ] = "fit_preprocessors", memory_saving_mode: MemorySavingMode = "auto", enable_torch_compile: bool = False, keep_cache_on_device: bool = True, kv_cache_precision: Literal["auto", "int8", "fp8", "adaptive"] | None = None, kv_cache_on_host: bool | None = None, random_state: int | np.random.RandomState | np.random.Generator | None = 0, n_jobs: Annotated[int | None, deprecated("Use n_preprocessing_jobs")] = None, n_preprocessing_jobs: int = 1, inference_config: dict | InferenceConfig | None = None, presets: str | Sequence[str] | None = None, differentiable_input: bool = False, eval_metric: str | ClassifierEvalMetrics | None = None, tuning_config: dict | ClassifierTuningConfig | None = None, show_progress_bar: bool = False, ) -> None: """Construct a TabPFN classifier. This constructs a classifier using the latest model and settings. If you would like to use a previous model version, use `create_default_for_version()` instead. You can also use `model_path` to specify a particular model. Args: n_estimators: The number of estimators in the TabPFN ensemble. We aggregate the predictions of `n_estimators`-many forward passes of TabPFN. Each forward pass has (slightly) different input data. Think of this as an ensemble of `n_estimators`-many "prompts" of the input data. With the default `"auto"`, the count comes from the checkpoint (`InferenceConfig.N_ESTIMATORS`), which is itself `"auto"` unless the checkpoint names a count. `"auto"` means `DEFAULT_N_ESTIMATORS`, raised on wide datasets so every feature is seen by some estimator (i.e. when the data has more than `max_features_per_estimator` features per estimator), to the smallest value that lets every feature appear in at least one ensemble member, emitting a warning when it does so. That auto-scaled value is capped at `MAX_AUTO_SCALED_N_ESTIMATORS`; beyond that some features may never be sampled unless you raise `n_estimators` yourself. An explicit integer — yours or the checkpoint's — is never overridden: if it is too small to cover every feature, a warning is emitted at fit time and the value is used as given. Your integer cannot be combined with an `N_ESTIMATORS` in `inference_config`, which is the other way of naming a count. auto_scale_n_estimators: Deprecated, removed in v9 — pass an explicit `n_estimators` instead. Only applies when `n_estimators="auto"`, where `False` keeps the auto value at `DEFAULT_N_ESTIMATORS` rather than raising it for feature coverage, exactly what passing that count as `n_estimators` does. Passing `False` emits a `FutureWarning` at fit time. categorical_features_indices: The indices of the columns that are suggested to be treated as categorical. If `None`, the model will infer the categorical columns. A column with pandas' `category` dtype counts as listed here. A string column declared this way is read as categorical whatever its cardinality, never as text; for a numeric one, we might ignore the suggestion to better fit the data seen during pre-training. !!! note The indices are 0-based and should represent the data passed to `.fit()`. If the data changes between the initializations of the model and the `.fit()`, consider setting the `.categorical_features_indices` attribute after the model was initialized and before `.fit()`. group_col: The label of the column that says which group a row belongs to, e.g. a patient, or a list of labels whose joint value is one composite key. The selected columns are replaced by one categorical feature holding that key's integer code. The codes are fitted on the training rows alone, every group keeping its own; a key `fit` did not see becomes a missing value. When set, `fit` and `predict` take a DataFrame holding those columns, without missing values, and raise `ValueError` otherwise. Combining it with `tuning_config`, `differentiable_input=True` or `fit_from_preprocessed` raises `ValueError` too. `APPEND_GROUP_AGGREGATES` and `POOL_GROUP_PREDICTIONS` in `inference_config` add transductive modes for grouped data. softmax_temperature: The temperature for the softmax function. This is used to control the confidence of the model's predictions. Lower values make the model's predictions more confident. This is only applied when predicting during a post-processing step. Set `softmax_temperature=1.0` for no effect. Be advised that `.predict()` does not currently sample, so this setting is only relevant for `.predict_proba()` and `.predict_logits()`. If `"auto"` (the default), the temperature is taken from the checkpoint (`InferenceConfig.SOFTMAX_TEMPERATURE`), which is `0.9` for every checkpoint released up to and including v8.5.0. Passing a float overrides the checkpoint for every model in the ensemble; it cannot be combined with a `SOFTMAX_TEMPERATURE` in `inference_config`, which is the other way of naming one. balance_probabilities: Whether to balance the probabilities based on the class distribution in the training data. This can help to improve predictive performance when the classes are highly imbalanced and the metric of interest is insensitive to class imbalance (e.g., balanced accuracy, balanced log loss, roc-auc macro ovo, etc.). This is only applied when predicting during a post-processing step. average_before_softmax: Only used if `n_estimators > 1`. Whether to average the predictions of the estimators before applying the softmax function. This can help to improve predictive performance when there are many classes or when calibrating the model's confidence. This is only applied when predicting during a post-processing. - If `True`, the predictions are averaged before applying the softmax function. Thus, we average the logits of TabPFN and then apply the softmax. - If `False`, the softmax function is applied to each set of logits. Then, we average the resulting probabilities of each forward pass. - If `"auto"` (the default), the value is taken from the checkpoint (`InferenceConfig.AVERAGE_BEFORE_SOFTMAX`), which is `False` unless the checkpoint sets it. Passing a bool overrides the checkpoint; it cannot be combined with an `AVERAGE_BEFORE_SOFTMAX` in `inference_config`, which is the other way of naming one. model_path: The path to the TabPFN model file, i.e., the pre-trained weights. Can be a list of paths to load multiple models. If a list is provided, the models are applied across different estimators. - If `"auto"`, the model will be downloaded upon first use. This defaults to your system cache directory, but can be overwritten with the use of an environment variable `TABPFN_MODEL_CACHE_DIR`. - If a path or a string of a path, the model will be loaded from the user-specified location if available, otherwise it will be downloaded to this location. Details on available checkpoints are available in the repository README. - If a ``ModelSpecs`` object or list of them, use the in-memory models without loading checkpoints. The same specs can be used with either estimator when the model supports both tasks. Models are used by reference, not copied. device: The device(s) to use for inference. See the documentation of `.to()`. ignore_pretraining_limits: Whether to ignore the pre-training limits of the model. The TabPFN models have been pre-trained on a specific range of input data. If the input data is outside of this range, the model may not perform well. You may ignore our limits to use the model on data outside the pre-training range. - If `True`, the model will not raise an error if the input data is outside the pre-training range. Also suppresses error when using the model with a large dataset on CPU. - If `False`, you can use the model outside the pre-training range, but the model could perform worse. !!! note For version 2.5, the pre-training limits are: - 50_000 samples/rows - 2_000 features/columns (Note that for more than 500 features we subsample 500 features per estimator. It is therefore important to use a sufficiently large number of `n_estimators`.) - 10 classes, this is not ignorable and will raise an error if the model is used with more classes. inference_precision: The precision to use for inference. This can dramatically affect the speed and reproducibility of the inference. Higher precision can lead to better reproducibility but at the cost of speed. By default, we optimize for speed and use torch's mixed-precision autocast. The options are: - If `torch.dtype`, we force precision of the model and data to be the specified torch.dtype during inference. This can is particularly useful for reproducibility. Here, we do not use mixed-precision. - If `"autocast"`, enable PyTorch's mixed-precision autocast. Ensure that your device is compatible with mixed-precision. - If `"auto"`, we determine whether to use autocast or not depending on the device type. Only `torch.float64` makes a row's prediction exactly independent of the other rows predicted with it, because matrix products are summed in an order that depends on the batch size. Otherwise its probabilities can change by about 1e-6 (`torch.float32`) or 1e-3 (autocast). fit_mode: Determine how the TabPFN model is "fitted". The mode determines how the data is preprocessed and cached for inference. This is unique to an in-context learning foundation model like TabPFN, as the "fitting" is technically the forward pass of the model. The options are: - If `"low_memory"`, the data is preprocessed on-demand during inference when calling `.predict()` or `.predict_proba()`. This is the most memory-efficient mode but can be slower for large datasets because the data is (repeatedly) preprocessed on-the-fly. Ideal with low GPU memory and/or a single call to `.fit()` and `.predict()`. - If `"fit_preprocessors"`, the data is preprocessed and cached once during the `.fit()` call. During inference, the cached preprocessing (of the training data) is used instead of re-computing it. Ideal with low GPU memory and multiple calls to `.predict()` with the same training data. - If `"fit_with_cache"`, the data is preprocessed and cached once during the `.fit()` call like in `fit_preprocessors`. Moreover, the transformer key-value cache is also initialized, allowing for much faster inference on the same data at a large cost of memory. Ideal with very high GPU memory and multiple calls to `.predict()` with the same training data. - If `"batched"`, the already pre-processed data is iterated over in batches. This can only be done after the data has been preprocessed with the get_preprocessed_datasets function. This is primarily used only for inference with the InferenceEngineBatchedNoPreprocessing class in Fine-Tuning. The fit_from_preprocessed() function sets this attribute internally. memory_saving_mode: Enable GPU/CPU memory saving mode. This can both avoid out-of-memory errors and improve fit+predict speed by reducing memory pressure. It saves memory by automatically batching certain model computations within TabPFN. - If "auto": memory saving mode is enabled/disabled automatically based on a heuristic - If True/False: memory saving mode is forced enabled/disabled. If speed is important to your application, you may wish to manually tune this option by comparing the time taken for fit+predict with it set to False and True. !!! warning This does not batch the original input data. We still recommend to batch the test set as necessary if you run out of memory. enable_torch_compile: Compile the regions supported by the model architecture. Compilation can speed up repeated inference but adds startup cost to the first prediction, or to fitting when building a key-value cache. Disabled by default. Architectures without compilation support ignore it. v3.5 compilation requires PyTorch 2.6 or newer. keep_cache_on_device: Only relevant when `fit_mode="fit_with_cache"`. If True (default), the key-value cache is kept on the inference device (e.g. GPU). Uses more device memory but gives lower latency. If False, the cache is stored on CPU. kv_cache_precision: Only relevant when `fit_mode="fit_with_cache"`. Resolved against what the model architecture supports. `None` (default) picks the architecture default (`"int8"` when it can quantize, e.g. TabPFN-3, else `"auto"`); `"int8"` quantizes the key-value cache to save memory; `"fp8"` stores it as 8-bit floats instead (same size, float rounding semantics; not supported on MPS); `"auto"` keeps the computed dtype; `"adaptive"` stores the cache on the grid an attention backend already rounded the keys and values to (one that declares `kv_grid_dtype` and took the call), and as `"int8"` otherwise. Requesting a quantized precision on an architecture that cannot quantize warns and falls back to `"auto"`. kv_cache_on_host: Only relevant when `fit_mode="fit_with_cache"`. Whether the key-value cache keeps its keys and values in host memory, from where a prediction copies to the inference device only what it reads. `None` (default) lets the model architecture decide. An architecture whose cache cannot be read from host memory ignores this option. random_state: Controls the randomness of the model. Pass an int for reproducible results and see the scikit-learn glossary for more information. If `None`, the randomness is determined by the system when calling `.fit()`. !!! warning We depart from the usual scikit-learn behavior in that by default we provide a fixed seed of `0`. !!! note Even if a seed is passed, we cannot always guarantee reproducibility due to PyTorch's non-deterministic operations and general numerical instability. To get the most reproducible results across hardware, we recommend using a higher precision as well (at the cost of a much higher inference time). Likewise, for scikit-learn, consider passing `USE_SKLEARN_16_DECIMAL_PRECISION=True` as kwarg. n_jobs: Deprecated, use `n_preprocessing_jobs` instead. This parameter never had any effect. n_preprocessing_jobs: The number of worker threads to use for the preprocessing. If `1`, the preprocessing runs in the calling thread. If `>1` and `n_estimators > 1`, the estimators are preprocessed on that many threads, which speeds up the fit on large tables. Threads beyond `n_estimators` are unused. With `APPEND_GROUP_AGGREGATES`, the aggregates are also selected on that many threads. `-1` uses all cores. inference_config: For advanced users, additional advanced arguments that adjust the behavior of the model interface. See [tabpfn.inference_config.InferenceConfig][] for details and options. - If `None`, the default InferenceConfig is used. - If `dict`, the key-value pairs are used to update the default `InferenceConfig`. Raises an error if an unknown key is passed. - If `InferenceConfig`, the object replaces the checkpoint's config as a whole, so any field not set on it takes a class default rather than the value the checkpoint declares. Deprecated. presets: Names of bundles of `inference_config` values, see `CLASSIFICATION_PRESETS`. `None` uses the checkpoint's settings as they are. The settings resolve in this order, a later one winning: the checkpoint, the presets, then the keys of an `inference_config` dict. Two presets that set one key to different values raise. A preset never changes `tuning_config`. - `"grouped"`: for `group_col` data, no effect without it. It sets `APPEND_GROUP_AGGREGATES=True` and `POOL_GROUP_PREDICTIONS="mean"`. Both are computed over the rows passed to predict, so predict all rows of a group in one call. differentiable_input: If true, the preprocessing will be adapted to be end-to-end differentiable with PyTorch. This is useful for explainability and prompt-tuning, essential in the prompttuning code. eval_metric: Metric by which predictions will be ultimately evaluated on test data. This can be used to improve this metric on validation data by calibrating the model's probabilities and tuning the decision thresholds during the `fit()/predict()` calls. The tuning can be enabled by configuring the `tuning_config` argument, see below. For currently supported metrics, see [tabpfn.classifier.ClassifierEvalMetrics][]. tuning_config: The settings to use to tune the model's predictions for the specified `eval_metric`. See [tabpfn.inference_tuning.ClassifierTuningConfig][] for details and options. show_progress_bar: Whether to show a progress bar during inference. Defaults to False. """ super().__init__() self.n_estimators = n_estimators self.auto_scale_n_estimators = auto_scale_n_estimators self.categorical_features_indices = categorical_features_indices self.group_col = group_col self.softmax_temperature = softmax_temperature self.balance_probabilities = balance_probabilities self.average_before_softmax = average_before_softmax self.model_path = model_path self.device = device self.ignore_pretraining_limits = ignore_pretraining_limits self.inference_precision: torch.dtype | Literal["autocast", "auto"] = ( inference_precision ) self.fit_mode = fit_mode self.show_progress_bar = show_progress_bar self.memory_saving_mode: MemorySavingMode = memory_saving_mode self.enable_torch_compile = enable_torch_compile self.keep_cache_on_device = keep_cache_on_device self.kv_cache_precision = kv_cache_precision self.kv_cache_on_host = kv_cache_on_host self.random_state = random_state self.inference_config = inference_config self.presets = presets self.differentiable_input = differentiable_input if n_jobs is not None: warnings.warn( "TabPFNClassifier(n_jobs=...) is deprecated and has no effect. " "Use `n_preprocessing_jobs` instead.", DeprecationWarning, stacklevel=2, ) self.n_jobs = n_jobs self.n_preprocessing_jobs = n_preprocessing_jobs self.eval_metric = eval_metric self.tuning_config = tuning_config @classmethod def create_default_for_version(cls, version: ModelVersion, **overrides) -> Self: """Construct a classifier that uses the given version of the model. In addition to selecting the model, this also configures certain settings to the default values associated with this model version. Any kwargs will override the default settings. """ if version == ModelVersion.V2: options = { "model_path": prepend_cache_path( ModelSource.get_classifier_v2().default_filename ), "n_estimators": "auto", } elif version == ModelVersion.V2_5: options = { "model_path": prepend_cache_path( ModelSource.get_classifier_v2_5().default_filename ), "n_estimators": "auto", } elif version == ModelVersion.V2_6: options = { "model_path": prepend_cache_path( ModelSource.get_classifier_v2_6().default_filename ), "n_estimators": "auto", } elif version == ModelVersion.V3: options = { "model_path": prepend_cache_path( ModelSource.get_classifier_v3().default_filename ), "n_estimators": "auto", } elif version == ModelVersion.V3_5: options = { "model_path": prepend_cache_path( ModelSource.get_v3_5().default_filename ), "n_estimators": "auto", } elif version == ModelVersion.V3_5_FAST: options = { "model_path": prepend_cache_path( ModelSource.get_v3_5_fast().default_filename ), "n_estimators": "auto", } else: raise ValueError(f"Unknown version: {version}") options.update(overrides) return cls(**options) @property def estimator_type(self) -> Literal["classifier"]: """The type of the model.""" return "classifier" @property def model_(self) -> Architecture: """The model used for inference. This is set after the model is loaded and initialized. """ if not hasattr(self, "models_"): raise ValueError( "The model has not been initialized yet. Please initialize the model " "before using the `model_` property." ) if len(self.models_) > 1: raise ValueError( "The `model_` property is not supported when multiple models are used. " "Use `models_` instead." ) return self.models_[0] def get_inference_config(self) -> InferenceConfig: """Load the model if needed and return the active inference config. Loads the model checkpoint without requiring fit data so the config can be inspected before calling `fit()`. Any ``inference_config`` override passed to the constructor is considered. Returns: A deep copy of the active inference config. """ if not hasattr(self, "inference_config_"): self._initialize_model_variables() return copy.deepcopy(self.inference_config_) # TODO: We can remove this from scikit-learn lower bound of 1.6 def _more_tags(self) -> dict[str, Any]: return { "allow_nan": True, "multilabel": False, } def __sklearn_tags__(self) -> Tags: # type: ignore tags = super().__sklearn_tags__() tags.input_tags.allow_nan = True tags.estimator_type = self.estimator_type return tags def _initialize_model_variables(self) -> int: """Initializes the model and configurations. Returns: The determined byte_size. """ byte_size = initialize_model_variables_helper(self, self.estimator_type) if self.presets is not None: self.inference_config_ = dataclasses.replace( self.inference_config_, **resolve_presets( self.presets, self.inference_config, CLASSIFICATION_PRESETS ), ) return byte_size def _initialize_for_differentiable_input( self, X: torch.Tensor, y: torch.Tensor, rng: np.random.Generator, ) -> tuple[list[ClassifierEnsembleConfig], torch.Tensor, torch.Tensor]: """Initialize the model for differentiable input.""" validate_dataset_size( X=X, y=y, max_num_samples=self.inference_config_.MAX_NUMBER_OF_SAMPLES, max_num_features=self.inference_config_.MAX_NUMBER_OF_FEATURES, max_cpu_samples=self.inference_config_.MAX_CPU_SAMPLES, devices=self.devices_, ignore_pretraining_limits=self.ignore_pretraining_limits, ) # We use the convention that the class labels are [0, ..., n-1] # for differentiable input. if not hasattr(self, "n_classes_"): self.n_classes_ = int(torch.max(y).item()) + 1 self.classes_ = torch.arange(self.n_classes_) validate_num_classes( num_classes=self.n_classes_, max_num_classes=self.inference_config_.MAX_NUMBER_OF_CLASSES, ) # Minimal preprocessing for prompt tuning reject_categoricals_for_differentiable_input(self.categorical_features_indices) reject_group_col(self.group_col, "differentiable_input=True") n_features = X.shape[1] features = [ Feature(name=f"f{i}", modality=FeatureModality.NUMERICAL) for i in range(n_features) ] self.inferred_feature_schema_ = FeatureSchema(features=features) # A tensor holds no dates, strings or named columns, so these fit nothing; # set anyway, so every predict path converts through them without first # checking. self.date_transformer_ = DateTransformer().fit(X) self.text_transformer_ = TextTransformer().fit(X) self.group_encoder_ = GroupIdEncoder().fit(X) self.group_feature_index_ = None preprocessor_configs = [PreprocessorConfig("none", differentiable=True)] self.n_estimators_ = scale_n_estimators_for_feature_coverage( n_estimators=resolved_n_estimators(self), n_total_features=n_features, preprocessor_configs=preprocessor_configs, auto_scale_n_estimators=self.auto_scale_n_estimators, ) ensemble_configs = generate_classification_ensemble_configs( num_estimators=self.n_estimators_, add_fingerprint_feature=self.inference_config_.FINGERPRINT_FEATURE, feature_shift_decoder=self.inference_config_.FEATURE_SHIFT_METHOD, polynomial_features=self.inference_config_.POLYNOMIAL_FEATURES, preprocessor_configs=preprocessor_configs, class_shift_method=None, n_classes=self.n_classes_, random_state=rng, num_models=len(self.models_), outlier_removal_std=self.inference_config_.get_resolved_outlier_removal_std( estimator_type=self.estimator_type ), passthrough_inf=self.get_inference_config().PASSTHROUGH_INF, ) assert len(ensemble_configs) == self.n_estimators_ return ensemble_configs, X, y def _initialize_dataset_preprocessing( self, X: XType, y: YType, random_state: int | np.random.Generator, ) -> tuple[list[ClassifierEnsembleConfig], np.ndarray, np.ndarray]: """Initialize the model for standard input. The table is float64: the caller gets no decisions to pass to the ensemble. """ ensemble_configs, X, y, _ = ( self._initialize_dataset_preprocessing_with_decisions( X=X, y=y, random_state=random_state, may_cast_to_float32=False ) ) return ensemble_configs, X, y def _initialize_dataset_preprocessing_with_decisions( self, X: XType, y: YType, random_state: int | np.random.Generator, *, may_cast_to_float32: bool, ) -> tuple[ list[ClassifierEnsembleConfig], np.ndarray, np.ndarray, SourceDecisions | None ]: """`_initialize_dataset_preprocessing`, and the decisions the ensemble takes on the fit input before it is cast to float32. """ # feature_names_in_/n_features_in_ have to describe what the caller passed, # not the wider frame expansion can make of it, so they come off the raw # input here, before any conversion. self.feature_names_in_, self.n_features_in_ = extract_input_shape(X) X_given = X categorical_indices = resolve_categorical_features_indices( X, self.categorical_features_indices ) # Before the expansion below, so each group key is read as the caller # passed it rather than as the features a date or text column becomes. self.group_encoder_ = GroupIdEncoder(group_col=self.group_col) groups = self.group_encoder_.fit(X).row_groups(X) X = self.group_encoder_.transform(X) categorical_indices = self.group_encoder_.output_indices(categorical_indices) X, date_transformer, text_transformer, feature_names, categorical_indices = ( expand_dates_and_text( X, categorical_features_indices=categorical_indices, inference_config=self.inference_config_, ) ) self.group_aggregator_ = GroupAggregator( append=self.inference_config_.APPEND_GROUP_AGGREGATES, pool=self.inference_config_.POOL_GROUP_PREDICTIONS is not None, n_jobs=self.n_preprocessing_jobs, # float64 is needed, which MPS lacks; on CPU pandas is faster. device=self.devices_[0] if self.inference_config_.ENABLE_GPU_PREPROCESSING and self.devices_[0].type == "cuda" else None, ) X = self.group_aggregator_.fit_transform( X, y, groups, exclude=self.group_encoder_.feature_name_ ) if feature_names is not None: feature_names = [*feature_names, *self.group_aggregator_.names_] self.group_feature_index_ = self.group_encoder_.feature_index(feature_names) X, y, original_y_name, feature_schema, ordinal_encoder, decisions = ( validate_and_clean_fit_input( self, X, y, X_given=X_given, feature_names=feature_names, categorical_indices=categorical_indices, group_feature_index=self.group_feature_index_, ensure_y_numeric=False, random_state=random_state, may_cast_to_float32=may_cast_to_float32, ) ) self.inferred_feature_schema_ = feature_schema self.ordinal_encoder_ = ordinal_encoder self.date_transformer_ = date_transformer self.text_transformer_ = text_transformer self.categorical_features_indices_ = categorical_indices self.n_train_samples_ = len(X) # Label encoding self.label_encoder_ = TabPFNLabelEncoder(original_target_name=original_y_name) y, label_metadata = self.label_encoder_.fit_transform( y=y, max_num_classes=self.inference_config_.MAX_NUMBER_OF_CLASSES ) self.classes_ = label_metadata.classes self.n_classes_ = label_metadata.n_classes self.class_counts_ = label_metadata.class_counts # Ensemble definition preprocessor_configs = self.inference_config_.PREPROCESS_TRANSFORMS self.n_estimators_ = scale_n_estimators_for_feature_coverage( n_estimators=resolved_n_estimators(self), n_total_features=feature_schema.num_columns, preprocessor_configs=preprocessor_configs, auto_scale_n_estimators=self.auto_scale_n_estimators, ) ensemble_configs = generate_classification_ensemble_configs( num_estimators=self.n_estimators_, add_fingerprint_feature=self.inference_config_.FINGERPRINT_FEATURE, feature_shift_decoder=self.inference_config_.FEATURE_SHIFT_METHOD, polynomial_features=self.inference_config_.POLYNOMIAL_FEATURES, preprocessor_configs=preprocessor_configs, class_shift_method=self.inference_config_.CLASS_SHIFT_METHOD, n_classes=self.n_classes_, random_state=random_state, num_models=len(self.models_), outlier_removal_std=self.inference_config_.get_resolved_outlier_removal_std( estimator_type=self.estimator_type ), passthrough_inf=self.get_inference_config().PASSTHROUGH_INF, ) assert len(ensemble_configs) == self.n_estimators_ return ensemble_configs, X, y, decisions def _compute_downsample_correction(self, *, y_encoded: np.ndarray) -> None: """Set `downsample_correction_weights_` from the fitted row sampler. Requires `ensemble_preprocessor_` and `n_classes_`. Uses `class_counts_` when the label encoder produced it, and the encoded labels otherwise (the differentiable-input path skips the encoder). """ preprocessor = self.ensemble_preprocessor_ if not preprocessor.downsample_shifted_prior: self.downsample_correction_weights_ = None return assert preprocessor.subsample_row_indices is not None train_counts = getattr(self, "class_counts_", None) if train_counts is None: train_counts = np.bincount( np.asarray(y_encoded).astype(np.int64), minlength=self.n_classes_ ) context_prior = context_class_prior( y_encoded, preprocessor.subsample_row_indices, self.n_classes_ ) self.downsample_correction_weights_ = downsample_class_weights( train_counts, context_prior ) def _resolve_row_weights( self, sample_weight: npt.ArrayLike | None, label_reliability: npt.ArrayLike | None, *, y: np.ndarray, ) -> tuple[np.ndarray | None, SampleWeightMode | None]: """Validate the per-row weights of `fit` against `y` and the models.""" if sample_weight is None and label_reliability is None: return None, None mode = resolve_sample_weight_mode( self.models_, self.inference_config_.SAMPLE_WEIGHT_MODE, uses_label_reliability=label_reliability is not None, task_type="multiclass", ) row_weights = validate_row_weights( sample_weight, label_reliability, n_samples=len(y), y_encoded=y, classes=self.classes_, ) return row_weights, mode def _uses_majority_downsample(self) -> bool: """Whether the configured row sampler is majority downsampling.""" config = self.get_inference_config() return ( config.SUBSAMPLE_SAMPLES is not None and SampleSubsamplingMethod(config.SAMPLE_SUBSAMPLING_METHOD) == SampleSubsamplingMethod.MAJORITY_DOWNSAMPLE ) def _get_tuning_classifier(self, **overwrite_kwargs: Any) -> TabPFNClassifier: """Return a fresh classifier configured for holdout tuning.""" params = self.get_params(deep=False) # Avoids sharing mutable config across instances for key in params: try: if isinstance(params.get(key), dict): params[key] = copy.deepcopy(params[key]) except Exception as e: # noqa: BLE001 logging.warning( "Error during initialization of tuning classifier when trying " f"to deepcopy configuration with name `{key}`: {e}. " "Falling back to original configuration" ) forced = { "fit_mode": "fit_preprocessors", "differentiable_input": False, "tuning_config": None, # never tune inside tuning # Fit on the already-expanded array, where a declared column may # have moved down past an expanded date or text column. "categorical_features_indices": self.categorical_features_indices_, } params.update(forced) params.update(overwrite_kwargs) return TabPFNClassifier(**params) @config_context(transform_output="default") # type: ignore def fit( self, X: XType, y: YType, sample_weight: npt.ArrayLike | None = None, label_reliability: npt.ArrayLike | None = None, additional_model_input: Any = None, ) -> Self: """Fit the model. Args: X: The input data. y: The target variable. sample_weight: Experimental. One non-negative weight per training row, roughly saying how many rows it stands for. Only relative values matter: scaling every weight changes nothing, and a weight of 2 is not the same as the row appearing twice. Rows with weight 0 stay in the context. Raises unless the model supports per-row weights, see `InferenceConfig.SAMPLE_WEIGHT_MODE`. label_reliability: Experimental. One value in [0, 1] per training row: how much to trust that row's label, from 1 (known to be right) to 0 (carries no information). Not a class probability or a soft label. Raises unless the model supports `SAMPLE_WEIGHT_MODE="learned"`. additional_model_input: Experimental. Additional input the model can use if its architecture supports it, passed unchanged. Raises if the architecture does not, or with `tuning_config`. With `tuning_config`, each tuning fold is fit with the weights of its rows, and a holdout row counts in the tuned metric in proportion to `sample_weight * label_reliability`. Returns: self """ # Validate eval_metric here instead of in __init__ as per sklearn convention self.eval_metric_ = _validate_eval_metric(self.eval_metric) if self.fit_mode == "batched": logging.warning( "The model was in 'batched' mode, likely after finetuning. " "Automatically switching to 'fit_preprocessors' mode for standard " "prediction. The model will be re-initialized." ) self.fit_mode: Literal[ "low_memory", "fit_preprocessors", "fit_with_cache", "batched", ] = "fit_preprocessors" static_seed, _ = infer_random_state(self.random_state) byte_size = self._initialize_model_variables() ensemble_configs, X, y, source_decisions = ( self._initialize_dataset_preprocessing_with_decisions( X=X, y=y, random_state=static_seed, may_cast_to_float32=True ) ) self.ensemble_configs_ = ensemble_configs row_weights, sample_weight_mode = self._resolve_row_weights( sample_weight, label_reliability, y=y ) if additional_model_input is not None: validate_additional_model_input(self.models_, self.tuning_config) self.ensemble_preprocessor_ = TabPFNEnsemblePreprocessor( configs=ensemble_configs, n_samples=X.shape[0], feature_schema=self.inferred_feature_schema_, # Note: we use the static_seed so we're independent of the random generation # inside the initialize function above random_state=static_seed, n_preprocessing_jobs=self.n_preprocessing_jobs, keep_fitted_cache=(self.fit_mode == "fit_with_cache"), enable_gpu_preprocessing=self.inference_config_.ENABLE_GPU_PREPROCESSING, feature_subsampling_method=FeatureSubsamplingMethod( self.inference_config_.FEATURE_SUBSAMPLING_METHOD ), constant_feature_count=self.inference_config_.FEATURE_SUBSAMPLING_CONSTANT_FEATURE_COUNT, subsample_samples=self.inference_config_.SUBSAMPLE_SAMPLES, sample_subsampling_method=SampleSubsamplingMethod( self.inference_config_.SAMPLE_SUBSAMPLING_METHOD ), importance_top_k_count=self.inference_config_.FEATURE_SUBSAMPLING_IMPORTANCE_TOP_K_COUNT, X_train=X, y_train=y, task_type=self.estimator_type, row_weights=row_weights, sample_weight_mode=sample_weight_mode, additional_model_input=additional_model_input, source_decisions=source_decisions, ) # Needs the row sampler's context prior, and must precede the tuning # step so calibration and thresholds see the corrected probabilities. self._compute_downsample_correction(y_encoded=y) self._maybe_calibrate_temperature_and_tune_decision_thresholds( X=X, y=y, sample_weight=sample_weight, label_reliability=label_reliability ) self.executor_ = create_inference_engine( fit_mode=self.fit_mode, X_train=X, y_train=y, models=self.models_, ensemble_preprocessor=self.ensemble_preprocessor_, devices_=self.devices_, byte_size=byte_size, forced_inference_dtype_=self.forced_inference_dtype_, memory_saving_mode=self.memory_saving_mode, enable_torch_compile=self.enable_torch_compile, use_autocast_=self.use_autocast_, task_type="multiclass", inference_mode=True, keep_cache_on_device=self.keep_cache_on_device, kv_cache_precision=self.kv_cache_precision, kv_cache_on_host=self.kv_cache_on_host, ) return self def fit_from_preprocessed( self, X_preprocessed: list[torch.Tensor], y_preprocessed: list[torch.Tensor], cat_ix: list[list[list[int]]], configs: list[list[EnsembleConfig]], *, performance_options: PerformanceOptions, no_refit: bool = True, ) -> TabPFNClassifier: """Used in Fine-Tuning. Fit the model to preprocessed inputs from torch dataloader inside a training loop a Dataset provided by get_preprocessed_datasets. This function always uses the "batched" fit_mode. Args: X_preprocessed: The input features obtained from the preprocessed Dataset The list contains one item for each ensemble predictor. use tabpfn.utils.collate_for_tabpfn_dataset to use this function with batch sizes of more than one dataset (see examples/tabpfn_finetune.py) y_preprocessed: The target variable obtained from the preprocessed Dataset cat_ix: categorical indices obtained from the preprocessed Dataset configs: Ensemble configurations obtained from the preprocessed Dataset performance_options: Performance and memory options forwarded to the model on each forward call inside the resulting executor. Compilation is enabled if either these options or the estimator's `enable_torch_compile` parameter enables it. no_refit: if True, the classifier will not be reinitialized when calling fit multiple times. """ reject_group_col(self.group_col, "fit_from_preprocessed") if self.fit_mode != "batched": logging.warning( "The model was not in 'batched' mode. " "Automatically switching to 'batched' mode for finetuning." ) self.fit_mode = "batched" # Finetuning batches are built without row subsampling, so no context # prior shift exists here. Clear any correction left over from an earlier # fit(); otherwise forward() would reweight every batch for a shift the # batch never had. self.downsample_correction_weights_ = None # If there is a model, and we are lazy, we skip reinitialization if not hasattr(self, "models_") or not no_refit: byte_size = self._initialize_model_variables() else: _, _, byte_size = determine_precision( self.inference_precision, self.devices_ ) # Preprocessed labels are integer-encoded [0, ..., n-1]. Needed so batched # *inference* postprocessing can shape outputs; harmless for fine-tuning, # where the wrapper sets these. Only set if not already provided. if not hasattr(self, "n_classes_"): self.n_classes_ = max(int(t.max().item()) for t in y_preprocessed) + 1 self.classes_ = torch.arange(self.n_classes_) feature_schema = convert_batch_of_cat_ix_to_schema( batch_of_cat_indices=cat_ix, num_features=X_preprocessed[0].shape[1], ) # Preprocessed tensors hold no dates or strings either, so these fit # nothing: the date transformer still refuses a date and converts a # duration, like any fitted one. self.date_transformer_ = DateTransformer().fit(X_preprocessed[0]) self.text_transformer_ = TextTransformer().fit(X_preprocessed[0]) self.group_encoder_ = GroupIdEncoder().fit(X_preprocessed[0]) self.group_feature_index_ = None self.n_estimators_ = len(configs[0]) self.executor_ = InferenceEngineBatchedNoPreprocessing( X_trains=X_preprocessed, y_trains=y_preprocessed, feature_schema=feature_schema, ensemble_configs=configs, models=self.models_, devices=self.devices_, dtype_byte_size=byte_size, force_inference_dtype=self.forced_inference_dtype_, save_peak_mem=self.memory_saving_mode, inference_mode=not self.differentiable_input, performance_options=dataclasses.replace( performance_options, enable_torch_compile=( self.enable_torch_compile or performance_options.enable_torch_compile ), ), ) return self def predict_proba_batched( # noqa: C901, PLR0912 self, X_train_list: list[XType], y_train_list: list[YType], X_test_list: list[XType], ) -> np.ndarray: """Predict probabilities for several independent datasets in one pass. Each ``(X_train, y_train, X_test)`` triple is preprocessed exactly as in ``fit()`` + ``predict_proba()`` (input validation, CPU and GPU preprocessing, same ensemble configs), then compatible model-input shapes are fused. Heterogeneous post-preprocessing shapes run in separate groups. All datasets must share the same set of classes (they are scored together with a single ``n_classes_``) and the same raw array shapes. Fitted transforms may produce different model-input shapes; these are grouped internally without padding. This method does not modify the estimator: the per-dataset fits run on an internal clone, so ``self`` is unchanged on return (any prior ``fit`` is preserved). Args: X_train_list: Training features, one array per dataset (all same shape). y_train_list: Training labels, one array per dataset. X_test_list: Test features, one array per dataset (all same shape). Returns: Probabilities of shape ``(n_datasets, n_test, n_classes)``. Raises: ValueError: If the input lists have unequal or zero length, the datasets do not all share the same set of classes, or the training (or test) arrays do not all share one shape. NotImplementedError: If ``balance_probabilities``, ``tuning_config``, or ``SAMPLE_SUBSAMPLING_METHOD="majority_downsample"`` is configured on the estimator — their state is per-dataset and cannot be applied correctly across a shared batch. Score those datasets individually with ``predict_proba``. Also raised for ``inference_precision=torch.float64``, which the fused forward does not support. """ # Both imported here rather than at module scope to avoid circular imports: # architectures.interface imported at runtime from classifier is circular # (the rest of the module only needs PerformanceOptions for type-checking), # and the `finetuning` package imports TabPFNClassifier. from tabpfn.architectures.interface import ( # noqa: PLC0415 PerformanceOptions, ) from tabpfn.finetuning.data_util import ( # noqa: PLC0415 ClassifierBatch, _collate_same_shape_for_batched_inference, _group_batches_by_shape, ) if not len(X_train_list) == len(y_train_list) == len(X_test_list): raise ValueError( "X_train_list, y_train_list and X_test_list must have equal length." ) if len(X_train_list) == 0: raise ValueError("Nothing to predict: empty dataset list.") # These per-prediction post-processing steps are configured globally on the # estimator but their fitted state (thresholds, class counts, calibrated # temperature) is per-dataset; applying the last dataset's state across the # whole batch would be wrong, so they are not supported here. if self.balance_probabilities: raise NotImplementedError( "predict_proba_batched does not support balance_probabilities=True; " "score datasets individually with predict_proba." ) if self._uses_majority_downsample(): raise NotImplementedError( "predict_proba_batched does not support " "SAMPLE_SUBSAMPLING_METHOD='majority_downsample'; its prior " "correction is fitted per dataset. Score datasets individually " "with predict_proba." ) if self.tuning_config is not None: raise NotImplementedError( "predict_proba_batched does not support tuning_config (tuned " "decision thresholds / temperature calibration); score datasets " "individually with predict_proba." ) if self.inference_precision == torch.float64: raise NotImplementedError( "predict_proba_batched does not support " "inference_precision=torch.float64; the fused forward runs at " "float32. Use predict_proba per dataset instead." ) # All datasets are scored with a single, shared n_classes_ (one fused # forward over the batch), so they must share the same set of classes. class_sets = [ tuple(sorted(np.unique(np.asarray(y)).tolist())) for y in y_train_list ] if len(set(class_sets)) > 1: raise ValueError( "predict_proba_batched requires all datasets to share the same " "set of classes (they are scored together with one n_classes_); " f"got differing class sets across datasets: {sorted(set(class_sets))}" ) # The fused forward stacks datasets on the model's batch dimension, which # requires identical shapes. Padding ragged datasets would feed the model # fake (zero) context/query rows and leave padded query rows untrimmed in # the output, silently corrupting results — so reject ragged batches. train_shapes = { tuple(X.shape) if hasattr(X, "shape") else np.asarray(X).shape for X in X_train_list } test_shapes = { tuple(X.shape) if hasattr(X, "shape") else np.asarray(X).shape for X in X_test_list } if len(train_shapes) > 1 or len(test_shapes) > 1: raise ValueError( "predict_proba_batched requires all training arrays to share one " "shape and all test arrays to share one shape (ragged batches are " f"not supported); got train shapes {sorted(train_shapes)} and test " f"shapes {sorted(test_shapes)}. Group datasets by shape and call " "once per group." ) # Run the per-dataset fits on an internal clone so this prediction method # does not mutate the estimator: ``self`` is left unchanged on return (any # prior fit is preserved), and the batched executor is dropped with the # clone rather than pinning every dataset's tensors on ``self``. The clone # shares the same model via the ``model_path`` param, so there is no reload. worker = clone(self) # Fit each dataset in "fit_preprocessors" mode so the fitted ensemble # members are cached on the executor and reused directly (no redundant # preprocessing). worker.fit_mode = "fit_preprocessors" items = [] for X, y, X_test in zip(X_train_list, y_train_list, X_test_list, strict=True): # Standard fit on the clone: builds the ensemble preprocessor + configs, # caches the fitted members on the executor, and sets classes_/n_classes_ # exactly as a normal predict would. worker.fit(X, y) # Validate/clean X_test exactly as the standard predict path does # (_raw_predict) before the per-member preprocessors run, so non-numeric # inputs (DataFrames, categoricals, NaNs) are handled identically. check_input_shape_matches(X_test, estimator=worker) X_test, _ = transform_columns(worker, X_test) # noqa: PLW2901 X_test = clean_predict_input(worker, X_test) # noqa: PLW2901 members = worker.executor_.ensemble_members x_context, x_query, cat_indices = [], [], [] y_context = [ torch.as_tensor(np.asarray(m.y_train), dtype=torch.float32) for m in members ] device = worker.devices_[0] for member in members: x_tr = as_tensor_to_read( np.asarray(member.X_train), dtype=torch.float32 ) x_te = as_tensor_to_read( np.asarray(member.transform_X_test(X_test)), dtype=torch.float32 ) full, schema = _maybe_run_gpu_preprocessing( torch.cat([x_tr, x_te], dim=0).to(device), member.gpu_preprocessor, member.feature_schema, num_train_rows=x_tr.shape[0], ) n = x_tr.shape[0] x_context.append(full[:n]) x_query.append(full[n:]) cat_indices.append( schema.indices_for(FeatureModality.CATEGORICAL) or [] ) n_test = x_query[0].shape[0] items.append( ClassifierBatch( X_context=x_context, X_query=x_query, y_context=y_context, y_query=torch.zeros(n_test), cat_indices=cat_indices, configs=worker.ensemble_configs_, ) ) results: list[np.ndarray | None] = [None] * len(items) worker.fit_mode = "batched" groups = _group_batches_by_shape(items) if len(groups) > 1: logger.debug( "predict_proba_batched split %d datasets into %d " "post-preprocessing shape groups with sizes %s; running one " "inference pass per group may be slower than homogeneous batched " "inference.", len(items), len(groups), [len(group) for group in groups], ) for group in groups: indices, group_items = zip(*group, strict=True) batch = _collate_same_shape_for_batched_inference(list(group_items)) worker.fit_from_preprocessed( batch.X_context, batch.y_context, batch.cat_indices, batch.configs, performance_options=PerformanceOptions(), ) out = worker.forward(batch.X_query, use_inference_mode=True) out = out.detach().float().cpu().numpy().transpose(1, 0, 2) for index, probabilities in zip(indices, out, strict=True): results[index] = probabilities test_shape = next(iter(test_shapes)) expected = (test_shape[0], len(class_sets[0])) if any(result is None or result.shape != expected for result in results): raise RuntimeError("Internal error: invalid batched prediction shape.") return np.stack(results) # type: ignore[arg-type] def fit_with_differentiable_input(self, X: torch.Tensor, y: torch.Tensor) -> Self: """Fit the model with differentiable input. Args: X: The input data. y: The target variable. Returns: self """ if self.fit_mode != "fit_preprocessors": logging.warning( "The model was not in 'fit_preprocessors' mode. " "Automatically switching to 'fit_preprocessors' mode for differentiable" " input." ) self.fit_mode = "fit_preprocessors" static_seed, rng = infer_random_state(self.random_state) is_first_fit_call = not hasattr(self, "models_") if is_first_fit_call: byte_size = self._initialize_model_variables() ensemble_configs, X, y = self._initialize_for_differentiable_input( X=X, y=y, rng=rng ) self.ensemble_configs_ = ensemble_configs # Store for prompt tuning reuse else: _, _, byte_size = determine_precision( self.inference_precision, self.devices_ ) ensemble_configs = self.ensemble_configs_ # Reuse from first fit self.n_estimators_ = len(ensemble_configs) self.ensemble_preprocessor_ = TabPFNEnsemblePreprocessor( configs=ensemble_configs, n_samples=X.shape[0], feature_schema=self.inferred_feature_schema_, # Note: we use the static_seed so we're independent of the random generation # inside the initialize function above random_state=static_seed, n_preprocessing_jobs=self.n_preprocessing_jobs, feature_subsampling_method=FeatureSubsamplingMethod( self.inference_config_.FEATURE_SUBSAMPLING_METHOD ), constant_feature_count=self.inference_config_.FEATURE_SUBSAMPLING_CONSTANT_FEATURE_COUNT, subsample_samples=self.inference_config_.SUBSAMPLE_SAMPLES, sample_subsampling_method=SampleSubsamplingMethod( self.inference_config_.SAMPLE_SUBSAMPLING_METHOD ), y_train=y, task_type=self.estimator_type, ) self._compute_downsample_correction(y_encoded=y.detach().cpu().float().numpy()) self.executor_ = InferenceEngineCachePreprocessing( X_train=X, y_train=y, models=self.models_, ensemble_preprocessor=self.ensemble_preprocessor_, devices=self.devices_, dtype_byte_size=byte_size, force_inference_dtype=self.forced_inference_dtype_, save_peak_mem=self.memory_saving_mode, inference_mode=False, enable_torch_compile=self.enable_torch_compile, ) return self def _maybe_calibrate_temperature_and_tune_decision_thresholds( # noqa: C901 self, X: XType, y: YType, sample_weight: npt.ArrayLike | None, label_reliability: npt.ArrayLike | None, ) -> None: """If this class was initialized with a 'tuning_config', calibrate and tune. This first computes scores on validation holdout data and then calibrates the softmax temperature and tunes the decision thresholds as per the tuning configuration. Results are stored in the 'tuned_classification_thresholds_' and 'softmax_temperature_' attributes. `sample_weight` and `label_reliability` are the validated arguments of `fit`, aligned with the rows of `X`. """ assert self.eval_metric_ is not None # Always set this to stay compatible with sklearn interface. # `softmax_temperature_` is already resolved by `_initialize_model_variables`. self.tuned_classification_thresholds_ = None tuning_config_resolved = resolve_tuning_config( tuning_config=self.tuning_config, num_samples=X.shape[0], config_cls=ClassifierTuningConfig, ) if tuning_config_resolved is None: if self.eval_metric_ is ClassifierEvalMetrics.F1: warnings.warn( f"You specified '{self.eval_metric_}' as the eval metric but " "haven't specified any tuning configuration. Consider configuring " "tuning via the `tuning_config` argument of the TabPFNClassifier " "to improve predictive performance.", UserWarning, stacklevel=2, ) if self.eval_metric_ is ClassifierEvalMetrics.BALANCED_ACCURACY: warnings.warn( f"You specified '{self.eval_metric_}' as the eval metric but " "haven't specified any tuning configuration. " f"For metric '{self.eval_metric_}' we recommend " "balancing the probabilities by class counts which can be achieved " "by setting `balance_probabilities` to True.", UserWarning, stacklevel=2, ) return assert isinstance(tuning_config_resolved, ClassifierTuningConfig) if self.group_encoder_.group_columns_: raise TabPFNValidationError( "`tuning_config` cannot be combined with `group_col` yet: tuning " "holds out random rows, not whole groups. Set `tuning_config=None` " "or drop `group_col`." ) if self.eval_metric_ is ClassifierEvalMetrics.ROC_AUC: if tuning_config_resolved.tune_decision_thresholds: raise ValueError( "eval_metric='roc_auc' does not support " "tune_decision_thresholds=True: thresholds cannot change ROC " "AUC, which scores the ranking of the predicted probabilities. " "Pass eval_metric='balanced_accuracy' to keep the previous " "behaviour, or tune_decision_thresholds=False." ) warnings.warn( f"You specified '{self.eval_metric_}' as the eval metric with " "temperature calibration enabled. ROC AUC is independent of this " "tuning and it will not improve this metric. Consider disabling " "it.", UserWarning, stacklevel=2, ) elif ( self.eval_metric_ is ClassifierEvalMetrics.LOG_LOSS and tuning_config_resolved.tune_decision_thresholds ): raise ValueError( "eval_metric='log_loss' does not support " "tune_decision_thresholds=True. Pass calibrate_temperature=True, " "which optimizes log loss directly, or " "tune_decision_thresholds=False." ) holdout = self._compute_holdout_validation_data( X=X, y=y, holdout_frac=float(tuning_config_resolved.tuning_holdout_frac), n_folds=int(tuning_config_resolved.tuning_n_folds), sample_weight=sample_weight, label_reliability=label_reliability, ) if holdout is None: warnings.warn( "Tuning was skipped: in every tuning fold, a class had only " "training rows with `sample_weight` 0.", UserWarning, stacklevel=2, ) return holdout_raw_logits, holdout_y_true, holdout_weights, holdout_row_weights = ( holdout ) # WARNING: ensure the calibration happens before threshold tuning! if tuning_config_resolved.calibrate_temperature: calibrated_softmax_temperature = self._get_calibrated_softmax_temperature( holdout_raw_logits=holdout_raw_logits, holdout_y_true=holdout_y_true, holdout_correction_weights=holdout_weights, holdout_row_weights=holdout_row_weights, ) # The calibrated temperature is fitted on this dataset and replaces # whatever the checkpoint declared. self.softmax_temperature_ = calibrated_softmax_temperature if tuning_config_resolved.tune_decision_thresholds: holdout_probas = ( self.logits_to_probabilities( holdout_raw_logits, downsample_correction_weights=holdout_weights, ) .float() .detach() .cpu() .numpy() ) tuned_classification_thresholds = find_optimal_classification_thresholds( metric_name=self.eval_metric_, y_true=holdout_y_true, y_pred_probas=holdout_probas, n_classes=self.n_classes_, sample_weight=holdout_row_weights, ) self.tuned_classification_thresholds_ = tuned_classification_thresholds def _compute_holdout_validation_data( self, X: XType, y: YType, holdout_frac: float, n_folds: int, sample_weight: npt.ArrayLike | None = None, label_reliability: npt.ArrayLike | None = None, ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray | None] | None: """Compute holdout validation data. Each fold is fit with the `sample_weight` and `label_reliability` of its training rows. A fold is skipped when a class has only training rows with `sample_weight` 0, because its classifier cannot be fit. Returns: `None` when every fold was skipped, otherwise a tuple of: - holdout_raw_logits: Array of holdout raw logits (shape `[n_estimators, n_holdout_samples, n_classes]`). - holdout_y_true: Array of holdout y true labels (shape `[n_holdout_samples]`). - holdout_correction_weights: Per-sample downsampling correction weights (shape `[n_holdout_samples, n_classes]`), taken from the fold's own tuning classifier. Each fold trains on a different split, so under an absolute context budget its class ratios differ from the full model's, and a fold too small to be subsampled applies no correction at all. Such rows carry weight one; the array is always explicit so that tuning never falls back to the full model's weights. - holdout_row_weights: The weight of each holdout row in the tuned metric (shape `[n_holdout_samples]`), `sample_weight * label_reliability`, or `None` when neither was given. """ X = copy.deepcopy(X) y = copy.deepcopy(y) split_indices = get_tuning_split_indices( X=X, y=y, holdout_frac=holdout_frac, random_state=self.random_state, n_splits=n_folds, task_type="classifier", ) if sample_weight is not None: sample_weight = np.asarray(sample_weight, dtype=np.float64) if label_reliability is not None: label_reliability = np.asarray(label_reliability, dtype=np.float64) row_weights = tuning_metric_row_weights(sample_weight, label_reliability) holdout_raw_logits = [] holdout_indices_kept: list[np.ndarray] = [] holdout_weights: list[np.ndarray] = [] # suffixes: Nt=num_train_samples, F=num_features, Nh=num_holdout_samples for train_indices, holdout_indices in split_indices: X_train_NtF, y_train_Nt = X[train_indices], y[train_indices] X_holdout_NhF, y_holdout_Nh = X[holdout_indices], y[holdout_indices] fit_kwargs: dict[str, np.ndarray] = {} if sample_weight is not None: fit_kwargs["sample_weight"] = sample_weight[train_indices] if len( classes_with_zero_weight(fit_kwargs["sample_weight"], y_train_Nt) ): continue if label_reliability is not None: fit_kwargs["label_reliability"] = label_reliability[train_indices] holdout_indices_kept.append(holdout_indices) calibration_classifier = self._get_tuning_classifier() with warnings.catch_warnings(): # Filter expected warnings during tuning warnings.filterwarnings( "ignore", message=".*haven't specified any tuning configuration*", category=UserWarning, ) calibration_classifier.fit(X_train_NtF, y_train_Nt, **fit_kwargs) # E=num estimators, Nh=num holdout samples, C=num classes raw_logits_ENhC = calibration_classifier.predict_raw_logits(X=X_holdout_NhF) holdout_raw_logits.append(raw_logits_ENhC) fold_weights = calibration_classifier.downsample_correction_weights_ if fold_weights is None: fold_weights = np.ones(self.n_classes_) holdout_weights.append( np.broadcast_to(fold_weights, (len(y_holdout_Nh), self.n_classes_)) ) if not holdout_raw_logits: return None holdout_raw_logits_all = np.concatenate(holdout_raw_logits, axis=1) holdout_weights_all = np.concatenate(holdout_weights, axis=0) kept = np.concatenate(holdout_indices_kept) return ( holdout_raw_logits_all, y[kept], holdout_weights_all, None if row_weights is None else row_weights[kept], ) def _raw_predict( self, X: XType, *, return_logits: bool, return_raw_logits: bool = False, ) -> torch.Tensor: """Internal method to run prediction. Handles input validation, preprocessing, and the forward pass. Returns the raw torch.Tensor output (either logits or probabilities) before final detachment and conversion to NumPy. Args: X: The input data for prediction. return_logits: If True, the logits are returned. Otherwise, probabilities are returned after softmax and other post-processing steps. return_raw_logits: If True, returns the raw logits without averaging estimators or temperature scaling. Returns: The raw torch.Tensor output, either logits or probabilities, depending on `return_logits` and `return_raw_logits`. """ check_is_fitted(self) groups = None if not self.differentiable_input: check_input_shape_matches(X, estimator=self) X, groups = transform_columns(self, X) X = clean_predict_input(self, X) with handle_oom_errors( self.devices_, X, model_type="classifier", n_train_samples=getattr(self, "n_train_samples_", None), ): output = self.forward( X, use_inference_mode=True, return_logits=return_logits, return_raw_logits=return_raw_logits, ) return pool_rows( output, groups, logits=return_logits or return_raw_logits, geometric=self.inference_config_.POOL_GROUP_PREDICTIONS == "geometric_mean", ) def predict(self, X: XType) -> np.ndarray: """Predict the class labels for the provided input samples. Args: X: The input data for prediction. Returns: The predicted class labels as a NumPy array. """ probas = self._predict_proba(X=X) y_pred = np.argmax(probas, axis=1) if hasattr(self, "label_encoder_") and self.label_encoder_ is not None: return self.label_encoder_.inverse_transform(y_pred) return y_pred @config_context(transform_output="default") def predict_logits(self, X: XType) -> np.ndarray: """Predict the raw logits for the provided input samples. Logits represent the unnormalized log-probabilities of the classes before the softmax activation function is applied. Args: X: The input data for prediction. Returns: The predicted logits as a NumPy array. Shape (n_samples, n_classes). """ logits_tensor = self._raw_predict(X, return_logits=True) return logits_tensor.float().detach().cpu().numpy() @config_context(transform_output="default") def predict_raw_logits(self, X: XType) -> np.ndarray: """Predict the raw logits for the provided input samples. Logits represent the unnormalized log-probabilities of the classes before the softmax activation function is applied. In contrast to the `predict_logits` method, this method returns the raw logits for each estimator, without averaging estimators or temperature scaling. Args: X: The input data for prediction. Returns: An array of predicted logits for each estimator, Shape (n_estimators, n_samples, n_classes). """ logits_tensor = self._raw_predict( X, return_logits=False, return_raw_logits=True, ) return logits_tensor.float().detach().cpu().numpy() def predict_proba(self, X: XType) -> np.ndarray: """Predict the probabilities of the classes for the provided input samples. This is a wrapper around the `_predict_proba` method. Args: X: The input data for prediction. Returns: The predicted probabilities of the classes as a NumPy array. Shape (n_samples, n_classes). """ return self._predict_proba(X) @config_context(transform_output="default") # type: ignore def _predict_proba(self, X: XType) -> np.ndarray: """Predict the probabilities of the classes for the provided input samples. Args: X: The input data for prediction. Returns: The predicted probabilities of the classes as a NumPy array. Shape (n_samples, n_classes). """ probas = ( self._raw_predict(X, return_logits=False).float().detach().cpu().numpy() ) probas = self._maybe_reweight_probas(probas=probas) if self.inference_config_.USE_SKLEARN_16_DECIMAL_PRECISION: probas = np.around(probas, decimals=SKLEARN_16_DECIMAL_PRECISION) probas = np.where(probas < PROBABILITY_EPSILON_ROUND_ZERO, 0.0, probas) # Ensure probabilities sum to 1 in case of minor floating point inaccuracies # going from torch to numpy return probas / probas.sum(axis=1, keepdims=True) # type: ignore def _get_calibrated_softmax_temperature( self, holdout_raw_logits: np.ndarray, holdout_y_true: np.ndarray, holdout_correction_weights: np.ndarray, holdout_row_weights: np.ndarray | None, ) -> float: """Calibrate temperature based on the holdout logits and true labels. `holdout_row_weights` weights each holdout row in the log loss. `holdout_correction_weights` are the per-sample downsampling correction weights of the folds that produced the logits (ones where a fold applied none), so the objective scores the probabilities those folds would actually have predicted rather than falling back to this model's weights. """ def logits_to_probabilities_fn( raw_logits: np.ndarray | torch.Tensor, softmax_temperature: float, ) -> np.ndarray: return ( self.logits_to_probabilities( raw_logits=raw_logits, softmax_temperature=softmax_temperature, average_before_softmax=resolved_average_before_softmax(self), downsample_correction_weights=holdout_correction_weights, balance_probabilities=self.balance_probabilities, ) .float() .detach() .cpu() .numpy() ) return find_optimal_temperature( raw_logits=holdout_raw_logits, y_true=holdout_y_true, logits_to_probabilities_fn=logits_to_probabilities_fn, current_default_temperature=self.softmax_temperature_, sample_weight=holdout_row_weights, ) def _maybe_reweight_probas(self, probas: np.ndarray) -> np.ndarray: """Reweights the probabilities if a target_metric is specified. If a target metric is specified, the probabilities are reweighted based on the true holdout sets labels and predicted logits. This is done to tune the threshold for classification to the specified target metric. Args: probas: The predicted probabilities of the classes as a NumPy array. Shape (n_samples, n_classes). Returns: The input probas if no tuning is done, otherwise the reweighted probabilities. """ if getattr(self, "tuned_classification_thresholds_", None) is None: return probas probas = probas / np.maximum(self.tuned_classification_thresholds_, 1e-8) return probas / probas.sum(axis=1, keepdims=True) def _apply_temperature(self, logits: torch.Tensor) -> torch.Tensor: """Scales logits by the softmax temperature.""" temp = resolved_softmax_temperature(self) if temp != 1.0: return logits / temp return logits def _average_across_estimators(self, tensors: torch.Tensor) -> torch.Tensor: """Averages a tensor across the estimator dimension (dim=0).""" return tensors.mean(dim=0) def _apply_softmax(self, logits: torch.Tensor) -> torch.Tensor: """Applies the softmax function to the last dimension.""" return torch.nn.functional.softmax(logits, dim=-1) def _apply_balancing(self, probas: torch.Tensor) -> torch.Tensor: """Applies class balancing to a probability tensor.""" counts = getattr(self, "class_counts_", None) if counts is None: return probas return balance_probas_by_class_counts(probas, counts) def logits_to_probabilities( self, raw_logits: np.ndarray | torch.Tensor, *, softmax_temperature: float | None = None, average_before_softmax: bool | None = None, balance_probabilities: bool | None = None, downsample_correction_weights: np.ndarray | None = None, ) -> torch.Tensor: """Convert logits to probabilities using the classifier's post-processing. Args: raw_logits: Logits with shape (n_estimators, n_samples, n_classes) or (n_samples, n_classes). If the logits have three dimensions, they are averaged across the estimator dimension (dim=0). softmax_temperature: Optional override for temperature scaling. average_before_softmax: Optional override for averaging order. balance_probabilities: Optional override for probability balancing. downsample_correction_weights: Optional override for the fitted `downsample_correction_weights_`, either one vector or one row per sample. `None` means "use the fitted weights"; tuning always passes explicit weights (ones where a fold applied no correction) because its folds carry their own correction. Returns: Probabilities with shape (n_samples, n_classes). """ raw_logits = ( raw_logits if isinstance(raw_logits, torch.Tensor) else torch.from_numpy(np.asarray(raw_logits)) ) used_temperature = ( resolved_softmax_temperature(self) if softmax_temperature is None else softmax_temperature ) use_average_before_softmax = ( resolved_average_before_softmax(self) if average_before_softmax is None else average_before_softmax ) use_balance = ( self.balance_probabilities if balance_probabilities is None else balance_probabilities ) steps: list[Callable[[torch.Tensor], torch.Tensor]] = [] if used_temperature != 1.0: def apply_temp(t: torch.Tensor) -> torch.Tensor: return t / used_temperature steps.append(apply_temp) if raw_logits.ndim >= 3: if use_average_before_softmax: steps.append(self._average_across_estimators) steps.append(self._apply_softmax) else: steps.append(self._apply_softmax) steps.append(self._average_across_estimators) elif raw_logits.ndim == 2: steps.append(self._apply_softmax) else: raise ValueError( f"Expected logits with 2 or more dims, got {raw_logits.ndim}" ) # Restore the training prior first, so balancing (if requested) acts on # probabilities that express the training prior rather than the context's. correction_weights = ( getattr(self, "downsample_correction_weights_", None) if downsample_correction_weights is None else downsample_correction_weights ) if correction_weights is not None: def apply_correction(probas: torch.Tensor) -> torch.Tensor: return apply_class_weights(probas, correction_weights) steps.append(apply_correction) if use_balance: steps.append(self._apply_balancing) output = raw_logits for fn in steps: output = fn(output) return output def forward( # noqa: C901, PLR0912 self, X: list[torch.Tensor] | torch.Tensor, *, use_inference_mode: bool = False, return_logits: bool = False, return_raw_logits: bool = False, ) -> torch.Tensor: """Forward pass returning predicted probabilities or logits for TabPFNClassifier Inference Engine. Used in Fine-Tuning and prediction. Called directly in FineTuning training loop or by predict() function with the use_inference_mode flag explicitly set to True. Iterates over outputs of InferenceEngine. Args: X: list[torch.Tensor] in fine-tuning, XType in normal predictions. use_inference_mode: Flag for inference mode., default at False since it is called within predict. During FineTuning forward() is called directly by user, so default should be False here. return_logits: If True, returns logits averaged across estimators. Otherwise, probabilities are returned. return_raw_logits: If True, returns the raw logits, without averaging estimators or temperature scaling. Returns: The predicted probabilities or logits of the classes as a torch.Tensor. - If `use_inference_mode` is True: Shape (N_samples, N_classes) - If `use_inference_mode` is False (e.g., for training/fine-tuning): Shape (Batch_size, N_classes, N_samples), suitable for NLLLoss. - If `return_raw_logits` is True: Shape (n_estimators, n_samples, n_classes) """ if return_logits and return_raw_logits: raise ValueError( "Cannot return both logits and raw logits. Please specify only one." ) # Scenario 1: Standard inference path is_standard_inference = use_inference_mode and not isinstance( self.executor_, InferenceEngineBatchedNoPreprocessing ) # Scenario 2: Batched path, typically for fine-tuning with gradients is_batched_for_grads = ( not use_inference_mode and isinstance(self.executor_, InferenceEngineBatchedNoPreprocessing) and isinstance(X, list) and (not X or isinstance(X[0], torch.Tensor)) ) # Scenario 3: Batched *inference* — score several independent datasets in # one fused forward per estimator (no gradients). Output keeps the dataset # batch dimension. is_batched_inference = ( use_inference_mode and isinstance(self.executor_, InferenceEngineBatchedNoPreprocessing) and isinstance(X, list) and (not X or isinstance(X[0], torch.Tensor)) ) assert is_standard_inference or is_batched_for_grads or is_batched_inference, ( f"Invalid forward pass: Bad combination of inference mode " f"({use_inference_mode=}), input X, " f"or executor type ({type(self.executor_)}). Ensure call is from standard " f"predict ({is_standard_inference=}), batched fine-tuning " f"({is_batched_for_grads=}), or batched inference " f"({is_batched_inference=})." ) # Specific check for float64 incompatibility if the batched engine is being # used, now framed as an assertion that the problematic condition is NOT met. assert not ( isinstance(self.executor_, InferenceEngineBatchedNoPreprocessing) and self.forced_inference_dtype_ == torch.float64 ), ( "Batched engine error: float64 precision is not supported for the " "fine-tuning workflow (requires float32 for backpropagation)." ) if self.fit_mode in ["fit_preprocessors", "batched"]: # Don't enable inference mode when differentiable_input=True (prompt tuning) # to allow gradients to flow through actual_inference_mode = use_inference_mode and not self.differentiable_input self.executor_.use_torch_inference_mode(use_inference=actual_inference_mode) outputs = [] for output, config in tqdm( self.executor_.iter_outputs( X, autocast=self.use_autocast_, task_type="multiclass", ), total=self.n_estimators_, desc="TabPFN inference", unit="estimator", disable=not self.show_progress_bar, ): # Upcast from autocast's reduced precision so the post-processing # (temperature scaling, softmax, estimator averaging) runs in # float32, keeping predict_proba consistent with predict_logits. output = output.float() # noqa: PLW2901 original_ndim = output.ndim # This block correctly handles both single configs and lists of configs if original_ndim == 2: # Shape is [Nsamples, NClasses] -> [Nsamples, 1, NClasses] processed_output = output.unsqueeze(1) config_list = [config] elif original_ndim == 3: # Shape is [Nsamples, batch_size, NClasses] processed_output = output config_list = config else: raise ValueError( f"Output tensor must be 2d or 3d, got {original_ndim}d" ) # Process the config_list (which is now guaranteed to be a list) output_batch = [] for i, batch_config in enumerate(config_list): assert isinstance(batch_config, ClassifierEnsembleConfig) # If class_permutation is None - class shifting is disabled # So we slice to self.n_classes_ to ensure the output tensor matches # the expected number of classes if batch_config.class_permutation is None: output_batch.append(processed_output[:, i, : self.n_classes_]) else: # make sure the processed_output num_classes are the same. if len(batch_config.class_permutation) != self.n_classes_: use_perm = np.arange(self.n_classes_) use_perm[: len(batch_config.class_permutation)] = ( batch_config.class_permutation ) else: use_perm = batch_config.class_permutation output_batch.append(processed_output[:, i, use_perm]) outputs.append(torch.stack(output_batch, dim=1)) # --- Post-processing --- stacked_outputs = torch.stack(outputs) if return_logits: temp_scaled = self._apply_temperature(stacked_outputs) output = self._average_across_estimators(temp_scaled) elif return_raw_logits: output = stacked_outputs else: output = self.logits_to_probabilities(stacked_outputs) # --- Final output shaping --- # Standard inference squeezes the singleton batch dim; batched inference # keeps it so the output is always (n_query, batch_size, n_classes). if output.ndim > 2 and use_inference_mode and not is_batched_inference: output = output.squeeze(1) if not return_raw_logits else output.squeeze(2) if not use_inference_mode: # This case is primarily for fine-tuning where NLLLoss expects [B, C, N] if output.ndim == 2: # was likely [N, C] output = output.unsqueeze(0) # [1, N, C] output = output.transpose(0, 1).transpose(1, 2) return output def get_embeddings( self, X: XType, data_source: Literal["train", "test"] = "test", ) -> np.ndarray: """Get embeddings for the input data ``X``. Args: X : XType The input data. data_source : {"train", "test"}, default="test" Select the transformer output to return. Use ``"train"`` to obtain embeddings from the training tokens and ``"test"`` for the test tokens. When ``n_estimators > 1`` the returned array has shape ``(n_estimators, n_samples, embedding_dim)``. ``"train"`` is not available with ``fit_mode="fit_with_cache"``; see :func:`tabpfn.base.get_embeddings`. Returns: np.ndarray The computed embeddings for each fitted estimator. """ return get_embeddings(self, X, data_source) def save_fit_state(self, path: Path | str) -> None: """Save a fitted classifier, light wrapper around save_fitted_tabpfn_model.""" save_fitted_tabpfn_model(self, path) @classmethod def load_from_fit_state( cls, path: Path | str, *, device: DevicesSpecification = "auto" ) -> TabPFNClassifier: """Restore a fitted clf, light wrapper around load_fitted_tabpfn_model.""" est = load_fitted_tabpfn_model(path, device=device) if not isinstance(est, cls): raise TypeError( f"Attempting to load a '{est.__class__.__name__}' as '{cls.__name__}'" ) return est def to(self, device: DevicesSpecification) -> None: """Move the estimator to the given device(s). If "auto": devices are selected based on availability in the following order of priority: all available CUDA GPUs, "mps", "cpu". To manually select a single device: specify a PyTorch device string e.g. "cuda:1". See PyTorch's documentation for information about supported devices. To use several GPUs: specify a list of PyTorch GPU device strings, e.g. ["cuda:0", "cuda:1"]. This can dramatically speed up inference for larger datasets, by executing the estimators in parallel on the GPUs. Multiple GPUs are only used when `fit_mode="fit_preprocessors"` or `fit_mode="low_memory"`. In other cases, only the first GPU is used. Note: The specified device is only used once the model is initialized. This occurs during the first .fit() call. """ estimator_to_device(self, device) def _validate_eval_metric( eval_metric: str | ClassifierEvalMetrics | None, ) -> ClassifierEvalMetrics: if eval_metric is None: return DEFAULT_CLASSIFICATION_EVAL_METRIC if isinstance(eval_metric, ClassifierEvalMetrics): return eval_metric try: return ClassifierEvalMetrics(eval_metric) # Convert string to Enum except ValueError as err: valid_values = [e.value for e in ClassifierEvalMetrics] raise ValueError( f"Invalid eval_metric: `{eval_metric}`. Must be one of {valid_values}" ) from err