architecture/network/onnx/export/layers

Decision router for ONNX layer emission.

This boundary does not build tensors directly. Its job is to inspect one export layer and choose the smallest valid emission strategy: Conv when an explicit mapping is present, recurrent single-step when the layer owns self-connections, compact dense export when activations are homogeneous, or per-neuron decomposition when activations differ.

flowchart TD
  Start[Layer inputs] --> Conv{Conv mapping for layer?}
  Conv -->|Yes| ConvEmit[Emit Conv path]
  Conv -->|No| Recurrent{Self-recurrent hidden layer?}
  Recurrent -->|Yes| RecEmit[Emit recurrent single-step path]
  Recurrent -->|No| Mixed{Mixed activations?}
  Mixed -->|No| DenseEmit[Emit dense Gemm + activation]
  Mixed -->|Yes| PerNeuron[Emit per-neuron Gemm + activation + Concat]

architecture/network/onnx/export/layers/network.onnx.export-conv.utils.ts

tryEmitConvLayer

tryEmitConvLayer(
  params: OnnxConvEmissionParams,
): string | undefined

Try to emit one layer as a Conv-shaped ONNX segment when the caller supplied an explicit Conv mapping for that export layer.

This path reconstructs kernels from a fully connected layer by assuming the declared Conv geometry really matches the flattened previous and current layer widths. When that contract does not hold, the exporter logs the mismatch and returns undefined so the broader layer router can fall back or fail with a more appropriate message.

In addition to the Conv and activation nodes, this helper also owns optional pooling, flatten-after-pooling, and the metadata hints required for import to rebuild the same semantic interpretation.

Parameters:

Returns: New output tensor name when handled, otherwise undefined.

Example:

const outputName = tryEmitConvLayer({
  model,
  options: {
    conv2dMappings: [{ layerIndex: 1, inHeight: 28, inWidth: 28, inChannels: 1, outChannels: 8, kernelSize: 3 }],
  },
  layerIndex: 1,
  previousOutputName: 'input',
  previousLayerNodes,
  currentLayerNodes,
});

architecture/network/onnx/export/layers/network.onnx.export-dense.utils.ts

appendDenseBiasInitializer

appendDenseBiasInitializer(
  layerContext: DenseLayerContext,
  biasTensorName: string,
  biasVector: number[],
): void

Append dense bias initializer.

Parameters:

Returns: Nothing.

appendDenseNodes

appendDenseNodes(
  model: OnnxModel,
  orderedNodes: DenseOrderedNodePayload[],
): void

Append ordered dense nodes to the model graph.

Parameters:

Returns: Nothing.

appendDenseWeightInitializer

appendDenseWeightInitializer(
  layerContext: DenseLayerContext,
  weightTensorName: string,
  weightMatrixValues: number[],
): void

Append dense weight initializer.

Parameters:

Returns: Nothing.

buildSingleNeuronWeightRow

buildSingleNeuronWeightRow(
  targetNodeInternal: NodeInternals,
  previousLayerNodes: default[],
): number[]

Build one neuron's incoming weight row against previous layer.

Parameters:

Returns: Weight row values.

collectDenseInitializerValues

collectDenseInitializerValues(
  layerContext: DenseLayerContext,
): DenseInitializerValues

Collect dense weight matrix and bias vector values.

Parameters:

Returns: Dense initializer values.

createActivationNode

createActivationNode(
  denseActivationContext: DenseActivationContext,
): DenseActivationNodePayload

Create dense activation node definition.

Parameters:

Returns: ONNX activation node payload.

createDefaultGemmAttributes

createDefaultGemmAttributes(): { name: string; type: string; f?: number | undefined; i?: number | undefined; }[]

Build default Gemm attributes for ONNX export.

Returns: Default Gemm attribute list.

createDenseTensorNames

createDenseTensorNames(
  layerIndex: number,
): DenseTensorNames

Build dense tensor names for initializer emission.

Parameters:

Returns: Dense tensor names.

createGemmNode

createGemmNode(
  denseActivationContext: DenseActivationContext,
): DenseGemmNodePayload

Create dense Gemm node definition.

Parameters:

Returns: ONNX Gemm node payload.

createSharedActivationNodePayload

createSharedActivationNodePayload(
  params: SharedActivationNodeBuildParams,
): DenseActivationNodePayload

Build a shared activation node payload.

Parameters:

Returns: Activation node payload.

createSharedGemmNodePayload

createSharedGemmNodePayload(
  params: SharedGemmNodeBuildParams,
): DenseGemmNodePayload

Build a shared Gemm node payload.

Parameters:

Returns: Gemm node payload.

emitDenseActivationSubgraph

