architecture/network/onnx

NeatapticTS ONNX-like serialization for networks.

This module provides the two public entry points:

What this format is (and is not):

How to read this chapter:

Why the folder is split this way:

Trust boundary:

Example (export → persist → import):

import { exportToONNX, importFromONNX } from './network.onnx';

const model = exportToONNX(network, { includeMetadata: true });
const jsonText = JSON.stringify(model);

const modelRoundTrip = JSON.parse(jsonText);
const restored = importFromONNX(modelRoundTrip);

architecture/network/onnx/network.onnx.ts

Conv2DMapping

Mapping declaration for treating a fully-connected layer as a 2D convolution during export.

This does not magically turn an MLP into a convolutional network at runtime. It annotates a particular export-layer index with a conv interpretation so that:

Pitfall: mappings must match the actual layer sizes. If inHeight * inWidth * inChannels does not correspond to the prior layer width (and similarly for outputs), export or import may reject the model.

exportToONNX

exportToONNX(
  network: default,
  options: OnnxExportOptions,
): OnnxModel

Export a NeatapticTS network to an ONNX-like JSON object (OnnxModel).

What you get:

When to use this:

Tradeoffs:

High-level algorithm:

  1. Normalize/rebuild local connection state for deterministic traversal.
  2. Infer an ordered layer view and validate export constraints.
  3. Materialize graph nodes/tensors and (optionally) attach metadata.

Example (export → JSON text):

const model = exportToONNX(network, { includeMetadata: true });
const jsonText = JSON.stringify(model);

Parameters:

Returns: ONNX-like model object suitable for persistence or re-import.

importFromONNX

importFromONNX(
  onnx: OnnxModel,
): default

Reconstruct a NeatapticTS network from an exported OnnxModel.

Expected input:

Trust boundary:

High-level behavior:

  1. Build a perceptron-shaped scaffold from the payload layer sizes.
  2. Assign weights/biases and activation functions.
  3. Re-apply recurrent and pooling metadata when present.

Example (JSON text → restore):

const model = JSON.parse(jsonText) as OnnxModel;
const restored = importFromONNX(model);
const output = restored.activate([0.1, 0.9]);

Parameters:

Returns: Reconstructed network ready for inference/evolution workflows.

OnnxExportOptions

Options controlling ONNX-like export.

These options trade off strictness, portability, and fidelity:

Key fields (high-level):

OnnxModel

ONNX-like model container (JSON-serializable).

This is the main “wire format” object in this folder. Persist it as JSON text:

const jsonText = JSON.stringify(model);
const restoredModel = JSON.parse(jsonText) as OnnxModel;

Notes:

Security/trust boundary:

Pool2DMapping

Mapping describing a pooling operation inserted after a given export-layer index.

This is represented as metadata and optional graph nodes during export. Import uses it to attach pooling-related runtime metadata back onto the reconstructed network (when supported).

architecture/network/onnx/network.onnx.utils.ts

ONNX export/import utilities for a constrained, documented subset of networks.

This file is the root compatibility barrel for the ONNX execution helpers. It exists so callers can keep a stable import surface while the heavier exporter and importer logic lives in the narrower export/ and import/ chapters.

How to read this file:

What still belongs here:

Phase Coverage (incremental roadmap implemented so far):

Scope & Assumptions (current):

Metadata Keys (may appear in model.metadata_props when includeMetadata true):

Design Goals:

Limitations / TODO (tracked for later phases):

NOTE: Import is only guaranteed to work for models produced by exportToONNX(); arbitrary ONNX graphs are NOT supported. Experimental fused recurrent nodes are best-effort and may silently degrade if shapes mismatch.

applyModelMetadata

applyModelMetadata(
  context: OnnxModelMetadataContext,
): void

Attach producer and opset metadata to a model when metadata emission is enabled.

Parameters:

Returns: Nothing.

assignActivationFunctions

assignActivationFunctions(
  network: default,
  onnx: OnnxModel,
  hiddenLayerSizes: number[],
): void

Assign node activation functions from ONNX activation nodes.

Parameters:

Returns: Nothing.

assignWeightsAndBiases

