Padding Utilities¶
spectrans.utils.padding ¶
Padding utilities for spectral transformations and signal processing.
This module provides comprehensive padding strategies specifically designed for spectral neural networks and signal processing operations. The padding functions maintain mathematical properties of transforms, handle boundary conditions properly, and optimize computational efficiency for various spectral operations.
Different padding modes are crucial for spectral transformers as they affect the mathematical properties of transforms, boundary artifacts, and computational efficiency. This module provides both basic and specialized padding operations with proper handling of edge cases and batch processing.
Functions:
| Name | Description |
|---|---|
pad_to_length |
Pad tensor to specified length with various padding modes. |
pad_to_power_of_2 |
Pad tensor to next power of 2 for efficient FFT operations. |
pad_for_fft |
Specialized padding for FFT operations with optimal performance. |
pad_for_convolution |
Pad tensor for convolution operations to maintain output size. |
zero_pad |
Apply zero padding along specified dimension. |
circular_pad |
Apply circular (periodic) padding for periodic signals. |
reflect_pad |
Apply reflection padding to minimize boundary artifacts. |
symmetric_pad |
Apply symmetric padding with proper boundary handling. |
pad_sequence |
Pad variable-length sequences to uniform length. |
unpad_to_length |
Remove padding to restore original tensor length. |
unpad_sequence |
Remove padding from batch of padded sequences. |
Examples:
Padding for FFT operations:
>>> import torch
>>> from spectrans.utils.padding import pad_to_power_of_2, pad_for_fft
>>> # Pad to nearest power of 2 for efficient FFT
>>> signal = torch.randn(32, 500) # Length 500
>>> padded = pad_to_power_of_2(signal, dim=-1) # Pads to 512
>>> print(f"Original: {signal.shape}, Padded: {padded.shape}")
>>>
>>> # Pad to specific FFT length
>>> fft_signal = pad_for_fft(signal, target_length=1024, dim=-1)
>>> # Use torch.fft.fft on fft_signal for optimal performance
Circular padding for periodic signals:
>>> from spectrans.utils.padding import circular_pad
>>> periodic_signal = torch.randn(32, 256)
>>> # Add 64 samples of circular padding on each side
>>> circularly_padded = circular_pad(periodic_signal, padding=64, dim=-1)
>>> # Signal boundaries are continuous (no edge discontinuities)
Reflection padding for boundary handling:
>>> from spectrans.utils.padding import reflect_pad
>>> image = torch.randn(32, 3, 224, 224)
>>> # Reflect pad for 2D convolution
>>> reflected = reflect_pad(image, padding=3, dim=(-2, -1))
>>> # Boundaries are smooth transitions
Variable-length sequence padding:
>>> from spectrans.utils.padding import pad_sequence
>>> sequences = [torch.randn(100, 768), torch.randn(150, 768), torch.randn(80, 768)]
>>> padded_batch = pad_sequence(sequences, batch_first=True, padding_value=0.0)
>>> # All sequences now have length 150 (max length)
Notes
Padding Strategies and Their Properties:
Zero Padding: - Adds zeros at boundaries - Simple and computationally efficient - Can introduce spectral artifacts due to discontinuities - Best for: General-purpose padding where simplicity is preferred
Circular Padding (Periodic): - Wraps signal around to create continuity - Maintains periodicity assumptions of DFT/FFT - No boundary artifacts in frequency domain - Best for: Periodic signals, DFT/FFT operations
Reflection Padding: - Mirrors signal at boundaries - Reduces boundary discontinuities - Maintains signal characteristics near boundaries - Best for: Image processing, minimizing edge effects
Symmetric Padding: - Creates symmetric extension of signal - Preserves certain symmetry properties - Useful for transforms with symmetry assumptions - Best for: DCT operations, symmetric signal processing
Mathematical Considerations:
- FFT Efficiency: Powers of 2 enable radix-2 FFT algorithms with optimal :math:
O(n \log n)complexity - Boundary Conditions: Different padding affects transform properties and numerical stability
- Aliasing: Improper padding can introduce aliasing artifacts in frequency domain
- Memory Usage: Padding increases memory requirements, important for large signals
Implementation Details:
- Batch Processing: All functions handle batched inputs efficiently
- Multi-Dimensional: Support for padding along multiple dimensions simultaneously
- Type Preservation: Maintains input tensor dtype and device
- Memory Efficiency: In-place operations where safe, memory-efficient algorithms
- Error Handling: Comprehensive validation of input parameters and dimensions
Performance Optimizations:
- Vectorized Operations: Use PyTorch's native vectorized padding operations
- GPU Acceleration: All operations are GPU-compatible
- Memory Layout: Optimized for PyTorch's memory layout conventions
- Caching: Efficient memory allocation patterns for repeated operations
Common Pitfalls:
- Padding too aggressively can change signal characteristics
- Wrong padding mode can introduce artifacts in spectral domain
- Not accounting for padding when calculating output sizes
- Forgetting to unpad results when original size is needed
See Also
spectrans.transforms : Spectral transforms requiring specific padding spectrans.utils.complex : Complex tensor operations for padded signals torch.nn.functional : PyTorch's native padding functions
Functions¶
pad_to_length ¶
Pad tensor to specified length along given dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor to pad. |
required |
target_length
|
int
|
Target length after padding. |
required |
dim
|
int
|
Dimension to pad along. |
-1
|
mode
|
str
|
Padding mode: "zero", "circular", "reflect", "symmetric". |
"zero"
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Padded tensor with target length along specified dimension. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If target_length is smaller than current length, or invalid mode. |
IndexError
|
If dimension is out of bounds. |
Source code in spectrans/utils/padding.py
unpad_to_length ¶
Remove padding to restore original length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Padded tensor. |
required |
target_length
|
int
|
Original length before padding. |
required |
dim
|
int
|
Dimension to unpad along. |
-1
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor with padding removed. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If target_length is larger than current length. |
IndexError
|
If dimension is out of bounds. |
Source code in spectrans/utils/padding.py
pad_sequence ¶
Pad a list of sequences to the same length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sequences
|
list[Tensor]
|
List of tensors to pad. |
required |
padding_value
|
float
|
Value to use for padding. |
0.0
|
dim
|
int
|
Dimension to pad along. |
-1
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Batched tensor with all sequences padded to same length. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If sequences is empty or tensors have incompatible shapes. |
IndexError
|
If dimension is out of bounds. |
Source code in spectrans/utils/padding.py
unpad_sequence ¶
Unpad a batched tensor back to individual sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
padded_tensor
|
Tensor
|
Batched, padded tensor. |
required |
lengths
|
list[int]
|
Original lengths of each sequence. |
required |
dim
|
int
|
Dimension that was padded. |
-1
|
Returns:
| Type | Description |
|---|---|
list[Tensor]
|
List of unpadded sequences. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If lengths don't match batch size. |
IndexError
|
If dimension is out of bounds. |
Source code in spectrans/utils/padding.py
circular_pad ¶
Apply circular (periodic) padding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
pad_amount
|
int
|
Number of elements to pad. |
required |
dim
|
int
|
Dimension to pad along. |
-1
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Circularly padded tensor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If pad_amount is negative or exceeds tensor size. |
IndexError
|
If dimension is out of bounds. |
Source code in spectrans/utils/padding.py
reflect_pad ¶
Apply reflection padding (mirror without repeating edge).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
pad_amount
|
int
|
Number of elements to pad. |
required |
dim
|
int
|
Dimension to pad along. |
-1
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Reflection padded tensor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If pad_amount is negative or too large for reflection. |
IndexError
|
If dimension is out of bounds. |
Source code in spectrans/utils/padding.py
symmetric_pad ¶
Apply symmetric padding (mirror including edge).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
pad_amount
|
int
|
Number of elements to pad. |
required |
dim
|
int
|
Dimension to pad along. |
-1
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Symmetrically padded tensor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If pad_amount is negative or too large for symmetry. |
IndexError
|
If dimension is out of bounds. |
Source code in spectrans/utils/padding.py
zero_pad ¶
Apply zero (constant) padding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
pad_amount
|
int
|
Number of elements to pad. |
required |
dim
|
int
|
Dimension to pad along. |
-1
|
value
|
float
|
Constant value to pad with. |
0.0
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Zero-padded tensor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If pad_amount is negative. |
IndexError
|
If dimension is out of bounds. |
Source code in spectrans/utils/padding.py
pad_for_fft ¶
Pad tensor to optimal size for FFT computation.
Pads to next power of 2 for optimal FFT performance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
dim
|
int
|
Dimension to pad along. |
-1
|
Returns:
| Type | Description |
|---|---|
tuple[Tensor, int]
|
Tuple of (padded_tensor, original_length). |
Raises:
| Type | Description |
|---|---|
IndexError
|
If dimension is out of bounds. |
ValueError
|
If tensor is empty along specified dimension. |
Source code in spectrans/utils/padding.py
pad_to_power_of_2 ¶
Find next power of 2 greater than or equal to length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
length
|
int
|
Input length. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Next power of 2. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If length is not positive. |
Source code in spectrans/utils/padding.py
wavelet_symmetric_pad ¶
Apply symmetric padding for wavelet transforms (PyWavelets-compatible).
This implements the exact symmetric padding used by PyWavelets which reflects the signal WITH edge repeat. This is equivalent to numpy's 'symmetric' mode and PyTorch's 'reflect' mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor to pad. |
required |
pad_len
|
int
|
Number of samples to pad on each side. |
required |
dim
|
int
|
Dimension along which to pad. |
-1
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Symmetrically padded tensor. |
Examples:
>>> x = torch.tensor([1, 2, 3, 4])
>>> padded = wavelet_symmetric_pad(x, 3)
>>> # Result: [3, 2, 1, 1, 2, 3, 4, 4, 3, 2]
Notes
For signal [a,b,c,d] with pad_len=3, creates [c,b,a|a,b,c,d|d,c,b]. This ensures continuity at boundaries for wavelet transforms.
Source code in spectrans/utils/padding.py
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 | |
pad_for_convolution ¶
Pad tensor for valid convolution without size reduction.
Applies symmetric padding to both sides of the specified dimension to ensure that convolution output has the same size as input (same padding).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
kernel_size
|
int
|
Size of convolution kernel. |
required |
dim
|
int
|
Dimension to pad along. |
-1
|
mode
|
str
|
Padding mode: "zero", "circular", "reflect", "symmetric". |
"zero"
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Padded tensor suitable for convolution. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If kernel_size is not positive odd integer or mode is invalid. |
IndexError
|
If dimension is out of bounds. |
Source code in spectrans/utils/padding.py
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 | |