Computation Cost Inference#

Overview#

Knowing the computational cost of an ONNX model — expressed as a count of floating-point operations (FLOPs) — is useful for model comparison, profiling, and guiding optimization decisions.

yobx.xshape.cost_inference implements a lightweight per-operator FLOPs estimator. The main entry point is estimate_node_flops(), which accepts a single ONNX node together with two callables that resolve tensor shapes and integer literals, and returns the estimated FLOPs count.

When input shapes contain symbolic dimensions (strings such as "batch" or "seq"), the returned value is a symbolic arithmetic expression (also a string) that can be evaluated once concrete shapes are known. Static shapes yield plain integer counts.

Integration with NativeShapeInference#

NativeShapeInference integrates cost inference through the run_model() method. Pass inference=InferenceMode.COST to enable it:

from yobx.xshape import NativeShapeInference, InferenceMode

builder = NativeShapeInference()
cost_list = builder.run_model(model, inference=InferenceMode.COST)
# cost_list: list of (op_type, flops, input_shapes) tuples

Each element of cost_list is a (op_type, flops, input_shapes) triple where flops is either an integer, a symbolic string expression, or None (unsupported op or unknown shapes).

To substitute concrete dimension values and obtain integer FLOPs counts, call evaluate_cost_with_true_inputs() with the actual input tensors:

import numpy as np

feeds = {"X": np.random.randn(2, 64, 64).astype("float32")}
concrete = builder.evaluate_cost_with_true_inputs(feeds, cost_list)
total = sum(f or 0 for _, f, _ in concrete)
print(f"Total FLOPs: {total:,}")

For a full worked example including a before/after optimization comparison see Symbolic Cost of a Model: Transpose Fusion.

How FLOPs Are Counted#

The estimator assigns FLOPs to operators using a set of simple, well-established counting conventions. Operators are partitioned into groups, each governed by a uniform formula:

Element-wise unary operators (Relu, Sigmoid, Exp, Sqrt, …)

1 FLOPs per output element. For Sigmoid specifically the formula accounts for the exp + add + div decomposition: 3 FLOPs per element. For Softmax / LogSoftmax: 3 FLOPs per element.

Element-wise binary operators (Add, Mul, Sub, Div, …)

1 FLOPs per output element.

Matrix multiplication (MatMul)

For inputs of shape (..., M, K) and (..., K, N) the formula is:

\[\text{FLOPs} = 2 \times \prod(\text{batch dims}) \times M \times K \times N\]

The factor of 2 accounts for one multiply-accumulate per inner-product step.

General matrix multiply (Gemm)

For an alpha * A @ B + beta * C operation with shapes (M, K) and (K, N):

\[\text{FLOPs} = 2 \times M \times K \times N + M \times N\]

The additional M*N term models the bias addition.

Convolution (Conv / ConvTranspose)

For output shape (N, C_out, *spatial_out) and weight shape (C_out, C_in_per_group, *kernel):

\[\text{FLOPs} = 2 \times N \times C_{out} \times C_{in/group} \times \prod(\text{kernel}) \times \prod(\text{spatial\_out})\]

Windowed pooling (MaxPool / AveragePool)

\[\text{FLOPs} = N \times C \times \prod(\text{spatial\_out}) \times \prod(\text{kernel\_shape})\]

Global pooling (GlobalAveragePool / GlobalMaxPool)

\[\text{FLOPs} = N \times C \times \prod(\text{spatial dims of input})\]
Normalization (BatchNormalization)

mean + var + normalise ≈ 2 FLOPs per output element.

Normalization (LayerNormalization / GroupNormalization / InstanceNormalization)

mean + var + sub + div + scale + bias ≈ 6 FLOPs per output element.

Reduction operators (ReduceSum, ReduceMean, ReduceMax, …)

1 FLOPs per input element (one comparison or accumulation step).

Recurrent cells

  • LSTM — 2 * seq * batch * (input_size + hidden) * 4 * hidden

  • GRU — 2 * seq * batch * (input_size + hidden) * 3 * hidden

  • RNN — 2 * seq * batch * (input_size + hidden) * hidden

Data-movement operators (Cast, Transpose, Gather, Pad, …)

Element count of the first output tensor (one read + one write per element).

Shape-manipulation operators (Reshape, Squeeze, Unsqueeze)

Rank of the output tensor (one metadata operation per dimension). Shape uses the rank of the input tensor.

Zero-cost operators (Identity)

0 FLOPs — these are purely logical copies that a compiler can eliminate.

Operators not covered by any of the above categories return None.

Programmatic Formula Listing#

The function list_op_cost_formulas() returns a sorted dictionary mapping every supported op_type to the symbolic FLOPs expression that the estimator produces on a representative ONNX backend test example. All static input dimensions of that example are replaced by symbolic variables (DIM<n>) before running the estimator, so the result shows the general formula rather than a single concrete number.

The complete table of supported operators and their symbolic FLOPs formulas is generated below by calling list_op_cost_formulas() at documentation-build time:

<<<

from yobx.xshape import list_op_cost_formulas

formulas = list_op_cost_formulas()

