Form B Temporal Operators: PyTorch Architecture¶
Navigation:
Mathematical Theory: See TEMPORAL_OPERATOR.md
Spectrum API Overview: See The Spectrum API
Overview & Formula Tokens¶
Form B Temporal Operators wrap an inner functional basis ('spline', 'fourier', or 'linear') and apply a causal time-mixing operator directly to the evaluated inner basis matrix \(\Phi_{\text{base}}\):
# Causal exponential attention operator over B-spline basis
formula = "Y ~ op_attn(temperature, inner='spline', k_base=6, decay=0.92)"
# Causal Legendre HiPPO operator over Fourier or B-spline basis
formula = "Y ~ op_hippo(Load_d1, inner='spline', k_base=6)"
# Causal Hankel SSA operator over B-spline basis
formula = "Y ~ op_ssa(Load_d1, inner='spline', k_base=6, window=12)"
# Stateful out-of-sample boundary continuation
preds = model.predict(df_test, continue_state=True)
Parameter Specification¶
Parameter |
Type |
Default |
Description |
|---|---|---|---|
|
|
|
Operator type: |
|
|
|
Inner basis family: |
|
|
|
Inner basis dimension \(K\). |
|
|
|
Exponential decay factor \(\gamma \in (0, 1)\) for |
|
|
|
Trailing Hankel window length for |
Complexity & Performance¶
End-to-End Statefulness:
StaticTAMcaches_effect_states_after fitting and passesstate_inintoTemporalOperatorEffectwhenpredict(..., continue_state=True)is called.Penalty Preservation: Reuses the exact \(K \times K\) inner penalty matrix \(P_{\text{base}}\) (e.g., \(D_2^\top D_2\) for splines), keeping the normal equations \(\mathcal{O}(T K^2)\).
State, Complexity and Limits¶
Class and file:
TemporalOperatorEffect,src/tam/model/spectrum/_temporal_operator.py. Label: (BETA).State (
stateful):attn{"S": (B, m, K), "Z": (B, m)},hippo{"h": (B, K)},ssa{"hist": (B, L - 1, K)}.Layout:
(B, T, d)(keeps_feature_dim);(T,)is one series. Only the first column feeds the inner basis;others=columns are read (they enterextrapolating_features) but not used by the three operators.Time and memory: \(\mathcal{O}(B\,T\,m\,K)\) for
attn, \(\mathcal{O}(B\,T\,K)\) forhippo, \(\mathcal{O}(B\,T\,L\,K)\) forssa; no \(T \times T\) matrix. Fifty thousand steps run in a few seconds.Penalty coordinates:
baseandop.Extrapolation:
'linear'and'saturation'are refused at construction; the inner basis is pointwise and keeps its own rule.Smoothing criterion: the effect has several penalty coordinates (see above). Prefer
auto_fit(criterion="reml")to the default coordinate GCV. Signature:auto_fit(self, data_train, alpha_p_bounds=(-30.0, 6.0), number_of_steps=10, alpha_p_list=None, gamma=1.4, verbose=False, criterion="gcv"). This is a recommendation, not a measured result for this effect: the repository’s REML tests check the analytic gradient, the penalty basis of the multi-coordinate effects and that REML is more stable than GCV on autocorrelated noise (test_reml_criterion); no benchmark compares the two criteria on this effect.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 TemporalOperatorEffect (build_feature_map):
def build_feature_map(
self,
x_col: torch.Tensor,
state_in: Optional[Dict[str, Any]] = None,
) -> torch.Tensor:
"""``(B, T, d)`` in, ``(B, T, 2 K)`` out: the inner basis and its causal temporal mix, one group at a time.
Every operator is a linear recurrence along time (``attn``, ``hippo``) or a window over a carried history (``ssa``):
time and memory are linear in ``T``. The state is per group: ``{"S", "Z"}`` (attn), ``{"h"}`` (hippo), ``{"hist"}`` (ssa).
"""
x3, shape, layout = to_btd(x_col, True)
phi_base = self._eval_inner_basis(x3) # (B, T, K_inner)
B, T, K = phi_base.shape
dtype = phi_base.dtype
device = phi_base.device
def carried(key: str, expected: tuple) -> Optional[torch.Tensor]:
"""The carried state ``key`` when it is there and has the expected shape, else None."""
if state_in is None or key not in state_in:
return None
s = state_in[key].to(device=device, dtype=dtype)
if tuple(s.shape) != expected:
raise ValueError(f"state '{key}' has shape {tuple(s.shape)}, expected {expected}: continue_state needs the same groups and features as training")
return s
if self.operator_type == "attn":
proj_w = self._proj_w.to(device=device, dtype=dtype) # (K, M)
# Bounded positive random features phi_rf(u) = exp(u @ W - ||u||^2 / 2)
u_norm = torch.clamp(phi_base, -4.0, 4.0)
proj = u_norm @ proj_w # (B, T, M)
norm_sq = 0.5 * torch.sum(u_norm * u_norm, dim=-1, keepdim=True) / max(float(K), 1.0)
phi_rf = torch.exp(torch.clamp(proj - norm_sq, min=-10.0, max=6.0)) # (B, T, M)
# Causal discounted prefix accumulators (the random-feature products and their normalizer), solved as linear recurrences along time
M = self.n_random_features
S_prev = carried("S", (B, M, K))
Z_prev = carried("Z", (B, M))
kv_outer = torch.einsum("btm,btk->btmk", phi_rf, phi_base) # (B, T, M, K)
S_seq = causal_linear_recurrence(
kv_outer.reshape(B, T, M * K), self.decay, 1.0 - self.decay, None if S_prev is None else S_prev.reshape(B, M * K)
).reshape(B, T, M, K)
Z_seq = causal_linear_recurrence(phi_rf, self.decay, 1.0 - self.decay, Z_prev)
num = torch.einsum("btm,btmk->btk", phi_rf, S_seq)
den = torch.clamp(torch.einsum("btm,btm->bt", phi_rf, Z_seq).unsqueeze(-1), min=1e-8)
phi_mixed = num / den
self._state_out = {"S": S_seq[:, -1].detach().clone(), "Z": Z_seq[:, -1].detach().clone()}
elif self.operator_type == "hippo":
gammas = self._hippo_gammas.to(device=device, dtype=dtype) # (K,)
h_prev = carried("h", (B, K))
if h_prev is None:
h_prev = phi_base[:, 0, :].clone()
phi_mixed = causal_linear_recurrence(phi_base, gammas, 1.0 - gammas, h_prev)
self._state_out = {"h": phi_mixed[:, -1].detach().clone()}
else: # operator_type == "ssa"
W = self.window
w_ssa = self._ssa_weights.to(device=device, dtype=dtype) # (W,)
x_hist = causal_history(phi_base, W - 1, state_in, key="hist")
windows = causal_window_unfold(x_hist, W, t_len=T) # (B, T, W, K), oldest step first
phi_mixed = torch.einsum("btwk,w->btk", torch.flip(windows, dims=[2]), w_ssa) # lag 0 weighs w_ssa[0]
self._state_out = {"hist": tail_state(x_hist, W - 1)}
out = torch.cat([phi_base, phi_mixed], dim=-1) # (B, T, 2*K)
return from_btk(out, shape, layout)
Penalty of TemporalOperatorEffect (build_penalty_matrix):
def build_penalty_matrix(self) -> torch.Tensor:
"""Penalty matrix of the effect, scaled by its smoothing weights (see the class docstring)."""
lam_base, lam_op = self.penalty_coordinates()
P_base = self._inner_penalty(lam_base)
P_op = self._inner_penalty(lam_op)
K = self.k_inner
dtype = P_base.dtype
device = P_base.device
P = torch.zeros((2 * K, 2 * K), dtype=dtype, device=device)
P[:K, :K] = P_base
# Slightly stronger regularization on temporal operator channels
P[K:, K:] = P_op + lam_op * torch.eye(K, dtype=dtype, device=device)
return P
Parsing of the op_attn / op_hippo / op_ssa(...) token in the factory:
elif ttype in ('temp_op', 'op_attn', 'op_hippo', 'op_ssa'):
default_op = ttype.split('_')[1] if ttype.startswith('op_') else 'attn'
op_type = str(params_resolved.get('op', params_resolved.get('operator_type', default_op))).lower()
inner_basis = str(params_resolved.get('inner', params_resolved.get('inner_basis', 'spline'))).lower()
k_base = int(params_resolved.get('k_base', params_resolved.get('k', 8)))
decay = float(params_resolved.get('decay', 0.92))
n_rf = int(params_resolved.get('n_random_features', params_resolved.get('m', 8)))
window = int(params_resolved.get('window', 12))
seed = int(params_resolved.get('seed', 42))
extrap_val = params_resolved.get('extrapolate', 'continue')
additional_features = _parse_additional_features(params_resolved)
effects_list.append(TemporalOperatorEffect(
feature_name=feature_name,
operator_type=op_type,
inner_basis=inner_basis,
k_base=k_base,
decay=decay,
n_random_features=n_rf,
window=window,
lambda_p=lambda_p,
seed=seed,
extrapolate=extrap_val,
additional_features=additional_features,
))