onnx_array_api.light_api#

Main API#

start#

onnx_array_api.light_api.start(opset: int | None = None, opsets: Dict[str, int] | None = None) OnnxGraph[source]#

Starts an onnx model.

Parameters:
  • opset – main opset version

  • opsets – others opsets as a dictionary

Returns:

an instance of onnx_array_api.light_api.OnnxGraph

A very simple model:

<<<

from onnx_array_api.light_api import start

onx = start().vin("X").Neg().rename("Y").vout().to_onnx()
print(onx)

>>>

    ir_version: 9
    opset_import {
      domain: ""
      version: 20
    }
    graph {
      node {
        input: "X"
        output: "Y"
        op_type: "Neg"
        domain: ""
      }
      name: "light_api"
      input {
        name: "X"
        type {
          tensor_type {
            elem_type: 1
            shape {
            }
          }
        }
      }
      output {
        name: "Y"
        type {
          tensor_type {
            elem_type: 1
            shape {
            }
          }
        }
      }
    }

Another with operator Add:

<<<

from onnx_array_api.light_api import start

onx = start().vin("X").vin("Y").bring("X", "Y").Add().rename("Z").vout().to_onnx()
print(onx)

>>>

    ir_version: 9
    opset_import {
      domain: ""
      version: 20
    }
    graph {
      node {
        input: "X"
        input: "Y"
        output: "Z"
        op_type: "Add"
        domain: ""
      }
      name: "light_api"
      input {
        name: "X"
        type {
          tensor_type {
            elem_type: 1
            shape {
            }
          }
        }
      }
      input {
        name: "Y"
        type {
          tensor_type {
            elem_type: 1
            shape {
            }
          }
        }
      }
      output {
        name: "Z"
        type {
          tensor_type {
            elem_type: 1
            shape {
            }
          }
        }
      }
    }

translate#

onnx_array_api.light_api.translate(proto: ModelProto, single_line: bool = False, api: str = 'light') str[source]#

Translates an ONNX proto into a code using Light API for ONNX: everything in one line to describe the ONNX graph.

Parameters:
  • proto – model to translate

  • single_line – as a single line or not

  • api – API to export into, default is “light” and this is handle by class onnx_array_api.light_api.emitter.Emitter, another value is “onnx” which is the inner API implemented in onnx package.

Returns:

code

<<<

from onnx_array_api.light_api import start, translate

onx = (
    start()
    .vin("X")
    .reshape((-1, 1))
    .Transpose(perm=[1, 0])
    .rename("Y")
    .vout()
    .to_onnx()
)
code = translate(onx)
print(code)

>>>

    (
        start(opset=20)
        .cst(np.array([-1, 1], dtype=np.int64))
        .rename('r')
        .vin('X', elem_type=TensorProto.FLOAT)
        .bring('X', 'r')
        .Reshape()
        .rename('r0_0')
        .bring('r0_0')
        .Transpose(perm=[1, 0])
        .rename('Y')
        .bring('Y')
        .vout(elem_type=TensorProto.FLOAT)
        .to_onnx()
    )

The inner API from onnx packahe is also available.

<<<

from onnx_array_api.light_api import start, translate

onx = (
    start()
    .vin("X")
    .reshape((-1, 1))
    .Transpose(perm=[1, 0])
    .rename("Y")
    .vout()
    .to_onnx()
)
code = translate(onx, api="onnx")
print(code)

>>>

    opset_imports = [
        make_opsetid('', 20),
    ]
    inputs = []
    outputs = []
    nodes = []
    initializers = []
    sparse_initializers = []
    functions = []
    initializers.append(
        from_array(
            np.array([-1, 1], dtype=np.int64),
            name='r'
        )
    )
    inputs.append(make_tensor_value_info('X', TensorProto.FLOAT, shape=[]))
    nodes.append(
        make_node(
            'Reshape',
            ['X', 'r'],
            ['r0_0']
        )
    )
    nodes.append(
        make_node(
            'Transpose',
            ['r0_0'],
            ['Y'],
            perm=[1, 0]
        )
    )
    outputs.append(make_tensor_value_info('Y', TensorProto.FLOAT, shape=[]))
    graph = make_graph(
        nodes,
        'light_api',
        inputs,
        outputs,
        initializers,
        sparse_initializer=sparse_initializers,
    )
    model = make_model(
        graph,
        functions=functions,
        opset_imports=opset_imports
    )

