Kalman TorchScript Optimizations & Block Updates [BETA]

🚧 Beta – Research Module

⚠️ Status: Active development

  • Core functionality is implemented but still evolving

  • Some features may be incomplete or subject to change

  • API is not yet stable

  • Intended for research use only (not production-ready)

Navigation:

Causal scaling (verified by tests/test_kalman_causal.py): KalmanTAM.prepare_data computes the tracked features, then _fit_reference fixes the feature normalisation (fitted by the internal StaticTAM extractor on the reference rows only) and stores the target centre and scale per group (scale_dict_ for predict()); _design builds the design matrix with that normalisation. The reference is the first calibration_steps rows of each group (burn-in message, calibration_steps_used_) or calibration_data. block_size=None means 1, the exact sequential filter. The TorchScript kernel returns the state after the last update (final_state_), which fit stores as last_state_dict_ for predict().

Process noise per term (verified by tests/test_kalman_per_term_noise.py): the TorchScript kernel takes the diagonal of \(Q\) as a tensor (process_noise_diag, one variance per design column) instead of a scalar. KalmanTAM._term_spans maps each formula term (the names of decomposition_names, plus "offset" for the two constant columns: the filter’s systematic offset and the formula’s intercept) to its design columns, and _noise_diagonal fills the diagonal from process_noise_var (a float, or a dict {term: q, "offset": q, "default": q}). The boost on the offset’s noise (offset_q_boost) is offset_boost unless the offset has a variance of its own; the initial covariance of the offset keeps offset_boost. A float call builds the same diagonal as before, so its forecasts are unchanged.

Base-model components (verified by tests/test_base_effect_columns.py): with add_base_effects=True, one l(effect_<name>) term per base-model component is appended to the Kalman formula, with the column names decompose_prediction emits (decomposition_names()).

Missing targets (verified by tests/test_kalman_missing_target.py): a row whose target is NaN brings no information: its innovation is zero and its regressors are zeroed in the gain and in the covariance update, so the state mean is untouched, the covariance is not contracted, and a block that holds missing rows gives the exact update on its observed rows. The process noise is still added for every step, observed or not, and the forecast and its variance keep the full regressors (a missing target is not a missing forecast).

Predictive quantiles

The compiled loop can also return the predictive variance of every forecast row (with_variance, off by default: the filter and its outputs are then identical to before). Per block it adds one batched product X P Xᵀ on the a priori covariance, and for horizon_steps > 1 the covariance of the delayed state grown by (h - 1) Q, written at the row it forecasts. _run_filter keeps it in _predictive_variance_; _online is the former body of predict_online, which now calls it, and predict_quantiles converts the standard deviation to the target scale with the reference scale and adds z_tau standard deviations to the online forecast:

src/tam/model/kalman.py (Gaussian quantiles from the filter variance)
    def predict_quantiles(self, data: pd.DataFrame, taus: Sequence[float] = (0.05, 0.5, 0.95)) -> pd.DataFrame:
        r"""
        Gaussian quantiles of the online forecast, from the predictive variance of the filter.

        The forecast of a row is Gaussian with the mean of ``predict_online`` and the variance ``x' P x + R`` (``P`` the covariance
        of the state that forecasts the row, ``R`` the observation noise; for ``horizon_steps > 1`` the covariance of the delayed
        state grown by the process noise of the delay), converted back to the target scale. Like ``predict_online``, ``data`` must
        hold the target and the state of the model is refitted on it. The variance is a function of the design and the noise
        parameters only, so a later target never moves an earlier quantile.

        The intervals are as calibrated as ``observation_noise_var`` and ``process_noise_var`` are (``tune_hyperparameters``
        sets them). A row without a target does not move the state but still shrinks the covariance, as in the filter.

        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 a level is outside (0, 1).
        """
        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}")
        frame = self._online(data, with_variance=True)
        mean = frame[f"KalmanAdapted_{self.target_col_}"].to_numpy(dtype=float)
        sd = frame["__sd__"].to_numpy(dtype=float)
        return pd.DataFrame({f"q{tau}": mean + sd * stats.norm.ppf(tau) for tau in levels}, index=frame.index)

The constructor and the outputs of predict_online, predict and fit are unchanged. One limit of the filter carries over: a row without a target leaves the state unchanged but still reduces the covariance, so the variance after a long gap of missing targets is understated.