architecture/network/onnx

NeatapticTS ONNX-like serialization for networks.

This module provides the four 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

AttentionMapping

Explicit export-only attention mapping for the Phase 5E shadow subset.

This contract keeps attention source-owned rather than heuristic: callers opt one target layer into a fixed-width self-attention shadow block while the stable dense path remains the canonical runtime behavior.

ConcatMapping

Explicit export-only concat mapping for the narrow Phase 5 merge subset.

This contract keeps concat source-owned instead of inferred: callers name one skipped source layer and one target layer, and export preserves the merge as a deterministic Concat -> Gemm path with the default adjacent-layer slice kept first in the merged input order.

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:

Quantized spatial lowering path:

flowchart LR
  Input[Float spatial input] --> Quantize[QuantizeLinear]
  Quantize --> QConv[QLinearConv]
  QConv --> Dequantize[DequantizeLinear]
  Dequantize --> Activation[Unary activation]
  Activation --> Boundary[Pool flatten reshape dense]

Dynamic dense guidance path:

flowchart LR
  Input[Float dense input] --> DQL[DynamicQuantizeLinear]
  DQL --> DQ[DequantizeLinear]
  DQ --> Gemm[Gemm]
  Gemm --> Activation[Unary activation]

The lighter metadata-only representation records the same dense-only lane without inserting DynamicQuantizeLinear nodes.

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.

exportToONNXBinary

exportToONNXBinary(
  network: default,
  options: OnnxExportOptions,
): Uint8Array<ArrayBufferLike>

Export a NeatapticTS network to protobuf ModelProto bytes.

What you get:

Important boundary:

When to use this:

High-level behavior:

  1. Build the shared exporter model view for the supported subset.
  2. Normalize binary-only graph boundaries and required ModelProto headers.
  3. Serialize the resulting model into deterministic protobuf bytes.
  4. Keep validation separate: use the validator seam when you need explicit external acceptance evidence for the current supported subset.

Parameters:

Returns: Binary protobuf ModelProto bytes.

importFromONNX

importFromONNX(
  onnx: OnnxModel,
): default

Reconstruct a NeatapticTS network from an exported OnnxModel.

Expected input:

Trust boundary:

Current 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.

importFromONNXBinary

importFromONNXBinary(
  binaryModel: Uint8Array<ArrayBufferLike>,
): default

Import the first supported external binary ONNX subset from protobuf ModelProto bytes.

Current subset:

High-level behavior:

  1. Decode and verify the binary ModelProto payload.
  2. Normalize one accepted external dense chain into an importer-owned canonical model.
  3. Reuse the existing reconstruction flow to rebuild a runtime network.

Parameters:

Returns: Reconstructed network ready for inference workflows.

networkOnnxUtils

Default export bundle for the ONNX-like serialization chapter.

Bundles the primary ONNX entry points so the network facade can bind them as methods without importing each function individually.

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:

Current capability set:

Scope & Assumptions (current):

Supported recurrent subset (current):

Fallback and rejection boundary:

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

Design Goals:

Known limitations:

NOTE: Import is only guaranteed to work for models produced by exportToONNX(); arbitrary ONNX graphs are NOT supported. The recurrent import promise is intentionally narrow: same-family export/import for the supported subset above, with explicit fallback to the layered baseline when fused recurrent tensors are incomplete.

applyModelMetadata

applyModelMetadata(
  context: OnnxModelMetadataContext,
): void

Apply model metadata to exported artifacts so downstream tools can inspect capability flags and advanced graph hints. This alias preserves a stable public seam for metadata population while implementation details stay split by concern.

assignActivationFunctions

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

Assign activation functions during import reconstruction so each rebuilt layer preserves nonlinear behavior captured by export metadata. This forwarding seam keeps root ONNX callers stable while the concrete activation mapping logic evolves in import internals.

assignWeightsAndBiases

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

Assign weights and biases onto imported layers so reconstructed parameters match serialized ONNX tensor values from export. Keeping this alias documented at the compatibility barrel helps users discover parameter hydration behavior without reading nested modules first.

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[]