rows = [
    ".. list-table::",
    "   :header-rows: 1",
    "   :widths: 30 70",
    "",
    "   * - Op type",
    "     - Symbolic FLOPs",
]
for op_type, formula in formulas.items():
    rows.append(f"   * - ``{op_type}``")
    rows.append(f"     - ``{formula}``")

print("\n".join(rows))

>>>

Op type

Symbolic FLOPs

Abs

DIM3*DIM4*DIM5

Acos

DIM3*DIM4*DIM5

Acosh

DIM3*DIM4*DIM5

Add

DIM3*DIM4*DIM5

And

DIM3*DIM4

Asin

DIM3*DIM4*DIM5

Asinh

DIM3*DIM4*DIM5

Atan

DIM3*DIM4*DIM5

Atanh

DIM3*DIM4*DIM5

AveragePool

9*DIM1*DIM1*DIM3*DIM3

BatchNormalization

2*DIM2*DIM3*DIM4*DIM5

BitShift

DIM3

Cast

DIM3*DIM5

CastLike

DIM3*DIM5

Ceil

DIM2*DIM3

Celu

DIM2*DIM3

Concat

DIM4

Constant

6

ConstantOfShape

ConstantOfShape_dim0

Conv

2*DIM1*DIM1*DIM1*DIM3*DIM3*DIM5*DIM5

ConvTranspose

2*DIM1*DIM2*DIM2*DIM3*DIM3*DIM5*DIM5

Cos

DIM2*DIM3

Cosh

DIM2*DIM3

Div

DIM2*DIM3

Elu

DIM2*DIM3

Equal

DIM2*DIM2

Erf

DIM2*DIM3

Exp

DIM2*DIM3

Expand

Expand_dim0

Flatten

dim1_b

Floor

DIM2*DIM3

GRU

2*DIM1*DIM18*(DIM18//3+DIM2)*DIM3

Gather

DIM2*DIM2*DIM4

GatherElements

DIM2*DIM2

GatherND

DIM2

Gemm

2*DIM3*DIM4*DIM5+DIM3*DIM4

GlobalAveragePool

dim0_x*dim1_x*dim2_x*dim3_x

GlobalMaxPool

dim0_x*dim1_x*dim2_x*dim3_x

Greater

DIM2*DIM2

GreaterOrEqual

DIM2*DIM2

GroupNormalization

6*DIM2*DIM2*DIM3*DIM4

HardSigmoid

DIM2*DIM3

HardSwish

DIM2*DIM3

Identity

0

InstanceNormalization

6*DIM1*DIM1*DIM256

LSTM

2*DIM1*(DIM2+DIM28//4)*DIM28*DIM3

LayerNormalization

6*DIM3*DIM4

LeakyRelu

DIM2*DIM3

Less

DIM2*DIM2

LessOrEqual

DIM2*DIM2

Log

DIM2*DIM3

LogSoftmax

3*DIM2*DIM3

MatMul

2*DIM3

MaxPool

2*DIM1*DIM3*DIM31

Mish

DIM2*DIM3

Mod

DIM3

Mul

DIM2*DIM3

Neg

DIM2*DIM3

Not

DIM2*DIM2

OneHot

DIM2*DIM3

Or

DIM2*DIM2

PRelu

DIM2*DIM3

Pad

DIM1*DIM12*DIM3*DIM7

Pow

DIM3

RNN

2*DIM2*DIM3*(DIM3+DIM5)*DIM5

ReduceL1

dim0_data*dim1_data*dim2_data

ReduceL2

dim0_data*dim1_data*dim2_data

ReduceLogSum

dim0_data*dim1_data*dim2_data

ReduceLogSumExp

dim0_data*dim1_data*dim2_data

ReduceMax

dim0_data*dim1_data*dim2_data

ReduceMean

dim0_data*dim1_data*dim2_data

ReduceMin

dim0_data*dim1_data*dim2_data

ReduceProd

dim0_data*dim1_data*dim2_data

ReduceSum

dim0_data*dim1_data*dim2_data

ReduceSumSquare

dim0_data*dim1_data*dim2_data

Relu

DIM2*DIM3

Reshape

1

Round

DIM2*DIM3

Scatter

DIM1*DIM5

ScatterElements

DIM1*DIM5

ScatterND

DIM4*DIM4*DIM4

Selu

DIM2*DIM3

Shape

3

Shrink

DIM2*DIM3

Sigmoid

3*DIM2*DIM3

Sign

DIM2*DIM3

Sin

DIM2*DIM3

Sinh

DIM2*DIM3

Slice

B*DIM3

Softmax

3*DIM2*DIM3

Softplus

DIM2*DIM3

Softsign

DIM2*DIM3

Split

DIM2*b

Sqrt

DIM2*DIM3

Squeeze

4

Sub

DIM2*DIM3

Tan

DIM5

Tanh

DIM2*DIM3

ThresholdedRelu

DIM2*DIM3

Tile

DIM9

Transpose

DIM2*DIM3

Unsqueeze

1

Xor

DIM2*DIM2

See also the gallery example Computation Cost: How It Works and Supported Operator Formulas for additional context and worked examples.