assignWeightsAndBiases(
  network: default,
  onnx: OnnxModel,
  hiddenLayerSizes: number[],
  metadataProps: OnnxMetadataProperty[] | undefined,
): void

Assign weights and biases from ONNX initializers to a newly created network.

Parameters:

Returns: Nothing.

buildOnnxModel

buildOnnxModel(
  network: default,
  layers: default[][],
  options: OnnxExportOptions,
): OnnxModel

Build an ONNX-like model from a validated layered network view.

Role in the ONNX pipeline:

Expected preconditions:

High-level behavior:

  1. Receive network, ordered layer matrix, and export options.
  2. Delegate model construction to the concrete builder implementation.
  3. Return the resulting ONNX-like JSON graph container unchanged.

Parameters:

Returns: ONNX-like model object representing graph nodes, tensors, and metadata.

Example:

const layers = inferLayerOrdering(network);
const model = buildOnnxModel(network, layers, { includeMetadata: true });

collectRecurrentLayerIndices

collectRecurrentLayerIndices(
  context: OnnxRecurrentCollectionContext,
): number[]

Detect hidden layers with self-recurrence and add matching previous-state graph inputs.

Parameters:

Returns: Export-layer indices with recurrent self-connections.

createBaseModel

createBaseModel(
  context: OnnxBaseModelBuildContext,
): OnnxModel

Create the base ONNX model shell with graph input/output declarations.

Parameters:

Returns: Initialized ONNX model with empty initializer/node lists.

createGraphDimensions

createGraphDimensions(
  context: OnnxGraphDimensionBuildContext,
): OnnxGraphDimensions

Build tensor dimensions for model input and output, optionally with symbolic batch dimension.

Parameters:

Returns: Input and output dimension arrays for ONNX value info.

deriveHiddenLayerSizes

deriveHiddenLayerSizes(
  initializers: OnnxTensor[],
  metadataProps: OnnxMetadataProperty[] | undefined,
): number[]

Extract hidden layer sizes from ONNX initializers (weight tensors).

Parameters:

Returns: Hidden layer sizes in order.

emitFusedRecurrentHeuristics

emitFusedRecurrentHeuristics(
  model: OnnxModel,
  layers: default[][],
  allowRecurrent: boolean | undefined,
  previousOutputName: string,
): void

Emit heuristic fused recurrent operators (LSTM/GRU) when recurrent export is enabled.

Parameters:

Returns: Nothing.

emitLayerGraph

emitLayerGraph(
  context: LayerBuildContext,
): string

Emit one export layer graph segment by routing the layer through the correct ONNX emission strategy.

Dispatch order matters:

Important invariants:

Parameters:

Returns: Output tensor name produced by this layer.

Example:

const outputName = emitLayerGraph({
  model,
  layers,
  layerIndex: 2,
  previousOutputName: 'Layer_1',
  options: { allowMixedActivations: true },
  recurrentLayerIndices: [],
  batchDimension: false,
  legacyNodeOrdering: false,
});

finalizeExportMetadata

finalizeExportMetadata(
  model: OnnxModel,
  layers: default[][],
  options: OnnxExportOptions,
  includeMetadata: boolean,
  hiddenSizesMetadata: number[],
  recurrentLayerIndices: number[],
): void

Finalize export metadata and optional conv-sharing validation.

Parameters:

Returns: Nothing.

inferLayerOrdering

inferLayerOrdering(
  network: default,
): default[][]

Infer strictly layered ordering from a network.

Parameters:

Returns: Ordered layers: input, hidden..., output.

OnnxModel

ONNX-like model container (JSON-serializable).

This is the main “wire format” object in this folder. Persist it as JSON text:

const jsonText = JSON.stringify(model);
const restoredModel = JSON.parse(jsonText) as OnnxModel;

Notes:

Security/trust boundary:

rebuildConnectionsLocal

rebuildConnectionsLocal(
  networkLike: default,
): void

Rebuild the network's flat connections array from each node's outgoing list.

Parameters:

Returns: Nothing.

runOnnxExportFlow

runOnnxExportFlow(
  network: default,
  options: OnnxExportOptions,
): OnnxModel

Execute the complete ONNX export flow for one network instance.

