kymatio developer on retainer: Scattering1D(J=6, Q=1) default max_order=2 produces 22 channels not 7 — nn.Linear hardcoded to J+1=7 raises RuntimeError — 2 weeks — kymatio developer on monthly retainer

kymatio 0.4.0 • Python 3.9; PyTorch 1.12; Scattering1D(J=6, Q=1, shape=(16384,)); max_order=2 default includes second-order path coefficients; channels = 1 + 6 + 15 = 22 (not J+1 = 7); developer hardcodes nn.Linear(7 × 256, 10); output flattened to 5632 not 1792; RuntimeError: mat1 and mat2 shapes cannot be multiplied; 2 weeks; fix: Sx.shape[1] dynamically or max_order=1 • Westfield Kymatio Ltd. (industrial machinery fault detection; 10,000 vibration recordings/month; 10 fault classes; 2 weeks; 2.0h retainer engagement)

Westfield Kymatio Ltd. built a machine learning pipeline for industrial machinery fault detection: 10,000 one-second vibration sensor recordings per month at 16 kHz from gearboxes, pumps, and compressors at 10 fault classes (bearing outer race, inner race, ball, cage, shaft unbalance, misalignment, looseness, cavitation, normal operation, indeterminate). The developer chose kymatio’s wavelet scattering transform as a fixed feature extractor, following published literature showing that scattering features provide translation-invariant spectro-temporal representations well-suited for vibration-based fault detection. The design: Scattering1D(J=6, Q=1, shape=(16384,)) for 1-second clips at 16 kHz (N = 16,384 samples; J = 6 octave scales; Q = 1 wavelet per octave), followed by flattening the output tensor and feeding it to a linear classification head. Reading the scattering transform literature as “J octave scales produce J first-order coefficient bands plus one zeroth-order average, giving J+1 = 7 coefficient groups,” the developer hardcoded nn.Linear(7 × 256, 10). On the first training step, PyTorch raised RuntimeError: mat1 and mat2 shapes cannot be multiplied (4×5632 and 1792×10). The 5632 and 1792 figures did not map obviously to any parameter in the pipeline, and the developer spent 2 weeks diagnosing what they believed was a data preprocessing error or model architecture mistake.

The mechanism: kymatio 0.4.0’s Scattering1D defaults to max_order=2, which computes both first-order and second-order scattering coefficients. First-order coefficients come from applying one wavelet filter at each of J scales and taking the modulus — these are the J × Q = 6 bands the developer expected. Second-order coefficients come from applying a second wavelet filter at each pair of scales (j1, j2) where j1 < j2 — these enumerate all ordered pairs from J scales: J × (J − 1) / 2 × Q² = 6 × 5 / 2 × 1 = 15 additional channels. Adding the zeroth-order average (1 channel), first-order (6 channels), and second-order (15 channels) gives C = 22 output channels, not 7. The time axis has T = N / 2J = 16384 / 64 = 256 frames. Scattering1D(x) with x.shape=(4,1,16384) returns Sx.shape=(4,22,256). When flattened: Sx.flatten(1).shape=(4, 5632). The nn.Linear(1792, 10) layer expects a 1792-dimensional input; it receives 5632. The error message reports the shapes correctly — 4×5632 vs 1792×10 — but nothing in the message mentions scattering channels, second-order coefficients, or max_order. The developer’s first-week debugging focused on data shape: they verified that signal length N = 16384 was correct, tried reshaping x as (batch, 16384) instead of (batch, 1, 16384) (which caused a different error from the missing channel dimension), and tried different flatten strategies. The second week shifted to J and Q values: changing to J = 4 (which gives C = 1 + 4 + 6 = 11 for max_order=2), J = 8 (C = 1 + 8 + 28 = 37), Q = 2 (C = 1 + 12 + 30 = 43). None of these matched 7 regardless of J and Q because max_order=2 was always adding second-order channels. The root cause was identified when print(Sx.shape) was added to the forward pass: torch.Size([4, 22, 256]) instead of the expected [4, 7, 256]. The 22 versus 7 discrepancy directed attention to the channel count formula.

The annotated scattering pipeline with dynamic channel computation, shape validation, and max_order selection guidance:

# Westfield Kymatio Ltd. — kymatio 0.4.0 Scattering1D channel count fix
# kymatio 0.4.0; Python 3.9; PyTorch 1.12; CUDA 11.6
# Industrial machinery fault detection; 10,000 vibration clips/month
# 1-second clips at 16 kHz; 10 fault classes
#
# Problem: Scattering1D(J=6, Q=1, shape=(16384,)) uses max_order=2 by default
#          Second-order coefficients: J*(J-1)//2 * Q^2 = 6*5//2 * 1 = 15
#          Total channels: 1 + 6 + 15 = 22 (not J+1=7)
#          Developer hardcodes nn.Linear(7*256, 10) → RuntimeError
# Fix:     Use Sx.shape[1] dynamically, or set max_order=1 for 7 channels

import torch
import torch.nn as nn
from kymatio.torch import Scattering1D


N = 16384    # signal length (1s at 16 kHz)
J = 6        # octave scales
Q = 1        # wavelets per octave
N_CLASSES = 10


def compute_scattering_channels(J: int, Q: int, max_order: int) -> int:
    """Compute expected number of Scattering1D output channels."""
    # Zeroth order: 1 (low-pass average)
    # First order:  J * Q
    # Second order: J*(J-1)//2 * Q**2  (all ordered pairs j1 < j2)
    c0 = 1
    c1 = J * Q
    c2 = J * (J - 1) // 2 * Q ** 2 if max_order >= 2 else 0
    return c0 + c1 + c2