Classes for the Light API#

domain#

..autofunction:: onnx_array_api.light_api.domain

BaseVar#

class onnx_array_api.light_api.var.BaseVar(*args, **kwargs)[source]#

Represents an input, an initializer, a node, an output, multiple variables.

Parameters:

parent – the graph containing the Variable

bring(*vars: List[str | Var]) Var | Vars[source]#

Creates a set of variable as an instance of onnx_array_api.light_api.Vars.

cst(value: ndarray, name: str | None = None) Var[source]#

Adds an initializer

Parameters:
  • value – constant tensor

  • name – input name

Returns:

instance of onnx_array_api.light_api.Var

left_bring(*vars: List[str | Var]) Vars[source]#

Creates a set of variables as an instance of onnx_array_api.light_api.Vars. *vars is added to the left, self is added to the right.

make_node(op_type: str, *inputs: List[Var | TensorProto | ndarray], domain: str = '', n_outputs: int = 1, output_names: List[str] | None = None, **kwargs: Dict[str, Any]) Var | Vars[source]#

Creates a node with this Var as the first input.

Parameters:
  • op_type – operator type

  • inputs – others inputs

  • domain – domain

  • n_outputs – number of outputs

  • output_names – output names, if not specified, outputs are given unique names

  • kwargs – node attributes

Returns:

instance of onnx_array_api.light_api.Var or onnx_array_api.light_api.Vars

right_bring(*vars: List[str | Var]) Vars[source]#

Creates a set of variables as an instance of onnx_array_api.light_api.Vars. *vars is added to the right, self is added to the left.

to_onnx() FunctionProto | GraphProto | ModelProto[source]#

Creates the onnx graph.

v(name: str) Var[source]#

Retrieves another variable than this one.

Parameters:

name – name of the variable

Returns:

instance of onnx_array_api.light_api.Var

vin(name: str, elem_type: int | dtype = 1, shape: Tuple[int, ...] | None = None) Var[source]#

Declares a new input to the graph.

Parameters:
  • name – input name

  • elem_type – element_type

  • shape – shape

Returns:

instance of onnx_array_api.light_api.Var

vout(**kwargs: Dict[str, Any]) Var | Vars[source]#

This method needs to be overwritten for Var and Vars depending on the number of variable to declare as outputs.

OnnxGraph#

class onnx_array_api.light_api.OnnxGraph(opset: int | None = None, opsets: Dict[str, int] | None = None, proto_type: ProtoType = ProtoType.MODEL)[source]#

Contains every piece needed to create an onnx model in a single instructions. This API is meant to be light and allows the description of a graph.

Parameters:
cst(value: ndarray, name: str | None = None) Var[source]#

Adds an initializer

Parameters:
  • value – constant tensor

  • name – input name

Returns:

instance of onnx_array_api.light_api.Var

has_name(name: str) bool[source]#

Tells if a name is already used.

property input_names: List[str]#

Returns the input names

make_constant(value: ndarray, name: str | None = None) TensorProto[source]#

Adds an initializer to the graph.

make_input(name: str, elem_type: int | dtype = 1, shape: Tuple[int, ...] | None = None) ValueInfoProto[source]#

Adds an input to the graph.

Parameters:
  • name – input name

  • elem_type – element type (the input is assumed to be a tensor)

  • shape – shape

Returns:

an instance of ValueInfoProto

make_node(op_type: str, *inputs: List[Var | TensorProto | ndarray], domain: str = '', n_outputs: int = 1, output_names: List[str] | None = None, **kwargs: Dict[str, Any]) NodeProto[source]#

Creates a node.

Parameters:
  • op_type – operator type

  • inputs – others inputs

  • domain – domain

  • n_outputs – number of outputs

  • output_names – output names, if not specified, outputs are given unique names

  • kwargs – node attributes

Returns:

NodeProto

make_output(name: str, elem_type: int | dtype = 1, shape: Tuple[int, ...] | None = None) ValueInfoProto[source]#

