Universal Foundation Basis: PyTorch Architecture

Navigation:

Overview & Formula Tokens

The foundation basis is exposed as the composite token foundation(), which carries its components internally (PatchBasisEffect, QuantileHistEffect, MultiRateFilterbankEffect, StructuralPriorEffect; the components are not formula tokens):

# Composite universal foundation basis
formula = "Y ~ foundation(temperature, others='Load_d1', patch_len=12, n_tokens=8, n_bins=8, scales='1|4|16', n_struct=8)"

Parameter Specification

Parameter

Type

Default

Description

others

str or list

None

Secondary features separated by | (read by the patch basis Lévy areas).

patch_len

int

16

Causal sliding patch length \(P\) (the histogram window is max(patch_len, 8)).

n_tokens

int

16

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

include_levy

bool

True

Append Lévy-area hysteresis tokens.

n_bins

int

16

Number of quantile histogram bins \(B\).

scales

Sequence[int] or str

(1, 4, 16, 64)

Time scales of the multi-rate filterbank.

n_struct

int

16

Size of the structural prior dictionary. n_pfn is accepted as an alias; giving both with different values raises an error.

seed

int

42

Seed of the patch projections.

State, Complexity and Limits

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

  • State: {"patch": (B, P - 1, D), "qhist": (B, W - 1, 1), "ema": (B, S), "env": (B, S)}.

  • Layout: (B, T, D) (keeps_feature_dim); the primary column feeds all blocks, the other columns only the patch basis.

  • Time and memory: linear in \(T\) for every block (the filterbank is a pair of linear recurrences, not a \(T \times T\) operator): fifty thousand steps run in a few seconds.

  • Penalty coordinates: patch, hist, mrfb, struct; set_penalty_coordinates accepts four values or one.

  • Extrapolation: 'linear' and 'saturation' are refused at construction.

  • Closed form: no network is trained; the fit is one penalized weighted least-squares solve.

  • 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.

  • Penalty ridge: _build_d2_penalty(n) is D2.T @ D2 + 1e-6 * I; the ridge is kept on purpose: it makes the second-difference blocks positive definite so that the REML log-determinant is defined, and it is part of the numbers of the benchmarks.

  • 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 FoundationEffect (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)."""
        x3, shape, layout = to_btd(x_col, True)
        x_primary = x3[..., :1]

        def sub(prefix_map: Dict[str, str]) -> Optional[Dict[str, Any]]:
            """The part of the carried state that belongs to one sub-effect."""
            if state_in is None:
                return None
            picked = {inner: state_in[outer] for outer, inner in prefix_map.items() if outer in state_in}
            return picked or None

        phi_patch = self.patch_effect.build_feature_map(x3, state_in=sub({"patch": "hist"}))
        phi_hist = self.hist_effect.build_feature_map(x_primary, state_in=sub({"qhist": "hist"}))
        phi_mrfb = self.mrfb_effect.build_feature_map(x_primary, state_in=sub({"ema": "ema", "env": "env"}))
        phi_struct = self.struct_effect.build_feature_map(x_primary)
        self._state_out = {
            "patch": self.patch_effect._state_out["hist"],
            "qhist": self.hist_effect._state_out["hist"],
            "ema": self.mrfb_effect._state_out["ema"],
            "env": self.mrfb_effect._state_out["env"],
        }
        return from_btk(torch.cat([phi_patch, phi_hist, phi_mrfb, phi_struct], dim=-1), shape, layout)

Penalty of FoundationEffect (build_penalty_matrix):

    def build_penalty_matrix(self) -> torch.Tensor:
        """Penalty matrix of the effect, scaled by its smoothing weights (see the class docstring)."""
        blocks = [e.build_penalty_matrix() for e in self.sub_effects]
        return torch.block_diag(*blocks)

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

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

            scales_raw = params_resolved.get('scales', (1, 4, 16, 64))
            if isinstance(scales_raw, str):
                clean_s = scales_raw.replace('[', '').replace(']', '').replace('(', '').replace(')', '').replace('|', ',')
                scales = [int(s.strip()) for s in clean_s.split(',') if s.strip()]
            elif isinstance(scales_raw, (int, float)):
                scales = [int(scales_raw)]
            else:
                scales = [int(s) for s in scales_raw]

            include_levy = _as_bool(params_resolved.get('include_levy', True))
            n_struct_raw = params_resolved.get('n_struct', None)
            n_pfn_raw = params_resolved.get('n_pfn', None)   # alias of n_struct
            if n_struct_raw is not None and n_pfn_raw is not None and int(n_struct_raw) != int(n_pfn_raw):
                raise ValueError(f"foundation: n_struct={n_struct_raw} and n_pfn={n_pfn_raw} disagree; n_pfn is an alias of n_struct")
            n_struct = int(n_struct_raw if n_struct_raw is not None else (n_pfn_raw if n_pfn_raw is not None else 16))

            effects_list.append(FoundationEffect(
                feature_name=feature_name,
                patch_len=int(params_resolved.get('patch_len', 16)),
                n_tokens=int(params_resolved.get('n_tokens', 16)),
                n_bins=int(params_resolved.get('n_bins', 16)),
                scales=scales,
                n_struct=n_struct,
                include_levy=include_levy,
                lambda_p=lambda_p,
                seed=seed,
                extrapolate=extrap_val,
                additional_features=additional_features,
            ))