Utility Functions¶
spectrans.utils ¶
Utility functions for spectral transformer implementations.
This module provides utility functions for spectral neural networks, including specialized complex number operations, initialization schemes for spectral parameters, and padding utilities for signal processing operations.
These utilities are designed to support the mathematical rigor and numerical stability required for spectral transformer architectures while providing convenient abstractions for common operations.
Modules:
| Name | Description |
|---|---|
complex |
Complex tensor operations and utilities. |
initialization |
Parameter initialization schemes for spectral networks. |
padding |
Padding utilities for signal processing. |
Functions:
| Name | Description |
|---|---|
complex_conjugate |
Compute complex conjugate with proper error handling. |
complex_multiply |
Element-wise complex multiplication with broadcasting. |
complex_divide |
Complex division with zero-division safety checks. |
complex_modulus |
Compute magnitude of complex tensors. |
complex_phase |
Extract phase angles from complex tensors. |
complex_polar |
Construct complex tensors from polar coordinates. |
complex_exp |
Complex exponential function. |
complex_log |
Complex logarithm with numerical safety. |
complex_relu |
ReLU activation applied to both real and imaginary parts. |
complex_dropout |
Dropout preserving phase relationships. |
make_complex |
Construct complex tensors from real/imaginary parts. |
split_complex |
Split complex tensors into real/imaginary components. |
spectral_init |
Initialize parameters for spectral neural networks. |
frequency_init |
Initialize parameters with frequency-domain properties. |
orthogonal_spectral_init |
Initialize with orthogonality constraints. |
complex_xavier_init |
Xavier initialization for complex-valued parameters. |
complex_kaiming_init |
Kaiming initialization for complex parameters. |
pad_to_power_of_2 |
Pad tensor to next power of 2 for efficient FFT. |
pad_for_fft |
Pad tensor for FFT operations. |
circular_pad |
Apply circular (periodic) padding. |
reflect_pad |
Apply reflection padding for boundary handling. |
Examples:
Complex number operations:
>>> import torch
>>> from spectrans.utils import complex_multiply, complex_polar, split_complex
>>> # Create complex tensors
>>> z1 = torch.complex(torch.randn(10), torch.randn(10))
>>> z2 = torch.complex(torch.randn(10), torch.randn(10))
>>> product = complex_multiply(z1, z2)
>>>
>>> # Convert to polar form
>>> magnitude = torch.abs(z1)
>>> phase = torch.angle(z1)
>>> z1_reconstructed = complex_polar(magnitude, phase)
Spectral parameter initialization:
>>> from spectrans.utils import spectral_init, complex_xavier_init
>>> import torch.nn as nn
>>> # Initialize a linear layer for spectral transforms
>>> linear = nn.Linear(512, 512)
>>> spectral_init(linear.weight, method='frequency')
>>>
>>> # Initialize complex-valued parameters
>>> complex_params = torch.empty(256, 256, dtype=torch.complex64)
>>> complex_xavier_init(complex_params)
Padding for spectral operations:
>>> from spectrans.utils import pad_to_power_of_2, pad_for_fft
>>> signal = torch.randn(32, 500) # 500 is not power of 2
>>> padded = pad_to_power_of_2(signal, dim=-1) # Pads to 512
>>>
>>> # Pad to specific FFT length
>>> fft_ready = pad_for_fft(signal, target_length=1024, dim=-1)
Notes
Design Philosophy:
The utility functions follow these principles:
-
Mathematical Safety: All operations include proper error checking and handle edge cases (zeros, infinities, etc.)
-
Numerical Stability: Implementations prioritize numerical stability over raw performance where trade-offs exist
-
Type Safety: Type checking and clear error messages for incorrect usage patterns
-
Gradient Compatibility: All operations support automatic differentiation for end-to-end neural network training
-
Broadcasting Support: Operations follow PyTorch broadcasting conventions for flexible tensor manipulation
Complex Number Operations:
The complex utilities provide a consistent interface for complex tensor operations with proper error handling and mathematical safety. While many wrap existing PyTorch functions, they add domain-specific validation and optimization for spectral neural networks.
Initialization Schemes:
Spectral neural networks often require specialized parameter initialization due to: - Different scaling properties of spectral transforms - Complex-valued parameters requiring magnitude/phase initialization - Orthogonality constraints for certain spectral methods - Frequency-domain parameter interpretation
Padding Utilities:
Signal processing operations often require specific padding strategies: - Power-of-2 lengths for efficient FFT computation - Circular padding for periodic signal assumptions - Reflection padding for boundary effect minimization - Zero padding with proper unpadding for shape restoration
Performance Considerations:
- All utilities are optimized for batch operations
- GPU acceleration through native PyTorch operations
- Memory efficiency with in-place operations where safe
- Vectorized implementations for throughput
See Also
spectrans.utils.complex : Complex tensor operations
spectrans.utils.initialization : Parameter initialization schemes
spectrans.utils.padding : Padding utilities for signal processing
spectrans.transforms : Spectral transforms using these utilities
Functions¶
complex_conjugate ¶
Compute complex conjugate of input tensor.
Essential operation for spectral transforms, particularly for ensuring Hermitian symmetry in frequency domain operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input complex tensor. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Complex conjugate tensor. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If input is not a complex tensor. |
Source code in spectrans/utils/complex.py
complex_divide ¶
Divide two complex tensors element-wise.
Essential for spectral filtering operations. Includes safety checks for division by zero, which can occur in spectral nulls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Tensor
|
Numerator complex tensor. |
required |
b
|
Tensor
|
Denominator complex tensor. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Complex division result. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If inputs are not complex tensors. |
ValueError
|
If denominator contains zeros. |
RuntimeError
|
If tensors cannot be broadcast together. |
Source code in spectrans/utils/complex.py
complex_dropout ¶
Apply dropout to complex tensor.
Applies dropout to magnitude while preserving phase relationships. This is superior to independent real/imaginary dropout for spectral data.
This specialized dropout maintains the complex structure essential for spectral transformations while providing regularization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input complex tensor. |
required |
p
|
float
|
Dropout probability. |
0.5
|
training
|
bool
|
Whether in training mode. |
True
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Complex tensor with dropout applied. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If input is not a complex tensor. |
ValueError
|
If dropout probability is not in [0, 1]. |
Source code in spectrans/utils/complex.py
complex_exp ¶
Compute complex exponential e^x.
Core operation for Fourier transforms and oscillatory functions. Accepts both real and complex inputs for flexibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor (can be real or complex). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Complex exponential tensor. |
Source code in spectrans/utils/complex.py
complex_log ¶
Compute complex natural logarithm.
Used in spectral domain operations and inverse transforms. Includes safety check for zeros where logarithm is undefined.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input complex tensor. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Complex logarithm tensor. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If input is not a complex tensor. |
ValueError
|
If input contains zeros (logarithm undefined). |
Source code in spectrans/utils/complex.py
complex_modulus ¶
Compute magnitude (absolute value) of complex tensor.
Critical for spectral analysis where magnitude represents signal energy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input complex tensor. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Real tensor containing magnitudes. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If input is not a complex tensor. |
Source code in spectrans/utils/complex.py
complex_multiply ¶
Multiply two complex tensors element-wise.
Performs (a_real + ia_imag) * (b_real + ib_imag) efficiently. Supports broadcasting according to PyTorch broadcasting rules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Tensor
|
First complex tensor. |
required |
b
|
Tensor
|
Second complex tensor. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Complex product tensor. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If inputs are not complex tensors. |
RuntimeError
|
If tensors cannot be broadcast together. |
Source code in spectrans/utils/complex.py
complex_phase ¶
Compute phase angle of complex tensor.
Phase information is crucial for spectral transformations and filter design.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input complex tensor. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Real tensor containing phase angles in radians [-π, π]. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If input is not a complex tensor. |
Source code in spectrans/utils/complex.py
complex_polar ¶
Construct complex tensor from magnitude and phase.
Fundamental for spectral operations where separate magnitude and phase processing is required. Includes validation for non-negative magnitudes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
magnitude
|
Tensor
|
Real tensor containing magnitudes (must be non-negative). |
required |
phase
|
Tensor
|
Real tensor containing phase angles in radians. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Complex tensor constructed from polar coordinates. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If inputs are not real tensors. |
ValueError
|
If magnitude contains negative values. |
RuntimeError
|
If tensors cannot be broadcast together. |
Source code in spectrans/utils/complex.py
complex_relu ¶
Apply ReLU activation to complex tensor.
Applies ReLU to both real and imaginary parts independently. Note: This is not holomorphic but useful for some neural architectures.
This specialized activation is designed for complex-valued neural networks in spectral transformers where non-linearity is needed in both components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input complex tensor. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Complex tensor with ReLU applied to each part. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If input is not a complex tensor. |
Source code in spectrans/utils/complex.py
make_complex ¶
Construct complex tensor from real and imaginary parts.
Fundamental constructor for complex tensors in spectral transforms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
real
|
Tensor
|
Real part tensor. |
required |
imag
|
Tensor
|
Imaginary part tensor. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Complex tensor. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If inputs are not real tensors. |
RuntimeError
|
If tensors cannot be broadcast together. |
Source code in spectrans/utils/complex.py
split_complex ¶
Split complex tensor into real and imaginary parts.
Useful for separate processing of real and imaginary components in spectral neural networks and filter implementations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input complex tensor. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Tensor, Tensor]
|
Tuple of (real_part, imaginary_part) tensors. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If input is not a complex tensor. |
Source code in spectrans/utils/complex.py
complex_kaiming_init ¶
complex_kaiming_init(tensor: Tensor, gain: float = 1.0, mode: Literal['fan_in', 'fan_out'] = 'fan_in') -> Tensor
Kaiming initialization for complex tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
Complex tensor to initialize. |
required |
gain
|
float
|
Scaling factor for initialization. |
1.0
|
mode
|
(fan_in, fan_out)
|
Fan mode for variance calculation. |
"fan_in"
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Initialized complex tensor. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If tensor is not complex. |
ValueError
|
If tensor dimensions or parameters are invalid. |
Source code in spectrans/utils/initialization.py
complex_normal_init ¶
Initialize complex tensor with complex normal distribution.
Both real and imaginary parts are initialized independently with normal distribution scaled to maintain proper variance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
Complex tensor to initialize. |
required |
std
|
float
|
Standard deviation for each component. |
1.0
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Initialized complex tensor. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If tensor is not complex. |
ValueError
|
If std is not positive. |
Source code in spectrans/utils/initialization.py
complex_xavier_init ¶
Xavier initialization for complex tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
Complex tensor to initialize. |
required |
gain
|
float
|
Scaling factor for initialization. |
1.0
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Initialized complex tensor. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If tensor is not complex. |
ValueError
|
If tensor dimensions or gain are invalid. |
Source code in spectrans/utils/initialization.py
dct_init ¶
Initialize tensor with DCT matrix properties.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
2D tensor to initialize. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Initialized tensor with DCT-like structure. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If tensor is not 2D. |
Source code in spectrans/utils/initialization.py
frequency_init ¶
Initialize tensor with frequency-domain aware values.
Initializes with small values at high frequencies and larger values at low frequencies, mimicking natural signal characteristics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
Tensor to initialize (typically frequency domain parameters). |
required |
max_freq
|
float
|
Maximum frequency for scaling. |
1.0
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Initialized tensor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If max_freq is not positive. |
Source code in spectrans/utils/initialization.py
hadamard_init ¶
Initialize tensor with Hadamard matrix properties.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
Square tensor to initialize. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Initialized tensor with Hadamard-like structure. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If tensor is not square or not power-of-2 sized. |
Source code in spectrans/utils/initialization.py
init_conv_spectral ¶
Initialize convolution layer with spectral-aware method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conv
|
Conv1d | Conv2d
|
Convolution layer to initialize. |
required |
method
|
str
|
Initialization method: "xavier", "kaiming". |
"kaiming"
|
Returns:
| Type | Description |
|---|---|
Conv1d | Conv2d
|
Initialized convolution layer. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If method is not supported. |
Source code in spectrans/utils/initialization.py
init_linear_spectral ¶
Initialize linear layer with spectral-aware method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
linear
|
Linear
|
Linear layer to initialize. |
required |
method
|
str
|
Initialization method: "xavier", "kaiming", "orthogonal". |
"xavier"
|
Returns:
| Type | Description |
|---|---|
Linear
|
Initialized linear layer. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If method is not supported. |
Source code in spectrans/utils/initialization.py
kaiming_spectral_init ¶
kaiming_spectral_init(tensor: Tensor, gain: float = 1.0, mode: Literal['fan_in', 'fan_out'] = 'fan_in', nonlinearity: str = 'relu') -> Tensor
Kaiming/He initialization adapted for spectral transforms.
Designed for networks with ReLU-like activations, maintaining variance through forward/backward passes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
Tensor to initialize. |
required |
gain
|
float
|
Scaling factor for initialization. |
1.0
|
mode
|
(fan_in, fan_out)
|
Fan mode for variance calculation. |
"fan_in"
|
nonlinearity
|
str
|
Nonlinearity type for gain calculation. |
"relu"
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Initialized tensor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If tensor has fewer than 2 dimensions, parameters are invalid. |
Source code in spectrans/utils/initialization.py
orthogonal_spectral_init ¶
Orthogonal initialization for spectral transform matrices.
Creates orthogonal matrices that preserve norms, which is important for spectral transforms that should maintain energy conservation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
2D tensor to initialize. |
required |
gain
|
float
|
Scaling factor for the orthogonal matrix. |
1.0
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Initialized orthogonal tensor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If tensor is not 2D or gain is not positive. |
Source code in spectrans/utils/initialization.py
spectral_init ¶
Initialize tensor with spectral-aware method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
Tensor to initialize. |
required |
mode
|
str
|
Initialization mode: "normal", "uniform", "xavier", "kaiming", "orthogonal". |
"normal"
|
gain
|
float
|
Scaling factor for initialization. |
1.0
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Initialized tensor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If mode is not supported or gain is not positive. |
RuntimeError
|
If tensor is not 2D for orthogonal initialization. |
Source code in spectrans/utils/initialization.py
wavelet_init ¶
Initialize tensor with wavelet-like properties.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
Tensor to initialize. |
required |
wavelet_type
|
str
|
Type of wavelet initialization. |
"db1"
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Initialized tensor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If wavelet_type is not supported. |
Source code in spectrans/utils/initialization.py
xavier_spectral_init ¶
xavier_spectral_init(tensor: Tensor, gain: float = 1.0, distribution: Literal['normal', 'uniform'] = 'normal') -> Tensor
Xavier/Glorot initialization adapted for spectral transforms.
Maintains variance of activations and gradients across layers by scaling based on input and output dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
Tensor to initialize. |
required |
gain
|
float
|
Scaling factor for initialization. |
1.0
|
distribution
|
(normal, uniform)
|
Distribution to use for initialization. |
"normal"
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Initialized tensor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If tensor has fewer than 2 dimensions, gain is not positive, or distribution is invalid. |
Source code in spectrans/utils/initialization.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
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 | |
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_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
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
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
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
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
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
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. |