PyTorch Wavelet Toolbox

repository·main·Indexed 19 days ago

https://github.com/v0lta/pytorch-wavelet-toolbox

A library providing differentiable and GPU-enabled fast wavelet transforms in PyTorch. It implements Discrete Wavelet Transforms (DWT), Continuous Wavelet Transforms (CWT), and Wavelet Packet Transforms (WPT), extending PyWavelets with gradient support for deep learning workflows. Key features include matrix forms of transforms via ptwt.MatrixWavedec and ptwt.MatrixWaverec, Gram-Schmidt boundary filters for perfect reconstruction, and support for common wavelet families like Daubechies and Symlets.

Tokens
17K
Snippets
77
Records
100
Agent score
66%

What's inside ptwt

  1. Use sparse-matrix-based boundary wavelet transforms

    main

    For transforms that do not add extra pixels at the edges (unlike padding/convolution approaches), use the MatrixWavedec and MatrixWaverec classes. These utilize torch.sparse.mm for efficiency.

    1D Sparse Transforms

    Use MatrixWavedec for forward and MatrixWaverec for backward transforms.

    2D Sparse Transforms

    Use MatrixWavedec2 and MatrixWaverec2.

    • Separable (Default): Uses a 1D transformation along both axes. This is generally faster.
    • Non-separable: Pass separable=False to the constructor to use a non-separable transformation.
    import torch
    import ptwt
    
    # 1D sparse matrix forward transform
    data = torch.arange(16, dtype=torch.float32)
    matrix_wavedec = ptwt.MatrixWavedec("haar", level=2)
    coeff = matrix_wavedec(data)
    
    # 1D sparse matrix backward transform
    matrix_waverec = ptwt.MatrixWaverec("haar")
    rec = matrix_waverec(coeff)
  2. How boundary wavelet filters ensure invertibility

    main

    When working with finite signals and higher-order wavelets, simple truncation of convolution matrices leads to a loss of information and prevents perfect reconstruction (i.e., $\mathbf{S}\mathbf{A} \neq \mathbf{I}$). Common methods like zero-padding or periodic extension can create artificial discontinuities at the boundaries.

    ptwt addresses this by using Gram-Schmidt boundary filters. These are specially constructed, shorter filters at the boundaries that preserve both the signal length and the perfect reconstruction property. When using ptwt.MatrixWavedec or ptwt.MatrixWaverec, the resulting matrices are orthogonalized/corrected so that their product results in an identity matrix, ensuring the transform is mathematically sound for finite-length inputs.

  3. Understand CWT Time-Scale Analysis

    main

    The Continuous Wavelet Transform (CWT) introduces the concept of scale alongside time, enabling a time-frequency representation of a signal.

    Key Concepts for Signal Analysis:

    • Wavelet Family: A mother wavelet $\psi(t)$ is transformed into a family of wavelets $\psi^{a,b}$ by scaling ($a$) and shifting ($b$).
    • Scale vs. Frequency: The scale parameter $a$ determines the frequency characteristics around a specific time point $t=b$.
    • Resolution Trade-off: There is an inherent trade-off between time and frequency resolution governed by the scale. Smaller scales focus on high-frequency components with high time precision, while larger scales focus on low-frequency components with high frequency precision.
    • Admissibility: For effective signal analysis (especially audio), wavelets should be mean-free and satisfy admissibility conditions to ensure signal energy normalization and invertibility.
    • Common Wavelets: The Morlet and Mexican-Hat wavelets are frequently used due to their favorable properties for time-frequency representation.
  4. Understand Wavelet-Packet Analysis for Deepfake Detection

    main

    Wavelet packets can be used to identify GAN-generated (fake) images by analyzing frequency energy distributions.

    Key Observation:

    • GAN-generated images (e.g., from StyleGAN) tend to exhibit higher energy in high-frequency bands compared to real images (e.g., from FFHQ).
    • This difference in high-frequency packet energy can be visualized using log-scaled mean absolute packet plots to distinguish between real and synthetic content.
  5. Understanding Wavelet Invertibility and Alias Cancellation

    main

    In the pytorch-wavelet-toolbox, wavelets are defined by their ability to satisfy two critical mathematical conditions:

    1. Perfect Reconstruction: Ensures the transform is invertible. For analysis filter coefficients $\mathbf{h}$ and synthesis filter coefficients $\mathbf{f}$, the condition is: $H_\mathcal{A}(z)F_\mathcal{A}(z) + H_\mathcal{D}(-z)F_\mathcal{D}(z) = 2z^{-l}$

    2. Alias Cancellation: Ensures an alias-free representation. The condition is: $F_\mathcal{A}(z)H_\mathcal{A}(-z) + F_\mathcal{D}(z)H_\mathcal{D}(-z) = 0$

    Filters that satisfy both equations are considered valid wavelets.

    Filter Characteristics

    • Daubechies Wavelets: Often exhibit alternating sign patterns between the decomposition highpass and reconstruction lowpass filters, which helps satisfy the alias cancellation condition.
    • Symlets: A variation of the Daubechies family. Symlets are designed to be more symmetric, typically having more mass concentrated at the center of the filter coefficients compared to Daubechies wavelets of the same degree.
  6. Adaptive Wavelets (Experimental)

    main

    The toolbox provides experimental support for training adaptive wavelet layers in PyTorch. This includes:

    • Adaptive product-filters
    • Optimizable orthogonal-wavelets

    Implementation examples can be found in the examples/network_compression/ directory of the repository.

  7. Understand 2D wavelet transform return types

    main

    2D wavelet transforms in ptwt return one of two types depending on the transform implementation:

    1. WaveletCoeff2d: The standard coefficient container for 2D transforms.
    2. WaveletDetailTuple2d: Used for specific 2D transform implementations where coefficients are returned as a tuple of detail components.
    3. WaveletCoeff2dSeparable: Specifically used for fully separable 2D transforms.
    WaveletCoeff2d
    WaveletDetailTuple2d
    WaveletCoeff2dSeparable
  8. Understand N-dimensional wavelet transform return types

    main

    For transforms in N dimensions, the library uses the following structures to return coefficients:

    • WaveletCoeffNd: The general container for N-dimensional wavelet coefficients.
    • WaveletDetailDict: A dictionary-based container used to organize detail coefficients in N-dimensional space.
    WaveletCoeffNd
    WaveletDetailDict
  9. Configure boundary handling modes in ptwt

    main

    The pytorch-wavelet-toolbox (ptwt) provides two primary strategies for handling signal boundaries when applying wavelet transforms to finite-size tensors:

    1. Signal extension via padding: Extends the signal using torch.nn.functional.pad. This is controlled via the BoundaryMode class.
    2. Boundary wavelets: Uses specialized boundary filters for coefficients located at the signal edges. This approach is managed via ExtendedBoundaryMode and PaddingMode.

    Choose padding when you want to extend the signal before the transform, and boundary wavelets when you want to use specific filter coefficients designed for edge cases.

  10. Setup speed tests for ptwt

    main

    To run the performance benchmarks provided in the examples, you must install ptwt along with its dependencies: pywt (PyWavelets) and pytorch-wavelets. You can re-run all available speed tests on your local machine using the run_all.sh script.

    # Ensure dependencies are installed
    pip install pywt pytorch-wavelets ptwt
    
    # Run all speed tests
    ./run_all.sh