Recursive AI

Run an ONNX If subgraph in C#

OneModel is a free, open-source neural-network library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

An ONNX If node runs one of two branches on the CPU.

Terminal
dotnet add package RecursiveAI.OneModel

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneModel.Graph;
using RecursiveAI.OneModel.Tensors;
 
using var session =
    Session.Load("conditional.onnx");
using var condition = Tensor.Scalar(true);
using var x = Tensor.FromSpan<float>(
    [3f], Shape.Create(1));
using var result = session.Run(
    new Dictionary<string, Tensor>
    {
        ["condition"] = condition,
        ["x"] = x
    });
Console.WriteLine(
    result["y"].Data<float>()[0]);
Text
6

conditional.onnx is in the download: scalar Boolean condition, float x[1], output y[1]; true adds x + x, false multiplies x * x.

Unzip the example, then dotnet run.

The code uses the console template’s implicit usings, including System.Collections.Generic for Dictionary.

The full program

C#
using RecursiveAI.OneModel.Graph;
using RecursiveAI.OneModel.Tensors;
 
using var session = Session.Load("conditional.onnx");
using var condition = Tensor.Scalar(true);
using var x = Tensor.FromSpan<float>([3f], Shape.Create(1));
foreach (bool choose in new[] { true, false })
{
    condition.MutableData<bool>()[0] = choose;
    using var result = session.Run(
        new Dictionary<string, Tensor>
        { ["condition"] = condition, ["x"] = x });
    Console.WriteLine($"{choose}: {result["y"].Data<float>()[0]}");
}
Text
True: 6
False: 9

The program changes only the condition between runs. Both branches read the same outer-scope tensor x, containing 3. The model is a small, original example with no trained weights or external data.

Its graph is:

Text
condition: bool scalar; x: float[1]
y = If(condition)
    then: yes = Add(x, x); return yes
    else: no = Mul(x, x); return no

If an operator in either branch is unavailable, session creation fails with SessionException naming the unsupported operators; it does not wait until that branch is selected.

Variations

Select the false branch. This standalone replacement for the snippet at the top prints the square rather than the double.

C#
using RecursiveAI.OneModel.Graph;
using RecursiveAI.OneModel.Tensors;
 
using var session = Session.Load("conditional.onnx");
using var condition = Tensor.Scalar(false);
using var x = Tensor.FromSpan<float>([3f], Shape.Create(1));
using var result = session.Run(new Dictionary<string, Tensor>
{ ["condition"] = condition, ["x"] = x });
Console.WriteLine(result["y"].Data<float>()[0]);
Text
9

The short answer

Load the ONNX file with Session.Load, create a Boolean scalar tensor for the condition, and supply the enclosing graph’s inputs by name. The session runs the selected body and returns its output. You do not rebuild the runtime or register an operator to use the published If implementation.

The example deliberately uses input 3: doubling produces 6, while squaring produces 9. Input 2 would produce 4 on both branches and would not make the choice visible. The download exercises both values of the condition in one session, rather than loading a separate model for each branch.

How do I run an ONNX If operator example in C#?

Use the named-tensor session API shown above. A mixed-input model needs separate tensors: condition is Boolean, while x is float32. A single flat float array cannot describe both input types. Keep the tensors alive through Run, and dispose the returned output collection after reading it.

The ONNX If specification defines a condition tensor containing a single Boolean element and two graph attributes, then_branch and else_branch. The output count of the two branches must match, and corresponding output types must agree. Their shapes need not be identical; the enclosing output shape must accommodate both possibilities. This example uses the same one-element float shape in both branches so the arithmetic is the only change.

Keep the ONNX input and output names distinct from C# variable names. Here result["y"] selects the enclosing graph’s output. It does not select yes or no, which are names inside the nested bodies. In another model, inspect the session’s Inputs and Outputs metadata rather than assuming it uses these example names.

How does an ONNX graph pass values into a conditional subgraph?

The branches in this example capture x from the enclosing graph. They do not declare it as a formal branch input, and the If node’s explicit input list contains only condition.

OneModel’s control-flow contract says it compiles every body into a nested session. Outer values the body reads become extra inputs in the compiled representation, allowing the runtime to track their lifetimes. You still pass x once, to the outer session, as the code shows.

Compilation and execution are separate decisions. Both bodies must compile when the outer session is created; only the chosen body runs for a given condition. An unsupported operator in the unchosen branch is therefore still a model-loading problem. Check the complete model, not just the branch your current input selects.

The runtime treats control-flow outputs as data-dependent and allocates results as bodies finish. If you move this pattern to caller-owned output tensors, provide storage compatible with the selected result and do not infer all possible branch shapes from a single run. Reuse a session for repeated decisions; change tensor contents between completed calls, not while another call is reading the same tensor.

All onemodel recipes