neuralqx.experimental.utils.struct.fields module¶
Public field declarations for neuralqx.utils.struct.
This module defines the declarative schema language for Struct classes.
- At a high level:
Struct fields are split into three runtime categories:
Node fields (
FieldKind.NODE) These are dynamic pytree leaves. JAX traces/transforms these values.Static fields (
FieldKind.STATIC) These become pytree auxiliary metadata, not leaves. They influence JIT cache identity, so values must be hashable and cannot contain array-like objects.Opaque fields (
FieldKind.OPAQUE) These are intentionally excluded from pytree leaves and are treated as runtime side-data. They are useful for handles, caches, tokens, or process-local objects that should not be traced.
The derived=... hook defines computed fields that are recomputed after
construction/replacement/deserialization. Derived fields:
must use
init=False,cannot define defaults,
cannot be node fields,
are never serialised (they are recomputed instead).
- class FieldSpec(name, default=MISSING, kind=FieldKind.NODE, factory=MISSING, init=True, repr=True, compare=True, serialize=None, kw_only=False, doc=None, metadata=<factory>, converter=None, validators=(), derived=None)¶
Bases:
objectImmutable metadata describing one struct field.
FieldSpecis the normalised internal representation used by the struct class processor. In user code, these are typically created byfield().You write class annotations/defaults/
field(...)declarations.Struct metaclass collects declarations and builds
FieldSpecobjects.Runtime processing validates and uses specs to drive constructor, pytree, equality, repr, and serialisation behaviour.
Notes
FieldSpecinstances are normally created byfield(). Advanced users may construct them directly when building custom decorators.
- field(*, static=False, pytree=True, default=MISSING, default_factory=MISSING, init=True, repr=True, compare=True, serialize=None, kw_only=False, doc=None, metadata=None, converter=None, validator=None, derived=None)¶
Declare metadata for one
Structfield.This function mirrors the ergonomics of
dataclasses.field()while adding pytree-aware semantics and runtime hooks (converter, validator, derived).Typical usage¶
class State(Struct): x: jax.Array tag: str = field(static=True, default="exp-A") token: object = field(pytree=False, default_factory=object) norm: float = field( static=True, init=False, derived=lambda self: float(np.asarray(self.x).sum()), )
The shape intentionally resembles
dataclasses.field(), but it adds JAX/Struct-specific controls:staticandpytreedecide field role.converterandvalidatoradd runtime hooks.derivedsupports deterministic computed fields.
- type static:
- param static:
Mark this field as static pytree metadata. Static values are part of JAX cache keys, so they must be hashable and array-free.
- type pytree:
- param pytree:
When
False, the field is opaque runtime data (not a pytree leaf).- type default:
- param default:
Concrete default value used when input is omitted.
- type default_factory:
- param default_factory:
Zero-argument callable used to lazily create defaults.
- type init:
- param init:
Include field in generated constructor.
- type repr:
- param repr:
Include field in
__repr__output.- type compare:
- param compare:
Include field in
__eq__checks.- type serialize:
- param serialize:
Override whether field participates in state dict/export I/O.
- type kw_only:
- param kw_only:
Make field keyword-only in generated constructor.
- type doc:
- param doc:
Optional per-field documentation string.
- type metadata:
- param metadata:
Free-form immutable metadata mapping for tooling.
- type converter:
- param converter:
Optional converter called on assignment paths. Accepts either
converter(value)orconverter(self, value).- type validator:
Union[Callable[...,Any],Sequence[Callable[...,Any]],None]- param validator:
Optional validator (or sequence of validators). Validators accept either
validator(value)orvalidator(self, value). ReturningFalseraisesValidationError.- type derived:
- param derived:
Optional callable for computed fields (must use
init=False). Acceptsderived()orderived(self)and is recomputed after construction, replacement, and deserialisation.- rtype:
- returns:
Frozen metadata object consumed by struct class processing.
- raises ValueError:
If declaration invariants are violated, for example: - both
defaultanddefault_factoryare provided, -static=Trueandpytree=Falseare combined, - derived-field constraints are broken.
Notes
- Validators may either:
raise exceptions directly, or
return
Falseto trigger aValidationError.
- Converters/validators support ergonomic signatures:
fn(value)fn(self, value)