fairseq2.utils.validation

This module provides a set of helper types for object state validation. These types are primarly used by recipe and asset configuration dataclasses to ensure that all options are set correctly.

A class -typically a configuration dataclass- that wants to support validation should expose a validate(self) -> ValidationResult method. Optionally, the class can derive from the runtime-checkable Validatable protocol to make its intent more clear.

A typical implementation of a validate() method looks like the following:

from dataclasses import dataclass

from fairseq2.utils.validation import Validatable, ValidationResult

@dataclass
class FooConfig(Validatable):
    field1: str
    field2: int

    def validate(self) -> ValidationResult:
        result = ValidationResult()

        if not self.field1:
            result.add_error("`field1` must be a non-empty string.")

        if self.field2 < 1:
            result.add_error("`field2` must be a positive integer.")

        return result

Note that FooConfig must NOT call validate() on its sub-fields that are validatable. ObjectValidator is responsible for traversing the object graph and call each validate() method it finds in dataclasses, as well as in composite objects of types list, Mapping, Set, and tuple.

Whenever FooConfig is used in a recipe configuration, fairseq2 will ensure that it is validated before setting RecipeContext.config. To manually validate an object outside of recipes, StandardObjectValidator can be used:

from dataclasses import dataclass

from fairseq2.utils.validation import (
    ObjectValidator,
    StandardObjectValidator,
    Validatable,
    ValidationError,
    ValidationResult,
)

@dataclass
class FooConfig(Validatable):
    field1: str
    field2: int

    def validate(self) -> ValidationResult:
        result = ValidationResult()

        if not self.field1:
            result.add_error("`field1` must be a non-empty string.")

        if self.field2 < 1:
            result.add_error("`field2` must be a positive integer.")

        return result

config = FooConfig(field1="foo", field2=0)

validator: ObjectValidator = StandardObjectValidator()

try:
    validator.validate(config)
except ValidationError as ex:
    # Prints an error message indicating that `field2` must be a
    # positive integer.
    print(ex.result)
class fairseq2.utils.validation.ObjectValidator[source]

Bases: ABC

Validates an object along with its sub-objects if it is a composite object (i.e. a dataclass, list, Mapping, Set, or tuple) and raises a ValidationError if any of them returns an error.

abstract validate(obj)[source]

Validates obj.

Parameters:

obj (object) – The object to validate.

Raises:

ValidationErrorobj or one of its sub-objects has a validation error.

final class fairseq2.utils.validation.StandardObjectValidator[source]

Bases: ObjectValidator

Represents the standard implementation of ObjectValidator.

validate(obj)[source]

Validates obj.

Parameters:

obj (object) – The object to validate.

Raises:

ValidationErrorobj or one of its sub-objects has a validation error.

class fairseq2.utils.validation.Validatable(*args, **kwargs)[source]

Bases: Protocol

Represents the protocol for validatable objects.

validate()[source]

Validates the state of the object.

Returns:

The result of the validation.

Return type:

ValidationResult

final class fairseq2.utils.validation.ValidationResult[source]

Bases: object

Holds the result of a validate() call.

add_error(message)[source]

Adds an error message to the result.

add_sub_result(field, result)[source]

Adds the validation result of a sub-object as a sub-result.

Parameters:
  • field (str) – The name of the sub-object. For a dataclass, it is the name of the field, for a Mapping it is the name of the key formatted as f"[{repr(key)}]", for list, Set, and tuple it is the index of the value formatted as f"[{index}]".

  • result (ValidationResult) – The validation result of the sub-object.

has_error()[source]

Returns True if the object or any of its sub-objects have a validation error.

Return type:

bool

property errors: Sequence[str]

Returns the validation errors of the object, excluding errors of its sub-objects.

property sub_results: Mapping[str, ValidationResult]

Returns the validation results of the sub-objects.

exception fairseq2.utils.validation.ValidationError(result, *, field=None)[source]

Bases: Exception

Raised when a validation error occurs.

Parameters:
  • result (ValidationResult) – The validation result. If str, will be converted to a result with ValidationResult(result).

  • field (str | None) – If not None, result will be treated as the sub-result of field.

result: ValidationResult

The result containing validation errors.