Prior Spectral Effect: PyTorch Architecture & Implementation

Navigation:

Overview & Formula Token

The Prior Spectral effect is exposed in formulas via the pspec() token:

# Univariate Prior Spectral effect with Matern-3/2 prior
formula = "Y ~ pspec(X, k=64, prior='matern', nu=1.5, length_scale=1.0)"

# Empirical periodogram prior estimated on short context
formula = "Y ~ pspec(time, k=32, prior='empirical')"

# Multivariate interaction with spatial covariates
formula = "Y ~ pspec(lat, others='lon', k=64, prior='matern', nu=2.5)"

# Tensor product interaction
formula = "Y ~ te(pspec(X1, k=16), s(X2, k=16))"

Parameter Specification

Parameter

Type

Default

Description

feature_name

str

required

Primary feature column name.

k

int

64

Number of frequencies \(M\). Generates \(2M\) feature columns (\(M\) cosines, \(M\) sines).

prior

str or Callable

'matern'

Spectral prior: 'matern', 'lorentzian', 'empirical', or custom inverse-CDF callable.

nu

float

1.5

Matérn smoothness parameter (\(\nu=0.5\) is Lorentzian/Cauchy).

length_scale

float

1.0

Characteristic length scale \(\ell\).

sobolev_order

float

1.0

Sobolev roughness penalty order \(s\). Weights scale as \((1 + |\omega_m|_2^2)^s\).

qmc

str

'halton'

Low-discrepancy sequence: 'halton', 'sobol', or 'mc'.

seed

int

42

Seed for low-discrepancy sampling.

others

str or list

None

Secondary feature names for multivariate inputs (separated by |).

ap

float

default_alpha_p

Log10 of the regularization parameter \(\lambda_p = 10^{\text{ap}}\).

extrapolate

str

'continue'

OOD behavior beyond \([-1, 1]\) ('continue', 'constant', 'linear').

Complexity & Performance

  • Memory Complexity: The feature map requires \(\mathcal{O}(T \cdot 2M)\) floats. The diagonal penalty matrix requires \(\mathcal{O}(2M)\) non-zero storage.

  • Compute Complexity: Feature map evaluation executes in \(\mathcal{O}(T \cdot M \cdot d)\) via single tensor matrix multiplication on CPU or GPU.

  • Solver Invariance: Solved directly within TAM’s closed-form \(\mathcal{O}(T D^2)\) P-WLS step, fully compatible with GCV and REML tuning.

State, Complexity and Limits

  • Class and file: PriorSpectralEffect, src/tam/model/spectrum/_prior_spectral.py. Label: (BETA).

  • State: none. Layout: any shape; (B, T, d) with others=. Time and memory: \(\mathcal{O}(B\,T\,k\,d)\).

  • Frozen at initialization: the frequencies (for prior='empirical' from the periodogram of the training values, groups concatenated).

  • Extrapolation: all modes of the router are available.

  • Limits: the empirical periodogram of concatenated groups sees the junctions between groups as discontinuities; for panels with very different series give the prior explicitly.

Code

Feature map of PriorSpectralEffect (build_feature_map):

    def build_feature_map(self, x_col: torch.Tensor) -> torch.Tensor:
        """Builds explicit Cosine/Sine Random Fourier Feature map scaled by 1/sqrt(M)."""
        if (
            isinstance(self.prior, str)
            and self.prior.lower() == "empirical"
            and not self._is_initialized
        ):
            self.initialize(x_col)
        d = len(self.required_features)
        self.frequencies = self._align_device(x_col, self.frequencies)

        if self.multi_input:
            if x_col.shape[-1] != d:
                x_expanded = x_col.unsqueeze(-1)
            else:
                x_expanded = x_col
        else:
            if x_col.dim() == 1:
                x_expanded = x_col.unsqueeze(-1)
            elif x_col.dim() == 2:
                x_expanded = x_col.unsqueeze(-1)
            elif x_col.shape[-1] != d:
                x_expanded = x_col.unsqueeze(-1)
            else:
                x_expanded = x_col

        freqs = self.frequencies.to(device=x_col.device, dtype=x_col.dtype)
        theta = torch.matmul(x_expanded, freqs.T)

        cos_features = torch.cos(theta)
        sin_features = torch.sin(theta)
        phi = torch.cat([cos_features, sin_features], dim=-1)

        scale = 1.0 / math.sqrt(self.m_freqs)
        return phi * scale

Penalty of PriorSpectralEffect (build_penalty_matrix):

    def build_penalty_matrix(self) -> torch.Tensor:
        """Builds diagonal Sobolev penalty matrix (1 + ||omega_m||^2)^s."""
        freqs = self.frequencies.to(device=TORCH_DEVICE, dtype=torch.get_default_dtype())
        squared_norms = torch.sum(freqs ** 2, dim=-1)
        gamma = (1.0 + squared_norms) ** self.sobolev_order
        diag = self.lambda_p * torch.cat([gamma, gamma])
        return torch.diag(diag)

Parsing of the pspec(...) token in the factory:

        elif ttype in ('pspec', 'bochner', 'prior_spectral'):
            k = int(params_resolved.get('k', params_resolved.get('m', 64)))
            prior = params_resolved.get('prior', 'matern')
            nu = float(params_resolved.get('nu', 1.5))
            length_scale = float(params_resolved.get('length_scale', params_resolved.get('ell', 1.0)))
            sobolev_order = float(params_resolved.get('sobolev_order', params_resolved.get('s', 1.0)))
            qmc = str(params_resolved.get('qmc', 'halton'))
            seed = int(params_resolved.get('seed', 42))
            extrap_val = params_resolved.get('extrapolate', 'continue')

            additional_features = _parse_additional_features(params_resolved)

            effects_list.append(PriorSpectralEffect(
                feature_name=feature_name,
                k=k,
                prior=prior,
                nu=nu,
                length_scale=length_scale,
                sobolev_order=sobolev_order,
                qmc=qmc,
                seed=seed,
                lambda_p=lambda_p,
                extrapolate=extrap_val,
                additional_features=additional_features
            ))