Online Error Correction (AdaptiveTAM)¶
Navigation:
Theory introduction: See the Intro
Related mathematical theory: See the Mathematical Theory
Standard Generalized Additive Models (GAMs) assume the underlying data generating process is globally stationary. However, real-world time series suffer from structural breaks, concept drift, and loss of exchangeability. While the underlying mathematics were explored in the theoretical formulations, AdaptiveTAM provides the production-grade hardware implementation.
It utilizes a Sliding Window tensorization approach to update the covariance matrices continuously, allowing the coefficients to smoothly adapt to new regimes without retraining the global model from scratch. This chapter details how this theory is translated into massively parallel PyTorch operations, strictly avoiding restrictive Python for loops.
Design Pattern: Instance Composition¶
The software architecture directly reflects the two-stage mathematical formulation of Online WeaKL. The AdaptiveTAM class does not inherit from StaticTAM; instead, it utilizes a Composition pattern.
Architectural Choice: By using composition, the framework prevents namespace collision and guarantees mathematical isolation between the physics-based macroscopic model and the reactive microscopic model. It owns and orchestrates two distinct instances:
self.base_model_: The expert instance, permanently frozen after its initial training.self.adaptive_model_: A blank, template instance that will be cloned and dynamically retrained on each sliding window to correct the base model’s residuals.add_base_effects=Trueappends onel(effect_<name>)term per base-model component to the adaptive formula, with the column namesdecompose_predictionemits (decomposition_names(): a shared feature is basis-prefixed, a tensor product iste_<a>_x_<b>).
_MODEL_TARGET = "__mu__"
# A scale needs a few residuals: below this count the base scale stands (s = 1).
_MIN_RESIDUALS_FOR_SCALE = 5
#: <online_scale>
def _online_scale(standardized: np.ndarray, group: np.ndarray, order: np.ndarray, window: int, interval: int, horizon: int) -> np.ndarray:
r"""
Rolling root mean square of the standardized residuals, one value per row, using past residuals only.
Rows of a group are taken in the order of ``order``. The first window forecasts the row ``window + horizon - 1`` (zero-based);
from there the scale is renewed every ``interval`` rows, at an origin ``o``, from the finite residuals of the rows
``o - window ... o - horizon``. A row before the first origin, or whose origin has fewer than ``_MIN_RESIDUALS_FOR_SCALE``
finite residuals, gets 1.
Args:
standardized: ``(y - location) / sigma_base`` per row (NaN where unknown).
group: Group label per row.
order: Sort key within a group (the dates).
window: ``training_window_periods``.
interval: ``update_interval_periods``.
horizon: ``horizon_steps``.
Returns:
The scale per row, in the row order of the input.
"""
scale = np.ones(len(standardized))
first = window + horizon - 1
frame = pd.DataFrame({"g": group, "o": order, "pos": np.arange(len(standardized))}).sort_values(["g", "o", "pos"], kind="stable")
for _, rows in frame.groupby("g", sort=False):
positions = rows["pos"].to_numpy()
residual = standardized[positions]
finite = np.isfinite(residual)
squares = np.where(finite, residual ** 2, 0.0)
cum_squares = np.concatenate([[0.0], np.cumsum(squares)])
cum_count = np.concatenate([[0], np.cumsum(finite)])
rank = np.arange(len(positions))
eligible = rank >= first
origin = first + ((rank - first) // interval) * interval
low = np.maximum(origin - window, 0)
high = origin - horizon + 1 # exclusive end of the rows known at the origin
usable = eligible & (high > low)
count = np.where(usable, cum_count[np.clip(high, 0, None)] - cum_count[low], 0)
total = np.where(usable, cum_squares[np.clip(high, 0, None)] - cum_squares[low], 0.0)
enough = usable & (count >= _MIN_RESIDUALS_FOR_SCALE)
scale[positions] = np.where(enough, np.sqrt(total / np.maximum(count, 1)), 1.0)
return scale
#: </online_scale>
class AdaptiveTAM:
r"""
Initializes the AdaptiveTAM model.
"""
def __init__(
self,
adaptive_formula: str,
update_interval_periods: int,
training_window_periods: int,
steps_per_period: int,
base_model: Optional[StaticTAM] = None,
horizon_steps: int = 1,
default_alpha_p: float = -9.0,
group_col: Optional[str] = None,
date_col: Optional[str] = None,
add_base_effects: bool = False,
clip_to_train_range: bool = False
):
r"""
Initializes the AdaptiveTAM model.
Args:
base_model: A fitted StaticTAM model instance. A fitted distributional StaticTAM (dict formula) is accepted: the correction is
fitted on its location on the model scale, and ``predict_quantiles`` rescales its scale online.
adaptive_formula: Formula for the adaptive correction model.
Features must be columns produced by base_model.decompose_prediction()
(e.g., 'effect_temp').
update_interval_periods (int): The number of periods to skip before updating
the coefficients for a specific group (determines n_windows).
training_window_periods (int): The historical look-back period used to solve
the local linear system for an independent group (determines num_samples_train).
steps_per_period (int): The number of observations a single group experiences
within one logical period.
- If the data is monthly and the period is a month: 1.
- If the data is 30-min, but group_col is 'Time of Day': 1 (since each group only sees one observation per day).
horizon_steps (int): The forecasting horizon (H) used to prevent target leakage.
Enforces an information delay by truncating the last (H-1) samples from the
training buffer of every group simultaneously.
default_alpha_p: Default regularization strength (log10).
clip_to_train_range: Clips the forecast of every window to the range of the target in the training rows of that
same window (False by default: no clipping).
Raises:
ValueError: If the base_model has not been fitted.
"""
if re.search(r"\boffset\s*\(", adaptive_formula):
raise ValueError("offset(...) is read by StaticTAM only; put it in the formula of the base_model, whose predictions the correction starts from.")
self.distributional_base_ = None
if base_model is not None and getattr(base_model, '_mode_', 'plain') == 'distributional':
# The correction is fitted on the model scale of the location sub-model (target ``__mu__``); the scale of the
# distributional base is kept for ``predict_quantiles``.
if getattr(base_model, '_location_submodel_', None) is None:
raise ValueError("The base_model must be fitted before initializing AdaptiveTAM.")
self.distributional_base_ = base_model
adaptive_formula = re.sub(rf"\bResidual{re.escape(base_model.target_col_)}\b", f"Residual{_MODEL_TARGET}", adaptive_formula)
base_model = base_model._location_submodel_
if base_model is not None and getattr(base_model, 'coefficients_', None) is None:
raise ValueError("The base_model must be fitted before initializing AdaptiveTAM.")
# The base of a non-Gaussian loss: the windows are GLMs on the link scale, with the base predictions as an offset.
self.glm_strategy_ = None
strategy = getattr(base_model, '_reweighting_strategy_', None)
if base_model is not None and getattr(strategy, 'is_glm', False) and getattr(base_model, '_mode_', 'plain') == 'plain':
if clip_to_train_range:
raise ValueError("clip_to_train_range is not available with the base of a non-Gaussian loss: the forecast keeps the support of the family.")
self.glm_strategy_ = strategy
# The correction column must not be the base target itself: `Estimated<target>` is the base forecast.
base_target = base_model.target_col_
adaptive_formula = re.sub(rf"^\s*{re.escape(base_target)}\s*~", f"Residual{base_target} ~", adaptive_formula, count=1)
if add_base_effects and base_model is not None:
# Column names as decompose_prediction emits them (shared features are basis-prefixed).
for name in decomposition_names(base_model.effects_list_):
effect_col = f"effect_{name}"
if effect_col not in adaptive_formula:
adaptive_formula += f" + l({effect_col})"
self.base_model_ = base_model
self.adaptive_formula_ = adaptive_formula # as the user gave it (a new AdaptiveTAM can be built from it)
if self.glm_strategy_ is not None:
adaptive_formula += f" + offset({_ETA_BASE})" # internal: the link of the base forecast, read as an offset
self.update_interval_periods_ = update_interval_periods
self.training_window_periods_ = training_window_periods
self.steps_per_period_ = steps_per_period
self.horizon_steps_ = horizon_steps
self.group_col_ = group_col or getattr(base_model, 'group_col_', "__dummy_group__")
self.date_col_ = date_col or getattr(base_model, 'date_col_', "__dummy_date__")
self.adaptive_model_ = StaticTAM(
formula=adaptive_formula,
group_col=self.group_col_,
date_col=self.date_col_,
default_alpha_p=default_alpha_p
)
self.coefficients_ = None
self.norm_params_ = None
self.unique_groups_ = None
self.simulation_data_ = None
self.predictions_ = None
target_col_bm = getattr(base_model, 'target_col_', self.adaptive_model_.target_col_)
self.target_col_ = self.adaptive_model_.target_col_ or f'Residual{target_col_bm}'
if self.base_model_ is not None:
base_target = getattr(self.base_model_, 'target_col_', None)
if base_target and self.adaptive_model_.target_col_:
expected_residual = f'Residual{base_target}'
if self.adaptive_model_.target_col_ not in [expected_residual, base_target]:
warnings.warn(
f"Adaptive target '{self.adaptive_model_.target_col_}' does not match the base target "
f"'{base_target}' or its expected residual '{expected_residual}'. "
"This will cause a cross-target correction.",
UserWarning
)
self.clip_to_train_range_ = clip_to_train_range
self.last_state_dict_ = None
self.window_layout_ = None
self.final_target_range_ = None
Advanced PyTorch Indexing (4D Vectorization)¶
One of the major engineering challenges of online learning is extracting the training windows. Sequentially extracting 10,000 localized windows using a Python for loop would completely stall the CUDA pipeline due to excessive CPU-GPU kernel launch latency.
To solve this, the _transform_data_adaptive function (located in _data.py) exploits PyTorch’s advanced indexing and broadcasting.
Architectural Choices & Frequency Agnosticism:
The code deliberately transitions from a rigid “Calendar Day” perspective to a Frequency-Agnostic Group Coordinate System. By using mathematical abstract variables like periods and steps_per_period, it perfectly isolates panel data entities regardless of whether the native sampling rate is monthly, daily, or half-hourly.
Anchor Calculation: The windows are anchored on the start of each group (
_window_starts, also exposed asta.rolling_windows): the first one trains on the firsttraining_window_periodsperiods and forecasts right after them (horizon_steps - 1rows later), the next ones follow everyupdate_interval_periods, and the last one is cut at the end of the data. The rows before the first forecast areNaNin the estimate, never 0; the adapted forecast falls back to the base model forecast there (NaNwithout a base model).Causal Offset Generation (Preventing Target Leakage): It generates two constant tensors:
predict_offsets(the indices of the prediction window) andtrain_offsets(the relative indices of the learning window). Crucially, to prevent Target Leakage in multi-step forecasting, thetrain_offsetsare dynamically shifted backward by-(horizon_steps - 1). This physically truncates the “illegal future” from the training buffer before the tensor is ever evaluated on the GPU.Vectorized Extraction: By adding the column matrix of start indices (
start_indices.view(-1, 1)) to the offset vectors, PyTorch instantly broadcasts a complete 2D index matrix. The framework then extracts the entirety of the causally safe historical data in a single, contiguous memory call:x_group[train_indices].Per-Window Normalisation: Every (group, window) is normalised to \([-1, 1]\) with the minimum and maximum of its own training rows, applied to that window’s training and forecast rows (categorical codes use their fixed level range). This is what
StaticTAM.fitfollowed bypredictdoes on that window, soAdaptiveTAMequals the loop of operational refits; the training rows of every window map exactly to \([-1, 1]\), so the spline knots are the same in every window. The tensors arefloat64when the device supports it.
class _AdaptiveWindows:
r"""Where the windows of an adaptive simulation sit in the data, and the normalisation each one trained with."""
def __init__(self, positions, starts, n_valid, norm_min, norm_max, y_min, y_max):
self.positions = positions # per group: row positions of the group in `data`, in date order
self.starts = starts # per group: first forecast position of each window (the last one may be the data end)
self.n_valid = n_valid # per group: forecast rows of each window that exist in the data
self.norm_min = norm_min # (n_groups, n_windows, n_features): minimum of the training rows of the window
self.norm_max = norm_max # (n_groups, n_windows, n_features)
self.y_min = y_min # (n_groups, n_windows): target range of the training rows of the window
self.y_max = y_max
@property
def final_index(self) -> List[int]:
r"""Per group, the window an operational refit would hold after the last row (-1 if the group is too short)."""
return [len(st) - 1 for st in self.starts]
def _transform_data_adaptive(
data: pd.DataFrame,
features: List[str],
group_col: str,
unique_groups: List,
target_col: str,
update_interval_periods: int,
training_window_periods: int,
steps_per_period: int,
horizon_steps: int = 1,
date_col: Optional[str] = None,
categorical_levels: Optional[Dict[str, int]] = None,
fixed_ranges: Optional[Dict[str, Tuple[float, float]]] = None
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, _AdaptiveWindows]:
r"""
Cuts the data into the windows of a rolling refit, and normalises each window on its own training rows.
A window trains on ``training_window_periods`` periods and forecasts the ``update_interval_periods`` that follow; windows are
anchored on the start of the data (see ``_window_starts``). Every (group, window) is normalised to [-1, 1] with the minimum and
maximum of its own training rows, applied to its training and its forecast rows: this is what ``StaticTAM.fit`` then
``predict`` does on that window. A group that does not hold a full window gets an all-zero placeholder and no forecast.
Args:
data: DataFrame holding only real rows (no balancing fill).
features: Feature list.
group_col: Grouping column.
unique_groups: Group names, in the order of the output tensors.
target_col: Target column.
update_interval_periods: Forecast length, in periods.
training_window_periods: Training length, in periods.
steps_per_period: Rows of one group in a period.
horizon_steps: Horizon of forecasting.
categorical_levels: ``{feature: n_cat}`` of the categorical features: normalised on their full level range.
fixed_ranges: ``{feature: (low, high)}`` of the features read on a fixed domain: every window uses that range.
Returns:
(x_stacked, y_stacked, x_to_predict, windows): (n_groups, n_windows, L, F), (n_groups, n_windows, L, 1),
(n_groups, n_windows, W, F) and the layout of the windows.
"""
if unique_groups is None:
raise ValueError("`unique_groups` cannot be None.")
learning_size_steps = training_window_periods * steps_per_period
window_size_steps = update_interval_periods * steps_per_period
dtype = torch.get_default_dtype()
n_features = len(features)
categorical = categorical_levels or {}
fixed = fixed_ranges or {}
x_all = data[features].to_numpy(dtype=np.float64)
y_all = data[target_col].to_numpy(dtype=np.float64)
group_values = data[group_col].to_numpy()
date_values = data[date_col].to_numpy() if date_col is not None else None
built = []
positions, starts_all, n_valid_all = [], [], []
for group_name in unique_groups:
pos = np.flatnonzero(group_values == group_name)
if date_values is not None:
pos = pos[np.argsort(date_values[pos], kind="stable")]
n = len(pos)
starts = _window_starts(n, learning_size_steps, window_size_steps, horizon_steps)
if n >= learning_size_steps + horizon_steps - 1 and (n - (learning_size_steps + horizon_steps - 1)) % window_size_steps == 0:
starts.append(n) # the window an operational refit holds after the last row; it has no forecast row yet
positions.append(pos)
starts_all.append(starts)
n_valid_all.append([int(min(window_size_steps, max(n - s, 0))) for s in starts])
if not starts:
built.append(None)
continue
s = torch.tensor(starts, dtype=torch.long)
x_g = torch.tensor(x_all[pos], dtype=torch.float64).view(n, n_features)
y_g = torch.tensor(y_all[pos], dtype=torch.float64).view(n, 1)
train_idx = s.view(-1, 1) + torch.arange(-(horizon_steps - 1) - learning_size_steps, -(horizon_steps - 1) if horizon_steps > 1 else 0)
predict_idx = (s.view(-1, 1) + torch.arange(window_size_steps)).clamp(max=n - 1)
x_train = x_g[train_idx] # (n_windows, L, F)
low = x_train.amin(dim=1, keepdim=True)
high = x_train.amax(dim=1, keepdim=True)
for j, name in enumerate(features):
if name in categorical:
n_cat = categorical[name]
integer = (x_train[..., j] == x_train[..., j].round()).all(dim=1, keepdim=True)
start = torch.where(high[..., j] <= n_cat - 1, torch.zeros_like(low[..., j]), low[..., j])
low[..., j] = torch.where(integer, start, low[..., j])
high[..., j] = torch.where(integer, start + (n_cat - 1), high[..., j])
elif name in fixed:
low[..., j], high[..., j] = fixed[name]
amplitude = high - low
amplitude = torch.where(amplitude == 0, torch.ones_like(amplitude), amplitude)
center = (high + low) / 2
y_train = y_g[train_idx]
built.append((
((x_train - center) / (amplitude / 2.0)).to(dtype),
y_train.to(dtype),
((x_g[predict_idx] - center) / (amplitude / 2.0)).to(dtype),
low.squeeze(1), high.squeeze(1), y_train.amin(dim=(1, 2)), y_train.amax(dim=(1, 2)),
))
if all(b is None for b in built):
raise ValueError("No simulation data could be generated. Check dataset length/window sizes.")
n_windows = max(len(st) for st in starts_all)
placeholders = (
torch.zeros(n_windows, learning_size_steps, n_features, dtype=dtype), torch.zeros(n_windows, learning_size_steps, 1, dtype=dtype),
torch.zeros(n_windows, window_size_steps, n_features, dtype=dtype), torch.zeros(n_windows, n_features, dtype=torch.float64),
torch.ones(n_windows, n_features, dtype=torch.float64), torch.zeros(n_windows, dtype=torch.float64), torch.ones(n_windows, dtype=torch.float64),
)
columns = [[] for _ in range(7)]
for entry in built:
for k in range(7):
if entry is None:
columns[k].append(placeholders[k])
continue
tensor = entry[k]
if tensor.shape[0] < n_windows: # a shorter group repeats its last window; the repeats are never read
tensor = torch.cat([tensor, tensor[-1:].expand(n_windows - tensor.shape[0], *tensor.shape[1:])], dim=0)
columns[k].append(tensor)
stacked = [torch.stack(c) for c in columns]
windows = _AdaptiveWindows(positions, starts_all, n_valid_all, stacked[3], stacked[4], stacked[5], stacked[6])
return stacked[0].to(TORCH_DEVICE), stacked[1].to(TORCH_DEVICE), stacked[2].to(TORCH_DEVICE), windows
Dynamic Target and Preparation¶
The prepare_simulation method is executed before launching the online loop. Its role is to massively vectorize the dataset and shift the target space.
Architectural Choice: It calculates the macroscopic predictions (data_pred) and subtracts them from the true target to isolate the residuals (\(\epsilon_t = Y_t - \hat{Y}_{base}\)) upfront. Executing this in a single block across the entire validation history prevents an immense computational bottleneck that would occur if the base model were evaluated repeatedly inside the sequential sliding window loop.
def _link_of_base(self, mean: np.ndarray) -> np.ndarray:
r"""The linear predictor of the base forecast, ``g(mu)``, for the base of a non-Gaussian loss."""
link = torch.as_tensor(np.array(mean, dtype=float), dtype=torch.get_default_dtype())
return self.glm_strategy_.link.link(link).numpy().astype(float)
def _solve_windows(self, phi: torch.Tensor, y: torch.Tensor, x: torch.Tensor, penalty: torch.Tensor,
loss_matrix: torch.Tensor, num_samples: int) -> torch.Tensor:
r"""The coefficients of a batch of windows: the penalized least squares of the residuals, or the reweighted fit on the link scale."""
if self.glm_strategy_ is None:
cov_X, cov_XY = _compute_weighted_covariances(phi, y, loss_matrix)
return solve_linear_system(cov_X, cov_XY, penalty, num_samples)
return batched_reweighted_solve(phi, y, self.adaptive_model_._offset_of(x), self.glm_strategy_, penalty, loss_matrix, num_samples)
def _forecast_windows(self, phi_pred: torch.Tensor, coefficients: torch.Tensor, x_pred: torch.Tensor) -> torch.Tensor:
r"""The correction the windows forecast: a residual, or ``g^-1(offset + Phi theta) - g^-1(offset)`` on the mean scale of a GLM base."""
correction = _predict_from_coeffs(phi_pred, coefficients)
if self.glm_strategy_ is None:
return correction
offset = self.adaptive_model_._offset_of(x_pred).to(device=correction.device, dtype=correction.dtype)
return self.glm_strategy_.inverse_link(correction + offset) - self.glm_strategy_.inverse_link(offset)
def _with_model_target(self, data: pd.DataFrame) -> pd.DataFrame:
r"""Adds the model-scale target column of a distributional base (``__mu__``) when ``data`` holds the target."""
base = self.distributional_base_
if base is None or base.target_col_ not in data.columns:
return data
data = data.copy()
data[_MODEL_TARGET] = base._to_model_scale(data[base.target_col_].to_numpy())
return data
def prepare_simulation(self, data: pd.DataFrame) -> 'AdaptiveTAM':
r"""
Prepares tensors for the adaptive sliding-window simulation.
This process:
1. Computes base model effects (features) and residuals (targets).
2. Normalizes the adaptive features.
3. Constructs sliding-window tensors (X_train, Y_train, X_predict).
Args:
data: The dataset (validation or test) for the simulation.
Returns:
self: The instance with populated ``simulation_data_``.
"""
data = self._with_model_target(data)
if self.base_model_ is not None:
data_bm = self.base_model_.decompose_prediction(data)
data_pred = self.base_model_.predict(data)
target_col_bm = self.base_model_.target_col_
else:
data_bm = data.copy()
data_pred = data.copy()
target_col_bm = self.target_col_
data_bm = _ensure_dummies(data_bm, self.group_col_, self.date_col_)
data_pred = _ensure_dummies(data_pred, self.group_col_, self.date_col_)
est_col_name = f'Estimated{target_col_bm}'
if est_col_name not in data_bm.columns:
data_bm[est_col_name] = data_pred.get(est_col_name, 0.0)
default_res_col = f'Residual{target_col_bm}'
data_bm[default_res_col] = data_bm[target_col_bm] - data_bm[est_col_name]
if self.glm_strategy_ is not None:
# The windows are fitted on the response itself, with the link of the base forecast as the offset.
data_bm[_ETA_BASE] = self._link_of_base(data_bm[est_col_name].to_numpy(dtype=float))
data_bm[self.target_col_] = data_bm[target_col_bm]
adaptive_features_config = self.adaptive_model_.features_config_
if 'features' not in adaptive_features_config or not isinstance(adaptive_features_config['features'], list):
raise KeyError("Invalid feature configuration in adaptive model.")
adaptive_features = adaptive_features_config['features']
required_cols = adaptive_features + [self.group_col_, self.target_col_, self.date_col_]
_check_features(dataset=data_bm, required_features=required_cols)
mask, balanced_data = _balance_groups(
dataset=data_bm, group_col=self.group_col_, date_col=self.date_col_, method="fill"
)
data_info = self.adaptive_model_._get_data_info(balanced_data)
if not self.adaptive_model_.effects_list_ and not self.adaptive_model_.is_grid_search_template_:
self.adaptive_model_.effects_list_ = create_effects_from_parsed_terms(
self.adaptive_model_.parsed_terms_,
token_values={},
default_alpha_p=self.adaptive_model_.default_alpha_p_,
data_info=data_info
)
hw.empty_cache()
# Only real rows are windowed: the rows added to balance the groups never train and are never forecast.
real = mask.to_numpy()
real_data = balanced_data[real]
self.unique_groups_ = sorted(real_data[self.group_col_].unique())
x_stacked, y_stacked, x_to_predict, self.window_layout_ = _transform_data_adaptive(
data=real_data,
features=adaptive_features,
group_col=self.group_col_,
unique_groups=self.unique_groups_,
target_col=self.target_col_,
update_interval_periods=self.update_interval_periods_,
training_window_periods=self.training_window_periods_,
steps_per_period=self.steps_per_period_,
horizon_steps=self.horizon_steps_,
date_col=self.date_col_,
categorical_levels=categorical_ranges(self.adaptive_model_.effects_list_),
fixed_ranges={**_resolve_fixed_ranges(real_data, fixed_ranges(self.adaptive_model_.effects_list_)),
**{name: (-1.0, 1.0) for name in self.adaptive_model_._offset_features_}}
)
# Data-dependent state (spline knots) comes from the training windows, never from a memory probe.
initialize_effects(
x_stacked.reshape(-1, x_stacked.shape[2], x_stacked.shape[3]), self.adaptive_model_.effects_list_,
feature_columns=adaptive_features
)
valid = torch.zeros(x_to_predict.shape[:3], dtype=torch.bool)
for i, counts in enumerate(self.window_layout_.n_valid):
for j, count in enumerate(counts):
valid[i, j, :count] = True
self._warn_extrapolation(x_to_predict.cpu(), valid)
self._warn_unseen_levels(x_stacked.cpu(), x_to_predict.cpu(), valid, real_data)
# Positions in `real_data` -> positions in `balanced_data` (real rows come first when groups are balanced by filling).
real_positions = np.flatnonzero(real)
self.window_layout_.positions = [real_positions[p] for p in self.window_layout_.positions]
self.simulation_data_ = (
x_stacked.cpu(),
y_stacked.cpu(),
x_to_predict.cpu(),
balanced_data, data_bm, target_col_bm, mask
)
del x_stacked, y_stacked, x_to_predict
hw.empty_cache()
return self
Batch Execution and Output¶
In the simulation() method, calculations are not executed step-by-step. The solver must simultaneously resolve the exact local empirical risk minimization problem for all sliding windows across all groups.
Architectural Choice 1: Dimensional Flattening:
The generated tensors naturally possess 4 dimensions (n_groups, n_windows, num_samples, features). The standard Core mathematical solvers (solve_linear_system) are built exclusively for 3D batches (batch, samples, features). Instead of rewriting the core linear algebra module, simulation() flattens the first two dimensions: total_items = n_groups * n_windows. This elegantly maps the massive localized window problem into a standard, independent batch structure, saturating the GPU cores perfectly.
Architectural Choice 2: OOM Resilience:
Because total_items can easily exceed tens of thousands of matrices, the method implements the dynamic hw.handle_oom fallback mechanism. If the GPU VRAM exhausts, it catches the torch.OutOfMemoryError and halves the safe_batch_size iteratively, ensuring the simulation completes gracefully even on constrained hardware.
Architectural Choice 3: No Hidden Clipping:
The forecasts are not clipped by default: a clip to the range of the whole period would use observations after the forecast. clip_to_train_range=True clips each window to the range of the target in the training rows of that same window. Rows no window forecasts stay NaN (the adapted forecast keeps the base forecast), and the rows added to balance the groups are never trained on nor forecast.
def simulation(self) -> pd.DataFrame:
r"""
Executes the sliding-window simulation using scalable batch processing.
It flattens the group and window dimensions to treat each sliding window
as an independent linear system. This strictly preserves the mathematical
regularization scale and prevents VRAM exhaustion when processing deep
historical data across multiple groups.
"""
if self.simulation_data_ is None:
raise RuntimeError("Simulation data is uninitialized. Call 'prepare_simulation()' first.")
if self.adaptive_model_.is_grid_search_template_:
raise RuntimeError("Model contains grid search tokens. Call 'grid_search_fit()' first.")
x_stacked, y_stacked, x_to_predict, balanced_data, data_bm, target_col_bm, mask = self.simulation_data_
n_groups = x_stacked.shape[0]
n_windows = x_stacked.shape[1]
num_samples_train = x_stacked.shape[2]
window_size_steps = x_to_predict.shape[2]
total_items = n_groups * n_windows
x_flat = x_stacked.view(total_items, num_samples_train, -1)
y_flat = y_stacked.view(total_items, num_samples_train, -1)
x_pred_flat = x_to_predict.view(total_items, window_size_steps, -1)
run_device = TORCH_DEVICE
sobolev_matrix = self.adaptive_model_._build_penalty_matrix().to(run_device)
loss_L_star_L = self.adaptive_model_._build_loss_matrix().to(run_device)
dummy_x = x_flat[0:1].to(run_device)
dummy_phi = self.adaptive_model_._build_design_matrix(dummy_x)
n_coeffs = dummy_phi.shape[-1]
del dummy_x, dummy_phi
safe_batch_size = get_safe_window_batch_size(
num_samples_per_window=num_samples_train,
total_d=n_coeffs,
device=run_device
)
safe_batch_size = min(safe_batch_size, total_items)
all_predictions = []
start_idx = 0
while start_idx < total_items:
end_idx = min(start_idx + safe_batch_size, total_items)
try:
batch_x = x_flat[start_idx:end_idx].to(run_device)
batch_y = y_flat[start_idx:end_idx].to(run_device)
batch_x_pred = x_pred_flat[start_idx:end_idx].to(run_device)
phi_batch = self.adaptive_model_._build_design_matrix(batch_x)
coeffs_batch = self._solve_windows(phi_batch, batch_y, batch_x, sobolev_matrix, loss_L_star_L, num_samples_train)
phi_pred_batch = self.adaptive_model_._build_design_matrix(batch_x_pred)
preds_batch = self._forecast_windows(phi_pred_batch, coeffs_batch, batch_x_pred)
all_predictions.append(preds_batch.detach().cpu())
del batch_x, batch_y, batch_x_pred, phi_batch, coeffs_batch, phi_pred_batch, preds_batch
start_idx += safe_batch_size
except (torch.OutOfMemoryError, MemoryError):
safe_batch_size, run_device = hw.handle_oom(
current_batch=safe_batch_size,
device=run_device,
context="adaptive simulation batch reduction",
allow_cpu_fallback=True
)
sobolev_matrix = sobolev_matrix.to(run_device)
loss_L_star_L = loss_L_star_L.to(run_device)
continue
hw.empty_cache()
predictions_flat = torch.cat(all_predictions, dim=0).squeeze(-1)
predictions_cpu = predictions_flat.view(n_groups, n_windows, window_size_steps)
mask = self.simulation_data_[6]
self.predictions_ = _cleanup_dummies(self._forecast_frame(predictions_cpu)[mask], self.group_col_, self.date_col_)
return self.predictions_
Coordinate Descent Search Algorithm¶
The grid_search_fit() method implements the “Multi-Start” hyperparameter solver described in the theory. It evaluates pairs (e.g., training_window_periods, default \(\lambda\)) sequentially, moving along a single axis at a time until local convergence is reached.
Architectural Choice: Because the global objective function evaluated across overlapping sliding windows creates highly non-convex search topologies, standard analytical Generalized Cross-Validation (GCV) breaks down. Coordinate Descent provides robust navigation through these complex spaces. To systematically avoid poor local minima, the algorithm leverages three distinct initialization strategies (Conservative, Median, Aggressive) before executing the cyclic axis search.
def grid_search_fit(
self,
data_val: pd.DataFrame,
grid_search_config: dict
) -> 'AdaptiveTAM':
r"""
Optimizes the adaptive model using Multi-Start Coordinate Descent.
Optimizes hyperparameters to minimize the RMSE of the final
adapted prediction over the simulation period.
Args:
data_val: Validation DataFrame for simulation.
grid_search_config: Dictionary mapping tokens to value lists.
Returns:
AdaptiveTAM: A new fitted model instance.
"""
print("--- Starting Grid Search (Multi-Start Coordinate Descent) ---")
self.prepare_simulation(data_val)
try:
return self._grid_search(data_val, grid_search_config)
finally:
self._free_simulation()
def _grid_search(self, data_val: pd.DataFrame, grid_search_config: dict) -> 'AdaptiveTAM':
search_axes, token_names = self.adaptive_model_._parse_grid_axes(grid_search_config)
data_info = self.adaptive_model_._get_data_info(data_val)
if not token_names:
raise ValueError("No grid tokens found in adaptive formula or config.")
print(f"Optimizing axes: {token_names}")
start_points = [
{"name": "Conservative", "tokens": {t: max(vals) if ('ap' in t or 'lambda_p' in t) else min(vals) for t, vals in search_axes.items()}},
{"name": "Median", "tokens": {t: vals[len(vals)//2] for t, vals in search_axes.items()}},
{"name": "Aggressive", "tokens": {t: min(vals) if ('ap' in t or 'lambda_p' in t) else max(vals) for t, vals in search_axes.items()}}
]
min_global_rmse = float('inf')
optimal_effects_list = None
current_best_tokens_global = None
for strategy in start_points:
print(f"\n=== Strategy: {strategy['name']} Start ===")
current_best_tokens = strategy["tokens"].copy()
try:
start_effects_list = create_effects_from_parsed_terms(
self.adaptive_model_.parsed_terms_,
current_best_tokens,
self.adaptive_model_.default_alpha_p_,
data_info=data_info
)
current_rmse = self._evaluate_adaptive_config(start_effects_list, current_best_tokens)
current_optimal_effects = start_effects_list
except Exception:
continue
if current_rmse >= float('inf'):
continue
print(f" Start RMSE: {current_rmse:.4f}")
cycle = 0
while True:
cycle += 1
has_improved_in_cycle = False
for token_name in token_names:
best_value = current_best_tokens[token_name]
original_val = best_value
for value in search_axes[token_name]:
if value == original_val: continue
tokens_to_test = current_best_tokens.copy()
tokens_to_test[token_name] = value
try:
effects_list = create_effects_from_parsed_terms(
self.adaptive_model_.parsed_terms_,
tokens_to_test,
self.adaptive_model_.default_alpha_p_,
data_info=data_info
)
rmse = self._evaluate_adaptive_config(effects_list, tokens_to_test)
if rmse < current_rmse:
current_rmse = rmse
current_optimal_effects = effects_list
best_value = value
has_improved_in_cycle = True
except Exception:
continue
current_best_tokens[token_name] = best_value
if not has_improved_in_cycle or cycle >= 5: break
if current_rmse < min_global_rmse:
print(f" >>> New Global Best found by {strategy['name']}! ({current_rmse:.4f})")
min_global_rmse = current_rmse
optimal_effects_list = current_optimal_effects
current_best_tokens_global = current_best_tokens
print("-" * 30)
print(f"Grid Search complete. Best RMSE: {min_global_rmse:.4f}")
if optimal_effects_list is None:
raise RuntimeError("Grid search failed.")
print(f"Best tokens: {current_best_tokens_global}")
final_model = AdaptiveTAM(
base_model=self.base_model_,
adaptive_formula=self.adaptive_formula_,
update_interval_periods=self.update_interval_periods_,
training_window_periods=self.training_window_periods_,
steps_per_period=self.steps_per_period_,
horizon_steps=self.horizon_steps_,
clip_to_train_range=self.clip_to_train_range_
)
final_adaptive_model_internal = StaticTAM(
formula=self.adaptive_model_.formula_,
group_col=self.base_model_.group_col_ if self.base_model_ is not None else self.group_col_,
date_col=self.base_model_.date_col_ if self.base_model_ is not None else self.date_col_,
_internal_effects_list=optimal_effects_list,
_internal_features_config=self.adaptive_model_.features_config_
)
final_model.adaptive_model_ = final_adaptive_model_internal
final_model.target_col_ = self.target_col_
final_model.predict_online(data_val)
return final_model
Corrector on the Link Scale of a GLM Base¶
When the base_model is a plain StaticTAM with a non-Gaussian loss (poisson, gamma, binomial, negative_binomial, tweedie), the constructor sets glm_strategy_ to the strategy of the base and appends offset(__eta_base__) to the adaptive formula (see the exposure offset of StaticTAM). prepare_simulation and predict add two columns: __eta_base__, the link of the base forecast, which the offset reads raw (the feature is normalised on (-1, 1) in every window), and the response itself as the target of the windows. The three places that solved a window (simulation, _save_final_state, _evaluate_adaptive_config) go through _solve_windows, which calls batched_reweighted_solve (statistics/estimation/_batched_glm.py): the reweighted loop of StaticTAM on all the windows at once, started at the base (theta = 0), with weights normalised to unit mean per window and a step-halving per window on its penalized deviance. _forecast_windows returns g^-1(offset + Phi theta) - g^-1(offset), so Estimated<target> stays the correction and AdaptedEstimated<target> is the adapted mean. The dispersion of a negative binomial or Tweedie base is the one of the base model. clip_to_train_range is refused for such a base. predict_quantiles of a base with a quantile function (poisson, negative_binomial, tweedie) returns the quantiles of the family at the adapted mean.
def batched_reweighted_solve(
phi: torch.Tensor,
y: torch.Tensor,
offset: torch.Tensor,
strategy: ReweightingStrategy,
penalty_matrix: torch.Tensor,
loss_matrix: torch.Tensor,
num_samples: int,
max_iter: int = 25,
tol: float = 1e-6,
max_halvings: int = 8,
) -> torch.Tensor:
"""Coefficients of every window, shape (n_windows, n_coeffs, 1).
Args:
phi: Design matrices, (n_windows, n_samples, n_coeffs).
y: Responses, (n_windows, n_samples, 1).
offset: Linear predictor of the base model, (n_windows, n_samples, 1).
strategy: The GLM family of the base model.
penalty_matrix: The penalty of the window model.
loss_matrix: The loss matrix of the window model.
num_samples: Rows of a window (the scale of the penalty).
max_iter: Maximum reweighting passes.
tol: Relative change of the linear predictor, in every window, under which the loop stops.
max_halvings: Maximum step-halvings per pass and window.
"""
dtype = phi.dtype
y = y.to(device=phi.device, dtype=dtype)
offset = offset.to(device=phi.device, dtype=dtype)
penalty = penalty_matrix.to(device=phi.device, dtype=dtype)
loss = loss_matrix.to(device=phi.device)
unit_deviance = getattr(strategy, "unit_deviance", None)
def objective(theta: torch.Tensor, eta: torch.Tensor) -> torch.Tensor:
mean = strategy.inverse_link(eta)
data_term = (unit_deviance(y, mean) if unit_deviance is not None else (y - mean) ** 2).mean(dim=(1, 2))
return data_term + (theta.mT @ penalty @ theta).reshape(theta.shape[0])
eta = offset.clone()
theta = None
for _ in range(max_iter):
working_response, weights = strategy.working_response_and_weights(y, eta)
weights = weights / weights.mean(dim=(1, 2), keepdim=True).clamp_min(_TINY)
cov_x, cov_xy = _compute_weighted_covariances(phi, working_response - offset, loss, weights)
candidate = solve_linear_system(cov_x, cov_xy, penalty, num_samples)
eta_candidate = phi @ candidate + offset
if theta is not None:
full_step = candidate
previous = objective(theta, eta)
current = objective(full_step, eta_candidate)
step = torch.ones(theta.shape[0], 1, 1, dtype=dtype, device=phi.device)
for _ in range(max_halvings):
worse = ~torch.isfinite(current) | (current > previous)
if not bool(worse.any()):
break
step = torch.where(worse.view(-1, 1, 1), step * 0.5, step)
candidate = theta + step * (full_step - theta)
eta_candidate = phi @ candidate + offset
current = objective(candidate, eta_candidate)
change = (eta_candidate - eta).flatten(1).norm(dim=1) / eta.flatten(1).norm(dim=1).clamp_min(_TINY)
theta, eta = candidate, eta_candidate
if bool((change < tol).all()):
break
return theta
Online Quantiles from a Distributional Base¶
AdaptiveTAM(base_model=...) also accepts a fitted distributional StaticTAM (a dict formula). The correction is then fitted on the model scale of its location sub-model (the target __mu__, the target after its transform): the constructor redirects the base to that sub-model, maps Residual<target> in adaptive_formula to Residual__mu__, and _with_model_target adds the model-scale column to any frame that holds the target. The forecasts of a plain base are untouched.
predict_quantiles(data, taus) is the probabilistic counterpart of predict_online, so data holds the target. It runs the online simulation, then rescales the scale of the base with _online_scale, a rolling root mean square of the standardized residuals computed per group from cumulative sums (vectorised), and goes back to the response scale with the transform of the base:
def _online_scale(standardized: np.ndarray, group: np.ndarray, order: np.ndarray, window: int, interval: int, horizon: int) -> np.ndarray:
r"""
Rolling root mean square of the standardized residuals, one value per row, using past residuals only.
Rows of a group are taken in the order of ``order``. The first window forecasts the row ``window + horizon - 1`` (zero-based);
from there the scale is renewed every ``interval`` rows, at an origin ``o``, from the finite residuals of the rows
``o - window ... o - horizon``. A row before the first origin, or whose origin has fewer than ``_MIN_RESIDUALS_FOR_SCALE``
finite residuals, gets 1.
Args:
standardized: ``(y - location) / sigma_base`` per row (NaN where unknown).
group: Group label per row.
order: Sort key within a group (the dates).
window: ``training_window_periods``.
interval: ``update_interval_periods``.
horizon: ``horizon_steps``.
Returns:
The scale per row, in the row order of the input.
"""
scale = np.ones(len(standardized))
first = window + horizon - 1
frame = pd.DataFrame({"g": group, "o": order, "pos": np.arange(len(standardized))}).sort_values(["g", "o", "pos"], kind="stable")
for _, rows in frame.groupby("g", sort=False):
positions = rows["pos"].to_numpy()
residual = standardized[positions]
finite = np.isfinite(residual)
squares = np.where(finite, residual ** 2, 0.0)
cum_squares = np.concatenate([[0.0], np.cumsum(squares)])
cum_count = np.concatenate([[0], np.cumsum(finite)])
rank = np.arange(len(positions))
eligible = rank >= first
origin = first + ((rank - first) // interval) * interval
low = np.maximum(origin - window, 0)
high = origin - horizon + 1 # exclusive end of the rows known at the origin
usable = eligible & (high > low)
count = np.where(usable, cum_count[np.clip(high, 0, None)] - cum_count[low], 0)
total = np.where(usable, cum_squares[np.clip(high, 0, None)] - cum_squares[low], 0.0)
enough = usable & (count >= _MIN_RESIDUALS_FOR_SCALE)
scale[positions] = np.where(enough, np.sqrt(total / np.maximum(count, 1)), 1.0)
return scale
def predict_quantiles(self, data: pd.DataFrame, taus: Sequence[float] = (0.05, 0.5, 0.95)) -> pd.DataFrame:
r"""
Online quantile forecasts of a distributional base, the probabilistic counterpart of ``predict_online``.
The adaptive correction moves the location; the scale of the base is kept and rescaled online. At each update of a
group, ``s_t`` is the root mean square of the standardized residuals ``(y - adapted location) / sigma_base`` of the
last ``training_window_periods`` rows that are at least ``horizon_steps`` old, and the quantile of level ``tau`` is
``g^-1(adapted location + s_t * sigma_base * z_tau)`` with ``z_tau`` from the tail family of the base and ``g`` its
target transform. A row before the first window, or without a usable residual, keeps the base scale (``s_t = 1``).
Only past residuals enter ``s_t``: changing a later ``y`` leaves earlier quantiles unchanged.
Like ``predict_online``, ``data`` must hold the target (a backtest over history); the state of the model is
refitted on it.
Args:
data: The rows to forecast, with the target.
taus: Quantile levels in (0, 1).
Returns:
A DataFrame with one ``q<tau>`` column per level, on the rows of ``predict_online(data)``.
Raises:
ValueError: If the base model is not a distributional StaticTAM, or a level is outside (0, 1).
"""
if self.glm_strategy_ is not None:
if not hasattr(self.glm_strategy_, 'quantiles'):
raise ValueError("predict_quantiles needs a base of a count or Tweedie loss (poisson, negative_binomial, tweedie) or a "
"distributional StaticTAM; the loss of this base has no quantile function.")
from .statistics.estimation._count_families import _check_levels
levels = _check_levels(taus)
frame = self.predict_online(data)
adapted = frame[f"AdaptedEstimated{self.base_model_.target_col_}"].to_numpy(dtype=float)
finite = np.isfinite(adapted)
quantiles = np.full((len(adapted), len(levels)), np.nan)
if finite.any(): # a row without forecast stays NaN (the Tweedie inversion would turn a NaN mean into 0)
quantiles[finite] = self.glm_strategy_.quantiles(adapted[finite], levels)
return pd.DataFrame({f"q{tau}": quantiles[:, j] for j, tau in enumerate(levels)}, index=frame.index)
base = self.distributional_base_
if base is None:
raise ValueError("predict_quantiles needs a distributional StaticTAM as base_model (a dict formula, such as "
"{'mu': 'y ~ s(x)', 'sigma': '~ s(x)'}); a plain base has no scale to rescale.")
levels = [float(tau) for tau in taus]
if any(not 0.0 < tau < 1.0 for tau in levels):
raise ValueError(f"taus must lie in (0, 1); got {list(taus)!r}")
from .statistics.estimation import _distributional
frame = self.predict_online(data)
location = frame[f"AdaptedEstimated{_MODEL_TARGET}"].to_numpy(dtype=float)
observed = frame[_MODEL_TARGET].to_numpy(dtype=float)
mu_base, sigma_base = base._mu_sigma(frame)
standardized = (observed - location) / sigma_base
group = frame[self.group_col_].to_numpy() if self.group_col_ in frame.columns else np.zeros(len(frame))
order_key = frame[self.date_col_] if self.date_col_ in frame.columns else pd.Series(np.arange(len(frame)), index=frame.index)
scale = _online_scale(standardized, group, order_key.to_numpy(), self.training_window_periods_,
self.update_interval_periods_, self.horizon_steps_)
columns = {
f"q{tau}": base._from_model_scale(location + scale * sigma_base * _distributional._standardized_ppf(base, tau),
f"the quantile at level {tau} (predict_quantiles)")
for tau in levels
}
return pd.DataFrame(columns, index=frame.index)
The first window forecasts the row training_window_periods + horizon_steps - 1 of a group, and the scale is renewed every update_interval_periods rows; each renewal reads the residuals of the training_window_periods rows that are at least horizon_steps old, so no residual of a later row enters an earlier quantile. A renewal with fewer than five usable residuals keeps the scale of the base. A plain base raises a ValueError.
Separation of Concerns: Simulation vs. Inference¶
To guarantee speed and safety in operational production pipelines, AdaptiveTAM strictly separates the continuous historical simulation from out-of-sample inference.
Architectural Choice (The \(O(1)\) Inference Optimization):
fit(data): Instead of running the massive sliding-window simulation over the entire dataset,fit()leverages the_save_final_state()method. This function slices only the window a refit would hold after the last row (the last window of the schedule, which may not have a forecast row yet), solves the exact Primal linear system for that single step, and freezes the optimal coefficients (last_state_dict_) and that window’s normalisation (norm_params_).predict(data): A purely deterministic, read-only method. It normalises the new data with the frozen window’s minimum and maximum (never with the new data’s own range), builds the design matrix \(\Phi\) and multiplies it directly against the frozen coefficients; this is theStaticTAMfitted on that window. By completely bypassing sliding-window tensorization and system resolution during inference, it guarantees blazing-fast \(O(1)\) execution time and absolute protection against target leakage.