Validation#

The validation module provides custom exceptions and validation utilities for parameter validation across TorchFX.

Overview#

TorchFX provides a comprehensive validation system with:

  • Custom exception hierarchy for specific error handling

  • Validator functions for common validation patterns

  • Context-aware error messages with suggestions for fixes

Import validation utilities:

from torchfx.validation import (
    TorchFXError,
    InvalidParameterError,
    validate_sample_rate,
    validate_range,
)

Exception Hierarchy#

All exceptions inherit from TorchFXError, enabling users to catch all library-specific errors with a single except clause:

try:
    # TorchFX operations
    wave = Wave.from_file("audio.wav")
    processed = wave | some_filter
except TorchFXError as e:
    print(f"TorchFX error: {e}")

The exception hierarchy is organized as follows:

TorchFXError (base)
├── InvalidParameterError
│   ├── InvalidSampleRateError
│   ├── InvalidRangeError
│   ├── InvalidShapeError
│   └── InvalidTypeError
└── AudioProcessingError
    ├── CoefficientComputationError
    └── FilterInstabilityError

Base Exception#

class torchfx.validation.TorchFXError(message, parameter_name=None, actual_value=None, suggestion=None)[source]#

Bases: Exception

Base exception for all TorchFX library errors.

All custom exceptions in TorchFX inherit from this class, enabling users to catch all library-specific errors with a single except clause.

Parameters:
  • message (str) – Human-readable error message.

  • parameter_name (str | None, optional) – Name of the parameter that caused the error, if applicable.

  • actual_value (Any | None, optional) – The actual value that caused the error.

  • suggestion (str | None, optional) – A suggestion for fixing the error.

Examples

>>> try:
...     raise TorchFXError("Something went wrong")
... except TorchFXError as e:
...     print(f"Error: {e}")
Error: Something went wrong

Parameter Validation Exceptions#

class torchfx.validation.InvalidParameterError(message, parameter_name, actual_value, expected=None, suggestion=None)[source]#

Bases: TorchFXError

Exception raised when a parameter value is invalid.

This is the base class for all parameter validation errors. Use more specific subclasses when possible.

Parameters:
  • message (str) – Human-readable error message.

  • parameter_name (str) – Name of the invalid parameter.

  • actual_value (Any) – The actual value that was provided.

  • expected (str | None, optional) – Description of what was expected.

  • suggestion (str | None, optional) – A suggestion for fixing the error.

Examples

>>> raise InvalidParameterError(
...     "Cutoff frequency must be positive",
...     parameter_name="cutoff",
...     actual_value=-100,
...     expected="positive float",
... )
Traceback (most recent call last):
    ...
torchfx.validation.exceptions.InvalidParameterError: ...
class torchfx.validation.InvalidSampleRateError(actual_value, suggestion=None)[source]#

Bases: InvalidParameterError

Exception raised when sample rate is invalid.

Sample rate must be a positive integer within reasonable bounds for audio processing (typically 1 Hz to 384000 Hz).

Parameters:
  • actual_value (int | None) – The invalid sample rate value.

  • suggestion (str | None, optional) – A suggestion for fixing the error.

Examples

>>> raise InvalidSampleRateError(actual_value=-44100)
Traceback (most recent call last):
    ...
torchfx.validation.exceptions.InvalidSampleRateError: ...
class torchfx.validation.InvalidRangeError(parameter_name, actual_value, min_value=None, max_value=None, min_inclusive=True, max_inclusive=True)[source]#

Bases: InvalidParameterError

Exception raised when a value is outside expected bounds.

Parameters:
  • parameter_name (str) – Name of the parameter.

  • actual_value (float | int) – The actual value that was provided.

  • min_value (float | int | None, optional) – Minimum allowed value. None means no minimum.

  • max_value (float | int | None, optional) – Maximum allowed value. None means no maximum.

  • min_inclusive (bool, optional) – If True, min_value is included in the range. Default is True.

  • max_inclusive (bool, optional) – If True, max_value is included in the range. Default is True.

Examples

>>> raise InvalidRangeError("decay", 1.5, min_value=0, max_value=1)
Traceback (most recent call last):
    ...