Collect recurrent layer indices so post-processing can identify hidden stages that use supported single-step recurrence. Export metadata and import diagnostics both depend on this deterministic recurrent-stage inventory.

createBaseModel

createBaseModel(
  context: OnnxBaseModelBuildContext,
): OnnxModel

Create the base ONNX-like model scaffold so later export stages can append graph nodes, initializers, and metadata in deterministic order.

createGraphDimensions

createGraphDimensions(
  context: OnnxGraphDimensionBuildContext,
): OnnxGraphDimensions

Create graph dimension metadata so emitted tensor shapes stay explicit and consistent across exporter and importer paths. Clear dimension records also improve debugging when validating compatibility between serialized tensors and rebuilt layers.

deriveHiddenLayerSizes

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

Derive hidden layer sizes from exported graph structures so import routines allocate correctly shaped intermediate containers. The helper also centralizes size inference assumptions used by reconstruction and compatibility diagnostics.

emitFusedRecurrentHeuristics

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

Emit fused recurrent heuristic nodes so eligible LSTM and GRU patterns can be represented compactly within the current conservative subset.

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 so generated models include complete capability records and audit hints for compatibility diagnostics. The finalization step normalizes emitted annotations before artifacts are returned to callers or saved.

inferLayerOrdering

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

Infer a strictly layered node ordering from an analyzed network structure.

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 local connections from layered ONNX-like data so import flows can restore deterministic adjacency wiring before activation or serialization passes.

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 layer homogeneity and connectivity so export and import paths fail early when topology assumptions required by the supported ONNX subset are broken.

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 for encoding activation operator type attributes.

AttentionMapping

Explicit export-only attention mapping for the Phase 5E shadow subset.

This contract keeps attention source-owned rather than heuristic: callers opt one target layer into a fixed-width self-attention shadow block while the stable dense path remains the canonical runtime behavior.

ConcatMapping

Explicit export-only concat mapping for the narrow Phase 5 merge subset.

This contract keeps concat source-owned instead of inferred: callers name one skipped source layer and one target layer, and export preserves the merge as a deterministic Concat -> Gemm path with the default adjacent-layer slice kept first in the merged input order.

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, comparing representative weights with tolerance.

ConvLayerPairContext

Context for one resolved Conv mapping layer pair, supplying the Conv spec and adjacent layer node lists.

ConvOutputCoordinate

Coordinate for one Conv output neuron, encoding the output channel, row, and column indices together.

ConvRepresentativeKernelContext

Context for representative Conv kernel collection per output channel, supplying neuron lists and the Conv spec.

ConvSharingValidationContext

Context for validating Conv sharing across all declared mappings, holding layer nodes and mapping specifications.

ConvSharingValidationResult

Result of Conv sharing validation across declared mappings, reporting verified and mismatched layer indices.

DenseActivationContext

Dense activation emission context carrying layer index, tensor names, graph names, squash function, and opset version.

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 identifying the Gemm output and activation output tensors for one layer.

DenseInitializerValues

Dense initializer value arrays holding the flattened weight matrix values and bias vector for one layer.

DenseLayerContext

Dense layer context enriched with the resolved activation squash function derived from the current layer nodes.

DenseLayerParams

Parameters for dense layer emission, grouping model, layer index, node lists, ordering flag, and export options.

DenseOrderedNodePayload

Dense node payload union used by ordered append helpers, covering Gemm and activation node payloads.

DenseTensorNames

Dense initializer tensor names for one emitted layer, naming the weight and bias initializer tensors.

DenseWeightBuildContext

Context for building dense layer initializers from two adjacent layers.

DenseWeightBuildResult

Dense layer initializer fold output, containing the flattened weight matrix values and bias vector.

DenseWeightRow

One collected dense row before fold to flattened initializers, containing per-neuron weights and bias value.

DenseWeightRowCollectionContext

Context for collecting one dense row, supplying previous layer nodes and the target neuron internals.

DiagonalRecurrentBuildContext

Context for building a diagonal recurrent matrix from self-connections, supplying the current layer node list.

FlattenAfterPoolingContext

Flatten emission context after optional pooling, carrying model, flatten flag, layer index, and source output name.

