DelegateState
Helpers & Utilities · AiDotNet.Serialization
Saves and restores a delegate a layer was constructed with.
How It Works
A delegate is the one kind of construction state that cannot simply be written down, and the
established answers are both unsatisfying. Python’s pickle refuses a lambda outright and
stores a module-level function as a name reference. Keras goes further and marshals the Lambda
layer’s Python bytecode into the model file, which is why loading one is arbitrary code
execution and why safe_mode=True blocks it by default – it was still bypassable
(CVE-2025-9906). PyTorch avoids the question: copy.deepcopy treats a function as atomic
and returns the same object, so a clone aliases the delegate and a save never round-trips it.
.NET makes better available, because a delegate is not opaque here: it is a
MethodInfo plus a target. So this tries progressively weaker descriptions and
keeps the first that fits, rather than marshalling code:
When none fits, the delegate is reported as unsaveable rather than written as something that will not come back. Cloning a layer in memory does not go through here at all: it hands the live delegate over, which is what PyTorch’s deepcopy does and is always correct in-process.
Methods
| Method | Summary |
|---|---|
TDelegate Load(string saved, string layerName, string key) |
Rebuilds a delegate from its saved form. |
string Save(Delegate value) |
Describes value well enough to rebuild it, or returns empty when no description fits. |
string Save(Delegate value, int[] inputShape) |
Describes value well enough to rebuild it, or returns empty when no description fits. |
Fields
| Field | Summary |
|---|---|
string ExpressionScheme |
Marks a saved value as a serialized expression tree. |
string GraphScheme |
Marks a saved value as a legacy traced computation graph (written by AiDotNet versions before the legacy autodiff was removed). |
string MethodScheme |
Marks a saved value as a reference to a named method. |
string ProgramScheme |
Marks a saved value as a portable tensor program: what a Func<Tensor<T>, Tensor<T>> computed, recorded as AiDotNet.Tensors engine calls (one program per input rank it was traced at). |