Skip to content

LocalFeatures

from tensorsig.offset_coded_signatures.layers import LocalFeatures

Bases: Module

Evaluate a compiled local feature plan on sliding path windows.

A trainable code or alphabet-projection matrix is registered as a parameter; a fixed matrix is registered as a buffer. Polynomial plans have no matrix state. stride is measured in path increments.

Source code in src/tensorsig/offset_coded_signatures/layers.py
def __init__(
    self,
    plan: FeaturePlan,
    stride: int = 1,
    *,
    backend: str = "auto",
    chunk_size: int | None = None,
) -> None:
    super().__init__()
    if not isinstance(plan, (SignaturePlan, LogSignaturePlan, PolynomialPlan)):
        raise TypeError(
            "plan must be a SignaturePlan, LogSignaturePlan, or PolynomialPlan."
        )
    if not isinstance(backend, str):
        raise TypeError("backend must be a string.")

    self.plan = plan
    self.stride = _validate_stride(stride)
    self.backend = backend
    self.chunk_size = _validate_chunk_size(chunk_size)

    if isinstance(plan, SignaturePlan):
        allowed = {"auto", "vectorized", "rolling"}
        if self.backend not in allowed:
            raise ValueError("backend must be 'auto', 'vectorized', or 'rolling'.")
        if self.backend == "rolling":
            if not isinstance(plan.mapping, OffsetCode):
                raise ValueError("rolling requires a separable OffsetCode.")
            if plan.coordinates == "chronological":
                if (
                    plan.certification != "structural"
                    or plan.mapping.family != "pascal"
                ):
                    raise ValueError(
                        "Chronological rolling requires a structural Pascal plan."
                    )
            elif self.stride < plan.window:
                plan.mapping.shift_operator(self.stride)
    elif isinstance(plan, LogSignaturePlan):
        allowed = (
            {"auto", "direct", "pbw", "tensor"}
            if plan.quotient is not None
            else {"auto", "dense", "rolling", "sparse"}
        )
        if self.backend not in allowed:
            choices = ", ".join(sorted(allowed - {"auto"}))
            raise ValueError(f"backend must be 'auto' or one of: {choices}.")
        if self.backend == "rolling" and self.stride < plan.window:
            plan.code.shift_operator(self.stride)
    elif self.backend != "auto":
        raise ValueError("PolynomialPlan supports only backend='auto'.")
    if not isinstance(plan, PolynomialPlan) and self.chunk_size is not None:
        raise ValueError("chunk_size applies only to PolynomialPlan.")

    if isinstance(plan, PolynomialPlan):
        self.register_parameter("matrix", None)
    elif plan._matrix_tensor().requires_grad:
        source_matrix = plan._matrix_tensor()
        matrix = (
            source_matrix
            if isinstance(source_matrix, torch.nn.Parameter)
            else torch.nn.Parameter(source_matrix.detach().clone())
        )
        self.register_parameter("matrix", matrix)
    else:
        self.register_buffer("matrix", plan._matrix_tensor().detach().clone())

window property

window: int

Number of increments in each local window.

channels property

channels: int

Expected path channel count.

feature_count property

feature_count: int

Number of output features per window.

forward

forward(path: Tensor) -> Tensor

Return (batch, windows, features) local coordinates.

Source code in src/tensorsig/offset_coded_signatures/layers.py
def forward(self, path: Tensor) -> Tensor:
    """Return ``(batch, windows, features)`` local coordinates."""
    validate_path_points(path, in_channels=self.channels)
    if self.matrix is not None and (
        path.device != self.matrix.device or path.dtype != self.matrix.dtype
    ):
        raise RuntimeError(
            "path dtype/device must match the module matrix; move the module "
            "and input explicitly before evaluation"
        )
    if isinstance(self.plan, SignaturePlan):
        if self.backend == "auto":
            constant = self._constant_code_signature(path)
            if constant is not None:
                return constant
        if self.backend == "rolling":
            assert self.matrix is not None
            if self.plan.coordinates == "chronological":
                assert isinstance(self.plan.mapping, OffsetCode)
                return _rolling_chronological_features(
                    path,
                    self.matrix,
                    self.plan.mapping,
                    self.plan._rolling_program(),
                    channels=self.channels,
                    stride=self.stride,
                )
            levels = _rolling_coded_signature_levels(
                path,
                self.matrix,
                channels=self.channels,
                depth=max(self.plan.depths),
                stride=self.stride,
            )
            return self.plan._coordinates_from_levels(levels)
    if isinstance(self.plan, LogSignaturePlan) and self.backend == "rolling":
        assert self.matrix is not None
        levels = _rolling_coded_signature_levels(
            path,
            self.matrix,
            channels=self.channels,
            depth=max(self.plan.depths),
            stride=self.stride,
        )
        return self.plan._coordinates_from_signature_levels(levels)
    windows = increment_windows(path, size=self.window, stride=self.stride)
    return self._evaluate_windows(windows)