High-level behavior:

  1. Rebuild runtime connection caches and assign stable export indices.
  2. Infer layered ordering and collect recurrent-pattern stubs.
  3. Validate structural constraints for the requested export options.
  4. Build ONNX graph payload and append inference-oriented metadata.

Parameters:

Returns: ONNX-like model payload.

runOnnxImportFlow

runOnnxImportFlow(
  onnx: OnnxModel,
): default

Execute the complete ONNX import flow and reconstruct a runtime network.

High-level behavior:

  1. Extract architecture dimensions and build a perceptron scaffold.
  2. Restore dense parameters and activation functions.
  3. Reconstruct recurrent/pooling metadata and rebuild connection caches.

Parameters:

Returns: Reconstructed network instance.

validateLayerHomogeneityAndConnectivity

validateLayerHomogeneityAndConnectivity(
  layers: default[][],
  network: default,
  options: OnnxExportOptions,
): void

Validate connectivity and activation homogeneity constraints per layer.

Parameters:

Returns: Nothing.

architecture/network/onnx/network.onnx.utils.types.ts

Types for NeatapticTS’s ONNX-like JSON export/import.

This file is now the root compatibility barrel for shared ONNX type surfaces. Most exporter-owned, importer-owned, and schema-owned type families have already moved into their chapter-local files. What remains here is the narrow bridge layer that still needs to be visible from the root ONNX API.

How to read this type surface:

What still belongs here:

The exporter produces an OnnxModel (a JSON-serializable object) and the importer reconstructs a Network from that object.

Practical notes:

Stability & compatibility expectations:

ActivationFunction

ActivationFunction(
  x: number,
  derivate: boolean | undefined,
): number

Runtime activation function signature used by ONNX activation import/export paths.

Neataptic-style activations support a dual-purpose call pattern:

This matches historical Neataptic semantics and keeps ONNX import/export compatible.

Example:

const y = activation(x);
const dy = activation(x, true);

ActivationSquashFunction

ActivationSquashFunction(
  x: number,
  derivate: boolean | undefined,
): number

Activation function signature used by ONNX layer emission helpers.

Conv2DMapping

Mapping declaration for treating a fully-connected layer as a 2D convolution during export.

This does not magically turn an MLP into a convolutional network at runtime. It annotates a particular export-layer index with a conv interpretation so that:

Pitfall: mappings must match the actual layer sizes. If inHeight * inWidth * inChannels does not correspond to the prior layer width (and similarly for outputs), export or import may reject the model.

ConvKernelConsistencyContext

Context for kernel-coordinate consistency checks at one output position.

ConvLayerPairContext

Context for one resolved Conv mapping layer pair.

ConvOutputCoordinate

Coordinate for one Conv output neuron position.

ConvRepresentativeKernelContext

Context for representative Conv kernel collection per output channel.

ConvSharingValidationContext

Context for validating Conv sharing across all declared mappings.

ConvSharingValidationResult

Result of Conv sharing validation across declared mappings.

DenseActivationContext

Dense activation emission context.

DenseActivationNodePayload

Strongly typed activation node payload used by dense export helpers.

DenseGemmNodePayload

Strongly typed Gemm node payload used by dense export helpers.

DenseGraphNames

Dense graph tensor names.

DenseInitializerValues

Dense initializer value arrays.

DenseLayerContext

Dense layer context enriched with resolved activation function.

DenseLayerParams

Parameters for dense layer emission.

DenseOrderedNodePayload

Dense node payload union used by ordered append helpers.

DenseTensorNames

Dense initializer tensor names.

DenseWeightBuildContext

Context for building dense layer initializers from two adjacent layers.

DenseWeightBuildResult

Dense layer initializer fold output.

DenseWeightRow

One collected dense row before fold to flattened initializers.

DenseWeightRowCollectionContext

Context for collecting one dense row.

DiagonalRecurrentBuildContext

Context for building a diagonal recurrent matrix from self-connections.

FlattenAfterPoolingContext

Flatten emission context after optional pooling.

FusedRecurrentEmissionExecutionContext

Shared execution context for emitting one fused recurrent layer payload.

FusedRecurrentGraphNames

Context for ONNX fused recurrent node payload names.

FusedRecurrentInitializerNames

