Temporal Joint-Embedding Predictive Architecture (T-JEPA): PyTorch Architecture

Navigation:

Overview & Formula Token

formula = "Y ~ tjepa(temperature, others='temp_smooth|temp_max', latent_dim=4, window=16, readout='linear')"

Parameter Specification

Parameter

Type

Default

Description

others

str or list

None

Additional exogenous channels separated by |.

latent_dim

int

4

Latent embedding dimension \(d\).

window

int

16

Causal context window length \(w\).

horizon

int

4

Self-supervised target prediction offset \(\delta\).

readout

str

'spline'

Readout map: 'linear' or 'spline'.

epochs

int

30

Self-supervised VICReg pre-training epochs on exogenous inputs only.

Complexity & Performance

  • Zero Target Leakage: Pre-trains the context encoder, EMA target encoder (\(\tau = 0.99\)), and predictor strictly on exogenous covariate streams without ever reading target \(y\), caching training standardization statistics \((\hat{\mu}_x, \hat{\sigma}_x)\) and carrying trailing \(w - 1\) samples across splits.

State, Complexity and Limits

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

  • State: {"hist": (B, window - 1, D)}. Layout: (B, T, D) (keeps_feature_dim); one column may also be given as (B, T).

  • Modes: mode="svd" (default) and mode="vicreg".

    mode

    encoder

    fit cost

    deterministic

    arguments read

    svd

    linear projection on the predictive modes of the context windows, then tanh (_fit_tjepa_svd)

    two SVDs, \(\mathcal{O}(n\,(wD)^2)\) with \(n\) window pairs

    yes: bit-identical for the same data

    latent_dim, window, horizon; seed only when there are fewer than 16 window pairs

    vicreg

    two-layer GELU encoder, moving-average target encoder and predictor trained with AdamW (_fit_tjepa_encoder)

    \(\mathcal{O}(\text{epochs}\cdot n\,wD)\)

    for a seed, on one machine

    those above and epochs (the optimizer settings are fixed)

  • Runtime: measured on the CPU of the development PC with \(T = 2500\) rows in each of \(B = 2\) groups, \(d = 4\), \(w = 16\) and 2 columns: svd 0.01 s, vicreg with 30 epochs 6 s. On the national load benchmark the fit of the vicreg effect took 88 s against 4 s for the spline reference. A feature map costs \(\mathcal{O}(B\,T\,w\,D)\) in both modes.

  • Why svd stays reproducible inside P-WLS: the encoder is a pure function of the training windows (no random initialization, no stochastic optimizer), so the design matrix, and therefore the penalized solution, is the same at every fit up to the rounding of the linear algebra; with vicreg it depends on the seed and on the order of the floating-point operations.

  • Errors: a group shorter than window + horizon rows raises a ValueError at initialization.

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

  • Reproducibility: the seed fixes the training; the global random state is restored.

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

    def build_feature_map(self, x_col: torch.Tensor, state_in: Optional[Dict[str, Any]] = None) -> torch.Tensor:
        r"""Constructs causal T-JEPA latent feature map.

        Args:
            x_col: ``(B, T, D)`` (or ``(B, T)`` for one column, ``(T,)`` for one series).
            state_in: The last ``window - 1`` standardized rows of every group, ``{"hist": (B, w - 1, D)}``.

        Returns:
            Design matrix :math:`\Phi \in \mathbb{R}^{B \times T \times M}`.
        """
        x3, shape, layout = self._to_btd(x_col)
        if self.encoder is None:
            self.initialize(x_col)
        B, T, D = x3.shape
        if D != self.n_in_features:
            raise ValueError(f"tjepa expects {self.n_in_features} input column(s), got {D}")
        w = self.window
        x_std = self._standardize(x3)
        x_hist = causal_history(x_std, 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).reshape(B * T, w * D)     # (B * T, w * D), a window never spans two groups
        enc_param = next(self.encoder.parameters())
        with torch.no_grad():
            z = torch.tanh(self.encoder(windows.to(device=enc_param.device, dtype=enc_param.dtype))).to(device=x3.device, dtype=x3.dtype)

        if self.readout == "linear":
            phi = z
        else:
            # Spline readout: k_spline B-spline functions per latent coordinate
            knots_out = self.knots_out.to(device=x3.device, dtype=x3.dtype)
            phi = torch.cat([_cox_de_boor(z[:, j], knots_out, self.spline_degree) for j in range(self.latent_dim)], dim=-1)  # (B * T, d * k_spline)

        return from_btk(phi.reshape(B, T, self.get_n_coeffs()), shape, layout)

Penalty of TJEPAEffect (build_penalty_matrix):

    def build_penalty_matrix(self) -> torch.Tensor:
        r"""Constructs block-diagonal regularization penalty, block ``j`` weighted by ``1 + res_j``."""
        d = self.latent_dim
        weights = self._latent_weights()
        if self.readout == "linear":
            return torch.diag(self.lambda_p * weights)

        # Block-diagonal Sobolev roughness penalty
        I_sub = torch.eye(self.n_outer_coeffs, device=TORCH_DEVICE, dtype=torch.get_default_dtype())
        D = torch.diff(I_sub, n=2, dim=0)
        P_sub = (D.T @ D) * self.lambda_p
        return torch.block_diag(*[weights[j] * P_sub for j in range(d)])

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

        elif ttype == 'tjepa':
            latent_dim = int(params_resolved.get('latent_dim', params_resolved.get('d', 4)))
            window = int(params_resolved.get('window', params_resolved.get('w', 16)))
            horizon = int(params_resolved.get('horizon', params_resolved.get('delta', 4)))
            readout = str(params_resolved.get('readout', 'spline')).lower()
            k_spline = int(params_resolved.get('k_spline', 8))
            epochs = int(params_resolved.get('epochs', 30))
            seed = int(params_resolved.get('seed', 42))
            tjepa_mode = str(params_resolved.get('mode', 'svd')).lower()
            extrap_val = params_resolved.get('extrapolate', 'continue')

            additional_features = _parse_additional_features(params_resolved)

            effects_list.append(TJEPAEffect(
                feature_name=feature_name,
                additional_features=additional_features,
                latent_dim=latent_dim,
                window=window,
                horizon=horizon,
                readout=readout,
                k_spline=k_spline,
                epochs=epochs,
                seed=seed,
                mode=tjepa_mode,
                lambda_p=lambda_p,
                extrapolate=extrap_val,
            ))