def build_scattering_buggy(n_classes: int) -> tuple:
    """BUGGY: hardcodes J+1=7 channels; fails with max_order=2 default."""
    scatter = Scattering1D(J=J, Q=Q, shape=(N,))
    # max_order defaults to 2 → C = 22, T = 256
    # BUG: assumes C = J+1 = 7 (first-order mental model only)
    # RuntimeError at first forward pass: 4×5632 cannot multiply 1792×10
    T = N // (2 ** J)                       # 256 time frames
    classifier = nn.Linear(7 * T, n_classes)  # BUG: 7 not 22
    return scatter, classifier


def build_scattering_dynamic(n_classes: int) -> tuple:
    """FIXED option 1: use Sx.shape[1] dynamically — works for any max_order."""
    scatter = Scattering1D(J=J, Q=Q, shape=(N,))
    # Determine actual output channels from a test forward pass
    with torch.no_grad():
        x_test = torch.randn(1, 1, N)
        Sx_test = scatter(x_test)             # shape: (1, C, T)
    C, T = Sx_test.shape[1], Sx_test.shape[2]
    print(f"Scattering1D output: C={C} channels, T={T} frames")
    # C=22 for max_order=2, J=6, Q=1; T=256
    classifier = nn.Linear(C * T, n_classes)  # FIXED: 22*256=5632
    return scatter, classifier


def build_scattering_first_order(n_classes: int) -> tuple:
    """FIXED option 2: explicit max_order=1 → C=7 (matches J+1 intuition)."""
    # max_order=1 computes only zeroth + first-order: C = 1 + J*Q = 7
    scatter = Scattering1D(J=J, Q=Q, shape=(N,), max_order=1)
    C_expected = compute_scattering_channels(J=J, Q=Q, max_order=1)
    T = N // (2 ** J)                                   # 256
    assert C_expected == J * Q + 1 == 7                 # sanity
    classifier = nn.Linear(C_expected * T, n_classes)  # 7*256=1792
    return scatter, classifier


class FaultClassifier(nn.Module):
    """FIXED: infer classifier input from scattering output at init time."""

    def __init__(self, J: int, Q: int, N: int, n_classes: int,
                 max_order: int = 1) -> None:
        super().__init__()
        self.scatter = Scattering1D(J=J, Q=Q, shape=(N,),
                                    max_order=max_order)
        # Compute output channels at construction time — never hardcode
        C = compute_scattering_channels(J=J, Q=Q, max_order=max_order)
        T = N // (2 ** J)
        self.n_features = C * T
        self.classifier = nn.Linear(self.n_features, n_classes)
        print(
            f"FaultClassifier: J={J}, Q={Q}, N={N}, max_order={max_order} "
            f"→ C={C} channels × T={T} frames = {self.n_features} features"
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # x: (batch, N)  →  add channel dim for kymatio torch backend
        x = x.unsqueeze(1)                   # (batch, 1, N)
        Sx = self.scatter(x)                 # (batch, C, T)
        Sx_flat = Sx.flatten(1)              # (batch, C*T)
        return self.classifier(Sx_flat)      # (batch, n_classes)


# Reference: max_order=2 (C=22) often gives marginally better accuracy
# but 3× more features and 1.8× slower inference than max_order=1 (C=7).
# For vibration fault detection with strong transient signatures:
#   J=6, Q=1, max_order=1 → 7 channels (fast, interpretable)
# For audio classification with pitch-sensitive features:
#   J=6, Q=8, max_order=2 → 1 + 48 + 1128 = 1177 channels (high-dimensional)
# Always print(Sx.shape) or use compute_scattering_channels() before building.

Why the second-order channel count is non-obvious and why the error message does not mention max_order

Three factors combine to make this bug expensive. First, the second-order coefficient count formula J × (J − 1) / 2 × Q² grows quadratically in J and is not documented in kymatio’s constructor docstring for Scattering1D — a developer building their first scattering pipeline cannot infer the output shape from the constructor arguments without either reading the theoretical papers on scattering networks or running a test forward pass. The first-order mental model (J scales plus one global average equals J+1 channels) is natural and correct if max_order=1 is set, but max_order=2 is the default, and there is no warning when the actual channel count differs substantially from the developer’s mental model. For J = 6, the second-order channels (15) outnumber the first-order channels (6) by 2.5×, making the total 3.14× larger than the first-order count. Second, the RuntimeError message reports raw tensor dimension products — 4×5632 and 1792×10 — without mentioning scattering channels, max_order, or the C×T product. A developer unfamiliar with the specific numbers 5632 = 22×256 and 1792 = 7×256 cannot infer the source from the error message alone. 5632 looks like a suspicious power-of-two multiple but does not obviously decompose into a channel count and a time axis. Third, the fix for a shape mismatch in a classifier is naturally sought in the reshape or flatten logic, not in the feature extractor. A developer who understands that the signal is 16,384 samples long and the scattering time axis has 256 frames naturally focuses on data preprocessing and tensor operations rather than on the scattering constructor’s optional parameters. Westfield Kymatio Ltd.’s retainer engagement was 2.0h: 0.25h triage (add print(Sx.shape) to forward pass; observe torch.Size([4, 22, 256]); identify 22 not 7); 0.75h root cause (look up kymatio channel count formula; max_order=2 default; second-order paths formula; verify 1 + 6 + 15 = 22; verify that J = 4 gives 1 + 4 + 6 = 11, not 5); 0.5h fix (add compute_scattering_channels() helper; replace hardcoded 7 with Sx.shape[1]; evaluate max_order=1 option for simpler model); 0.5h validation (retrain on 10,000 clips; max_order=1 accuracy 94.2% vs max_order=2 93.8%; selected max_order=1 for lower dimensionality and faster inference; 2.0h total). Hours logged to HourTab with per-session breakdown.

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →