Fourier Neural Operator: PyTorch Architecture

Navigation:

Overview & Formula Tokens

The Fourier Neural Operator block is exposed via fno():

# Resolution-invariant 1D Fourier Neural Operator spectral block
formula = "Y ~ fno(temperature, modes=6, width=6)"

Parameter Specification

OperatorEffect (fno())

Parameter

Type

Default

Description

modes

int

12

Truncated Fourier frequency modes \(k_{\max}\).

width

int

8

Number of spectral channels (and of columns).

window

int

32

Causal sliding-window length (W is accepted as an alias).

causal

bool

True

Read each step through its causal window (True) or the whole pass at once (False).

Complexity & Performance

  • Spectral synthesis: irfft over the truncated modes, in \(\mathcal{O}(B\,T\,W\log W)\) for the causal form and \(\mathcal{O}(B\,T\log T)\) for the non-causal one.

State, Complexity and Limits

  • Class and file: OperatorEffect, src/tam/model/spectrum/_fno.py; formula token fno(). Label: (BETA).

  • State: {"hist": (B, window - 1, 1)} for the causal form; none for causal=False. Layout: (B, T), one column.

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

  • Limits: the operator weights are random and fixed (seed): two seeds give two different feature maps.

  • 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 OperatorEffect (build_feature_map):

    def build_feature_map(self, x_col: torch.Tensor, state_in: Optional[Dict[str, Any]] = None) -> torch.Tensor:
        r"""Constructs causal or resolution-invariant FNO spectral channels.

        Args:
            x_col: Input sequence tensor ``(B, T)``, ``(B, T, 1)`` or ``(T,)``; every group is read alone.
            state_in: ``{"hist": (B, window - 1, 1)}`` of the pass before (causal form).

        Returns:
            Design matrix :math:`\Phi \in \mathbb{R}^{B \times T \times \text{width}}`.
        """
        x3, shape, layout = to_btd(x_col, False)
        if x3.shape[-1] != 1:
            raise ValueError(f"fno reads one column, got {x3.shape[-1]}")
        v = x3[..., 0]  # (B, T)
        B, T = v.shape
        dtype = v.dtype
        w_loc = self.w_local.to(device=v.device, dtype=dtype)
        channels = []

        if self.causal:
            W = self.window
            x_hist = causal_history(x3, self._n_hist, state_in)
            self._state_out = {"hist": tail_state(x_hist, self._n_hist)}
            windows = causal_window_unfold(x_hist, W, t_len=T)[..., 0]  # (B, T, W)
            win_hat = torch.fft.rfft(windows, n=W, dim=-1)  # (B, T, W // 2 + 1)
            k_modes = min(self.modes, win_hat.shape[-1])
            for m in range(self.width):
                conv_m = torch.fft.irfft(self._mix(win_hat, m, k_modes), n=W, dim=-1)[..., -1]
                channels.append(torch.nn.functional.gelu(w_loc[m] * v + conv_m))
        else:
            # Non-causal spatial 1D FFT along the full domain of each group
            v_hat = torch.fft.rfft(v, n=T, dim=-1)  # (B, T // 2 + 1)
            k_modes = min(self.modes, v_hat.shape[-1])
            for m in range(self.width):
                conv_m = torch.fft.irfft(self._mix(v_hat, m, k_modes), n=T, dim=-1)
                channels.append(torch.nn.functional.gelu(w_loc[m] * v + conv_m))

        return from_btk(torch.stack(channels, dim=-1), shape, layout)

Penalty of OperatorEffect (build_penalty_matrix):

    def build_penalty_matrix(self) -> torch.Tensor:
        r"""Constructs Sobolev operator smoothness penalty."""
        # Penalty weighted by spectral energy in high Fourier modes
        k_indices = torch.arange(1, self.modes + 1, dtype=torch.float64)
        spectral_roughness = torch.sum(
            (k_indices ** 2) * (torch.abs(self.R) ** 2), dim=-1
        ).to(device=TORCH_DEVICE, dtype=torch.get_default_dtype())

        diag_vals = (1.0 + spectral_roughness) * self.lambda_p
        return torch.diag(diag_vals)

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

        elif ttype == 'fno':
            modes = int(params_resolved.get('modes', 12))
            width = int(params_resolved.get('width', 8))
            window = int(params_resolved.get('window', params_resolved.get('W', 32)))
            causal = _as_bool(params_resolved.get('causal', True))
            seed = int(params_resolved.get('seed', 42))
            extrap_val = params_resolved.get('extrapolate', 'continue')
            effects_list.append(OperatorEffect(
                feature_name=feature_name,
                modes=modes,
                width=width,
                window=window,
                causal=causal,
                seed=seed,
                lambda_p=lambda_p,
                extrapolate=extrap_val,
            ))