CausalConv1D#

class CausalConv1D(*args, is_causal=True, **kwargs)#

Bases: Conv1d

1D convolution with configurable causal (left-only) or symmetric padding.

Subclasses torch.nn.Conv1d and overrides forward() to apply explicit left-only padding rather than the built-in padding argument. This guarantees that output[b, :, i] depends only on input[b, :, 0 i] (the causal constraint).

Padding formulae

For a kernel of size K with dilation D:

  • Causal (is_causal=True): left_pad = (K-1)*D, right_pad = 0. Output length equals input length for stride=1.

  • Symmetric (is_causal=False): sym_pad = ((K-1)*D) // 2 on both sides. Equivalent to Conv1d(padding='same') for odd K.

Pass padding=0 to the parent constructor (the default) — padding is handled explicitly in forward().

Parameters:

is_causal (bool)

is_causal#

If True, left-only padding is applied.

Type:

bool

Example:

conv = CausalConv1D(in_channels=16, out_channels=16, kernel_size=7, groups=16)
x = torch.randn(2, 16, 100)  # [B, C, L]
y = conv(x)                  # [B, 16, 100] — same length, strictly causal

Notes

  • Stride > 1 reduces the output length as in standard convolutions.

  • For depthwise convolutions set groups=in_channels.

  • The padding argument of the parent constructor is ignored; always pass padding=0 (or omit it) when constructing this class.

__init__(*args, is_causal=True, **kwargs)#

Initialise CausalConv1D.

Parameters:
  • *args – Positional arguments forwarded to torch.nn.Conv1d (in_channels, out_channels, kernel_size, …).

  • is_causal (bool) – If True (default), apply left-only (causal) padding. If False, apply symmetric same-padding.

  • **kwargs – Keyword arguments forwarded to torch.nn.Conv1d. padding should be 0 (or omitted) since forward() handles padding explicitly.

Return type:

None

forward(input)#

Apply 1D convolution with causal or symmetric padding.

Parameters:

input (Tensor) – Input tensor of shape [B, C_in, L].

Returns:

Output of shape [B, C_out, L_out].

  • L_out = L when stride=1 (same-length output).

  • L_out = ceil(L / stride) for stride > 1.

Return type:

torch.Tensor