Context for ONNX fused recurrent initializer names.

GruEmissionContext

Context for heuristic GRU emission when a layer matches expected shape.

HiddenLayerActivationTraversalContext

Hidden-layer traversal context for assigning imported activation functions.

HiddenLayerHeuristicContext

Context for one hidden layer during heuristic recurrent emission.

IndexedMetadataAppendContext

Append-an-index metadata context for JSON-array metadata keys.

LayerActivationContext

Activation analysis context for one layer.

LayerActivationValidationContext

Activation-homogeneity decision context for one current layer.

LayerBuildContext

Layer build context used while emitting one ONNX graph layer segment.

LayerConnectivityValidationContext

Connectivity decision context for one source-target node pair.

LayerOrderingNodeGroups

Node partitions used by ONNX layered-ordering inference traversal.

LayerOrderingResolutionContext

Mutable traversal state while resolving hidden-layer ordering.

LayerRecurrentDecisionContext

Context used to decide recurrent emission branch usage.

LayerTraversalContext

Layer traversal context with adjacent layers and output classification.

LayerValidationTraversalContext

Layer-wise validation context for activation and connectivity checks.

LstmEmissionContext

Context for heuristic LSTM emission when a layer matches expected shape.

NetworkWithOnnxImportPooling

Network instance augmented with optional imported ONNX pooling metadata.

NodeInternals

Runtime interface for accessing node internal properties.

This is intentionally "internal": it exposes mutable fields that the ONNX exporter/importer needs (connections, bias, squash). Regular library users should generally interact with the public Node API instead.

NodeInternalsWithExportIndex

Runtime node internals augmented with optional export index metadata.

OnnxActivationAssignmentContext

Shared activation-assignment context for hidden and output traversal.

OnnxActivationLayerOperations

Layer-indexed activation operator lookup extracted from ONNX graph nodes.

OnnxActivationOperation

Supported ONNX activation operators recognized during activation import.

OnnxActivationOperationResolutionContext

Activation operation resolution context for one neuron or layer default.

OnnxActivationParseResult

Parsed ONNX activation-node naming payload.

OnnxAttribute

ONNX node attribute payload.

This simplified JSON-first shape is enough for the operators emitted by the current exporter. It intentionally avoids protobuf-level complexity while still preserving the attribute variants needed by the importer.

OnnxBaseModelBuildContext

Context for constructing a base ONNX model shell.

OnnxBuildResolvedOptions

Resolved options used by ONNX model build orchestration.

OnnxConvEmissionContext

Context used after resolving Conv mapping for one layer.

OnnxConvEmissionParams

Parameters accepted by Conv layer emission.

OnnxConvKernelCoordinate

Coordinate for one Conv kernel weight lookup.

OnnxConvParameters

Flattened Conv parameters for ONNX initializers.

OnnxConvTensorNames

Tensor names generated for Conv parameters.

OnnxDimension

One dimension inside an ONNX tensor shape.

Use dim_value for fixed numeric widths and dim_param for symbolic names such as a batch dimension.

OnnxExportOptions

Options controlling ONNX-like export.

These options trade off strictness, portability, and fidelity:

Key fields (high-level):

OnnxFusedGateApplicationContext

Gate-weight application context for one reconstructed fused layer.

OnnxFusedGateRowAssignmentContext

Context for assigning one gate-neuron row from flattened ONNX tensors.

OnnxFusedLayerNeighborhood

Hidden-layer neighborhood slices around a reconstructed fused layer.

OnnxFusedLayerReconstructionContext

Execution context for one fused recurrent layer reconstruction.

OnnxFusedLayerRuntime

Runtime interface of a reconstructed fused recurrent layer instance.

The importer only relies on a narrow runtime contract: access to the reconstructed nodes, an input wiring hook, and an optional output group that can be reconnected to the next restored layer.

OnnxFusedRecurrentKind

Supported fused recurrent operator families recognized during ONNX import.

OnnxFusedRecurrentSpec

Fused recurrent family specification used during import reconstruction.

This tells the importer how to interpret one emitted ONNX recurrent family: how many gates to expect, what order those gates were serialized in, and which gate owns the self-recurrent diagonal replay.

OnnxFusedTensorPayload