torchfx.validation.exceptions.InvalidRangeError: ...
class torchfx.validation.InvalidShapeError(parameter_name, actual_shape, expected_ndim=None, expected_shape=None, suggestion=None)[source]#

Bases: InvalidParameterError

Exception raised when tensor shape is invalid.

Parameters:
  • parameter_name (str) – Name of the parameter.

  • actual_shape (tuple[int, ...]) – The actual shape of the tensor.

  • expected_ndim (int | None, optional) – Expected number of dimensions.

  • expected_shape (tuple[int | None, ...] | None, optional) – Expected shape (None elements are wildcards).

  • suggestion (str | None, optional) – A suggestion for fixing the error.

Examples

>>> raise InvalidShapeError(
...     "waveform",
...     actual_shape=(4, 2, 1000),
...     expected_ndim=2,
...     suggestion="Audio should be (channels, samples)"
... )
Traceback (most recent call last):
    ...
torchfx.validation.exceptions.InvalidShapeError: ...
class torchfx.validation.InvalidTypeError(parameter_name, actual_type, expected_types)[source]#

Bases: InvalidParameterError

Exception raised when a parameter has an invalid type.

Parameters:
  • parameter_name (str) – Name of the parameter.

  • actual_type (type) – The actual type of the value.

  • expected_types (tuple[type, ...]) – Tuple of expected types.

Examples

>>> raise InvalidTypeError(
...     "gain",
...     actual_type=str,
...     expected_types=(int, float),
... )
Traceback (most recent call last):
    ...
torchfx.validation.exceptions.InvalidTypeError: ...

Audio Processing Exceptions#

class torchfx.validation.AudioProcessingError(message, parameter_name=None, actual_value=None, suggestion=None)[source]#

Bases: TorchFXError

Exception raised during audio processing operations.

This error indicates a problem during the actual processing of audio, not during parameter validation.

Parameters:
  • message (str) – Human-readable error message.

  • suggestion (str | None, optional) – A suggestion for fixing the error.

  • parameter_name (str | None)

  • actual_value (Any | None)

Examples

>>> raise AudioProcessingError(
...     "Failed to process audio buffer",
...     suggestion="Check input tensor dimensions"
... )
Traceback (most recent call last):
    ...
torchfx.validation.exceptions.AudioProcessingError: ...
class torchfx.validation.CoefficientComputationError(filter_type, reason, suggestion=None)[source]#

Bases: AudioProcessingError

Exception raised when filter coefficient computation fails.

This typically occurs when filter parameters result in mathematically invalid or numerically unstable coefficients.

Parameters:
  • filter_type (str) – The type of filter that failed.

  • reason (str) – The reason for the failure.

  • suggestion (str | None, optional) – A suggestion for fixing the error.

Examples

>>> raise CoefficientComputationError(
...     filter_type="LoButterworth",
...     reason="Cutoff frequency exceeds Nyquist",
... )
Traceback (most recent call last):
    ...
torchfx.validation.exceptions.CoefficientComputationError: ...
class torchfx.validation.FilterInstabilityError(filter_type, suggestion=None)[source]#

Bases: AudioProcessingError

Exception raised when a filter is numerically unstable.

Unstable filters can produce infinite or NaN values and should not be used for audio processing.

Parameters:
  • filter_type (str) – The type of filter that is unstable.

  • suggestion (str | None, optional) – A suggestion for fixing the error.

Examples

>>> raise FilterInstabilityError(
...     filter_type="HiChebyshev1",
...     suggestion="Try reducing filter order",
... )
Traceback (most recent call last):
    ...
torchfx.validation.exceptions.FilterInstabilityError: ...

Validator Functions#

Sample Rate Validation#

torchfx.validation.validate_sample_rate(fs, *, allow_none=False, min_rate=1, max_rate=384000)[source]#

Validate a sample rate parameter.

Parameters:
  • fs (int | None) – The sample rate to validate.

  • allow_none (bool, optional) – If True, None is a valid value (for lazy initialization). Default is False.

  • min_rate (int, optional) – Minimum allowed sample rate in Hz. Default is 1.

  • max_rate (int, optional) – Maximum allowed sample rate in Hz. Default is 384000.

Raises:

InvalidSampleRateError – If the sample rate is invalid.

Return type:

None

Examples