FusedRecurrentEmissionExecutionContext

Shared execution context for emitting one fused recurrent layer payload.

FusedRecurrentGraphNames

Context for ONNX fused recurrent node payload names, holding the graph node name and its output tensor name.

FusedRecurrentInitializerNames

Context for ONNX fused recurrent initializer names, grouping weight, recurrent-weight, and bias tensor name strings.

GruEmissionContext

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

HiddenLayerActivationTraversalContext

Hidden-layer traversal context for assigning imported activation functions, carrying layer index, size, and node lists.

HiddenLayerHeuristicContext

Context for one hidden layer during heuristic recurrent emission, tracking layer index and model state.

IndexedMetadataAppendContext

Append-an-index metadata context for JSON-array metadata keys, supplying model, key, and layer index.

LayerActivationContext

Activation analysis context for one layer, capturing whether the layer contains mixed activation functions.

LayerActivationValidationContext

Activation-homogeneity decision context for one current layer, capturing activation names and mixed-activation policy.

LayerBuildContext

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

LayerConnectivityValidationContext

Connectivity decision context for one source-target node pair, including layer index and partial-connectivity policy.

LayerOrderingNodeGroups

Node partitions used by ONNX layered-ordering inference traversal, grouping input, hidden, and output nodes.

LayerOrderingResolutionContext

Mutable traversal state while resolving hidden-layer ordering, carrying remaining nodes and accumulated layer groups.

LayerRecurrentDecisionContext

Context used to decide recurrent emission branch usage, carrying layer index and recurrent layer index list.

LayerTraversalContext

Layer traversal context with adjacent layers, output classification, and the full LayerBuildContext fields.

LayerValidationTraversalContext

Layer-wise validation context for activation and connectivity checks, supplying layer index and adjacent node lists.

LstmEmissionContext

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

NetworkWithOnnxImportAdvancedGraph

Network instance augmented with optional imported advanced-graph metadata via the _onnxAdvancedGraph field.

NetworkWithOnnxImportPooling

Network instance augmented with optional imported ONNX pooling metadata via the _onnxPooling field.

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, used for deterministic ONNX graph ordering.

OnnxActivationAssignmentContext

Shared activation-assignment context for hidden and output traversal, grouping node lists and per-layer operations.

OnnxActivationLayerOperations

Layer-indexed activation operator lookup extracted from ONNX graph nodes for import assignment passes.

OnnxActivationOperation

Supported ONNX activation operator strings recognized and mapped during network activation import traversal.

OnnxActivationOperationResolutionContext

Activation operation resolution context for one neuron or layer default.

OnnxActivationParseResult

Parsed ONNX activation-node naming payload, carrying the extracted layer index and optional neuron index.

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, supplying input and output dimension arrays for the graph.

OnnxBuildResolvedOptions

Resolved options for ONNX model build orchestration, with all export option defaults already applied and normalized.

OnnxConvEmissionContext

Context used after resolving Conv mapping for one layer, extending OnnxConvEmissionParams with the resolved Conv2DMapping spec.

OnnxConvEmissionParams

Parameters accepted by Conv layer emission, grouping model, options, layer index, previous output, and adjacent node lists.

OnnxConvKernelCoordinate

Coordinate for one Conv kernel weight lookup, encoding input channel index, kernel row, and column position.

OnnxConvParameters

Flattened Conv parameters for ONNX initializers, containing weight and bias arrays derived from Conv layer neurons.

OnnxConvTensorNames

Tensor names generated for Conv parameters, holding weight and bias initializer name strings for one layer.

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, carrying spec, unit size, and weight arrays.

OnnxFusedGateRowAssignmentContext

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

OnnxFusedLayerNeighborhood

Hidden-layer neighborhood slices around a reconstructed fused layer, including old, previous, and next node lists.

OnnxFusedLayerReconstructionContext

Execution context for one fused recurrent layer reconstruction, carrying spec, export index, and hidden layer index.

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, currently limited to LSTM and GRU.

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, carrying width values and the batch-dimension flag.

OnnxGraphDimensions

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

OnnxImportAdvancedGraphCrossLayerConnection