Fused recurrent tensor payload read from ONNX initializers.

The importer resolves the three recurrent tensor families up front so the reconstruction pass can focus on wiring and row assignment instead of repeatedly re-looking up initializers.

OnnxGraph

Graph body of an ONNX-like model.

The exporter writes three main collections here:

OnnxGraphDimensionBuildContext

Context for constructing input/output ONNX graph dimensions.

OnnxGraphDimensions

Output dimensions used by ONNX graph input/output value info payloads.

OnnxImportAggregatedLayerAssignmentContext

Context for assigning aggregated dense tensors for one layer.

OnnxImportAggregatedNeuronAssignmentContext

Context for assigning one aggregated dense target neuron row.

OnnxImportArchitectureContext

Shared architecture extraction context with resolved graph dimensions.

OnnxImportArchitectureResult

Parsed architecture dimensions extracted from ONNX import graph payloads.

OnnxImportConvCoordinateAssignmentContext

Context for applying Conv weights and bias at one output coordinate.

OnnxImportConvKernelAssignmentContext

Context for assigning one concrete Conv kernel connection weight.

OnnxImportConvLayerContext

Context for reconstructing one Conv layer's imported connectivity.

OnnxImportConvLayerContextBuildParams

Build params for creating one Conv reconstruction layer context.

OnnxImportConvMetadata

Parsed Conv metadata payload used for optional reconstruction pass.

OnnxImportConvNodeSlices

Layer node slices used while applying Conv reconstruction assignments.

OnnxImportConvOutputCoordinate

Coordinate for one Conv output neuron traversal position.

OnnxImportConvTensorContext

Resolved Conv initializer tensors and dimensions for one layer.

OnnxImportDimensionRecord

Loose ONNX shape-dimension record used by legacy import payload access.

OnnxImportHiddenLayerSpan

Hidden-layer span payload with one-based layer numbering and global offset.

OnnxImportHiddenSizeDerivationContext

Context for deriving hidden layer sizes from initializer tensors and metadata.

OnnxImportInboundConnectionMap

Inbound connection lookup map keyed by source node for one target neuron.

OnnxImportLayerConnectionContext

Execution context for assigning one hidden-layer recurrent diagonal tensor.

OnnxImportLayerNodePair

Node slices for one sequential imported layer assignment pass.

OnnxImportLayerNodePairBuildParams

Build params for one sequential layer node-pair slice operation.

OnnxImportLayerTensorNames

Weight tensor names for one imported layer index.

OnnxImportLayerWeightBucket

Bucketed ONNX dense/per-neuron tensors for one exported layer index.

OnnxImportPerNeuronAssignmentContext

Context for assigning one per-neuron imported target node.

OnnxImportPerNeuronLayerAssignmentContext

Context for assigning per-neuron tensors for one layer.

OnnxImportPoolingMetadata

Parsed pooling metadata payload attached to imported network instances.

OnnxImportRecurrentRestorationContext

Context for recurrent self-connection restoration from ONNX metadata and tensors.

OnnxImportSelfConnectionUpsertContext

Context for upserting one hidden node self-connection from recurrent weight.

OnnxImportWeightAssignmentBuildParams

Build params for creating shared ONNX import weight-assignment context.

OnnxImportWeightAssignmentContext

Shared weight-assignment context built once per ONNX import.

OnnxIncomingWeightAssignmentContext

Context for assigning dense incoming weights for one gate-neuron row.

OnnxLayerEmissionContext

Context for emitting non-input layers during model build.

OnnxLayerEmissionResult

Result of emitting non-input export layers.

OnnxLayerFactory

Runtime factory map used to construct dynamic recurrent layer modules.

OnnxMetadataProperty

Canonical metadata key-value pair used in ONNX model metadata_props.

OnnxModel

ONNX-like model container (JSON-serializable).

This is the main “wire format” object in this folder. Persist it as JSON text:

const jsonText = JSON.stringify(model);
const restoredModel = JSON.parse(jsonText) as OnnxModel;

Notes:

Security/trust boundary:

OnnxModelMetadataContext

Context for applying optional ONNX model metadata.

OnnxNode

One ONNX operator invocation inside the graph.

