"""TabPFNRegressor class. !!! example ```python import sklearn.datasets from tabpfn import TabPFNRegressor model = TabPFNRegressor() X, y = sklearn.datasets.make_regression(n_samples=50, n_features=10) 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 numbers import typing import warnings from collections.abc import Iterator, Sequence from functools import partial from pathlib import Path from typing import TYPE_CHECKING, Annotated, Any, Literal, overload from typing_extensions import Self, TypedDict, deprecated import numpy as np import torch from sklearn import config_context from sklearn.base import ( BaseEstimator, RegressorMixin, check_is_fitted, clone, ) from sklearn.pipeline import Pipeline from tqdm.auto import tqdm from tabpfn.architectures import ARCHITECTURE_CONFIGS_UP_TO_V3_5 from tabpfn.architectures.shared.bar_distribution import ( FullSupportBarDistribution, expected_value, ) 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 ( REGRESSION_CONSTANT_TARGET_BORDER_EPSILON, ModelVersion, ) from tabpfn.downsample_correction import ( downsample_bucket_log_weights, temper_and_correct_logits, ) from tabpfn.errors import TabPFNValidationError, handle_oom_errors from tabpfn.inference import ( InferenceEngineBatchedNoPreprocessing, InferenceEngineExplicitKVCache, _maybe_run_gpu_preprocessing, ) from tabpfn.inference_tuning import ( RegressorEvalMetrics, RegressorTuningConfig, find_mean_calibration_scale, find_regression_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 ( EnsembleConfig, FeatureSubsamplingMethod, PreprocessorConfig, RegressorEnsembleConfig, SampleSubsamplingMethod, generate_regression_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.row_weights import ( resolve_sample_weight_mode, tuning_metric_row_weights, validate_row_weights, ) from tabpfn.preprocessing.steps import ( get_all_reshape_feature_distribution_preprocessors, ) from tabpfn.preprocessing.target_transform import ( ZERO_INFLATED_TARGET_TRANSFORMS, StandardizeTarget, make_target_transform, ) from tabpfn.preprocessing.text import TextTransformer from tabpfn.settings import settings from tabpfn.utils import ( DevicesSpecification, as_tensor_to_read, convert_batch_of_cat_ix_to_schema, infer_random_state, transform_borders_one, translate_probs_across_borders, ) from tabpfn.validation import ( check_input_shape_matches, extract_input_shape, validate_dataset_size, ) 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, XType, YType from tabpfn.inference import InferenceEngine 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 # --- Prediction Output Types and Constants --- # 1. Tuples for runtime validation and internal logic. # These are defined directly as tuples of strings for immediate clarity. _OUTPUT_TYPES_BASIC = ("mean", "median", "mode") _OUTPUT_TYPES_QUANTILES = ("quantiles",) _OUTPUT_TYPES = _OUTPUT_TYPES_BASIC + _OUTPUT_TYPES_QUANTILES _OUTPUT_TYPES_COMPOSITE = ("full", "main") _USABLE_OUTPUT_TYPES = _OUTPUT_TYPES + _OUTPUT_TYPES_COMPOSITE # 2. Type aliases for static type checking and IDE support. OutputType = Literal["mean", "median", "mode", "quantiles", "full", "main"] """The type hint for the `output_type` parameter in `predict`.""" REGRESSION_PRESETS: dict[str, dict[str, Any]] = { "zero_inflated": { "REGRESSION_Y_PREPROCESS_TRANSFORMS": ("log_fixed_atom",), "REGRESSION_READOUT": "nonnegative_and_capped", "REGRESSION_TARGET_SIGN_FLIP": False, "AVERAGE_BEFORE_SOFTMAX": False, }, "grouped": GROUPED_PRESET, } """The named bundles of `inference_config` values that `presets` selects.""" ZERO_INFLATED_INFERENCE_CONFIG_UP_TO_V3_5: dict[str, Any] = { **REGRESSION_PRESETS["zero_inflated"], "REGRESSION_Y_PREPROCESS_TRANSFORMS": ("log_quantile_gap",), } """What the "zero_inflated" preset sets on the models up to TabPFN-3.5.""" ZERO_SHARE_WARNING_THRESHOLD = 0.2 """`fit` suggests the "zero_inflated" preset for nonnegative targets with a larger share of exact zeros, if their positives pass the checks below.""" ZERO_SHARE_WARNING_MIN_POSITIVES = 50 """Fewer positive targets than this give no suggestion.""" ZERO_SHARE_WARNING_MIN_DECADES = 0.5 """The least log10(q95 / q50) of the positive targets for a suggestion. Narrower positives gain little from a log map.""" ZERO_SHARE_WARNING_MAX_COUNT_LEVELS = 10 """Integer positives with at most this many distinct values are counts, and give no suggestion.""" class MainOutputDict(TypedDict): """Specifies the return structure for `output_type="main"`.""" mean: np.ndarray median: np.ndarray mode: np.ndarray quantiles: list[np.ndarray] class FullOutputDict(MainOutputDict): """Specifies the return structure for `output_type="full"`.""" criterion: FullSupportBarDistribution logits: torch.Tensor RegressionResultType = np.ndarray | list[np.ndarray] | MainOutputDict | FullOutputDict """The type hint for the return value of the `predict` method.""" DEFAULT_REGRESSION_EVAL_METRIC = RegressorEvalMetrics.NLL def _unflip_member( output: torch.Tensor, std_borders: np.ndarray, config: RegressorEnsembleConfig, ) -> tuple[torch.Tensor, np.ndarray]: """Return a member's logits and the standardized borders they belong to. A member that saw the negated target predicts on the mirrored grid: its bucket j is bucket -1 - j there. """ if not config.flip_target: return output, std_borders return output.flip(-1), -std_borders[::-1] class TabPFNRegressor(RegressorMixin, BaseEstimator): """TabPFN regressor 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 inference 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.""" n_outputs_: Literal[1] # We only support single output """The number of outputs the model supports. Only 1 for now""" znorm_space_bardist_: FullSupportBarDistribution """The bar distribution of the target variable, used by the model. This is the bar distribution in the normalized target space. """ raw_space_bardist_: FullSupportBarDistribution """The bar distribution in the raw target space, used for computing the predictions.""" 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.""" 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.""" eval_metric_: RegressorEvalMetrics """The validated evaluation metric to optimize for during prediction.""" ensemble_softmax_temperature_: float """The temperature applied to the aggregated ensemble distribution at predict time, after the per-estimator `softmax_temperature`. This is `1.0`, a no-op, when no temperature calibration is done.""" softmax_temperature_: float """The resolved per-estimator `softmax_temperature`, i.e. the one the checkpoint declares unless it was overridden.""" average_before_softmax_: bool """The resolved `average_before_softmax`, i.e. the one the checkpoint declares unless it was overridden.""" mean_calibration_scale_: float """The constant that multiplies the `"mean"` output, fitted with `RegressorTuningConfig.calibrate_mean`. This is `1.0`, a no-op, otherwise.""" y_train_max_: float """The largest training target, above which the "nonnegative_and_capped" readout drops the predicted mass.""" 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", 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 | RegressorEvalMetrics | None = None, tuning_config: dict | RegressorTuningConfig | None = None, show_progress_bar: bool = False, ) -> None: """Construct a TabPFN regressor. This constructs a regressor 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. 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. 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. - 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. Regression distributions are constructed from ``model.regression_borders`` unless ``norm_criterion`` is supplied. Older models without embedded borders require that explicit normalized-space distribution (including legacy finetuning; use ``znorm_space_bardist_``). 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`.) device: The device to use for inference with TabPFN. If `"auto"`, the device is `"cuda"` if available, otherwise `"cpu"`. See PyTorch's documentation on devices for more information about supported devices. 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 it can change by a relative 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 `REGRESSION_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`. - `"zero_inflated"`: for nonnegative targets with many exact zeros, such as claim amounts or demand. It sets `REGRESSION_Y_PREPROCESS_TRANSFORMS` to `("log_fixed_atom",)` and `REGRESSION_READOUT` to `"nonnegative_and_capped"`, and turns off `REGRESSION_TARGET_SIGN_FLIP` and `AVERAGE_BEFORE_SOFTMAX`. On the models up to TabPFN-3.5 it sets `log_quantile_gap` as the y transform. An `average_before_softmax` argument wins over the preset. - `"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, preprocessing attempts to be end-to-end differentiable. Less relevant for standard regression fine-tuning compared to prompt-tuning. eval_metric: Metric by which predictions will be evaluated on test data for temperature calibration. For currently supported metrics, see [tabpfn.inference_tuning.RegressorEvalMetrics][]. tuning_config: The settings to use to tune the model's predictions for the specified `eval_metric`. See [tabpfn.inference_tuning.RegressorTuningConfig][] 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.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: Literal[ "low_memory", "fit_preprocessors", "fit_with_cache", "batched", ] = 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 self.eval_metric = eval_metric self.tuning_config = tuning_config if n_jobs is not None: warnings.warn( "TabPFNRegressor(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 @classmethod def create_default_for_version(cls, version: ModelVersion, **overrides) -> Self: """Construct a regressor 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_regressor_v2().default_filename ), "n_estimators": "auto", } elif version == ModelVersion.V2_5: options = { "model_path": prepend_cache_path( ModelSource.get_regressor_v2_5().default_filename ), "n_estimators": "auto", } elif version == ModelVersion.V2_6: options = { "model_path": prepend_cache_path( ModelSource.get_regressor_v2_6().default_filename ), "n_estimators": "auto", } elif version == ModelVersion.V3: options = { "model_path": prepend_cache_path( ModelSource.get_regressor_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["regressor"]: """The type of the model.""" return "regressor" @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] downsample_correction_log_weights_: torch.Tensor | None """Per-bar log weights that undo the prior shift of `SAMPLE_SUBSAMPLING_METHOD="majority_downsample"`, added to the aggregated log-probabilities. `None` when that sampler is not in effect.""" @property def norm_bardist_(self) -> FullSupportBarDistribution: """WARNING: DEPRECATED. Please use `raw_space_bardist_` instead. This attribute will be removed in a future version. """ warnings.warn( "`norm_bardist_` is deprecated and will be removed in a future version. " "Please use `raw_space_bardist_` instead.", DeprecationWarning, stacklevel=2, ) return self.raw_space_bardist_ @norm_bardist_.setter def norm_bardist_(self, value: FullSupportBarDistribution) -> None: warnings.warn( "`norm_bardist_` is deprecated and will be removed in a future version. " "Please use `raw_space_bardist_` instead.", DeprecationWarning, stacklevel=2, ) self.raw_space_bardist_ = value @property def bardist_(self) -> FullSupportBarDistribution: """WARNING: DEPRECATED. Please use `znorm_space_bardist_` instead. This attribute will be removed in a future version. """ warnings.warn( "`bardist_` is deprecated and will be removed in a future version. " "Please use `znorm_space_bardist_` instead.", DeprecationWarning, stacklevel=2, ) return self.znorm_space_bardist_ @bardist_.setter def bardist_(self, value: FullSupportBarDistribution) -> None: warnings.warn( "`bardist_` is deprecated and will be removed in a future version. " "Please use `znorm_space_bardist_` instead.", DeprecationWarning, stacklevel=2, ) self.znorm_space_bardist_ = value 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, } def __sklearn_tags__(self) -> Tags: 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_ = _apply_presets( self.inference_config_, self.presets, self.inference_config, self.configs_, average_before_softmax=self.average_before_softmax, ) self.average_before_softmax_ = self.inference_config_.AVERAGE_BEFORE_SOFTMAX return byte_size def _rebuild_raw_space_bardist(self) -> None: """Rebuild ``raw_space_bardist_`` from current ``y_train_mean_``/std_. Detaches the znorm-space borders so the rebuilt buffer never holds a y autograd graph — required for the differentiable-input path and a no-op for the standard path. Both ``y_train_mean_`` and ``y_train_std_`` must already be set as Python floats. """ borders = self.znorm_space_bardist_.borders.detach() self.raw_space_bardist_ = _place_raw_space_bardist( FullSupportBarDistribution( borders.cpu().double() * self.y_train_std_ + self.y_train_mean_, ), borders.device, ) def _build_ensemble_preprocessor_and_executor( # noqa: PLR0913 self, *, X: Any, y: Any, ensemble_configs: list[RegressorEnsembleConfig], static_seed: int, byte_size: int, n_preprocessing_jobs: int, inference_mode: bool, row_weights: np.ndarray | None, sample_weight_mode: SampleWeightMode | None, additional_model_input: Any, source_decisions: SourceDecisions | None, ) -> None: """Build ``self.ensemble_preprocessor_`` and ``self.executor_``. Shared between the standard fit path and the differentiable-input path. The two paths differ only in ``n_preprocessing_jobs`` (forced to 1 in the differentiable path so the autograd graph on ``X`` is built in the calling thread) and ``inference_mode`` (False under differentiable input so backprop works through the executor). """ self.ensemble_preprocessor_ = TabPFNEnsemblePreprocessor( configs=ensemble_configs, n_samples=X.shape[0], feature_schema=self.inferred_feature_schema_, # Use static_seed so we're independent of any random generation # inside the initialize functions above. random_state=static_seed, n_preprocessing_jobs=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, ) self.executor_ = create_inference_engine( fit_mode=self.fit_mode, X_train=X, y_train=y, ensemble_preprocessor=self.ensemble_preprocessor_, models=self.models_, 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="regression", 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, inference_mode=inference_mode, ) def _resolve_row_weights( self, sample_weight: npt.ArrayLike | None, label_reliability: npt.ArrayLike | None, *, n_samples: int, ) -> tuple[np.ndarray | None, SampleWeightMode | None]: """Validate the per-row weights of `fit` against 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="regression", ) row_weights = validate_row_weights( sample_weight, label_reliability, n_samples=n_samples ) return row_weights, mode def _initialize_for_differentiable_input( self, X: torch.Tensor, rng: np.random.Generator, ) -> tuple[list[RegressorEnsembleConfig], torch.Tensor]: """First-call setup for the differentiable path. Mirrors the classifier-side helper so that gradients can flow from a loss back to upstream torch modules feeding ``X`` (and optionally ``y``). Skips the standard numpy preprocessing path and uses a differentiable identity preprocessor. y-target normalization happens every call inside ``fit_with_differentiable_input``; this helper is only for the cached feature-schema and ensemble-config setup. """ # Minimal preprocessing for prompt tuning: no categorical features, # all-numerical schema, identity preprocessor that preserves grads. reject_categoricals_for_differentiable_input(self.categorical_features_indices) reject_group_col(self.group_col, "differentiable_input=True") n_features = X.shape[1] # One Feature instance per column — list multiplication would share # the same dataclass and any later in-place update would leak across # columns. features = [ Feature(name=None, modality=FeatureModality.NUMERICAL) for _ 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 self.n_features_in_ = n_features 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, ) if self.inference_config_.REGRESSION_TARGET_SIGN_FLIP: warnings.warn( "REGRESSION_TARGET_SIGN_FLIP is ignored with differentiable input.", UserWarning, stacklevel=3, ) # Polynomial features go through sklearn StandardScaler on numpy and # are not differentiable; force "no" regardless of the runtime default # (the regressor config defaults to a non-zero value). ensemble_configs = generate_regression_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="no", preprocessor_configs=preprocessor_configs, target_transforms=[None], random_state=rng, num_models=len(self.models_), outlier_removal_std=self.inference_config_.get_resolved_outlier_removal_std( estimator_type=self.estimator_type ), ) assert len(ensemble_configs) == self.n_estimators_ return ensemble_configs, X def _initialize_dataset_preprocessing( self, X: XType, y: YType, random_state: int | np.random.Generator, ) -> tuple[ list[RegressorEnsembleConfig], np.ndarray, np.ndarray, FullSupportBarDistribution, ]: """Prepare ensemble configs and validate X, y for one dataset/chunk. The table is float64: the caller gets no decisions to pass to the ensemble. """ ensemble_configs, X, y, bardist, _ = ( self._initialize_dataset_preprocessing_with_decisions( X=X, y=y, random_state=random_state, may_cast_to_float32=False ) ) return ensemble_configs, X, y, bardist def _initialize_dataset_preprocessing_with_decisions( self, X: XType, y: YType, random_state: int | np.random.Generator, *, may_cast_to_float32: bool, ) -> tuple[ list[RegressorEnsembleConfig], np.ndarray, np.ndarray, FullSupportBarDistribution, SourceDecisions | None, ]: """Prepare ensemble configs and validate X, y for one dataset/chunk. Handle the preprocessing of the input (X and y). We also return the BarDistribution here, since it is vital for computing the standardized target variable in the DatasetCollectionWithPreprocessing class. """ # 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, _, 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=True, random_state=random_state, may_cast_to_float32=may_cast_to_float32, ) ) # Set class variables for sklearn compatibility self.n_train_samples_ = len(X) 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 # TODO: Introduce regressor target transformer that also keeps track of # target name possible_target_transforms = get_all_reshape_feature_distribution_preprocessors( num_examples=y.shape[0], # Use length of validated y random_state=random_state, # Use the provided rng ) for preset in self.inference_config_.REGRESSION_Y_PREPROCESS_TRANSFORMS: if preset == "log" and np.any(y <= 0): raise ValueError( "The 'log' regression target transform requires strictly positive " "raw targets (y > 0). Use 'safepower' or None for " "nonpositive targets." ) if preset == "1_plus_log" and np.any(y <= -1): raise ValueError( "The '1_plus_log' regression target transform requires raw targets " "greater than -1. Use 'safepower' or None for targets <= -1." ) if preset in ZERO_INFLATED_TARGET_TRANSFORMS and np.any(y < 0): raise ValueError( f"The '{preset}' regression target transform requires " "nonnegative raw targets (y >= 0). Use 'safepower' or None for " "negative targets." ) if preset == "exp": overflow_threshold = np.log(np.finfo(np.float32).max) overflow_count = np.count_nonzero(y >= overflow_threshold) if overflow_count: warnings.warn( f"The 'exp' regression target transform would make " f"{overflow_count} of {y.size} raw targets overflow " "in float32. " "Even one infinite value makes target standardization invalid. " "Rescale the targets or use 'safepower' or None.", UserWarning, stacklevel=2, ) # Yeo-Johnson depends on units and offset; fit it on standardized targets. for preset in ("power", "safepower"): possible_target_transforms[preset] = Pipeline( steps=[ ("standardize_input", StandardizeTarget()), (preset, possible_target_transforms[preset]), ] ) possible_target_transforms.update( { name: transform() for name, transform in ZERO_INFLATED_TARGET_TRANSFORMS.items() } ) # Each member fits its target pipeline on raw targets. target_preprocessors: list[Pipeline] = [ make_target_transform( None if y_target_preprocessor in (None, "none") else possible_target_transforms[y_target_preprocessor] ) for y_target_preprocessor in ( self.inference_config_.REGRESSION_Y_PREPROCESS_TRANSFORMS ) ] 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_regression_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, target_transforms=target_preprocessors, 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, target_sign_flip=self.inference_config_.REGRESSION_TARGET_SIGN_FLIP, ) self.znorm_space_bardist_ = self.znorm_space_bardist_.to(self.devices_[0]) assert len(ensemble_configs) == self.n_estimators_ return ensemble_configs, X, y, self.znorm_space_bardist_, decisions def _compute_downsample_correction(self, *, y_raw: np.ndarray) -> None: """Set `downsample_correction_log_weights_` from the fitted row sampler. Requires `ensemble_preprocessor_` and `raw_space_bardist_`; `y_raw` is the target in its original units. """ distribution = self.ensemble_preprocessor_.row_sampling_distribution_ if distribution is None: self.downsample_correction_log_weights_ = None return probabilities, unobserved_probability = distribution self.downsample_correction_log_weights_ = downsample_bucket_log_weights( self.raw_space_bardist_, y_raw=y_raw, row_inclusion_probabilities=probabilities, unobserved_target_probability=unobserved_probability, ) 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_regressor(self, **overwrite_kwargs: Any) -> TabPFNRegressor: """Return a fresh regressor 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 regressor 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 TabPFNRegressor(**params) def fit_from_preprocessed( self, X_preprocessed: list[torch.Tensor], y_preprocessed: list[torch.Tensor], # These y are standardized cat_ix: list[list[list[int]]], configs: list[list[EnsembleConfig]], # Should be RegressorEnsembleConfig *, performance_options: PerformanceOptions, y_train_mean: float, y_train_std: float, no_refit: bool = True, ) -> TabPFNRegressor: """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. y_train_mean: Raw training-target mean for the batch. y_train_std: Raw training-target standard deviation plus epsilon. no_refit: if True, the classifier will not be reinitialized when calling fit multiple times. """ reject_group_col(self.group_col, "fit_from_preprocessed") self.y_train_mean_ = y_train_mean self.y_train_std_ = y_train_std 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 the logit reduction would reweight every batch. self.downsample_correction_log_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_ ) if self._readout() != "default": raise NotImplementedError( "fit_from_preprocessed supports only " "REGRESSION_READOUT='default'; the 'nonnegative_and_capped' readout " "needs the largest training target. Use fit instead." ) 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=True, performance_options=dataclasses.replace( performance_options, enable_torch_compile=( self.enable_torch_compile or performance_options.enable_torch_compile ), ), ) return self def fit_with_differentiable_input(self, X: torch.Tensor, y: torch.Tensor) -> Self: """Fit the model with differentiable input. Mirror of ``TabPFNClassifier.fit_with_differentiable_input``. Lets gradients flow from a downstream loss back through ``X`` (and ``y``, if it carries grads) into upstream torch modules. Use this instead of ``fit`` when ``differentiable_input=True``. Args: X: The input data as a torch tensor. y: The target variable as a torch tensor. 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 = self._initialize_for_differentiable_input( X=X, 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 # Mirror classifier.py: re-assert n_estimators_ from cached # configs so a subsequent call after pickling restores it. self.n_estimators_ = len(ensemble_configs) if self._readout() != "default": raise NotImplementedError( "fit_with_differentiable_input supports only " "REGRESSION_READOUT='default'; the 'nonnegative_and_capped' readout " "needs the largest training target. Use fit instead." ) # Refresh target stats and rebuild the raw-space bardist on every # call so they track the current fit data; cached state is only the # model load, feature schema, and ensemble configs above. 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, ) self.n_train_samples_ = int(X.shape[0]) y_float = ( y.float() if isinstance(y, torch.Tensor) else torch.as_tensor(y, dtype=torch.float32) ) y_mean = y_float.mean() # Match the standard fit's np.std (population std, ddof=0). torch.std # defaults to correction=1 and returns NaN for N=1; clamp keeps the # divisor non-zero. The constant-target guard below catches the # remaining bardist-collapse case. y_std = torch.clamp(y_float.std(correction=0), min=1e-20) if y_std.detach().item() <= 1e-12: raise ValueError( "Constant or near-constant target (std≈0) is not supported " "by fit_with_differentiable_input; there is no signal to " "predict differentiably. Use fit() for constant-target data." ) # Detach when storing as Python floats — raw_space_bardist_ is a # frozen lookup and must not hold a y autograd graph. Users who need # fully differentiable target scaling should z-normalise y themselves # before calling so the mean/std are constants here. self.y_train_mean_ = y_mean.detach().item() self.y_train_std_ = y_std.detach().item() y = (y_float - y_mean) / y_std self.downsample_correction_log_weights_ = None self._rebuild_raw_space_bardist() # Force sequential preprocessing: with differentiable input X carries # an autograd graph, which is built in the calling thread. self._build_ensemble_preprocessor_and_executor( X=X, y=y, ensemble_configs=ensemble_configs, static_seed=static_seed, byte_size=byte_size, n_preprocessing_jobs=1, inference_mode=False, row_weights=None, sample_weight_mode=None, additional_model_input=None, source_decisions=None, ) # `y` is z-normalized by now; histogramming on the raw-space borders # needs the original target values. self._compute_downsample_correction( y_raw=y_float.detach().cpu().float().numpy() ) return self @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 target, from 1 (known to be right) to 0 (carries no information). 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) # Set here as well as in `_maybe_tune_on_holdout` below, so that the # constant-target fit, which returns before calibration, still exposes the # attributes. self.ensemble_softmax_temperature_ = 1.0 self.mean_calibration_scale_ = 1.0 self.downsample_correction_log_weights_ = None if self.differentiable_input: raise ValueError( "differentiable_input=True requires fit_with_differentiable_input " "with torch tensor X and y, not fit()." ) 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 = "fit_preprocessors" static_seed, _ = infer_random_state(self.random_state) byte_size = self._initialize_model_variables() ensemble_configs, X, y, znorm_space_bardist, source_decisions = ( self._initialize_dataset_preprocessing_with_decisions( X=X, y=y, random_state=static_seed, may_cast_to_float32=True ) ) self.znorm_space_bardist_ = znorm_space_bardist self.ensemble_configs_ = ensemble_configs self.y_train_max_ = float(np.max(y)) if self._readout() == "nonnegative_and_capped" and np.any(y < 0): raise TabPFNValidationError( "The 'nonnegative_and_capped' readout requires nonnegative targets " "(y >= 0)." ) row_weights, sample_weight_mode = self._resolve_row_weights( sample_weight, label_reliability, n_samples=len(y) ) if additional_model_input is not None: validate_additional_model_input(self.models_, self.tuning_config) assert len(ensemble_configs) == self.n_estimators_ self.is_constant_target_ = np.unique(y).size == 1 self.constant_value_ = y[0] if self.is_constant_target_ else None if self.is_constant_target_: # Use relative epsilon, s.t. it works for small and large constant values border_adjustment = max( abs(self.constant_value_ * REGRESSION_CONSTANT_TARGET_BORDER_EPSILON), REGRESSION_CONSTANT_TARGET_BORDER_EPSILON, ) self.znorm_space_bardist_ = FullSupportBarDistribution( borders=torch.tensor( [ self.constant_value_ - border_adjustment, self.constant_value_ + border_adjustment, ] ) ) # No need to create an inference engine for a constant prediction return self transforms = self.inference_config_.REGRESSION_Y_PREPROCESS_TRANSFORMS if not any(t in ZERO_INFLATED_TARGET_TRANSFORMS for t in transforms): _warn_if_zero_inflated(y) # Each tuning fold must derive its target statistics from its own raw targets. self._maybe_tune_on_holdout( X=X, y=y, sample_weight=sample_weight, label_reliability=label_reliability ) y_raw = np.asarray(y, dtype=np.float64) # Shared aggregation frame; each member standardizes raw targets separately. self.y_train_mean_ = float(np.mean(y)) self.y_train_std_ = float(np.std(y)) + StandardizeTarget.EPSILON self._rebuild_raw_space_bardist() self._build_ensemble_preprocessor_and_executor( X=X, y=y, ensemble_configs=ensemble_configs, static_seed=static_seed, byte_size=byte_size, n_preprocessing_jobs=self.n_preprocessing_jobs, # TODO: Standard fit usually uses inference_mode=True, before it was enabled inference_mode=True, row_weights=row_weights, sample_weight_mode=sample_weight_mode, additional_model_input=additional_model_input, source_decisions=source_decisions, ) self._compute_downsample_correction(y_raw=y_raw) return self @overload def predict( self, X: XType, *, output_type: Literal["mean", "median", "mode"] = "mean", quantiles: list[float] | None = None, ) -> np.ndarray: ... @overload def predict( self, X: XType, *, output_type: Literal["quantiles"], quantiles: list[float] | None = None, ) -> list[np.ndarray]: ... @overload def predict( self, X: XType, *, output_type: Literal["main"], quantiles: list[float] | None = None, ) -> MainOutputDict: ... @overload def predict( self, X: XType, *, output_type: Literal["full"], quantiles: list[float] | None = None, ) -> FullOutputDict: ... @config_context(transform_output="default") # type: ignore def predict( self, X: XType, *, # TODO: support "ei", "pi" output_type: OutputType = "mean", quantiles: list[float] | None = None, ) -> RegressionResultType: """Runs the forward() method and then transform the logits from the binning space in order to predict target variable. Args: X: The input data. output_type: Determines the type of output to return. - If `"mean"`, we return the mean over the predicted distribution. With `RegressorTuningConfig.calibrate_mean`, the mean is multiplied by `mean_calibration_scale_`, also in `"main"` and `"full"`. The predicted distribution is not rescaled, so the median, mode, quantiles and logits stay as they are. - If `"median"`, we return the median over the predicted distribution. - If `"mode"`, we return the mode over the predicted distribution. - If `"quantiles"`, we return the quantiles of the predicted distribution. The parameter `quantiles` determines which quantiles are returned. - If `"main"`, we return the all output types above in a dict. - If `"full"`, we return the full output of the model, including the logits and the criterion, and all the output types from "main". quantiles: The quantiles to return if `output="quantiles"`. By default, the `[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]` quantiles are returned. The predictions per quantile match the input order. With `fit_mode="fit_with_cache"`, test sets larger than the `TABPFN_MAX_REGRESSOR_PREDICT_ROWS` setting are predicted block by block, so peak memory does not grow with the number of test rows. `output_type="full"` and predictions pooled per group always run in one pass. Returns: The prediction, which can be a numpy array, a list of arrays (for quantiles), or a dictionary with detailed outputs. """ check_is_fitted(self) # TODO: Move these at some point to InferenceEngine check_input_shape_matches(X, estimator=self) X, groups = transform_columns(self, X) X = clean_predict_input(self, X) check_is_fitted(self) if quantiles is None: quantiles = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] elif not all(isinstance(q, numbers.Real) and 0 <= q <= 1 for q in quantiles): raise TabPFNValidationError( f"All quantiles must be real numbers between 0 and 1, got {quantiles}." ) quantiles = [float(q) for q in quantiles] if output_type not in _USABLE_OUTPUT_TYPES: raise TabPFNValidationError(f"Invalid output type: {output_type}") if hasattr(self, "is_constant_target_") and self.is_constant_target_: return self._handle_constant_target(X.shape[0], output_type, quantiles) decode = partial( _decode_logits, output_type=output_type, quantiles=quantiles, znorm_space_bardist=self.znorm_space_bardist_, raw_space_bardist=self.raw_space_bardist_, y_mean=self.y_train_mean_, y_std=self.y_train_std_, truncate_above=self._truncate_above(), # `getattr` keeps models pickled before this attribute existed loadable. mean_scale=getattr(self, "mean_calibration_scale_", 1.0), ) block_rows = settings.tabpfn.max_regressor_predict_rows use_blocks = ( block_rows > 0 and output_type != "full" and X.shape[0] > block_rows and isinstance(self.executor_, InferenceEngineExplicitKVCache) # Pooling needs all rows of a group in one pass. and groups is None ) if not use_blocks: logits = pool_rows( self._aggregate_cleaned_logits(X), groups, logits=True, geometric=self.inference_config_.POOL_GROUP_PREDICTIONS == "geometric_mean", ) return decode(logits) # Each test row only attends to the cached training context, and every # later step is per row, so blocks give the same result as one call. # Decoding each block keeps the [rows, n_buckets] tensors block-sized. parts: list[RegressionResultType] = [] speed_metrics = self.executor_._speed_metrics forward_seconds = 0.0 for start in tqdm( range(0, X.shape[0], block_rows), desc="TabPFN inference", unit="block", disable=not self.show_progress_bar, ): logits = self._aggregate_cleaned_logits( X[start : start + block_rows], show_progress_bar=False ) parts.append(decode(logits)) del logits # Each block overwrites the metric, so accumulate the per-block time. forward_seconds += speed_metrics.get("predict_model_forward_seconds", 0.0) speed_metrics["predict_model_forward_seconds"] = forward_seconds return _concat_block_outputs(parts, output_type) def _truncate_above(self) -> float | None: """The largest training target for the "nonnegative_and_capped" readout, or None. """ return ( self.y_train_max_ if self._readout() == "nonnegative_and_capped" else None ) def _readout(self) -> str: # `getattr` keeps models pickled before this field existed loadable. return getattr(self.inference_config_, "REGRESSION_READOUT", "default") def _maybe_tune_on_holdout( self, X: XType, y: YType, sample_weight: npt.ArrayLike | None, label_reliability: npt.ArrayLike | None, ) -> None: """If a `tuning_config` was given, calibrate on holdout folds. The regressor analogue of the classifier's `_maybe_calibrate_temperature_and_tune_decision_thresholds`. Fits throwaway regressors on cross-validation splits of `X`/`y`, sweeps the temperature against `eval_metric_` on their pooled holdout rows, and stores the winner in `ensemble_softmax_temperature_`, which `_compute_aggregated_logits` applies to every prediction. With `calibrate_mean`, it then fits `mean_calibration_scale_` on the holdout means, with the temperature applied. `y` must be the *raw* target: each fold's regressor performs its own z-normalisation, and passing an already-normalised `y` would normalise it twice. `sample_weight` and `label_reliability` are the validated arguments of `fit`, aligned with the rows of `X`. Unlike the classifier's counterpart there are no metric-specific warnings, as NLL is the only supported metric and calibrating the temperature always targets it directly. """ assert self.eval_metric_ is not None # Always set these, so the attributes exist on every fitted estimator # regardless of whether tuning runs (sklearn compatibility). 1.0 is a # no-op, leaving predictions bit-identical to an uncalibrated fit. self.ensemble_softmax_temperature_ = 1.0 self.mean_calibration_scale_ = 1.0 tuning_config_resolved = resolve_tuning_config( tuning_config=self.tuning_config, num_samples=X.shape[0], config_cls=RegressorTuningConfig, ) if tuning_config_resolved is None: return assert isinstance(tuning_config_resolved, RegressorTuningConfig) calibrate_mean = tuning_config_resolved.calibrate_mean if not (tuning_config_resolved.calibrate_temperature or calibrate_mean): return if calibrate_mean and np.min(y) < 0: raise TabPFNValidationError( "`calibrate_mean` with `mean_calibration_mode='tweedie'` minimizes " "a Tweedie deviance, which needs nonnegative targets, but the " "smallest target is " f"{np.min(y)}." ) 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`." ) holdout_folds = 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 tuning_config_resolved.calibrate_temperature: # Falls back to the current no-op temperature if every fold was # dropped, e.g. because each training split had a constant target. self.ensemble_softmax_temperature_ = find_regression_optimal_temperature( holdout_folds=[fold[:5] for fold in holdout_folds], metric_name=self.eval_metric_, current_default_temperature=self.ensemble_softmax_temperature_, ) # Keeps the no-op scale if every fold was dropped. if calibrate_mean and holdout_folds: y_holdout = ( torch.cat([y_fold for _, _, y_fold, *_ in holdout_folds]).cpu().numpy() ) row_weights = np.concatenate( [ np.ones(len(fold[2])) if fold[4] is None else fold[4].cpu().numpy() for fold in holdout_folds ] ) if not np.any((y_holdout > 0) & (row_weights > 0)): # The fitted constant would be 0 and zero out every mean. warnings.warn( "`calibrate_mean` found no tuning holdout row with a " "positive target and a positive weight, and leaves the mean " "unscaled.", UserWarning, stacklevel=3, ) return self.mean_calibration_scale_ = find_mean_calibration_scale( y_true=y_holdout, mean=np.concatenate( [self._holdout_mean(fold) for fold in holdout_folds] ), power=tuning_config_resolved.mean_calibration_power, sample_weight=row_weights, ) def _holdout_mean(self, fold: _HoldoutFold) -> np.ndarray: """The mean `predict` returns for one fold's holdout rows, before the mean calibration. """ logits, raw_space_bardist, _, log_weights, _, truncate_above = fold # `raw_space_bardist` is already in target units. return typing.cast( "np.ndarray", _logits_to_output( output_type="mean", logits=temper_and_correct_logits( logits, temperature=self.ensemble_softmax_temperature_, log_weights=log_weights, ), znorm_space_bardist=raw_space_bardist, y_mean=0.0, y_std=1.0, quantiles=[], truncate_above=truncate_above, ), ) 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, ) -> list[_HoldoutFold]: """Compute holdout validation data, one entry per cross-validation fold. Folds are kept separate rather than concatenated: every fold normalises the target with its own mean and standard deviation, so every fold's `raw_space_bardist_` has its own borders and only scores that fold's own logits correctly. Each fold is fit with the `sample_weight` and `label_reliability` of its training rows. Returns: One `(logits, raw_space_bardist, y_holdout, log_weights, row_weights, truncate_above)` tuple per usable fold. `logits` has shape `[n_holdout_samples, n_buckets]` and carries no temperature and no downsampling correction; `log_weights` is the fold's own per-bar correction (or `None`), kept separate so the temperature sweep can compose the two exactly as prediction does. `y_holdout` has shape `[n_holdout_samples]` in the *original* units of the target, to match the borders of the fold's `raw_space_bardist`. `row_weights` has shape `[n_holdout_samples]` and holds the weight of each holdout row in the tuned metric, `sample_weight * label_reliability`, or is `None` when neither was given. `truncate_above` is the fold regressor's largest training target for the "nonnegative_and_capped" readout, or `None`. Folds whose training target turned out to be constant, or whose training rows all have `sample_weight` 0, are omitted, so the list may be shorter than `n_folds` and may be empty. """ 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="regressor", ) 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_folds: list[_HoldoutFold] = [] # suffixes: Nt=num_train_samples, F=num_features, Nh=num_holdout_samples, # B=num buckets 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 not fit_kwargs["sample_weight"].any(): continue if label_reliability is not None: fit_kwargs["label_reliability"] = label_reliability[train_indices] tuning_regressor = self._get_tuning_regressor() with warnings.catch_warnings(): # Filter expected warnings during tuning warnings.filterwarnings( "ignore", message=".*haven't specified any tuning configuration*", category=UserWarning, ) # Only the full fit suggests the zero_inflated preset. warnings.filterwarnings( "ignore", message=".*zero-inflated targets.*", category=UserWarning ) tuning_regressor.fit(X_train_NtF, y_train_Nt, **fit_kwargs) if tuning_regressor.is_constant_target_: # This fold's training split is single-valued, so its regressor # returned early with a degenerate two-border distribution and no # executor. There is nothing to calibrate against; skip the fold. continue # The tuning regressor has no `ensemble_softmax_temperature_`, so these # are the untempered aggregated logits, with the per-estimator # `softmax_temperature` correctly still applied. check_input_shape_matches(X_holdout_NhF, estimator=tuning_regressor) X_holdout_NhF, _ = transform_columns(tuning_regressor, X_holdout_NhF) logits_NhB = tuning_regressor._compute_aggregated_logits( X_holdout_NhF, apply_downsample_correction=False ) # `raw_space_bardist_` undoes this fold's normalisation, so the targets # are scored in their original units and need no transformation -- # only a tensor of the dtype and device the bar distribution expects. raw_space_bardist = tuning_regressor.raw_space_bardist_ y_holdout_Nh_tensor = torch.as_tensor( y_holdout_Nh, dtype=raw_space_bardist.borders.dtype, device=logits_NhB.device, ) holdout_folds.append( ( logits_NhB, raw_space_bardist, y_holdout_Nh_tensor, tuning_regressor.downsample_correction_log_weights_, None if row_weights is None else torch.as_tensor( row_weights[holdout_indices], dtype=raw_space_bardist.borders.dtype, device=logits_NhB.device, ), tuning_regressor._truncate_above(), ) ) return holdout_folds def _compute_aggregated_logits( self, X: XType, *, apply_downsample_correction: bool = True ) -> torch.Tensor: """Run the ensemble and aggregate it into one log-probability tensor. Each estimator's bucket probabilities are translated onto the `znorm_space_bardist_` borders, averaged across the ensemble (before or after the softmax, per `average_before_softmax` flat), and returned in log space. Used by `_compute_holdout_validation_data`. Constant-target models have no executor and must be routed to `_handle_constant_target` by the caller instead. Args: X: The input data, after `transform_columns`. apply_downsample_correction: Whether to add the majority-downsampling correction. Temperature tuning passes `False` so it can compose the fold's own correction with each candidate temperature. Returns: A `[n_samples, n_buckets]` tensor of log-probabilities over the `znorm_space_bardist_` buckets, with the calibrated `ensemble_softmax_temperature_` applied. """ return self._aggregate_cleaned_logits( clean_predict_input(self, X), apply_downsample_correction=apply_downsample_correction, ) def _aggregate_cleaned_logits( self, X: np.ndarray, *, apply_downsample_correction: bool = True, show_progress_bar: bool | None = None, ) -> torch.Tensor: """`_compute_aggregated_logits` for input `clean_predict_input` returned. Args: X: The cleaned input data. apply_downsample_correction: As in `_compute_aggregated_logits`. show_progress_bar: Show the per-estimator progress bar. `None` uses `self.show_progress_bar`. """ if show_progress_bar is None: show_progress_bar = self.show_progress_bar n_estimators = 0 accumulated_logits: torch.Tensor | None = None average_before_softmax = resolved_average_before_softmax(self) with handle_oom_errors( self.devices_, X, model_type="regressor", n_train_samples=getattr(self, "n_train_samples_", None), ): for borders_t, output in tqdm( self._iter_forward_executor(X, use_inference_mode=True), total=self.n_estimators_, desc="TabPFN inference", unit="estimator", disable=not show_progress_bar, ): transformed = translate_probs_across_borders( output, frm=torch.as_tensor(borders_t, device=output.device), to=self.znorm_space_bardist_.borders.to(output.device), ) if average_before_softmax: transformed = transformed.log() if accumulated_logits is None: accumulated_logits = transformed else: accumulated_logits = accumulated_logits + transformed n_estimators += 1 assert n_estimators > 0 if accumulated_logits is None: raise ValueError( "Cannot make predictions, possibly due to `n_estimators=0`." ) return self._reduce_accumulated_logits( accumulated_logits, n_estimators, apply_downsample_correction=apply_downsample_correction, ) def _reduce_accumulated_logits( self, accumulated_logits: torch.Tensor, n_estimators: int, *, apply_downsample_correction: bool = True, ) -> torch.Tensor: """Average the ensemble's accumulated output and apply the temperature. Args: accumulated_logits: Summed per-estimator output for one dataset. Already in log space if `average_before_softmax` is True. n_estimators: How many estimators contributed to the sum. apply_downsample_correction: Whether to add the majority-downsampling correction after the temperature. Returns: A `[n_samples, n_buckets]` tensor of log-probabilities with `ensemble_softmax_temperature_` applied. """ if resolved_average_before_softmax(self): logits = (accumulated_logits / n_estimators).softmax(dim=-1) else: logits = accumulated_logits / n_estimators # Post-process the logits logits = logits.log() if logits.dtype == torch.float16: logits = logits.float() # The calibrated temperature acts on the aggregated logits of n_estimators: # softmax(log(sum(probs_i)/T)). The softmax is implicit, as # `FullSupportBarDistribution.compute_scaled_log_probs` applies # `log_softmax` to whatever it receives. `getattr` keeps models pickled # before this attribute existed loadable; the guard keeps the # uncalibrated path allocation-free and bit-identical. # Temperature first, then the per-bar downsampling correction; the bar # distribution's log_softmax renormalizes afterwards. Tuning composes the # same way through `temper_and_correct_logits`. return temper_and_correct_logits( logits, temperature=getattr(self, "ensemble_softmax_temperature_", 1.0), log_weights=( getattr(self, "downsample_correction_log_weights_", None) if apply_downsample_correction else None ), ) def predict_batched( # noqa: C901, PLR0912 self, X_train_list: list[XType], y_train_list: list[YType], X_test_list: list[XType], *, output_type: OutputType = "mean", quantiles: list[float] | None = None, ) -> list[RegressionResultType]: """Predict for several independent datasets in one pass. Each triple is preprocessed exactly as ``fit()`` + ``predict()`` does, then compatible model-input shapes are fused. Heterogeneous post-preprocessing shapes run in separate groups. This is equivalent to independent prediction and leaves ``self`` unchanged. Datasets need not share a target scale (each is decoded with its own bar distribution) but must share raw array shapes. Fitted transforms may produce different shapes; these are grouped internally without padding. Args: X_train_list: Training features, one array per dataset (all same shape). y_train_list: Training targets, one array per dataset. X_test_list: Test features, one array per dataset (all same shape). output_type: As in :meth:`predict`, applied to every dataset. quantiles: As in :meth:`predict`. Returns: One entry per dataset, in input order, each being what :meth:`predict` would return for that dataset. Raises: ValueError: If the input lists have unequal or zero length, or the training (or test) arrays do not all share one shape. TabPFNValidationError: If ``output_type`` or ``quantiles`` are invalid. NotImplementedError: If ``tuning_config`` is configured on the estimator -- the calibrated ensemble temperature is per-dataset state and cannot be applied correctly across a shared batch, so score those datasets individually with :meth:`predict`. Also raised for ``inference_precision=torch.float64``, which the fused forward does not support. Note: Constant-target datasets are answered analytically and take no part in the fused forward. """ # Imported here rather than at module scope: importing # architectures.interface at runtime is circular, as is `finetuning`, # which imports TabPFNRegressor. from tabpfn.architectures.interface import ( # noqa: PLC0415 PerformanceOptions, ) from tabpfn.finetuning.data_util import ( # noqa: PLC0415 RegressorBatch, _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.") # `ensemble_softmax_temperature_` is calibrated per dataset on that # dataset's own holdout, so there is no single temperature to apply to a # shared batch. Mirrors the same guard in # `TabPFNClassifier.predict_proba_batched`. if self._uses_majority_downsample(): raise NotImplementedError( "predict_batched does not support " "SAMPLE_SUBSAMPLING_METHOD='majority_downsample'; its prior " "correction is fitted per dataset. Score datasets individually " "with predict." ) if self.get_inference_config().REGRESSION_READOUT != "default": raise NotImplementedError( "predict_batched supports only REGRESSION_READOUT='default'; the " "'nonnegative_and_capped' readout needs each dataset's largest target. " "Score datasets individually with predict." ) if self.tuning_config is not None: raise NotImplementedError( "predict_batched does not support tuning_config (ensemble " "temperature calibration); the calibrated temperature is fitted " "per dataset and cannot be applied across a shared batch. Score " "datasets individually with predict." ) if self.inference_precision == torch.float64: raise NotImplementedError( "predict_batched does not support inference_precision=torch.float64; " "the fused forward runs at float32. Use predict per dataset instead." ) if quantiles is None: quantiles = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] elif not all(isinstance(q, numbers.Real) and 0 <= q <= 1 for q in quantiles): raise TabPFNValidationError( f"All quantiles must be real numbers between 0 and 1, got {quantiles}." ) quantiles = [float(q) for q in quantiles] if output_type not in _USABLE_OUTPUT_TYPES: raise TabPFNValidationError(f"Invalid output type: {output_type}") # Padding ragged datasets would feed the model fake context rows and leave # padded query rows untrimmed, silently corrupting results. train_shapes = {np.asarray(X).shape for X in X_train_list} test_shapes = {np.asarray(X).shape for X in X_test_list} if len(train_shapes) > 1 or len(test_shapes) > 1: raise ValueError( "predict_batched requires all training arrays to share one shape " "and all test arrays to share one shape (ragged batches are not " f"supported); got train shapes {sorted(train_shapes)} and test " f"shapes {sorted(test_shapes)}. Group datasets by shape and call " "once per group." ) # Fit on a clone so a prior fit on ``self`` survives and the batched # executor is dropped with the clone. The clone shares the model via the # ``model_path`` param, so there is no reload. worker = clone(self) # "fit_preprocessors" caches the fitted members on the executor, so the # loop below reuses them instead of preprocessing twice. worker.fit_mode = "fit_preprocessors" results: list[RegressionResultType | None] = [None] * len(X_train_list) items: list[RegressorBatch] = [] item_indices: list[int] = [] item_y_scales: list[tuple[float, float]] = [] znorm_borders: torch.Tensor | None = None for idx, (X, y, X_test) in enumerate( zip(X_train_list, y_train_list, X_test_list, strict=True) ): worker.fit(X, y) if worker.is_constant_target_: # fit() returns before building an executor here, so there is # nothing to score. results[idx] = worker._handle_constant_target( len(np.asarray(X_test)), output_type, quantiles ) continue # Rebuilt fresh on every fit, so each dataset keeps its own object. # Fixed by the checkpoint, so identical across datasets. if znorm_borders is None: znorm_borders = worker.znorm_space_bardist_.borders.clone() # Clean X_test as the standard predict path does, so DataFrames, # categoricals and NaNs behave 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( RegressorBatch( X_context=x_context, X_query=x_query, y_context=y_context, y_query=torch.zeros(n_test), cat_indices=cat_indices, # From the members, not ``worker.ensemble_configs_``: the members # hold the ``target_transform`` that preprocessing fitted, which # the border mapping needs. configs=[m.config for m in members], y_train_mean=worker.y_train_mean_, y_train_std=worker.y_train_std_, raw_space_bardist=worker.raw_space_bardist_, znorm_space_bardist=worker.znorm_space_bardist_, X_query_raw=torch.zeros(n_test, 1), y_query_raw=torch.zeros(n_test), ) ) item_indices.append(idx) item_y_scales.append((worker.y_train_mean_, worker.y_train_std_)) if items: worker.fit_mode = "batched" assert znorm_borders is not None std_borders = znorm_borders.cpu().numpy() groups = _group_batches_by_shape(items) if len(groups) > 1: logger.debug( "predict_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: positions, 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(), y_train_mean=batch.y_train_mean, y_train_std=batch.y_train_std, ) accumulated: list[torch.Tensor | None] = [None] * len(group) n_estimators = 0 for output, configs in worker.executor_.iter_outputs( batch.X_query, autocast=worker.use_autocast_, task_type="regression", ): for lane in range(len(group)): contribution = worker._translate_batched_logits( output=output[:, lane, :], config=configs[lane], znorm_borders=znorm_borders, std_borders=std_borders, znorm_mean=group_items[lane].y_train_mean, znorm_std=group_items[lane].y_train_std, ) previous = accumulated[lane] accumulated[lane] = ( contribution if previous is None else previous + contribution ) n_estimators += 1 del output for lane, position in enumerate(positions): logits = accumulated[lane] assert logits is not None # Release each lane's bucket logits as it is decoded instead of # retaining every dataset's tensor through the whole decode loop. accumulated[lane] = None item = items[position] y_mean, y_std = item_y_scales[position] results[item_indices[position]] = worker._decode_batched_dataset( accumulated_logits=logits, n_estimators=n_estimators, raw_space_bardist=item.raw_space_bardist, znorm_space_bardist=item.znorm_space_bardist, y_mean=y_mean, y_std=y_std, output_type=output_type, quantiles=quantiles, ) assert all(r is not None for r in results) return typing.cast("list[RegressionResultType]", results) def _translate_batched_logits( self, *, output: torch.Tensor, config: RegressorEnsembleConfig, znorm_borders: torch.Tensor, std_borders: np.ndarray, znorm_mean: float, znorm_std: float, ) -> torch.Tensor: """Map one estimator's output for one dataset onto the shared borders. Same border translation as :meth:`predict`, for a single (estimator, dataset) pair of the fused forward. `znorm_mean` and `znorm_std` belong to this dataset, not to `self`: the worker is refitted per dataset, so its own attributes only ever hold the last one's. """ out_d = output.float() temperature = resolved_softmax_temperature(self) if temperature != 1: out_d = out_d / temperature if config.target_transform is None: raise ValueError( "A fitted target pipeline is required for batched prediction." ) out_d, member_borders = _unflip_member(out_d, std_borders, config) logit_cancel_mask, descending_borders, borders_t = transform_borders_one( member_borders, target_transform=config.target_transform, znorm_mean=znorm_mean, znorm_std=znorm_std, repair_nan_borders_after_transform=self.inference_config_.FIX_NAN_BORDERS_AFTER_TARGET_TRANSFORM, ) if descending_borders: # The borders come back reversed to ascending; reverse the buckets too. out_d = out_d.flip(-1) if logit_cancel_mask is not None: out_d = out_d.clone() out_d[..., logit_cancel_mask] = float("-inf") transformed = translate_probs_across_borders( out_d, frm=torch.as_tensor(borders_t, device=out_d.device), to=znorm_borders.to(out_d.device), ) return ( transformed.log() if resolved_average_before_softmax(self) else transformed ) def _decode_batched_dataset( self, *, accumulated_logits: torch.Tensor, n_estimators: int, raw_space_bardist: FullSupportBarDistribution, znorm_space_bardist: FullSupportBarDistribution, y_mean: float, y_std: float, output_type: OutputType, quantiles: list[float], ) -> RegressionResultType: """Turn one dataset's accumulated logits into its prediction output. Shares :meth:`_reduce_accumulated_logits` with :meth:`predict`, so the two paths average identically, and decodes with this dataset's own target mean and std; `raw_space_bardist` is the returned criterion. """ assert n_estimators > 0 # `predict_batched` rejects `tuning_config`, so the temperature applied # here is always the 1.0 no-op; the call is shared with `predict` so the # two reductions cannot drift apart again. logits = self._reduce_accumulated_logits(accumulated_logits, n_estimators) return _decode_logits( logits, output_type=output_type, quantiles=quantiles, znorm_space_bardist=znorm_space_bardist, raw_space_bardist=raw_space_bardist, y_mean=y_mean, y_std=y_std, # `predict_batched` rejects the "nonnegative_and_capped" readout. truncate_above=None, # `predict_batched` rejects `tuning_config`, which fits the scale. mean_scale=1.0, ) def _iter_forward_executor( self, X: list[torch.Tensor] | XType, *, use_inference_mode: bool = False, ) -> Iterator[tuple[np.ndarray, torch.Tensor]]: # 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)) ) assert is_standard_inference or is_batched_for_grads, ( "Invalid forward pass: Bad combination of inference mode, input X, " "or executor type. Ensure call is from standard predict or a " "batched fine-tuning context." ) # 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)." ) check_is_fitted(self) # Ensure torch.inference_mode is OFF to allow gradients if self.fit_mode in ["fit_preprocessors", "batched"]: # only these two modes support this option. # 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) std_borders = self.znorm_space_bardist_.borders.cpu().numpy() temperature = resolved_softmax_temperature(self) for output, config in self.executor_.iter_outputs( X, autocast=self.use_autocast_, task_type="regression" ): # Widen half-precision autocast output, but keep float64 when # `inference_precision=torch.float64` asked for it. if output.dtype in (torch.float16, torch.bfloat16): output = output.float() # noqa: PLW2901 if temperature != 1: output = output / temperature # noqa: PLW2901 # BSz.= 1 Scenario, the same as normal predict() function # Handled by first if-statement config_for_ensemble = config if isinstance(config, list) and len(config) == 1: single_config = config[0] config_for_ensemble = single_config if isinstance(config_for_ensemble, RegressorEnsembleConfig): borders_t: np.ndarray logit_cancel_mask: np.ndarray | None descending_borders: bool # TODO(eddiebergman): Maybe this could be parallelized or done in fit # but I somehow doubt it takes much time to be worth it. # One reason to make it worth it is if you want fast predictions, i.e. # don't re-do this each time. # However it gets a bit more difficult as you need to line up the # outputs from `iter_outputs` above (which may be in arbitrary order), # along with the specific config the output belongs to. This is because # the transformation done to the borders for a given output is dependant # upon the target_transform of the config. output, member_borders = _unflip_member( # noqa: PLW2901 output, std_borders, config_for_ensemble ) if config_for_ensemble.target_transform is None: # The differentiable-input path supplies standardized targets. borders_t = member_borders.copy() logit_cancel_mask = None descending_borders = False else: logit_cancel_mask, descending_borders, borders_t = ( transform_borders_one( member_borders, target_transform=config_for_ensemble.target_transform, znorm_mean=self.y_train_mean_, znorm_std=self.y_train_std_, repair_nan_borders_after_transform=self.inference_config_.FIX_NAN_BORDERS_AFTER_TARGET_TRANSFORM, ) ) if descending_borders: # The borders come back reversed to ascending; reverse # the buckets too. output = output.flip(-1) # noqa: PLW2901 if logit_cancel_mask is not None: output = output.clone() # noqa: PLW2901 output[..., logit_cancel_mask] = float("-inf") yield borders_t, output else: raise ValueError( "Unexpected config format " "and Batch prediction is not supported yet!" ) def forward( self, X: list[torch.Tensor] | XType, *, use_inference_mode: bool = False, ) -> tuple[torch.Tensor | None, list[torch.Tensor], list[np.ndarray]]: """Forward pass for TabPFNRegressor 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. Returns: A tuple containing: - Averaged logits over the ensemble (for fine-tuning). - Raw outputs from each estimator in the ensemble. - Borders used for each estimator. """ outputs: list[torch.Tensor] = [] borders: list[np.ndarray] = [] for border, output in tqdm( self._iter_forward_executor(X, use_inference_mode=use_inference_mode), total=self.n_estimators_, desc="TabPFN inference", unit="estimator", disable=not self.show_progress_bar, ): borders.append(border) outputs.append(output) averaged_logits = None all_logits = None if outputs: all_logits = torch.stack(outputs, dim=0) # [N_est, N_sampls, N_bord] averaged_logits_over_ensemble = torch.mean(all_logits, dim=0) averaged_logits = averaged_logits_over_ensemble.transpose(0, 1) return averaged_logits, outputs, borders def _handle_constant_target( self, n_samples: int, output_type: OutputType, quantiles: list[float] ) -> RegressionResultType: """Handles prediction when the training target `y` was a constant value.""" constant_prediction = np.full(n_samples, self.constant_value_) if output_type in _OUTPUT_TYPES_BASIC: return constant_prediction if output_type == "quantiles": return [np.copy(constant_prediction) for _ in quantiles] # Handle "main" and "full" main_outputs = MainOutputDict( mean=constant_prediction, median=np.copy(constant_prediction), mode=np.copy(constant_prediction), quantiles=[np.copy(constant_prediction) for _ in quantiles], ) if output_type == "full": return FullOutputDict( **main_outputs, criterion=self.znorm_space_bardist_, logits=torch.zeros((n_samples, 1)), ) return main_outputs def get_embeddings( self, X: XType, data_source: Literal["train", "test"] = "test", ) -> np.ndarray: """Gets the 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 regressor, 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" ) -> TabPFNRegressor: """Restore a fitted regressor, 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) if hasattr(self, "znorm_space_bardist_"): self.znorm_space_bardist_.to(self.devices_[0]) if hasattr(self, "raw_space_bardist_"): # Rebuilt rather than moved: a float32 copy left behind by MPS must # not carry over to a device that supports float64. if hasattr(self, "y_train_mean_"): self._rebuild_raw_space_bardist() else: self.raw_space_bardist_ = _place_raw_space_bardist( self.raw_space_bardist_, self.devices_[0] ) _HoldoutFold = tuple[ torch.Tensor, FullSupportBarDistribution, torch.Tensor, torch.Tensor | None, torch.Tensor | None, float | None, ] """`(logits, raw_space_bardist, y_holdout, log_weights, row_weights, truncate_above)` of one tuning fold, see `TabPFNRegressor._compute_holdout_validation_data`.""" def _apply_presets( config: InferenceConfig, presets: str | Sequence[str], user_config: dict | InferenceConfig | None, architecture_configs: Sequence[ArchitectureConfig], *, average_before_softmax: bool | Literal["auto"], ) -> InferenceConfig: """`config` with the presets' values, except the keys `user_config` names, and `AVERAGE_BEFORE_SOFTMAX` if `average_before_softmax` is not "auto". On a model up to TabPFN-3.5, "zero_inflated" sets `ZERO_INFLATED_INFERENCE_CONFIG_UP_TO_V3_5` instead. """ registry = REGRESSION_PRESETS if any(type(c) in ARCHITECTURE_CONFIGS_UP_TO_V3_5 for c in architecture_configs): registry = { **REGRESSION_PRESETS, "zero_inflated": ZERO_INFLATED_INFERENCE_CONFIG_UP_TO_V3_5, } values = resolve_presets(presets, user_config, registry) if average_before_softmax != "auto": values.pop("AVERAGE_BEFORE_SOFTMAX", None) return dataclasses.replace(config, **values) _zero_share_warning_issued = False """Whether `fit` has suggested the "zero_inflated" preset in this process.""" def _warn_if_zero_inflated(y: np.ndarray) -> None: """Suggest the "zero_inflated" preset, once per process.""" global _zero_share_warning_issued # noqa: PLW0603 if _zero_share_warning_issued: return zero_share = float(np.mean(y == 0)) if zero_share <= ZERO_SHARE_WARNING_THRESHOLD or np.min(y) < 0: return positives = y[y > 0] if len(positives) < ZERO_SHARE_WARNING_MIN_POSITIVES: return q50, q95 = np.quantile(positives, [0.5, 0.95]) if np.log10(q95 / q50) < ZERO_SHARE_WARNING_MIN_DECADES: return is_integer = np.array_equal(positives, np.round(positives)) if is_integer and len(np.unique(positives)) <= ZERO_SHARE_WARNING_MAX_COUNT_LEVELS: return _zero_share_warning_issued = True warnings.warn( f"{zero_share:.0%} of the training targets are exactly 0, and none is " 'negative. For such zero-inflated targets, consider `presets="zero_inflated"`, ' "which models the zeros as a separate point mass.", UserWarning, # Past fit and the frame of its `config_context` decorator. stacklevel=4, ) def _place_raw_space_bardist( bardist: FullSupportBarDistribution, device: torch.device | str ) -> FullSupportBarDistribution: """Keep the raw-space criterion in float64, except on MPS, which lacks it.""" if torch.device(device).type == "mps": return bardist.float().to(device) return bardist.to(device) def _decode_logits( logits: torch.Tensor, *, output_type: OutputType, quantiles: list[float], znorm_space_bardist: FullSupportBarDistribution, raw_space_bardist: FullSupportBarDistribution, y_mean: float, y_std: float, truncate_above: float | None, mean_scale: float, ) -> RegressionResultType: """Turn aggregated log-probabilities into the output `predict` returns. The mean is multiplied by `mean_scale`. `raw_space_bardist` is only returned, as the criterion of `output_type="full"`. """ logit_to_output = partial( _logits_to_output, logits=logits, znorm_space_bardist=znorm_space_bardist, y_mean=y_mean, y_std=y_std, quantiles=quantiles, truncate_above=truncate_above, ) def read_mean() -> np.ndarray: return mean_scale * typing.cast( "np.ndarray", logit_to_output(output_type="mean") ) if output_type == "mean": return read_mean() if output_type not in _OUTPUT_TYPES_COMPOSITE: return logit_to_output(output_type=output_type) main_outputs = MainOutputDict( mean=read_mean(), median=typing.cast("np.ndarray", logit_to_output(output_type="median")), mode=typing.cast("np.ndarray", logit_to_output(output_type="mode")), quantiles=typing.cast( "list[np.ndarray]", logit_to_output(output_type="quantiles") ), ) if output_type == "full": return FullOutputDict( **main_outputs, criterion=raw_space_bardist, logits=logits ) return main_outputs def _concat_block_outputs( parts: list[RegressionResultType], output_type: OutputType ) -> RegressionResultType: """Join the outputs `predict` decoded for consecutive blocks of test rows.""" if output_type in _OUTPUT_TYPES_BASIC: return np.concatenate(typing.cast("list[np.ndarray]", parts)) if output_type == "quantiles": lists = typing.cast("list[list[np.ndarray]]", parts) return [np.concatenate(per_q) for per_q in zip(*lists, strict=True)] if output_type == "main": dicts = typing.cast("list[MainOutputDict]", parts) return MainOutputDict( mean=np.concatenate([d["mean"] for d in dicts]), median=np.concatenate([d["median"] for d in dicts]), mode=np.concatenate([d["mode"] for d in dicts]), quantiles=[ np.concatenate(per_q) for per_q in zip(*(d["quantiles"] for d in dicts), strict=True) ], ) raise ValueError(f"Cannot join block outputs of output_type={output_type!r}.") def _logits_to_output( *, output_type: str, logits: torch.Tensor, znorm_space_bardist: FullSupportBarDistribution, y_mean: float, y_std: float, quantiles: list[float], truncate_above: float | None, ) -> np.ndarray | list[np.ndarray]: """Converts raw model logits to the desired prediction format. Decodes in z-normalised space and undoes the normalisation in float64, so the decode never has to resolve the target's magnitude. With `truncate_above`, every output is read from the distribution of max(Y, 0) given Y <= `truncate_above`. The buckets that start at or above `truncate_above` are dropped; the bucket that holds it is kept whole. The grid bucket that holds 0 and every bucket below it are read as a point at 0: `translate_probs_across_borders` moves a member's mass at 0 into that bucket. If 0 lies below the grid, no bucket is read at 0 and outputs are clipped at 0. """ criterion = znorm_space_bardist def to_raw(output: torch.Tensor) -> np.ndarray: return output.cpu().detach().numpy().astype(np.float64) * y_std + y_mean if truncate_above is not None: raw_borders = to_raw(criterion.borders) # The buckets that start at or below 0 are read at 0. Outputs at or below # the upper border of the last of them read 0. n_zero = int(np.searchsorted(raw_borders, 0.0, side="right")) zero_cut = raw_borders[n_zero] if n_zero > 0 else 0.0 above = raw_borders[:-1] >= truncate_above logits = logits.masked_fill( torch.as_tensor(above, device=logits.device), float("-inf") ) # The kept buckets end where the first dropped one starts. With none # dropped, the last bucket keeps its unbounded half-normal tail. upper = raw_borders[above.argmax()] if above.any() else np.inf def decode(output: torch.Tensor) -> np.ndarray: raw = to_raw(output) if truncate_above is None: return raw # `icdf` returns inf for the quantile 1 without reading the logits. return np.minimum(np.where(raw <= zero_cut, 0.0, raw), upper) if output_type == "quantiles": return [decode(criterion.icdf(logits, q)) for q in quantiles] # TODO: support # "pi": criterion.pi(logits, np.max(self.y)), # "ei": criterion.ei(logits), if output_type == "mean": if truncate_above is None: return to_raw(criterion.mean(logits)) # In target units, so the buckets read at 0 add exactly 0. values = torch.as_tensor(to_raw(criterion.bucket_means())) values[:n_zero] = 0.0 return expected_value(logits.detach().cpu(), values).numpy() if output_type == "median": output = criterion.median(logits) elif output_type == "mode": output = criterion.mode(logits) else: raise ValueError(f"Invalid output type: {output_type}") return decode(output) def _validate_eval_metric( eval_metric: str | RegressorEvalMetrics | None, ) -> RegressorEvalMetrics: if eval_metric is None: return DEFAULT_REGRESSION_EVAL_METRIC if isinstance(eval_metric, RegressorEvalMetrics): return eval_metric try: return RegressorEvalMetrics(eval_metric) # Convert string to Enum except ValueError as err: valid_values = [e.value for e in RegressorEvalMetrics] raise ValueError( f"Invalid eval_metric: `{eval_metric}`. Must be one of {valid_values}" ) from err