Causal RevIN Patch Basis: PyTorch Architecture

Navigation:

Overview & Formula Tokens

The causal patch basis is exposed via patch_basis():

# Causal RevIN patch basis
formula = "Y ~ patch_basis(temperature, others='Load_d1', patch_len=12, n_tokens=12, include_levy=True)"

Parameter Specification

Parameter

Type

Default

Description

others

str or list

None

Secondary features separated by | (used by patch_basis Lévy areas).

patch_len

int

16

Causal sliding patch length \(P\).

n_tokens

int

16

Number of random-phase orthogonal patch tokens \(M\).

include_levy

bool

True

Append Level-2 antisymmetric Lévy area hysteresis tokens for multivariate inputs.

Complexity & Performance

  • Zero future leakage: the instance statistics are those of the patch ending at the current step.

State, Complexity and Limits

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

  • State: {"hist": (B, patch_len - 1, D)}. Layout: (B, T) for one column, (B, T, D) with others=.

  • Time and memory: \(\mathcal{O}(B\,T\,P\,M)\) for the tokens and \(\mathcal{O}(B\,T\,D\,P)\) for the Lévy areas; all groups in one batch.

  • Penalty: ridge weighted by filter roughness on the \(M\) tokens, plain ridge on the other columns (one coordinate; inside foundation it is the patch coordinate).

  • Extrapolation: 'linear' and 'saturation' are refused at construction; the tokens are bounded, so extreme values saturate.

  • Limits: a pass shorter than the patch uses the replicated first row as history.

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

    def build_feature_map(
        self,
        x_col: torch.Tensor,
        state_in: Optional[Dict[str, Any]] = None,
    ) -> torch.Tensor:
        """Design block of the effect for the input ``x_col``; ``state_in`` carries the causal state of a previous chunk (see the class docstring)."""
        x_in, shape, layout = to_btd(x_col, self.multi_input)
        B, T, D = x_in.shape
        P = self.patch_len
        dtype = x_in.dtype
        device = x_in.device

        padded = causal_history(x_in, P - 1, state_in)  # (B, T + P - 1, D)
        self._state_out = {"hist": tail_state(padded, P - 1)}

        # Primary channel patches: shape (B, T, P)
        primary_padded = padded[:, :, 0]
        patches = primary_padded.unfold(dimension=1, size=P, step=1)  # (B, T, P)

        # Causal RevIN local statistics
        mu_p = torch.mean(patches, dim=-1, keepdim=True)  # (B, T, 1)
        var_p = torch.mean((patches - mu_p) ** 2, dim=-1, keepdim=True)
        sigma_p = torch.sqrt(var_p + 1e-6)  # (B, T, 1)
        patches_norm = (patches - mu_p) / sigma_p  # (B, T, P)

        w_patch = self._w_patch.to(device=device, dtype=dtype)  # (M, P)
        b_patch = self._b_patch.to(device=device, dtype=dtype)  # (M,)
        proj = torch.einsum("btp,mp->btm", patches_norm, w_patch) + b_patch.view(1, 1, -1)
        phi_tokens = math.sqrt(2.0 / float(self.n_tokens)) * torch.cos(proj)  # (B, T, M)

        revin_tokens = torch.cat([
            torch.tanh(0.25 * mu_p),
            torch.tanh(0.5 * torch.log(sigma_p)),
        ], dim=-1)  # (B, T, 2)

        parts = [phi_tokens, revin_tokens]

        if self.n_levy > 0:
            # Windows across all D channels: (B, T, D, P)
            all_patches = padded.unfold(dimension=1, size=P, step=1)
            # Local center each channel over the patch
            all_centered = all_patches - torch.mean(all_patches, dim=-1, keepdim=True)
            all_std = torch.sqrt(torch.mean(all_centered ** 2, dim=-1, keepdim=True) + 1e-6)
            u_path = all_centered / all_std  # (B, T, D, P)
            du = u_path[..., 1:] - u_path[..., :-1]  # (B, T, D, P-1)
            u_mid = 0.5 * (u_path[..., 1:] + u_path[..., :-1]) - u_path[..., :1]  # (B, T, D, P-1)

            levy_list = []
            if D >= 2:
                for a in range(D):
                    for b in range(a + 1, D):
                        area_ab = 0.5 * torch.mean(
                            u_mid[:, :, a, :] * du[:, :, b, :] - u_mid[:, :, b, :] * du[:, :, a, :],
                            dim=-1,
                            keepdim=True,
                        )
                        levy_list.append(torch.tanh(area_ab))
            else:
                # Hoff Lead-Lag self-hysteresis area between x_s and its 1-step delayed path
                u_lead = u_path[:, :, 0, 1:]
                u_lag = u_path[:, :, 0, :-1]
                du_lead = u_lead[..., 1:] - u_lead[..., :-1]
                du_lag = u_lag[..., 1:] - u_lag[..., :-1]
                mid_lead = 0.5 * (u_lead[..., 1:] + u_lead[..., :-1]) - u_lead[..., :1]
                mid_lag = 0.5 * (u_lag[..., 1:] + u_lag[..., :-1]) - u_lag[..., :1]
                area_self = 0.5 * torch.mean(mid_lead * du_lag - mid_lag * du_lead, dim=-1, keepdim=True)
                levy_list.append(torch.tanh(area_self))

            parts.append(torch.cat(levy_list, dim=-1))

        return from_btk(torch.cat(parts, dim=-1), shape, layout)

Penalty of PatchBasisEffect (build_penalty_matrix):

    def build_penalty_matrix(self) -> torch.Tensor:
        """Penalty matrix of the effect, scaled by its smoothing weights (see the class docstring)."""
        weights = torch.ones(self.n_coeffs, dtype=torch.get_default_dtype(), device=TORCH_DEVICE)
        weights[: self.n_tokens] = self._token_roughness_weights()   # the RevIN statistics and the Levy-area tokens keep a ridge
        return self.lambda_p * torch.diag(weights)

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

        elif ttype == 'patch_basis':
            extrap_val = params_resolved.get('extrapolate', 'continue')
            seed = int(params_resolved.get('seed', 42))
            additional_features = _parse_additional_features(params_resolved)

            include_levy = _as_bool(params_resolved.get('include_levy', True))

            effects_list.append(PatchBasisEffect(
                feature_name=feature_name,
                patch_len=int(params_resolved.get('patch_len', 16)),
                n_tokens=int(params_resolved.get('n_tokens', params_resolved.get('k', 16))),
                include_levy=include_levy,
                lambda_p=lambda_p,
                seed=seed,
                extrapolate=extrap_val,
                additional_features=additional_features,
            ))