emitDenseActivationSubgraph(
  model: OnnxModel,
  denseActivationContext: DenseActivationContext,
): void

Emit Gemm and activation nodes using requested ordering.

Parameters:

Returns: Nothing.

emitDenseInitializers

emitDenseInitializers(
  layerContext: DenseLayerContext,
): DenseTensorNames

Emit dense initializers and return tensor names.

Parameters:

Returns: Tensor names.

emitDenseLayer

emitDenseLayer(
  params: DenseLayerParams,
): string

Emit the compact dense export path for a layer whose neurons all share the same activation.

This is the cheapest ONNX shape the exporter can produce for a standard MLP layer: one Gemm node for the affine transform and one activation node for the whole layer. The same helper also preserves the library's legacy node-ordering compatibility mode when older snapshots need deterministic graph ordering.

Parameters:

Returns: Output tensor name.

Example:

const outputName = emitDenseLayer({
  model,
  layerIndex: 2,
  previousOutputName: 'Layer_1',
  previousLayerNodes,
  currentLayerNodes,
  options: {},
  legacyNodeOrdering: false,
});

emitOptionalLayerOutput

emitOptionalLayerOutput(
  params: OptionalLayerOutputParams,
): string

Emit optional pooling and flatten output fold.

Parameters:

Returns: Output tensor name.

emitPerNeuronLayer

emitPerNeuronLayer(
  params: PerNeuronLayerParams,
): string

Emit the fallback dense-family representation for a layer whose target neurons use different activations.

Instead of pretending the layer is homogeneous, this path exports one tiny Gemm-plus-activation subgraph per neuron and then concatenates the results. The graph is larger, but it preserves mixed activation behavior that a single layer-wide activation node cannot express.

Parameters:

Returns: Output tensor name.

Example:

const outputName = emitPerNeuronLayer({
  model,
  layerIndex: 2,
  previousOutputName: 'Layer_1',
  previousLayerNodes,
  currentLayerNodes,
  options: { allowMixedActivations: true },
});

emitPerNeuronSubgraph

emitPerNeuronSubgraph(
  perNeuronSubgraphContext: PerNeuronSubgraphContext,
): string

Emit per-neuron Gemm + activation subgraph.

Parameters:

Returns: Per-neuron activation output name.

resolveDenseNodeOrder

resolveDenseNodeOrder(
  gemmNode: DenseGemmNodePayload,
  activationNode: DenseActivationNodePayload,
  legacyNodeOrdering: boolean,
): DenseOrderedNodePayload[]

Resolve dense node order for legacy and current exports.

Parameters:

Returns: Ordered node list.

resolveSingleNeuronInboundWeight

resolveSingleNeuronInboundWeight(
  targetNodeInternal: NodeInternals,
  sourceNode: default,
): number

Resolve one inbound connection weight for a source node.

Parameters:

Returns: Inbound weight or zero when missing.

architecture/network/onnx/export/layers/network.onnx.export-recurrent.utils.ts

buildDefaultGemmAttributes

buildDefaultGemmAttributes(): { name: string; type: string; f?: number | undefined; i?: number | undefined; }[]

Build the shared attribute list for ONNX Gemm node payloads.

Returns: Gemm attribute payload list.

buildInputBranchGemmEmissionContext

buildInputBranchGemmEmissionContext(
  context: RecurrentLayerEmissionContext,
  initializerNames: RecurrentInitializerNames,
  graphNames: RecurrentGraphNames,
): RecurrentGemmEmissionContext

Build Gemm emission context for the feed-forward branch.

Parameters:

Returns: Gemm emission context.

buildRecurrentBranchGemmEmissionContext

buildRecurrentBranchGemmEmissionContext(
  context: RecurrentLayerEmissionContext,
  initializerNames: RecurrentInitializerNames,
  graphNames: RecurrentGraphNames,
): RecurrentGemmEmissionContext

Build Gemm emission context for the recurrent hidden-state branch.

Parameters:

Returns: Gemm emission context.

buildRecurrentGraphNames

buildRecurrentGraphNames(
  context: RecurrentLayerEmissionContext,
): RecurrentGraphNames

Build deterministic graph names for recurrent-node emission.

Parameters:

Returns: Graph-name group for branch and activation nodes.

buildRecurrentInitializerNames

buildRecurrentInitializerNames(
  context: RecurrentLayerEmissionContext,
): RecurrentInitializerNames

Build deterministic tensor names for recurrent initializer emission.

Parameters:

Returns: Tensor-name group for initializer emission.

buildRecurrentLayerEmissionContext

buildRecurrentLayerEmissionContext(
  params: RecurrentLayerEmissionParams,
): RecurrentLayerEmissionContext