Adds an output to the graph.

Parameters:
  • name – input name

  • elem_type – element type (the input is assumed to be a tensor)

  • shape – shape

Returns:

an instance of ValueInfoProto

property output_names: List[str]#

Returns the output names

rename(old_name: str, new_name: str)[source]#

Renames a variable. The renaming does not change anything but is stored in a container.

Parameters:
  • old_name – old name

  • new_name – new name

to_onnx() FunctionProto | GraphProto | ModelProto[source]#

Converts the graph into an ONNX graph.

true_name(name: str) str[source]#

Some names were renamed. If name is one of them, the function returns the new name.

unique_name(prefix='r', value: Any | None = None) str[source]#

Returns a unique name.

Parameters:
  • prefix – prefix

  • value – this name is mapped to this value

Returns:

unique name

vin(name: str, elem_type: int | dtype = 1, shape: Tuple[int, ...] | None = None) Var[source]#

Declares a new input to the graph.

Parameters:
  • name – input name

  • elem_type – element_type

  • shape – shape

Returns:

instance of onnx_array_api.light_api.Var

ProtoType#

class onnx_array_api.light_api.model.ProtoType(value)[source]#

The same code can be used to output a GraphProto, a FunctionProto or a ModelProto. This class specifies the output type at the beginning of the code.

SubDomain#

class onnx_array_api.light_api.var.SubDomain(var: BaseVar)[source]#

Declares a domain or a piece of it (if it contains ‘.’ in its name).

Var#

class onnx_array_api.light_api.Var(*args, **kwargs)[source]#

Represents an input, an initializer, a node, an output.

Parameters:
  • parent – graph the variable belongs to

  • name – input name

  • elem_type – element_type

  • shape – shape

astype(to: int | dtype) Var[source]#

Casts a tensor into another element type.

bring(*vars: List[str | Var]) Var | Vars#

Creates a set of variable as an instance of onnx_array_api.light_api.Vars.

cst(value: ndarray, name: str | None = None) Var#

Adds an initializer

Parameters:
  • value – constant tensor

  • name – input name

Returns:

instance of onnx_array_api.light_api.Var

left_bring(*vars: List[str | Var]) Vars#

Creates a set of variables as an instance of onnx_array_api.light_api.Vars. *vars is added to the left, self is added to the right.

make_node(op_type: str, *inputs: List[Var | TensorProto | ndarray], domain: str = '', n_outputs: int = 1, output_names: List[str] | None = None, **kwargs: Dict[str, Any]) Var | Vars#

Creates a node with this Var as the first input.

Parameters:
  • op_type – operator type

  • inputs – others inputs

  • domain – domain

  • n_outputs – number of outputs

  • output_names – output names, if not specified, outputs are given unique names

  • kwargs – node attributes

Returns:

instance of onnx_array_api.light_api.Var or onnx_array_api.light_api.Vars

property name#

Returns the name of the variable or the new name if it was renamed.

rename(new_name: str) Var[source]#

Renames a variable.

reshape(new_shape: Var | TensorProto | ndarray) Var[source]#

Reshapes a variable.

right_bring(*vars: List[str | Var]) Vars#

Creates a set of variables as an instance of onnx_array_api.light_api.Vars. *vars is added to the right, self is added to the left.

to(to: int | dtype) Var[source]#

Casts a tensor into another element type.

to_onnx() FunctionProto | GraphProto | ModelProto#

Creates the onnx graph.

v(name: str) Var#

Retrieves another variable than this one.

Parameters:

name – name of the variable

Returns:

instance of onnx_array_api.light_api.Var

vin(name: str, elem_type: int | dtype = 1, shape: Tuple[int, ...] | None = None) Var#

Declares a new input to the graph.

Parameters:
  • name – input name

  • elem_type – element_type

  • shape – shape

Returns:

instance of onnx_array_api.light_api.Var

vout(elem_type: int | dtype = 1, shape: Tuple[int, ...] | None = None) Var[source]#

Declares a new output to the graph.

Parameters:
  • elem_type – element_type

  • shape – shape

Returns:

instance of onnx_array_api.light_api.Var