Audit-only cross-layer feed-forward edge carried through Phase 5 import fallback.

OnnxImportAdvancedGraphMetadata

Parsed advanced-graph metadata attached to imported network instances, grouping merges, residual adds, and blocks.

OnnxImportAggregatedLayerAssignmentContext

Context for assigning aggregated dense tensors for one layer, supplying the initializer map and layer node pair.

OnnxImportAggregatedNeuronAssignmentContext

Context for assigning one aggregated dense target neuron row, carrying previous nodes, target, and tensor refs.

OnnxImportArchitectureContext

Shared architecture extraction context with resolved graph dimensions, initializers, and metadata properties.

OnnxImportArchitectureResult

Parsed architecture dimensions extracted from ONNX import graph payloads, with input, output, and hidden sizes.

OnnxImportAttentionBlock

Explicit fixed-width self-attention block carried through Phase 5 import fallback.

OnnxImportConcatMerge

Explicit concat merge carried through Phase 5 import hardening, identifying layer indices and merge tensor names.

OnnxImportConvCoordinateAssignmentContext

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

OnnxImportConvKernelAssignmentContext

Context for assigning one concrete Conv kernel connection weight, carrying tensor context, coordinate, and channels.

OnnxImportConvLayerContext

Context payload used when rebuilding one imported convolution layer from ONNX graph metadata and tensor shelves. The contract captures grouped node slices, tensor mappings, and assignment state so reconstruction stays deterministic across import passes.

OnnxImportConvLayerContextBuildParams

Build params for creating one Conv reconstruction layer context, supplying assignment context and Conv metadata.

OnnxImportConvMetadata

Parsed Conv metadata payload used for optional reconstruction pass, listing Conv layer indices and mapping specs.

OnnxImportConvNodeSlices

Layer node slices used while applying Conv reconstruction assignments, carrying target and previous layer nodes.

OnnxImportConvOutputCoordinate

Coordinate for one Conv output neuron traversal position, encoding output channel, row, and column indices.

OnnxImportConvTensorContext

Resolved Conv initializer tensors and dimensions for one layer, including channels, kernel height, and width.

OnnxImportDimensionRecord

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

OnnxImportFlattenConsistencyAudit

Metadata-only audit record comparing a flattened pooled width to the next dense width.

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, carrying model, nodes, and span.

OnnxImportLayerNodePair

Node slices for one sequential imported layer assignment pass, carrying current and previous layer node lists.

OnnxImportLayerNodePairBuildParams

Build params for one sequential layer node-pair slice operation, specifying layer index and sequential position.

OnnxImportLayerTensorNames

Weight tensor names for one imported layer index, identifying weight and bias initializer name strings.

OnnxImportLayerWeightBucket

Bucketed ONNX dense/per-neuron tensors for one exported layer index, holding the aggregated and per-neuron lists.

OnnxImportPerNeuronAssignmentContext

Context for assigning one per-neuron imported target node, carrying previous nodes and weight and bias tensors.

OnnxImportPerNeuronLayerAssignmentContext

Context for assigning per-neuron tensors for one layer, supplying the initializer map and sequential layer node pair.

OnnxImportPoolingMetadata

Parsed pooling metadata payload attached to imported network instances, listing pool specs and virtual shapes.

OnnxImportPoolingVirtualShape

Virtual spatial shape derived from Conv and Pool metadata during import.

OnnxImportRecurrentRestorationContext

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

OnnxImportResidualAdd

Explicit one-hop residual-add merge carried through Phase 5 import hardening.

OnnxImportSelfConnectionUpsertContext

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

OnnxImportSharedInitializerAlias

Audit-only shared initializer alias carried through Phase 5 import fallback.

OnnxImportWeightAssignmentBuildParams

Build params for creating shared ONNX import weight-assignment context, supplying network, model, and hidden sizes.

OnnxImportWeightAssignmentContext

Shared weight-assignment context built once per ONNX import, carrying model, layers, metadata, and initializer map.

OnnxIncomingWeightAssignmentContext

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

OnnxLayerEmissionContext

Context for emitting non-input layers during model build, including layer list, options, and ordering flags.