>>> validate_sample_rate(44100)  # OK
>>> validate_sample_rate(None, allow_none=True)  # OK
>>> validate_sample_rate(-1)  # Raises InvalidSampleRateError

Range Validation#

torchfx.validation.validate_positive(value, parameter_name, *, allow_zero=False)[source]#

Validate that a value is positive.

Parameters:
  • value (int | float) – The value to validate.

  • parameter_name (str) – Name of the parameter (for error messages).

  • allow_zero (bool, optional) – If True, zero is allowed. Default is False.

Raises:

InvalidRangeError – If the value is not positive (or non-negative if allow_zero=True).

Return type:

None

Examples

>>> validate_positive(1.0, "cutoff")  # OK
>>> validate_positive(0, "cutoff", allow_zero=True)  # OK
>>> validate_positive(-1, "cutoff")  # Raises InvalidRangeError
torchfx.validation.validate_range(value, parameter_name, *, min_value=None, max_value=None, min_inclusive=True, max_inclusive=True)[source]#

Validate that a value falls within a specified range.

Parameters:
  • value (int | float) – The value to validate.

  • parameter_name (str) – Name of the parameter (for error messages).

  • min_value (int | float | None, optional) – Minimum allowed value. None means no minimum.

  • max_value (int | float | None, optional) – Maximum allowed value. None means no maximum.

  • min_inclusive (bool, optional) – If True, min_value is included in the range. Default is True.

  • max_inclusive (bool, optional) – If True, max_value is included in the range. Default is True.

Raises:

InvalidRangeError – If the value is outside the specified range.

Return type:

None

Examples

>>> validate_range(0.5, "decay", min_value=0, max_value=1)  # OK
>>> validate_range(0, "decay", min_value=0, max_value=1, min_inclusive=False)  # Raises
torchfx.validation.validate_in_set(value, parameter_name, valid_values)[source]#

Validate that a value is in a set of allowed values.

Parameters:
  • value (Any) – The value to validate.

  • parameter_name (str) – Name of the parameter (for error messages).

  • valid_values (Sequence[Any]) – Sequence of allowed values.

Raises:

InvalidParameterError – If the value is not in the set of valid values.

Return type:

None

Examples

>>> validate_in_set("amplitude", "gain_type", ["amplitude", "db", "power"])  # OK
>>> validate_in_set("invalid", "gain_type", ["amplitude", "db", "power"])  # Raises

Tensor Shape Validation#

torchfx.validation.validate_tensor_ndim(tensor, parameter_name, *, expected_ndim)[source]#

Validate tensor dimensionality.

Parameters:
  • tensor (Tensor) – The tensor to validate.

  • parameter_name (str) – Name of the parameter (for error messages).

  • expected_ndim (int | Sequence[int]) – Expected number of dimensions, or sequence of allowed dimensions.

Raises:

InvalidShapeError – If the tensor has wrong number of dimensions.

Return type:

None

Examples

>>> t = torch.randn(2, 1000)
>>> validate_tensor_ndim(t, "waveform", expected_ndim=2)  # OK
>>> validate_tensor_ndim(t, "waveform", expected_ndim=[1, 2, 3])  # OK
torchfx.validation.validate_audio_tensor(tensor, parameter_name='waveform', *, allow_mono=True, min_channels=None, max_channels=None, min_samples=None)[source]#

Validate an audio tensor has correct shape.

Audio tensors in TorchFX should have shape: - [T] for mono (if allow_mono=True) - [C, T] for multi-channel - [B, C, T] for batched multi-channel

Parameters:
  • tensor (Tensor) – The audio tensor to validate.

  • parameter_name (str, optional) – Name of the parameter. Default is “waveform”.

  • allow_mono (bool, optional) – If True, allow 1D mono tensors. Default is True.

  • min_channels (int | None, optional) – Minimum number of channels required.

  • max_channels (int | None, optional) – Maximum number of channels allowed.

  • min_samples (int | None, optional) – Minimum number of samples required.

Raises:

InvalidShapeError – If the tensor shape is invalid for audio.

Return type:

None

Examples

>>> mono = torch.randn(1000)
>>> stereo = torch.randn(2, 1000)
>>> validate_audio_tensor(mono)  # OK
>>> validate_audio_tensor(stereo)  # OK
>>> validate_audio_tensor(stereo, min_channels=2)  # OK

