Penalized Single-Index Distributed Lags: PyTorch Architecture

Navigation:

Overview & Formula Tokens

Single-index distributed lags are exposed via si():

# Semiparametric Single-Index distributed-lag B-spline
formula = "Y ~ si(temperature, lag_window=12, k=6)"

Parameter Specification

SingleIndexEffect (si())

Parameter

Type

Default

Description

others

str or list

None

Multivariate covariates (mutually exclusive with lag_window).

lag_window

int

None

Distributed-lag window length for univariate inputs.

k

int

10

Univariate outer B-spline knots on normalized index \(u_t = X_t^\top \alpha\).

Complexity & Performance

  • Boundary Safety: SingleIndexEffect caches self.u_bounds at fit time and applies linear boundary extrapolation outside \([-1, 1]\).

State, Complexity and Limits

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

  • State: {"hist": (B, lag_window - 1, 1)} for the distributed-lag form only (stateful is true only then); none for others=.

  • Layout: (B, T, d) (keeps_feature_dim); a batch of one column may also be given as (B, T).

  • Time and memory: \(\mathcal{O}(B\,T\,L)\) for the lag form (one windowed dot product per step), \(\mathcal{O}(B\,T\,d)\) for the block; no loop over groups.

  • Extrapolation: the lag form refuses 'linear' and 'saturation' at construction (they would need a finite difference on isolated steps). The spline itself continues linearly outside the index range.

  • Limits: \(\alpha\) is fixed before the solve: the coefficients are linear, the index is not re-fitted.

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

    def build_feature_map(self, x_col: torch.Tensor, state_in: Optional[Dict[str, Any]] = None) -> torch.Tensor:
        """Constructs causal single-index B-spline design matrix: ``(B, T, d)`` in, ``(B, T, k + degree)`` out."""
        x3, shape, layout = to_btd(x_col, len(self.input_features) > 1 or (x_col.dim() == 2 and x_col.shape[-1] == 1))
        if self.u_bounds is None:
            self.initialize(x_col)
        knots = self._build_knots(device=x3.device, dtype=x3.dtype)
        u, state = self._index(x3, state_in)
        phi = self._eval_normalized_spline(u, knots).reshape(u.shape[0], u.shape[1], self._n_coeffs)
        if state is not None:
            self._state_out = state
        return from_btk(phi, shape, layout)

Penalty of SingleIndexEffect (build_penalty_matrix):

    def build_penalty_matrix(self) -> torch.Tensor:
        """Builds second-difference penalty matrix for outer B-spline."""
        n_coeffs = self.get_n_coeffs()
        I = torch.eye(n_coeffs, device=TORCH_DEVICE, dtype=torch.get_default_dtype())
        if self.penalty_order == 0:
            D = I
        else:
            D = torch.diff(I, n=self.penalty_order, dim=0)
        return self.lambda_p * (D.T @ D)

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

        elif ttype in ('si', 'single_index'):
            k = int(params_resolved.get('k', 10))
            deg = int(params_resolved.get('deg', params_resolved.get('spline_degree', 3)))
            p = int(params_resolved.get('p', params_resolved.get('penalty_order', 2)))
            lag_w_raw = params_resolved.get('lag_window', params_resolved.get('window', params_resolved.get('lags', None)))
            lag_window = int(lag_w_raw) if lag_w_raw is not None else None
            alpha_raw = params_resolved.get('alpha', None)
            alpha_pen = float(params_resolved.get('alpha_pen', 1.0))
            extrap_val = params_resolved.get('extrapolate', 'continue')

            additional_features = _parse_additional_features(params_resolved)

            effects_list.append(SingleIndexEffect(
                feature_name=feature_name,
                additional_features=additional_features,
                k=k,
                lag_window=lag_window,
                alpha=alpha_raw,
                alpha_pen=alpha_pen,
                spline_degree=deg,
                penalty_order=p,
                lambda_p=lambda_p,
                extrapolate=extrap_val,
            ))