OnnxLayerEmissionResult

Result of emitting non-input export layers, carrying the last output name and the layer output name map.

OnnxLayerFactory

Runtime factory map used to construct dynamic recurrent layer modules.

OnnxMetadataProperty

Canonical metadata key-value pair used by OnnxModel.metadata_props.

Keys are exporter-defined semantic hints (for example layout or fallback reasons) and values are serialized as plain strings.

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, carrying model reference, opset, producer info, and inclusion flags.

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, supplying sizes, minimum count, and message.

OnnxPostProcessingContext

Context for post-processing and export metadata finalization, holding model, layers, options, and layer emission result.

OnnxRecurrentCollectionContext

Context for collecting recurrent layer indices during model build, providing the layer list and export options.

OnnxRecurrentInputValueInfoContext

Context for constructing one recurrent previous-state graph input payload, carrying name, hidden width, and batch flag.

OnnxRecurrentLayerProcessingContext

Execution context for processing one hidden recurrent layer during model build traversal and emission.

OnnxRecurrentLayerTraversalContext

Traversal context for one hidden layer during recurrent-input collection, supplying layer index and batch-dimension flag.

OnnxRuntimeFactories

Runtime factories consumed during ONNX import network reconstruction, grouping the perceptron and layer module.

OnnxRuntimeLayerFactory

OnnxRuntimeLayerFactory(
  size: number,
): default

Runtime layer-constructor signature used for recurrent layer reconstruction, accepting size and returning a Layer.

OnnxRuntimeLayerFactoryMap

Runtime layer module shape widened for fused-recurrent reconstruction wiring and dynamic layer factory dispatch.

OnnxRuntimeLayerModule

Runtime layer module shape consumed by ONNX import orchestration, exposing LSTM and GRU factory constructors.

OnnxRuntimePerceptronFactory

OnnxRuntimePerceptronFactory(
  sizes: number[],
): default

Runtime perceptron factory signature used by ONNX import orchestration, producing a Network from size arguments.

OnnxShape

Canonical shape descriptor for ONNX tensors used by export, import, and schema validation paths. Each entry preserves axis intent so runtime bridges can validate rank-sensitive operators without guessing dimension semantics.

OnnxTensor

Serialized tensor payload stored inside graph initializers.

NeatapticTS currently writes floating-point parameter vectors and matrices to float_data, while the storage-fp16 lane can pack float16 words into int32_data for JSON-first persistence without changing the logical tensor shape.

OnnxTensorType

Canonical tensor element type shelf used by schema, import coercion, and export metadata emission. Keep this alias at the ONNX root so callers can depend on one stable type name while chapter ownership remains in schema contracts.

OnnxValueInfo

Canonical tensor value-info descriptor used to name and type graph inputs, outputs, and intermediate values. This alias keeps metadata surfaces consistent across ONNX schema parsing, importer reconstruction, and exporter graph emission.

OptionalLayerOutputParams

Shared parameters for optional pooling or flatten output emission after one dense layer output tensor.

OptionalPoolingAndFlattenParams

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

OutputLayerActivationContext

Output-layer activation assignment context, carrying output layer index, node list, and activation operations map.

PerNeuronConcatNodePayload

Per-neuron concat node payload used to merge individual neuron outputs into one combined layer tensor.

PerNeuronGraphNames

Per-neuron graph tensor names identifying the Gemm output and activation output for one neuron subgraph.

PerNeuronLayerContext

Per-neuron layer context alias for PerNeuronLayerParams, used at the per-neuron layer traversal boundary.

PerNeuronLayerParams

Parameters for per-neuron layer emission, grouping model, layer index, node lists, options, and batch-dimension flag.

PerNeuronNodeContext

Per-neuron normalized node context replacing raw Node references with resolved NodeInternals for safe emission.

PerNeuronSubgraphContext

Per-neuron subgraph emission context carrying layer index, neuron index, previous output name, and opset version.

PerNeuronTensorNames

Per-neuron initializer tensor names identifying weight and bias tensors for one neuron subgraph.

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, grouping kernel shape, strides, and padding values.

PoolingEmissionContext

