Skip to content

GapFactorizedVolterra

from tensorsig.offset_coded_signatures.layers import GapFactorizedVolterra

Bases: Module

A low-rank gap-factorized readout of a strict polynomial plan.

For strict offsets r_1 < ... < r_m, the temporal coefficient of one rank component is a product of factors indexed by the positive internal gaps r_{j+1} - r_j and the terminal lag window - 1 - r_m. A learned channel tensor is then contracted with each component. The represented functions are exactly a structured subset of the supplied PolynomialPlan.

Parameters:

Name Type Description Default
plan PolynomialPlan

A plan compiled with max_offset_multiplicity=1. Span-filtered plans are supported through the enumerated backend.

required
out_features int

Number of output channels.

required
temporal_rank int

Number of separable temporal/channel components at every degree.

required
stride int

Window stride measured in path increments.

1
bias bool

Whether to learn an output bias.

True
backend ('auto', 'dynamic', 'enumerate')

"dynamic" avoids tuple enumeration and requires an unfiltered strict plan. "enumerate" evaluates the plan's retained tuples.

"auto"
gap_initialization ('ones', 'uniform')

Initialization for internal-gap and terminal-lag factors.

"ones"
device device or str

Initial parameter device.

None
dtype dtype

Initial floating-point parameter dtype.