Nodes connect named tensors rather than object references, which keeps the exported payload easy to serialize, inspect, and diff as plain JSON.

OnnxPerceptronBuildContext

Build context for mapping ONNX layer sizes into a Neataptic MLP factory call.

OnnxPerceptronSizeValidationContext

Validation context for perceptron size-list checks during ONNX import.

OnnxPostProcessingContext

Context for post-processing and export metadata finalization.

OnnxRecurrentCollectionContext

Context for collecting recurrent layer indices during model build.

OnnxRecurrentInputValueInfoContext

Context for constructing one recurrent previous-state graph input payload.

OnnxRecurrentLayerProcessingContext

Execution context for processing one hidden recurrent layer.

OnnxRecurrentLayerTraversalContext

Traversal context for one hidden layer during recurrent-input collection.

OnnxRuntimeFactories

Runtime factories consumed during ONNX import network reconstruction.

OnnxRuntimeLayerFactory

OnnxRuntimeLayerFactory(
  size: number,
): default

Runtime layer-constructor signature used for recurrent layer reconstruction.

OnnxRuntimeLayerFactoryMap

Runtime layer module shape widened for fused-recurrent reconstruction wiring.

OnnxRuntimeLayerModule

Runtime layer module shape consumed by ONNX import orchestration.

OnnxRuntimePerceptronFactory

OnnxRuntimePerceptronFactory(
  sizes: number[],
): default

Runtime perceptron factory signature used by ONNX import orchestration.

OnnxShape

ONNX tensor type shape.

OnnxTensor

Serialized tensor payload stored inside graph initializers.

NeatapticTS currently writes floating-point parameter vectors and matrices to float_data, along with the tensor name, element type, and logical shape.

OnnxTensorType

ONNX tensor type.

OnnxValueInfo

ONNX value info (input/output description).

OptionalLayerOutputParams

Shared parameters for optional pooling/flatten output emission.

OptionalPoolingAndFlattenParams

Parameters for optional pooling + flatten emission after a layer output.

OutputLayerActivationContext

Output-layer activation assignment context.

PerNeuronConcatNodePayload

Per-neuron concat node payload.

PerNeuronGraphNames

Per-neuron graph tensor names.

PerNeuronLayerContext

Per-neuron layer context alias.

PerNeuronLayerParams

Parameters for per-neuron layer emission.

PerNeuronNodeContext

Per-neuron normalized node context.

PerNeuronSubgraphContext

Per-neuron subgraph emission context.

PerNeuronTensorNames

Per-neuron initializer tensor names.

Pool2DMapping

Mapping describing a pooling operation inserted after a given export-layer index.

This is represented as metadata and optional graph nodes during export. Import uses it to attach pooling-related runtime metadata back onto the reconstructed network (when supported).

PoolingAttributes

Pooling tensor attributes for ONNX node payloads.

PoolingEmissionContext

Pooling emission context resolved for one layer output.

RecurrentActivationEmissionContext

Context for selecting and emitting recurrent activation node payload.

RecurrentGateBlockCollectionContext

Context for collecting one gate parameter block.

RecurrentGateParameterCollectionResult

Flattened recurrent gate parameter vectors for one fused operator.

RecurrentGateRow

One recurrent gate row payload before flatten fold.

RecurrentGateRowCollectionContext

Context for collecting one recurrent gate row (one neuron).

RecurrentGemmEmissionContext

Context for emitting one Gemm node for recurrent single-step export.

RecurrentGraphNames

Derived graph names for one recurrent single-step layer payload.

RecurrentHeuristicEmissionContext

Context for heuristic recurrent operator emission traversal.

RecurrentInitializerEmissionContext

Context for pushing recurrent initializers into ONNX graph state.

RecurrentInitializerNames

Initializer tensor names for one single-step recurrent layer.

RecurrentInitializerValues

Collected initializer vectors for one single-step recurrent layer.

RecurrentLayerEmissionContext

Derived execution context for single-step recurrent layer emission.

RecurrentLayerEmissionParams

Parameters for single-step recurrent layer emission.

RecurrentRowCollectionContext

Context for collecting one recurrent matrix row.

SharedActivationNodeBuildParams