Pooling emission context resolved for one layer output, extending OptionalLayerOutputParams with the Pool2DMapping spec.

RecurrentActivationEmissionContext

Context for selecting and emitting recurrent activation node payload using the layer's dominant squash function.

RecurrentGateBlockCollectionContext

Context for collecting one gate parameter block, supplying gate nodes, previous layer, unit size, and diagonal flag.

RecurrentGateParameterCollectionResult

Flattened recurrent gate parameter vectors for one fused operator, grouping input, recurrent, and bias arrays.

RecurrentGateRow

One recurrent gate row payload before flatten fold, containing input weights, recurrent weights, and bias.

RecurrentGateRowCollectionContext

Context for collecting one recurrent gate row (one neuron), supplying the previous layer node list and unit size.

RecurrentGemmEmissionContext

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

RecurrentGraphNames

Derived graph names for one recurrent single-step layer payload, with all tensor and node names resolved.

RecurrentHeuristicEmissionContext

Context for heuristic recurrent operator emission traversal, carrying model, layer list, and previous output tensor name.

RecurrentInitializerEmissionContext

Context for pushing recurrent initializers into ONNX graph state, carrying widths, tensor names, and value arrays.

RecurrentInitializerNames

Initializer tensor names for one single-step recurrent layer, naming weight, bias, and recurrent-weight tensors.

RecurrentInitializerValues

Collected initializer vectors for one single-step recurrent layer, storing weight matrix, biases, and recurrent weights.

RecurrentLayerEmissionContext

Derived execution context for single-step recurrent layer emission, extending params with layer slot and widths.

RecurrentLayerEmissionParams

Parameters for single-step recurrent layer emission, supplying model, layer index, and adjacent node lists.

RecurrentRowCollectionContext

Context for collecting one recurrent matrix row, supplying the layer node list and the row index to extract.

SharedActivationNodeBuildParams

Shared parameters for constructing an activation node payload, carrying activation type and output name strings.

SharedGemmNodeBuildParams

Shared parameters for constructing a Gemm node payload, carrying weight, bias, output tensor names, and node name.

SpecMetadataAppendContext

Append-a-spec metadata context for JSON-array metadata keys, supplying model, key, and Conv or Pool spec.

WeightToleranceComparisonContext

Context for comparing two scalar weights with numeric tolerance, used by Conv sharing validation helpers.

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 activation functions.

NetworkOnnxShapeValidationError

Raised when ONNX export produces inconsistent or mismatched tensor dimensions.

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 a strictly layered node ordering from an analyzed network structure.

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; },
  opset: number,
): OnnxActivationOperation

Map an internal activation function (squash) to an ONNX op_type. Mapping flows through the exporter activation resolver so opset-gated operators and identity fallbacks stay centralized in one compatibility decision path.

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. Rehydrating this cache from node-owned adjacency shelves keeps exporter traversal deterministic after structural edits that may leave the flat cache stale.

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.

resolveOnnxActivationNodeConfig

resolveOnnxActivationNodeConfig(
  squash: ((x: number, derivate?: boolean | undefined) => number) & { name?: string | undefined; },
  opset: number,
): { operation: OnnxActivationOperation; attributes?: OnnxAttribute[] | undefined; }

Resolve the ONNX activation node payload for one runtime activation. The payload includes both the resolved operator and any mandatory attributes, allowing downstream graph emission to stay declarative and free of activation-specific branching.

Parameters:

Returns: Activation operator plus any required ONNX attributes.

resolveOnnxActivationOperation

resolveOnnxActivationOperation(
  squash: ((x: number, derivate?: boolean | undefined) => number) & { name?: string | undefined; },
  opset: number,
): { operation: OnnxActivationOperation; attributes?: OnnxAttribute[] | undefined; didUseFallback: boolean; }

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. Validation enforces exporter baseline assumptions before node emission so unsupported mixed-activation or sparse connectivity cases are surfaced with actionable errors.

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; }; didUseFallback: boolean; },
): void

Emit a warning when activation export falls back to Identity.

Parameters:

Returns: Nothing.

Generated from source JSDoc • GitHub