None
Source code in src/tensorsig/offset_coded_signatures/gap_factorized_volterra.py
def __init__(
    self,
    plan: PolynomialPlan,
    out_features: int,
    temporal_rank: int,
    stride: int = 1,
    bias: bool = True,
    *,
    backend: VolterraBackend = "auto",
    gap_initialization: GapInit = "ones",
    device: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> None:
    super().__init__()
    offset_levels = _validate_plan(plan)
    _validate_positive_integer(out_features, "out_features")
    _validate_positive_integer(temporal_rank, "temporal_rank")
    _validate_positive_integer(stride, "stride")
    if not isinstance(bias, bool):
        raise TypeError("bias must be a boolean.")
    if dtype is not None and not dtype.is_floating_point:
        raise ValueError("dtype must be floating-point.")

    self.plan = plan
    self.out_features = int(out_features)
    self.temporal_rank = int(temporal_rank)
    self.stride = int(stride)
    self.backend = _validate_backend(backend)
    self.gap_initialization = _validate_gap_init(gap_initialization)
    self._span_filtered = any(
        offsets.shape[0] < math.comb(plan.window, depth)
        for depth, offsets in zip(plan.depths, offset_levels, strict=True)
    )
    if self.backend == "dynamic" and self._span_filtered:
        raise ValueError("backend='dynamic' does not support a span-filtered plan.")
    self._resolved_backend = (
        "enumerate"
        if self.backend == "enumerate" or self._span_filtered
        else "dynamic"
    )

    internal_factors: list[torch.nn.Parameter | None] = []
    terminal_factors = []
    channel_weights = []
    max_span = plan.max_offset_span
    for index, (depth, offsets) in enumerate(
        zip(plan.depths, offset_levels, strict=True)
    ):
        terminal_width = plan.window - depth + 1
        if depth == 1:
            internal_factors.append(None)
        else:
            internal_width = terminal_width
            if max_span is not None:
                internal_width = min(
                    internal_width,
                    max_span - (depth - 2),
                )
            internal_factors.append(
                torch.nn.Parameter(
                    torch.empty(
                        temporal_rank,
                        depth - 1,
                        internal_width,
                        device=device,
                        dtype=dtype,
                    )
                )
            )
        terminal_factors.append(
            torch.nn.Parameter(
                torch.empty(
                    temporal_rank,
                    terminal_width,
                    device=device,
                    dtype=dtype,
                )
            )
        )
        channel_weights.append(
            torch.nn.Parameter(
                torch.empty(
                    out_features,
                    temporal_rank,
                    *([plan.channels] * depth),
                    device=device,
                    dtype=dtype,
                )
            )
        )
        if self._resolved_backend == "dynamic":
            positions = torch.arange(plan.window, device=device)
            gaps = positions[:, None] - positions[None, :]
            if depth > 1:
                self.register_buffer(
                    f"_gap_indices_{index}",
                    (gaps - 1).clamp(min=0, max=internal_width - 1),
                    persistent=False,
                )
                self.register_buffer(
                    f"_valid_gaps_{index}",
                    (gaps > 0) & (gaps <= internal_width),
                    persistent=False,
                )
            lags = torch.arange(plan.window - 1, -1, -1, device=device)
            self.register_buffer(
                f"_lag_indices_{index}",
                lags.clamp(max=terminal_width - 1),
                persistent=False,
            )
            self.register_buffer(
                f"_valid_lags_{index}",
                lags < terminal_width,
                persistent=False,
            )
        else:
            dictionary = plan._dictionaries[index]
            _, offset_tuple_indices = torch.unique_consecutive(
                dictionary.offsets,
                dim=0,
                return_inverse=True,
            )
            self.register_buffer(
                f"_offset_tuples_{index}",
                offsets.to(device=device),
                persistent=False,
            )
            self.register_buffer(
                f"_offset_tuple_indices_{index}",
                offset_tuple_indices.to(device=device),
                persistent=False,
            )
            self.register_buffer(
                f"_channel_tuples_{index}",
                dictionary.channels.to(device=device),
                persistent=False,
            )

    self.internal_gap_factors = torch.nn.ParameterList(internal_factors)
    self.terminal_lag_factors = torch.nn.ParameterList(terminal_factors)
    self.channel_weights = torch.nn.ParameterList(channel_weights)
    if bias:
        self.bias = torch.nn.Parameter(
            torch.empty(out_features, device=device, dtype=dtype)
        )
    else:
        self.register_parameter("bias", None)
    self.reset_parameters()

window property

window: int

Number of increments in each local window.

channels property

channels: int

Expected path channel count.

depths property

depths: tuple[int, ...]

Homogeneous polynomial degrees represented by the layer.

reset_parameters

reset_parameters() -> None

Initialize gap factors, channel weights, and bias.

Source code in src/tensorsig/offset_coded_signatures/gap_factorized_volterra.py
def reset_parameters(self) -> None:
    """Initialize gap factors, channel weights, and bias."""
    for depth, internal, terminal, channel_weight in zip(
        self.depths,
        self.internal_gap_factors,
        self.terminal_lag_factors,
        self.channel_weights,
        strict=True,
    ):
        if self.gap_initialization == "ones":
            if internal is not None:
                torch.nn.init.ones_(internal)
            torch.nn.init.ones_(terminal)
        else:
            if internal is not None:
                torch.nn.init.uniform_(internal, -0.1, 0.1)
            torch.nn.init.uniform_(terminal, -0.1, 0.1)
        bound = (self.temporal_rank * self.channels**depth) ** -0.5
        torch.nn.init.uniform_(channel_weight, -bound, bound)
    if self.bias is not None:
        torch.nn.init.zeros_(self.bias)

forward

forward(path: Tensor) -> Tensor

Return one gap-factorized Volterra readout per local window.

Source code in src/tensorsig/offset_coded_signatures/gap_factorized_volterra.py
def forward(self, path: Tensor) -> Tensor:
    """Return one gap-factorized Volterra readout per local window."""
    batch, _, _ = validate_path_points(path, in_channels=self.channels)
    reference = self.channel_weights[0]
    if path.device != reference.device or path.dtype != reference.dtype:
        raise RuntimeError(
            "path dtype/device must match the module parameters; move the "
            "module and input explicitly before evaluation"
        )
    windows = increment_windows(path, size=self.window, stride=self.stride)
    if self._resolved_backend == "enumerate":
        output = self.plan.contract(windows, self._expanded_weight())
    else:
        output = path.new_zeros(batch, windows.shape[1], self.out_features)
        for index, channel_weight in enumerate(self.channel_weights):
            output = output + contract_features_with_readout(
                self._dynamic_level(windows, index),
                channel_weight,
            )
    if self.bias is not None:
        output = output + self.bias
    return output