Shared parameters for constructing an activation node payload.

SharedGemmNodeBuildParams

Shared parameters for constructing a Gemm node payload.

SpecMetadataAppendContext

Append-a-spec metadata context for JSON-array metadata keys.

WeightToleranceComparisonContext

Context for comparing two scalar weights with numeric tolerance.

architecture/network/onnx/network.onnx.errors.ts

Raised when ONNX export cannot resolve a valid layered ordering.

NetworkOnnxLayerOrderingUnresolvableError

Raised when ONNX export cannot resolve a valid layered ordering.

NetworkOnnxMixedActivationsUnsupportedError

Raised when ONNX export encounters mixed activations without mixed-activation support enabled.

NetworkOnnxPartialConnectivityUnsupportedError

Raised when ONNX export requires a connection that is missing.

NetworkOnnxPerceptronSizeValidationError

Raised when ONNX import perceptron metadata omits required input/output sizes.

NetworkOnnxRecurrentMixedActivationsUnsupportedError

Raised when recurrent ONNX export encounters unsupported mixed activations.

architecture/network/onnx/network.onnx.layer-analysis.utils.ts

appendLastResolvedLayer

appendLastResolvedLayer(
  resolutionContext: LayerOrderingResolutionContext,
): LayerOrderingResolutionContext

Append the final resolved hidden layer into ordered layer output.

Parameters:

Returns: Traversal state with last hidden layer persisted.

buildLayerValidationContexts

buildLayerValidationContexts(
  layers: default[][],
  options: OnnxExportOptions,
): LayerValidationTraversalContext[]

Build per-layer validation contexts for all non-input layers.

Parameters:

Returns: Traversal contexts used by layer validators.

collectCurrentResolvableHiddenLayer

collectCurrentResolvableHiddenLayer(
  resolutionContext: LayerOrderingResolutionContext,
): default[]

Collect unresolved hidden nodes that can be placed in the next layer.

Parameters:

Returns: Hidden nodes that are resolvable in this pass.

collectLayerOrderingNodeGroups

collectLayerOrderingNodeGroups(
  network: default,
): LayerOrderingNodeGroups

Partition all network nodes into input/hidden/output groups.

Parameters:

Returns: Node groups used by layered-ordering inference.

collectUniqueOutgoingConnections

collectUniqueOutgoingConnections(
  nodes: default[],
): default[]

Collect unique outgoing connections across a node list.

Parameters:

Returns: Stable array of unique connections.

createLayerActivationValidationContext

createLayerActivationValidationContext(
  layerValidationContext: LayerValidationTraversalContext,
): LayerActivationValidationContext

Create activation validation context from one layer traversal context.

Parameters:

Returns: Activation validation context.

ensureLayerWasResolved

ensureLayerWasResolved(
  currentLayerNodes: default[],
): void

Ensure current hidden-layer resolution pass produced at least one node.

Parameters:

Returns: Nothing.

filterNodesByType

filterNodesByType(
  nodes: default[],
  nodeType: string,
): default[]

Filter nodes by one expected node type.

Parameters:

Returns: Matching nodes.

filterUnresolvedHiddenNodes

filterUnresolvedHiddenNodes(
  context: { remainingHiddenNodes: default[]; currentLayerNodes: default[]; },
): default[]

Remove just-resolved hidden nodes from unresolved candidates.

Parameters:

Returns: Hidden nodes still unresolved.

finalizeOrderingWithoutHiddenNodes

finalizeOrderingWithoutHiddenNodes(
  nodeGroups: LayerOrderingNodeGroups,
): default[][]

Finalize ordering for networks without hidden layers.

Parameters:

Returns: Input and output layers only.

finalizeOrderingWithOutputLayer

finalizeOrderingWithOutputLayer(
  context: { orderedLayers: default[][]; outputNodes: default[]; },
): default[][]

Append output layer to resolved input/hidden ordering.

Parameters:

Returns: Full layer ordering including output layer.

hasAllIncomingConnectionsFromPreviousLayer

hasAllIncomingConnectionsFromPreviousLayer(
  context: { hiddenNode: default; previousLayerNodes: default[]; },
): boolean

Check whether a hidden node receives all inputs from the previous layer.

Parameters:

