Path Signature and Log-Signature Effect: PyTorch Architecture & Implementation¶
Navigation:
Mathematical Theory: See SIGNATURE.md
Spectrum API Overview: See The Spectrum API
Overview & Formula Token¶
The Path Signature effect is exposed in formulas via the sig() token:
# Univariate sliding-window path signature with time augmentation
formula = "Y ~ sig(Temperature, w=9, N=3)"
# Compressed Log-Signature on the Free Lie algebra via Lyndon basis
formula = "Y ~ sig(Temperature, w=9, N=3, log_sig=True)"
# Cross-channel causal lead-lag discovery with Hoff's transform
formula = "Y ~ sig(Temperature, others='Load_d1', w=9, N=2, lead_lag=True)"
# Combined with non-linear spline and tensor interaction
formula = "Y ~ s(Temperature, k=10) + sig(Temperature, w=7, N=3) + te(sig(Temperature, w=5, N=2), c(day_type_week))"
Parameter Specification¶
Parameter |
Type |
Default |
Description |
|---|---|---|---|
|
|
required |
Primary feature column name. |
|
|
|
Sliding window length in rows/steps. |
|
|
|
Iterated integral truncation level (maximum 4). |
|
|
|
Delay rows applied before the end of the sliding window. |
|
|
|
Appends normalized time coordinate \(\tau \in [0, 1]\) across the window (\(D = d + 1\)). |
|
|
|
Compresses signature into Free Lie algebra via tensor log and Lyndon basis. |
|
|
|
Applies Hoff’s Lead-Lag embedding (\(2w - 1\) steps in \(\mathbb{R}^{2d}\)) for quadratic covariation. |
|
|
|
Pipe-delimited or list of additional multivariate feature columns. |
|
|
|
Log10 of the regularization parameter \(\lambda_p = 10^{\text{ap}}\). |
|
|
|
OOD extrapolation strategy beyond \([-1, 1]\). |
Complexity & Performance¶
Memory Complexity: The feature map requires \(\mathcal{O}(T \cdot K)\) floats where \(K = \sum_{k=1}^N D^k\) for signatures or \(\sum_{k=1}^N \beta(D, k)\) for log-signatures.
Compute Complexity: Each window of length \(w\) requires \(w - 1\) segment exponentials and Chen tensor products, executing in \(\mathcal{O}(T \cdot w \cdot D^N)\).
Free Lie Algebra Compression: Setting
log_sig=Truereduces dimensionality from \(\frac{D^{N+1}-1}{D-1}\) to the Lyndon basis dimension \(\sum_{k=1}^N \beta(D, k)\), eliminating shuffle-product collinearity and improving design matrix conditioning.Factorial Penalty: Level-dependent factorial scaling \((k!)^2\) regularizes higher-order terms proportionally to their natural decay scale.
State, Complexity and Limits¶
Class and file:
SignatureEffect,src/tam/model/spectrum/_signature.py(iterated-integral algebra in_signature_ops.py). Label: (BETA).State:
{"hist": (B, w - 1 + lag, d)}, the last rows of every group, detached.StaticTAM.predict(data, continue_state=True)passes it back; a state with another number of groups raises aValueError.Layout:
(B, T)for one column,(B, T, d)withothers=; one signature per step and per group.Time and memory: \(\mathcal{O}(B\,T\,w\,D^{N})\) time and \(\mathcal{O}(B\,T\,K)\) memory (\(K\) = number of coefficients); the windows of all groups are processed as one batch, with no Python loop over groups.
Extrapolation: the effect is temporal, so
'linear'and'saturation'are refused at construction; use'continue'(default) or'constant'.Limits: the truncation level is at most 4; the windows read the standardized increments of the training period, so a regime far from the training range gives large (but finite) coefficients.
Chunk equivalence bound:
tests/spectrum/test_stateful_contract.pychecks that the second of two chunks, started from the state of the first, equals the matching rows of the one-pass features withinatol=1e-8(float64), and that every group computed alone equals the same group inside a batch withinatol=1e-10.
Code¶
Feature map of SignatureEffect (build_feature_map):
def build_feature_map(self, x_col: torch.Tensor, state_in: Optional[Dict[str, Any]] = None) -> torch.Tensor:
"""Builds explicit causal path signature Primal basis matrix; ``(B, T)`` or ``(B, T, d)`` in, ``(B, T, K)`` out."""
x3, shape, layout = to_btd(x_col, self.multi_input)
if x3.shape[-1] != len(self.input_features):
raise ValueError(f"signature expects {len(self.input_features)} input column(s), got {x3.shape[-1]}")
if self._delta_scale is None:
self.initialize(x_col)
B, T, d_in = x3.shape
windows, self_state = self._windows(x3, state_in)
d_scale = self._delta_scale.to(device=x3.device, dtype=x3.dtype).view(1, 1, 1, d_in)
windows = windows / (d_scale + 1e-8)
phi = self._signatures_of_windows(windows.reshape(B * T, self.w, d_in)).reshape(B, T, self._n_coeffs)
self._state_out = {"hist": self_state}
return from_btk(phi, shape, layout)
Penalty of SignatureEffect (build_penalty_matrix):
def build_penalty_matrix(self) -> torch.Tensor:
r"""Builds strictly positive-definite level-dependent factorial Ridge penalty matrix.
.. math::
\lambda_k = \lambda \cdot (k!)^2
Returns:
torch.Tensor: Diagonal penalty matrix :math:`P_{\text{sig}}` of shape ``(n_coeffs, n_coeffs)``.
"""
drop_pure_time = self.time_augment and self.D > 1
weights = []
for k in range(1, self.N + 1):
level_fact = float(math.factorial(k)) ** 2
if self.log_sig:
witt_k = compute_witt_dimension(self.D, k)
level_dim = (witt_k - 1) if (k == 1 and drop_pure_time) else witt_k
else:
if self.D == 1:
level_dim = 1
elif drop_pure_time:
level_dim = self.D ** k - 1
else:
level_dim = self.D ** k
weights.extend([level_fact] * level_dim)
diag = self.lambda_p * torch.tensor(
weights, device=TORCH_DEVICE, dtype=torch.get_default_dtype()
)
return torch.diag(diag)
Parsing of the sig(...) token in the factory:
elif ttype == 'sig':
w = int(params_resolved.get('w', 9))
N = int(params_resolved.get('N', params_resolved.get('level', 3)))
lag = int(params_resolved.get('lag', 0))
time_aug_raw = params_resolved.get('time_augment', True)
time_augment = _as_bool(time_aug_raw)
log_sig_raw = params_resolved.get('log_sig', False)
log_sig = _as_bool(log_sig_raw)
lead_lag_raw = params_resolved.get('lead_lag', False)
lead_lag = _as_bool(lead_lag_raw)
extrap_val = params_resolved.get('extrapolate', 'continue')
k = int(params_resolved['k']) if ('k' in params_resolved and params_resolved['k'] is not None) else None
additional_features = _parse_additional_features(params_resolved)
effects_list.append(SignatureEffect(
feature_name=feature_name,
w=w,
N=N,
lag=lag,
time_augment=time_augment,
log_sig=log_sig,
lead_lag=lead_lag,
lambda_p=lambda_p,
extrapolate=extrap_val,
additional_features=additional_features,
k=k
))