Bispectrum Effect: PyTorch Architecture & Implementation¶
Navigation:
Mathematical Theory: See BISPECTRUM.md
Spectrum API Overview: See The Spectrum API
Overview & Formula Token¶
The Bispectrum effect is exposed in formulas via the bispec() token:
# Default bispectrum with K=8 canonical triads
formula = "Load ~ f(Hour, m=12) + bispec(Hour, k=8)"
# Custom FFT window length and higher Sobolev order
formula = "Load ~ bispec(Hour, k=12, n_fft=128, s=2.0)"
# Explicit triads from a diagnostic pre-screening are given to the class (a formula cannot hold a list of pairs):
# BispectrumEffect("Hour", triads=[(12, 18), (6, 12)], n_fft=128)
# Interaction with ambient temperature via tensor product
formula = "Load ~ te(bispec(Hour, k=4), s(Temperature, k=8))"
Diagnostic Pre-Screening: Hinich Bispectrum Test¶
The module provides an automated diagnostic tool to detect quadratic phase coupling (QPC), test Gaussianity, and select top coupled frequency triads:
from tam.model.diagnostics import hinich_bispectrum_test
# Analyze series with Welch-averaged bicoherence
diag = hinich_bispectrum_test(
data["Load"].values,
n_fft=128,
overlap=0.5,
top_k=8,
)
print(f"Gaussianity p-value: {diag['p_value_gaussianity']:.4e} (Is Gaussian: {diag['is_gaussian']})")
print(f"Linearity IQR: {diag['linearity_iqr']:.4f}")
# Extract top coupled triads
top_triads = diag["top_triads"]
for t in top_triads:
print(f"Coupled: (k1={t['k1']}, k2={t['k2']}) -> k3={t['k3']}, b^2={t['bicoherence']:.3f}")
Parameter Specification¶
Parameter |
Type |
Default |
Description |
|---|---|---|---|
|
|
required |
Primary feature column name. |
|
|
|
Number of coupled frequency triads (\(4K\) primal columns). |
|
|
|
Window length for FFT segmentation and discrete frequency scaling ( |
|
|
|
Exponent of the bi-frequency Sobolev penalty \((1 + \sum \omega_i^2)^s\). |
|
|
|
Optional sequence of discrete harmonic pairs \((k_1, k_2)\) or diagnostic dicts. |
|
|
|
Optional bicoherence weights \(b^2\) for the specified triads. |
|
|
|
Log10 of the regularization parameter \(\lambda_p = 10^{\text{ap}}\). |
|
|
|
OOD extrapolation strategy beyond \([-1, 1]\). |
Complexity & Performance¶
Memory Complexity: The feature map requires \(\mathcal{O}(T \cdot 4K)\) floats, identical in memory footprint to standard Fourier features.
Compute Complexity: Evaluated by short-time convolutions in \(\mathcal{O}(B\,T\,n_{\text{fft}}\,F)\) operations (\(F\) distinct frequencies); the effect carries the last \(n_{\text{fft}}-1\) samples as its state (see the state section).
Penalty Matrix: Diagonal \(4K \times 4K\) matrix with \(\mathcal{O}(K)\) non-zero entries, adding zero fill-in overhead to the Primal normal equations.
Hardware Acceleration: Full compatibility with mixed-precision, float32/float64, and chunked Cholesky/QR solvers.
State, Complexity and Limits¶
Class and file:
BispectrumEffect,src/tam/model/spectrum/_bispectrum.py. Label: (BETA).State:
{"hist": (B, n_fft - 1, 1)}. Layout:(B, T); one column only (others=is refused).Columns:
4 k, four per triad: \(\operatorname{Re}B/s\), \(\operatorname{Im}B/s\), \(|z_1z_2|/s_a\) and the cosine of the biphase; their scales are frozen at initialization. With the default triads and noise the design has full column rank.Time and memory: \(\mathcal{O}(B\,T\,n_{\text{fft}}\,F)\) for the convolutions (\(F\) = number of distinct frequencies of the triads), \(\mathcal{O}(B\,T\,k)\) for the columns.
Extrapolation:
'linear'and'saturation'are refused at construction.Limits: the window is \(n_{\text{fft}}\) samples long (alias
window), so a triad needs a series much longer than that; the first \(n_{\text{fft}}\) steps of a pass without a state read replicated history.Smoothing weight: in a formula
bispec(x)starts fromap = -5(log10 of the weight), the value the benchmarks use, instead of the model default of-9; an explicitap=wins. The columns of a very smooth series (a seasonal and a diurnal sinusoid with little noise) are nearly collinear (condition number of the Gram matrix up to 1e7), and with the default-9the unpenalised solve amplified small differences between the training and the test chunk: on such a frame the test RMSE was about 90 times that of the spline-only baseline (388.6 against 4.3; 146 withap=-5, 6.5 withap=-1).auto_fittunesap;-5is the value used in the benchmarks, not an optimum.Short groups:
initializewarns (UserWarning) when the window is longer than the shortest training group: no window ever fills and the columns come from zero-padded start-ups (the smoke frame of 40 rows per group with the default window of 128 gave a test RMSE of 4437 for this reason). The warning is raised atinitializeonly; a short chunk continued withcontinue_state=Truecarries its history and is valid.Benchmark note: on the national load benchmark the effect shows no static gain (the 2026-11-14 retest: static test +1.4 % against the spline reference, adaptive test +0.5 %). No gain was measured on national load, static or adaptive; the effect ships as BETA for other series and for Opera pools.
Chunk equivalence bound:
tests/spectrum/test_stateful_contract.pychecks that the second of two chunks, started from the state of the first, equals the matching rows of the one-pass features withinatol=1e-8(float64), and that every group computed alone equals the same group inside a batch withinatol=1e-10.
Code¶
Feature map of BispectrumEffect (build_feature_map):
def build_feature_map(self, x_col: torch.Tensor, state_in: Optional[Dict[str, Any]] = None) -> torch.Tensor:
r"""Builds the causal bispectral columns: ``(B, T)`` in, ``(B, T, 4 k)`` out; the state is the last ``n_fft - 1`` samples."""
x3, shape, layout = to_btd(x_col, False)
if x3.shape[-1] != 1:
raise ValueError(f"bispec reads one column, got {x3.shape[-1]}")
if self._scales is None:
self.initialize(x_col)
T = x3.shape[1]
x_hist = causal_history(x3, self._n_hist, state_in)
self._state_out = {"hist": tail_state(x_hist, self._n_hist)}
re, im, a, b, _ = self._components(x_hist, T)
scales = self._scales.to(device=x3.device, dtype=x3.dtype)
cols = []
for j in range(self.k):
s_bis, s_a, eps = scales[j, 0], scales[j, 1], scales[j, 2]
real_norm = re[j] / s_bis # (B, T)
imag_norm = im[j] / s_bis # (B, T)
pair_amp_norm = a[j] / s_a # (B, T)
cos_biphase = re[j] / (a[j] * b[j] + eps) # (B, T)
cols.extend([real_norm, imag_norm, pair_amp_norm, cos_biphase])
return from_btk(torch.stack(cols, dim=-1), shape, layout)
Penalty of BispectrumEffect (build_penalty_matrix):
def build_penalty_matrix(self) -> torch.Tensor:
r"""Constructs the diagonal Sobolev-bicoherence penalty matrix."""
weights = []
eps_b = 1e-4
for j, (k1, k2) in enumerate(self.triads):
k3 = k1 + k2
omega1 = 2.0 * math.pi * float(k1) / self.n_fft
omega2 = 2.0 * math.pi * float(k2) / self.n_fft
omega3 = 2.0 * math.pi * float(k3) / self.n_fft
sobolev_energy = 1.0 + (omega1**2 + omega2**2 + omega3**2) ** self.s
b2 = max(self.bicoherences[j] if j < len(self.bicoherences) else 1.0, eps_b)
triad_weight = self.lambda_p * (sobolev_energy / b2)
# 4 identical diagonal weights for the 4 quadrature columns
weights.extend([triad_weight] * 4)
diag_tensor = torch.tensor(weights, device=TORCH_DEVICE, dtype=torch.get_default_dtype())
return torch.diag(diag_tensor)
Parsing of the bispec(...) token in the factory:
elif ttype == 'bispec':
if 'ap' not in params_resolved:
# The columns of a smooth series are nearly collinear: the model default (a very small weight) lets the coefficients blow up
# out of sample, so this effect starts from the weight the benchmarks use (log10 of the weight: minus five); an explicit `ap=` still wins.
lambda_p = 10 ** _BISPEC_DEFAULT_AP
k = int(params_resolved.get('k', params_resolved.get('m', 8)))
if 'n_fft' in params_resolved and 'window' in params_resolved:
if int(params_resolved['n_fft']) != int(params_resolved['window']):
raise ValueError(
f"Conflicting 'n_fft' ({params_resolved['n_fft']}) and 'window' "
f"({params_resolved['window']}) in bispec()."
)
n_fft = int(params_resolved.get('n_fft', params_resolved.get('window', 128)))
sobolev_order = float(params_resolved.get('sobolev_order', params_resolved.get('s', 1.0)))
triads = params_resolved.get('triads', None)
bicoherences = params_resolved.get('bicoherences', None)
extrap_val = params_resolved.get('extrapolate', 'continue')
additional_features = _parse_additional_features(params_resolved)
effects_list.append(BispectrumEffect(
feature_name=feature_name,
k=k,
n_fft=n_fft,
sobolev_order=sobolev_order,
triads=triads,
bicoherences=bicoherences,
lambda_p=lambda_p,
extrapolate=extrap_val,
additional_features=additional_features,
))