Returns: True when the hidden node is layer-resolvable.

hasNoHiddenNodes

hasNoHiddenNodes(
  nodeGroups: LayerOrderingNodeGroups,
): boolean

Check whether the layer groups contain no hidden nodes.

Parameters:

Returns: True when hidden layer traversal can be skipped.

inferLayerOrdering

inferLayerOrdering(
  network: default,
): default[][]

Infer strictly layered ordering from a network.

Parameters:

Returns: Ordered layers: input, hidden..., output.

initializeLayerOrderingResolutionContext

initializeLayerOrderingResolutionContext(
  nodeGroups: LayerOrderingNodeGroups,
): LayerOrderingResolutionContext

Create initial hidden-layer resolution context.

Parameters:

Returns: Initial mutable state for hidden-layer resolution.

mapActivationToOnnx

mapActivationToOnnx(
  squash: ((x: number, derivate?: boolean | undefined) => number) & { name?: string | undefined; },
): OnnxActivationOperation

Map an internal activation function (squash) to an ONNX op_type.

Parameters:

Returns: ONNX activation operator name.

normalizeActivationName

normalizeActivationName(
  squash: ((x: number, derivate?: boolean | undefined) => number) & { name?: string | undefined; },
): string

Normalize activation function name to uppercase for token matching.

Parameters:

Returns: Uppercased activation name or empty string.

rebuildConnectionsLocal

rebuildConnectionsLocal(
  networkLike: default,
): void

Rebuild the network's flat connections array from each node's outgoing list.

Parameters:

Returns: Nothing.

resolveAllHiddenLayers

resolveAllHiddenLayers(
  initialContext: LayerOrderingResolutionContext,
): LayerOrderingResolutionContext

Resolve all hidden layers in dependency order.

Parameters:

Returns: Final resolved layer-ordering context.

resolveNextHiddenLayer

resolveNextHiddenLayer(
  resolutionContext: LayerOrderingResolutionContext,
): LayerOrderingResolutionContext

Resolve the next hidden layer from unresolved candidates.

Parameters:

Returns: Updated resolution state.

resolveOnnxActivationOperation

resolveOnnxActivationOperation(
  normalizedActivationName: string,
): OnnxActivationOperation

Resolve ONNX activation op from a normalized activation name token.

Parameters:

Returns: ONNX activation operation.

validateLayerActivationHomogeneity

validateLayerActivationHomogeneity(
  activationValidationContext: LayerActivationValidationContext,
): void

Validate that a layer has homogeneous activation unless explicitly allowed.

Parameters:

Returns: Nothing.

validateLayerConnectivity

validateLayerConnectivity(
  layerValidationContext: LayerValidationTraversalContext,
): void

Validate that each current-layer node has required incoming connectivity.

Parameters:

Returns: Nothing.

validateLayerHomogeneityAndConnectivity

validateLayerHomogeneityAndConnectivity(
  layers: default[][],
  network: default,
  options: OnnxExportOptions,
): void

Validate connectivity and activation homogeneity constraints per layer.

Parameters:

Returns: Nothing.

validateSingleLayer

validateSingleLayer(
  layerValidationContext: LayerValidationTraversalContext,
): void

Validate one current layer against activation/connectivity constraints.

Parameters:

Returns: Nothing.

validateSourceToTargetConnectivity

validateSourceToTargetConnectivity(
  connectivityValidationContext: LayerConnectivityValidationContext,
): void

Validate one source->target connection pair under export constraints.

Parameters:

Returns: Nothing.

validateTargetNodeConnectivity

validateTargetNodeConnectivity(
  context: { targetNode: default; previousLayerNodes: default[]; layerIndex: number; allowPartialConnectivity: boolean; },
): void

Validate full source coverage for one target node.

Parameters:

Returns: Nothing.

warnWhenActivationFallbackIsUsed

warnWhenActivationFallbackIsUsed(
  context: { squash: ((x: number, derivate?: boolean | undefined) => number) & { name?: string | undefined; }; resolvedActivationOperation: OnnxActivationOperation; },
): void

Emit a warning when activation export falls back to Identity.

Parameters:

Returns: Nothing.

Generated from source JSDoc • GitHub