LayerStateAttribute

Attributes · AiDotNet.Attributes

Marks a constructor parameter as state that must survive a serialization round-trip, so the layer can be rebuilt exactly rather than guessed at from its shape.

Inheritance: Attribute → LayerStateAttribute

For Beginners

When a model is saved and loaded, each layer has to be built again from scratch. This attribute marks the numbers the constructor needs so they get written down at save time, instead of the loader trying to work them out from the data’s shape and getting it wrong.

How It Works

Deserialization used to reverse-engineer constructor arguments out of the saved input shape — int maxSeqLen = inputShape[0]; and 92 more like it. That only ever worked because layers encoded their capacity in their declared shape. The moment a layer told the truth about an axis being dynamic, the same line handed the constructor a -1.

A parameter marked with this attribute is written to the layer’s metadata by generated code and read back by a generated factory, so the constructor receives the value it was originally given. The generator resolves the value through a backing field or property matching the parameter name (name, _name, m_name, Name or _Name) and fails the build when no such member exists — a layer that cannot round-trip does not compile.

Parameters left unmarked are still handled: activation functions are restored from the activation metadata the base layer already writes, and optional parameters fall back to their defaults. A required, unmarked, non-activation parameter is a build error, because nothing could supply it.

Example

public partial class PositionalEncodingLayer<T> : LayerBase<T>
{
    public PositionalEncodingLayer(
        [LayerState] int maxSequenceLength,
        [LayerState] int embeddingSize)
        : base([-1, embeddingSize], [-1, embeddingSize])
    {
    }
}

Constructors

Constructor Summary
LayerStateAttribute()

Properties

Property Summary
bool OmitWhenNonPositive { get; set; } Skips writing this parameter when its backing member is zero or negative, meaning the layer has not resolved it yet.
string Key { get; set; } Overrides the metadata key used for this parameter.
string Member { get; set; } Names the field or property holding this parameter, when it is not one the generator would look for on its own.