Transformer FAVOR+ Attention Effect: PyTorch Architecture & Implementation

Navigation:

Overview & Formula Token

The Transformer attention effect is exposed in formulas via the attn() token:

# Univariate causal multi-head self-attention
formula = "Y ~ attn(Load_yesterday, m_features=16, n_heads=4)"

# Multi-scale causal decay with custom decay rates
formula = "Y ~ attn(Temperature, m_features=16, n_heads=3, decay=(1.0, 0.95, 0.80))"

# Multivariate interaction using others
formula = "Y ~ attn(Load_yesterday, others='Temperature|NetLoad', m_features=32, n_heads=4)"

# Tensor product interaction with spline
formula = "Y ~ te(attn(Load_yesterday, m_features=16, n_heads=2), s(Temperature, k=8))"

Parameter Specification

Parameter

Type

Default

Description

feature_name

str

required

Primary feature column name.

m_features

int

16

Number of positive random features \(m\).

n_heads

int

4

Number of multi-scale attention heads \(H\).

causal

bool

True

Whether attention is strictly causal (\(\tau \le t\)).

decay

tuple[float]

(1.0, 0.99, 0.95, 0.85)

Exponential memory decay rates \(\gamma_h \in (0, 1]\) per head.

mode

str

'head'

Output representation: 'head' (\(\mathbb{R}^{T \times (H \cdot d)}\)) or 'bilinear' (\(\mathbb{R}^{T \times (m \cdot d)}\)).

orthogonal

bool

True

Whether to use Orthogonal Random Features (ORF) via Mezzadri QR for variance reduction.

seed

int

42

Deterministic PRNG seed for the random projection matrix.

others

str / list[str]

None

Pipe-delimited or list of additional multivariate feature columns.

k

int

None

Total coefficient budget (\(H \cdot d\)). Overrides n_heads if provided.

ap

float

default_alpha_p

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

extrapolate

str

'continue'

OOD extrapolation strategy beyond \([-1, 1]\).

Complexity & Performance

  • Memory Complexity: The feature map requires \(\mathcal{O}(T \cdot H \cdot d)\) floats in 'head' mode. No \(T \times T\) attention matrix is ever materialized.

  • Compute Complexity: Feature map evaluation executes in strictly linear time \(\mathcal{O}(T \cdot m \cdot d)\). For heads with \(\gamma = 1.0\), evaluation uses a single vectorized torch.cumsum in \(\approx 5\text{ ms}\) for \(T = 5000\).

  • Orthogonal Random Features: Uses Mezzadri QR phase correction on Gaussian blocks with \(\sqrt{d}\) norm scaling, achieving lower empirical variance than independent random Fourier features while maintaining unbiasedness.

State, Complexity and Limits

  • Class and file: TransformerEffect, src/tam/model/spectrum/_transformer.py; formula token attn(). Label: (BETA).

  • State (causal form): {"S": (B, H, m, d), "Z": (B, H, m)}; none for causal=False.

  • Layout: (B, T) for one column, (B, T, d) with others=.

  • Time and memory: \(\mathcal{O}(B\,H\,T\,m\,d)\) for the features and the recurrences; no \(T \times T\) matrix.

  • Penalty: in head mode \(\lambda\operatorname{diag}(1 + h) \otimes I_d\); the per-head projections differ but share these penalty weights. In bilinear mode \(\lambda(1 + \|\omega_j\|^2)\otimes I_d\) with the first head’s projection.

  • Extrapolation: 'linear' and 'saturation' are refused at construction for the causal form.

  • Chunk equivalence bound: tests/spectrum/test_stateful_contract.py checks that the second of two chunks, started from the state of the first, equals the matching rows of the one-pass features within atol=1e-8 (float64), and that every group computed alone equals the same group inside a batch within atol=1e-10.

Code

Feature map of TransformerEffect (build_feature_map):

    def build_feature_map(self, x_col: torch.Tensor, state_in: Optional[Dict[str, Any]] = None) -> torch.Tensor:
        """Builds explicit linearized attention Primal basis matrix: ``(B, T)`` or ``(B, T, d)`` in, ``(B, T, out)`` out."""
        x3, shape, layout = to_btd(x_col, self.multi_input)
        B, _, d_in = x3.shape
        if d_in != len(self.input_features):
            raise ValueError(f"attn expects {len(self.input_features)} input column(s), got {d_in}")
        init_m = init_z = None
        if self.causal and state_in is not None and "S" in state_in and "Z" in state_in:
            init_m = state_in["S"].to(device=x3.device, dtype=x3.dtype)
            init_z = state_in["Z"].to(device=x3.device, dtype=x3.dtype)
            expected = (B, self.n_heads, self.m_features, d_in)
            if tuple(init_m.shape) != expected or tuple(init_z.shape) != expected[:3]:
                raise ValueError(f"state 'S' has shape {tuple(init_m.shape)}, expected {expected}: continue_state needs the same groups and features as training")
        states, term_m, term_z = self._compute_attention_context(x3, initial_m=init_m, initial_z=init_z)
        if self.causal:
            self._state_out = {"S": term_m.detach().clone(), "Z": term_z.detach().clone()}
        return from_btk(states, shape, layout)

Penalty of TransformerEffect (build_penalty_matrix):

    def build_penalty_matrix(self) -> torch.Tensor:
        r"""Builds strictly positive-definite Ridge penalty matrix :math:`P_{\text{attn}}`."""
        d_in = len(self.input_features)

        if self.mode == "head":
            # Diagonal head decay penalty: (1 + h) (x) I_d
            h_idx = torch.arange(
                1, self.n_heads + 1, device=TORCH_DEVICE, dtype=torch.get_default_dtype()
            )
            head_weights = torch.repeat_interleave(h_idx, d_in)
            diag = self.lambda_p * head_weights
            return torch.diag(diag)

        # Bilinear mode: (1 + ||\omega_j||^2) (x) I_d
        weights = self._get_weights(d_in)          # the first head's projection
        omega_norms_sq = torch.sum(weights * weights, dim=-1)
        rff_weights = torch.repeat_interleave(1.0 + omega_norms_sq, d_in)
        diag = self.lambda_p * rff_weights.to(
            device=TORCH_DEVICE, dtype=torch.get_default_dtype()
        )
        return torch.diag(diag)

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

        elif ttype in ('attn', 'transformer', 'favor_plus', 'performer'):
            m_features = int(params_resolved.get('m_features', 16))
            n_heads = int(params_resolved.get('n_heads', 4))
            causal_raw = params_resolved.get('causal', True)
            causal = _as_bool(causal_raw)
            decay = params_resolved.get('decay', (1.0, 0.99, 0.95, 0.85))
            mode = str(params_resolved.get('mode', 'head')).lower().strip()
            orth_raw = params_resolved.get('orthogonal', True)
            orthogonal = _as_bool(orth_raw)
            seed = int(params_resolved.get('seed', 42))
            extrap_val = params_resolved.get('extrapolate', 'continue')
            k = int(params_resolved['k']) if ('k' in params_resolved and params_resolved['k'] is not None) else None

            additional_features = _parse_additional_features(params_resolved)

            effects_list.append(TransformerEffect(
                feature_name=feature_name,
                m_features=m_features,
                n_heads=n_heads,
                causal=causal,
                decay=decay,
                mode=mode,
                orthogonal=orthogonal,
                seed=seed,
                lambda_p=lambda_p,
                extrapolate=extrap_val,
                additional_features=additional_features,
                k=k
            ))