Type Validation#

torchfx.validation.validate_type(value, parameter_name, expected_types)[source]#

Validate that a value has the expected type.

Parameters:
  • value (Any) – The value to validate.

  • parameter_name (str) – Name of the parameter (for error messages).

  • expected_types (type | tuple[type, ...]) – Expected type or tuple of expected types.

Raises:

InvalidTypeError – If the value is not of the expected type.

Return type:

None

Examples

>>> validate_type(1.0, "gain", (int, float))  # OK
>>> validate_type("hello", "gain", (int, float))  # Raises InvalidTypeError

Audio-Specific Validation#

torchfx.validation.validate_cutoff_frequency(cutoff, fs, parameter_name='cutoff')[source]#

Validate a filter cutoff frequency.

The cutoff must be positive and below the Nyquist frequency (fs/2).

Parameters:
  • cutoff (float) – Cutoff frequency in Hz.

  • fs (int | None) – Sample rate in Hz. If None, only validates that cutoff is positive.

  • parameter_name (str, optional) – Parameter name for error messages. Default is “cutoff”.

Raises:

InvalidRangeError – If cutoff is invalid.

Return type:

None

Examples

>>> validate_cutoff_frequency(1000, 44100)  # OK
>>> validate_cutoff_frequency(30000, 44100)  # Raises (above Nyquist)
torchfx.validation.validate_filter_order(order, parameter_name='order', *, min_order=1, max_order=None)[source]#

Validate a filter order parameter.

Parameters:
  • order (int) – Filter order to validate.

  • parameter_name (str, optional) – Parameter name for error messages. Default is “order”.

  • min_order (int, optional) – Minimum allowed order. Default is 1.

  • max_order (int | None, optional) – Maximum allowed order. None means no maximum.

Raises:
Return type:

None

Examples

>>> validate_filter_order(4)  # OK
>>> validate_filter_order(0)  # Raises InvalidRangeError
torchfx.validation.validate_q_factor(q, parameter_name='q', *, min_q=0.001, max_q=None)[source]#

Validate a Q factor (quality factor) parameter.

Parameters:
  • q (float) – Q factor to validate.

  • parameter_name (str, optional) – Parameter name for error messages. Default is “q”.

  • min_q (float, optional) – Minimum allowed Q. Default is 0.001.

  • max_q (float | None, optional) – Maximum allowed Q. None means no maximum.

Raises:

InvalidRangeError – If Q is invalid.

Return type:

None

Examples

>>> validate_q_factor(0.707)  # OK
>>> validate_q_factor(0)  # Raises InvalidRangeError

Constants#

torchfx.validation.COMMON_SAMPLE_RATES = (8000, 11025, 16000, 22050, 44100, 48000, 88200, 96000, 176400, 192000)#

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items.

If the argument is a tuple, the return value is the same object.

Usage Examples#

Validating Parameters in Custom Effects#

from torchfx import FX
from torchfx.validation import (
    validate_positive,
    validate_range,
    validate_sample_rate,
)

class CustomEffect(FX):
    def __init__(
        self,
        gain: float,
        mix: float = 0.5,
        fs: int | None = None,
    ) -> None:
        super().__init__()

        # Validate parameters
        validate_positive(gain, "gain")
        validate_range(mix, "mix", min_value=0, max_value=1)
        validate_sample_rate(fs, allow_none=True)

        self.gain = gain
        self.mix = mix
        self.fs = fs

Validating Audio Tensors#

import torch
from torchfx.validation import validate_audio_tensor

def process_audio(waveform: torch.Tensor) -> torch.Tensor:
    # Ensure tensor is valid audio shape
    validate_audio_tensor(
        waveform,
        min_channels=1,
        max_channels=8,
        min_samples=100,
    )
    # Process...
    return waveform

Catching Specific Errors#

from torchfx.validation import (
    InvalidRangeError,
    InvalidSampleRateError,
    TorchFXError,
)

try:
    # Some operation
    pass
except InvalidSampleRateError as e:
    print(f"Invalid sample rate: {e.actual_value}")
except InvalidRangeError as e:
    print(f"Value out of range: {e.parameter_name} = {e.actual_value}")
except TorchFXError as e:
    print(f"Other TorchFX error: {e}")