Vars#

class onnx_array_api.light_api.Vars(*args, **kwargs)[source]#

Represents multiple Var.

Parameters:
  • parent – graph the variable belongs to

  • vars – list of names or variables

bring(*vars: List[str | Var]) Var | Vars#

Creates a set of variable as an instance of onnx_array_api.light_api.Vars.

cst(value: ndarray, name: str | None = None) Var#

Adds an initializer

Parameters:
  • value – constant tensor

  • name – input name

Returns:

instance of onnx_array_api.light_api.Var

left_bring(*vars: List[str | Var]) Vars#

Creates a set of variables as an instance of onnx_array_api.light_api.Vars. *vars is added to the left, self is added to the right.

make_node(op_type: str, *inputs: List[Var | TensorProto | ndarray], domain: str = '', n_outputs: int = 1, output_names: List[str] | None = None, **kwargs: Dict[str, Any]) Var | Vars#

Creates a node with this Var as the first input.

Parameters:
  • op_type – operator type

  • inputs – others inputs

  • domain – domain

  • n_outputs – number of outputs

  • output_names – output names, if not specified, outputs are given unique names

  • kwargs – node attributes

Returns:

instance of onnx_array_api.light_api.Var or onnx_array_api.light_api.Vars

rename(*new_names: List[str]) Vars[source]#

Renames variables.

right_bring(*vars: List[str | Var]) Vars#

Creates a set of variables as an instance of onnx_array_api.light_api.Vars. *vars is added to the right, self is added to the left.

to_onnx() FunctionProto | GraphProto | ModelProto#

Creates the onnx graph.

v(name: str) Var#

Retrieves another variable than this one.

Parameters:

name – name of the variable

Returns:

instance of onnx_array_api.light_api.Var

vin(name: str, elem_type: int | dtype = 1, shape: Tuple[int, ...] | None = None) Var#

Declares a new input to the graph.

Parameters:
  • name – input name

  • elem_type – element_type

  • shape – shape

Returns:

instance of onnx_array_api.light_api.Var

vout(*elem_type_shape: List[int | dtype | Tuple[int | dtype, Tuple[int, ...] | None]]) Vars[source]#

Declares a new output to the graph.

Parameters:

elem_type_shape – list of tuple(element_type, shape)

Returns:

instance of onnx_array_api.light_api.Vars

Classes for the Translater#

BaseEmitter#

class onnx_array_api.light_api.emitter.BaseEmitter[source]#
render_attribute_value(value: Any) Tuple[List[str], str][source]#

Renders an attribute value into a string.

Parameters:

value – value to converter

Returns:

rows to append before, actual value

Emitter#

class onnx_array_api.light_api.emitter.Emitter[source]#

Converts event into proper code.

join(rows: List[str], single_line: bool = False) str[source]#

Join the rows

EventType#

class onnx_array_api.light_api.translate.EventType(value)[source]#

An enumeration.

InnerEmitter#

class onnx_array_api.light_api.inner_emitter.InnerEmitter[source]#

Converts event into proper code.

join(rows: List[str], single_line: bool = False) str[source]#

Returns the separators. single_line is unused.

render_attribute_value(value: Any) Tuple[List[str], str][source]#

Renders an attribute value into a string.

Parameters:

value – value to converter

Returns:

rows to append before, actual value

Translater#

class onnx_array_api.light_api.translate.Translater(proto: ModelProto | FunctionProto | GraphProto, emitter: Emitter | None = None)[source]#

Translates an ONNX graph into a code following the light API.

export(as_str, single_line: bool = False) str | List[str][source]#

Exports into a code.

Parameters:
  • as_str – as a single string or by rows

  • single_line – tries to compress the output into a single line

Returns:

list of instructions

extract_attributes(node: NodeProto) Dict[str, Tuple[AttributeProto, Any]][source]#

Extracts all atributes of a node.

Parameters:

node – node proto

Returns:

dictionary

Available operators#

One input#

class onnx_array_api.light_api._op_var.OpsVar[source]#

Operators taking only one input.

Two inputs or more#

class onnx_array_api.light_api._op_vars.OpsVars[source]#

Operators taking multiple inputs.