Build derived recurrent-layer context from input params.

Parameters:

Returns: Derived context with cached dimensions and layer slot.

collectRecurrentInitializerValues

collectRecurrentInitializerValues(
  context: RecurrentLayerEmissionContext,
): RecurrentInitializerValues

Collect recurrent initializer vectors for one layer.

Parameters:

Returns: Dense and recurrent initializer vectors.

emitRecurrentActivationNode

emitRecurrentActivationNode(
  context: RecurrentActivationEmissionContext,
): void

Emit activation node for recurrent branch sum output.

Parameters:

Returns: Nothing.

emitRecurrentAddNode

emitRecurrentAddNode(
  model: OnnxModel,
  graphNames: RecurrentGraphNames,
): void

Emit Add node that fuses feed-forward and recurrent branch outputs.

Parameters:

Returns: Nothing.

emitRecurrentGemmNode

emitRecurrentGemmNode(
  context: RecurrentGemmEmissionContext,
): void

Emit one recurrent Gemm node with shared ONNX attributes.

Parameters:

Returns: Nothing.

emitRecurrentInitializers

emitRecurrentInitializers(
  context: RecurrentInitializerEmissionContext,
): void

Emit dense and recurrent initializer tensors.

Parameters:

Returns: Nothing.

emitRecurrentLayer

emitRecurrentLayer(
  params: RecurrentLayerEmissionParams,
): string

Emit the constrained recurrent single-step export path for one hidden layer.

This boundary models recurrence with two parallel Gemm branches: one for the feed-forward input and one for the previous hidden state. The recurrent branch uses a diagonal matrix derived from self-connections only, which keeps the exported shape simple and matches the importer's current reconstruction contract.

Hidden-state inputs are named hidden_prev for the first recurrent layer and hidden_prev_l{n} for later recurrent layers. Mixed activations are not supported on this path because the single activation node is applied after the input and recurrent branches are summed.

Parameters:

Returns: Output tensor name.

Example:

const outputName = emitRecurrentLayer({
  model,
  layerIndex: 1,
  previousOutputName: 'input',
  previousLayerNodes,
  currentLayerNodes,
});

readNodeInternals

readNodeInternals(
  node: default,
): NodeInternals

Normalize runtime node shape to recurrent-export internals contract.

Parameters:

Returns: Node internals used by ONNX emission helpers.

resolvePreviousHiddenInputName

resolvePreviousHiddenInputName(
  layerIndex: number,
): string

Resolve recurrent branch hidden-state input for one layer.

Parameters:

Returns: Hidden-state tensor input name.

resolveRecurrentActivationType

resolveRecurrentActivationType(
  currentLayerNodes: default[],
): string

Resolve ONNX activation type from first node in recurrent layer.

Parameters:

Returns: ONNX activation op type.

architecture/network/onnx/export/layers/network.onnx.export-layer-graph.utils.ts

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,
});

architecture/network/onnx/export/layers/network.onnx.export-layer-common.utils.ts

appendIndexedMetadata

appendIndexedMetadata(
  model: OnnxModel,
  key: string,
  layerIndex: number,
): void

Append an integer index to JSON-array metadata key.

Parameters:

Returns: Nothing.

appendMetadataSpec

appendMetadataSpec(
  model: OnnxModel,
  key: string,
  spec: Conv2DMapping | Pool2DMapping,
): void

Append a JSON object to JSON-array metadata key.

Parameters:

Returns: Nothing.

appendPoolingMetadata

appendPoolingMetadata(
  context: PoolingEmissionContext,
): void

Append pooling metadata for one emitted pooling layer.

Parameters:

Returns: Nothing.

asNodeInternals

asNodeInternals(
  node: default,
): NodeInternals

Normalize a public node instance into ONNX export internals.

Parameters:

Returns: Internal runtime-facing node representation.

buildDenseWeightsAndBiases

buildDenseWeightsAndBiases(
  previousLayerNodes: default[],
  currentLayerNodes: default[],
): DenseWeightBuildResult

Build the shared dense initializer payload used by both compact dense export and recurrent single-step export.

The returned weight matrix is flattened in row-major order by destination neuron. Missing edges are encoded as zeroes so partially connected layers can still be represented in a deterministic rectangular tensor layout. Biases are collected in the same destination-neuron order.

Parameters:

Returns: Flattened row-major weight matrix and bias vector.

Example:

const { weightMatrixValues, biasVector } = buildDenseWeightsAndBiases(
  previousLayerNodes,
  currentLayerNodes,
);

buildDiagonalRecurrentWeights

buildDiagonalRecurrentWeights(
  currentLayerNodes: default[],
): number[]

Build a diagonal recurrent matrix from self-connections.

Parameters:

Returns: Flattened row-major recurrent matrix.

buildIndexedMetadataProperty

buildIndexedMetadataProperty(
  key: string,
  layerIndex: number,
): OnnxMetadataProperty

Build a new index-array metadata property.

Parameters:

Returns: Metadata property.

buildSpecMetadataProperty

buildSpecMetadataProperty(
  key: string,
  spec: Conv2DMapping | Pool2DMapping,
): OnnxMetadataProperty

Build a new spec-array metadata property.

Parameters:

Returns: Metadata property.

collectDenseRows

collectDenseRows(
  context: DenseWeightBuildContext,
): DenseWeightRow[]

Collect dense rows for each target node in current layer.

Parameters:

Returns: Dense rows containing per-target weights and bias.

collectDenseRowWeights

collectDenseRowWeights(
  context: DenseWeightRowCollectionContext,
): number[]

Collect source-to-target weights for one dense row.

Parameters:

Returns: Row weights in source-node order.

collectPoolingAttributes

collectPoolingAttributes(
  poolSpec: Pool2DMapping,
): PoolingAttributes

Collect ONNX pooling attributes from one pooling spec.

Parameters:

Returns: Pooling attributes for ONNX node payload.

collectRecurrentRow

collectRecurrentRow(
  context: RecurrentRowCollectionContext,
): number[]

Collect one recurrent matrix row.

Parameters:

Returns: Recurrent row values.

collectRecurrentRows

collectRecurrentRows(
  context: DiagonalRecurrentBuildContext,
): number[][]

Collect recurrent matrix rows for one layer.

Parameters:

Returns: Recurrent row collection.

emitOptionalFlattenAfterPooling

emitOptionalFlattenAfterPooling(
  context: FlattenAfterPoolingContext,
): string

Conditionally emit flatten node after pooling.

Parameters:

Returns: Output tensor name after optional flatten.

emitOptionalPoolingAndFlatten

emitOptionalPoolingAndFlatten(
  params: OptionalPoolingAndFlattenParams,
): string

Emit optional pooling and flatten nodes after a layer output.

Parameters:

Returns: Final output tensor name after optional pooling/flatten.

emitPoolingNode

emitPoolingNode(
  context: PoolingEmissionContext,
): string

Emit one pooling node and return its output tensor name.

Parameters:

Returns: Pooling output tensor name.

ensureMetadataRegistry

ensureMetadataRegistry(
  model: OnnxModel,
): OnnxMetadataProperty[]

Ensure model metadata registry exists.

Parameters:

Returns: Mutable metadata registry.

findMetadataProperty

findMetadataProperty(
  metadataRegistry: OnnxMetadataProperty[],
  key: string,
): OnnxMetadataProperty | undefined

Find a metadata property by key.

Parameters:

Returns: Matching metadata property if present.

foldDenseRowsToInitializers

foldDenseRowsToInitializers(
  denseRows: DenseWeightRow[],
): DenseWeightBuildResult

Fold dense rows into flattened ONNX initializer arrays.

Parameters:

Returns: Flattened dense initializer result.

parseMetadataArray

parseMetadataArray(
  metadataValue: string,
): ItemType[] | undefined

Parse a metadata JSON array value safely.

Parameters:

Returns: Parsed array when valid, otherwise undefined.

resolveDiagonalRecurrentWeight

resolveDiagonalRecurrentWeight(
  context: RecurrentRowCollectionContext,
  columnIndex: number,
): number

Resolve recurrent weight value for one matrix coordinate.

Parameters:

Returns: Recurrent weight for diagonal entries, otherwise zero.

resolveInboundWeight

resolveInboundWeight(
  targetNodeInternal: NodeInternals,
  sourceNode: default,
): number

Resolve source-to-target inbound connection weight.

Parameters:

Returns: Inbound weight or zero for disconnected edges.

serializeIndexedMetadataValue

serializeIndexedMetadataValue(
  currentValue: string,
  layerIndex: number,
): string

Serialize index metadata after appending one unique index.

Parameters:

Returns: Serialized JSON value.

serializeSpecMetadataValue

serializeSpecMetadataValue(
  currentValue: string,
  spec: Conv2DMapping | Pool2DMapping,
): string

Serialize spec metadata after appending one spec object.

Parameters:

Returns: Serialized JSON value.

toPoolingEmissionContext

toPoolingEmissionContext(
  params: OptionalPoolingAndFlattenParams,
): PoolingEmissionContext

Resolve pooling emission context from optional pooling parameters.

Parameters:

Returns: Pooling emission context.

Generated from source JSDoc • GitHub