Skip to content
Snippets Groups Projects
Commit 0876f7a3 authored by auphelia's avatar auphelia
Browse files

[Notebooks] Update basics/0_how_to_work_with_onnx notebook

parent e53b529d
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# FINN - How to work with ONNX # FINN - How to work with ONNX
This notebook should give an overview of ONNX ProtoBuf, help to create and manipulate an ONNX model and use FINN functions to work with it. This notebook should give an overview of ONNX ProtoBuf, help to create and manipulate an ONNX model and use FINN functions to work with it.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Outline ## Outline
* #### How to create a simple ONNX model * #### How to create a simple ONNX model
* #### How to manipulate an ONNX model * #### How to manipulate an ONNX model
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### How to create a simple ONNX model ### How to create a simple ONNX model
To explain how to create an ONNX model a simple example with mathematical operations is used. All nodes are from the [standard operations library of ONNX](https://github.com/onnx/onnx/blob/master/docs/Operators.md). To explain how to create an ONNX model a simple example with mathematical operations is used. All nodes are from the [standard operations library of ONNX](https://github.com/onnx/onnx/blob/master/docs/Operators.md).
First ONNX is imported, then the helper function can be used to make a node. First ONNX is imported, then the helper function can be used to make a node.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import onnx import onnx
Add1_node = onnx.helper.make_node( Add1_node = onnx.helper.make_node(
'Add', 'Add',
inputs=['in1', 'in2'], inputs=['in1', 'in2'],
outputs=['sum1'], outputs=['sum1'],
name='Add1' name='Add1'
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The first attribute of the node is the operation type. In this case it is `'Add'`, so it is an adder node. Then the input names are passed to the node and at the end a name is assigned to the output. The first attribute of the node is the operation type. In this case it is `'Add'`, so it is an adder node. Then the input names are passed to the node and at the end a name is assigned to the output.
For this example we want two other adder nodes, one abs node and the output shall be rounded so one round node is needed. For this example we want two other adder nodes, one abs node and the output shall be rounded so one round node is needed.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
Add2_node = onnx.helper.make_node( Add2_node = onnx.helper.make_node(
'Add', 'Add',
inputs=['sum1', 'in3'], inputs=['sum1', 'in3'],
outputs=['sum2'], outputs=['sum2'],
name='Add2', name='Add2',
) )
Add3_node = onnx.helper.make_node( Add3_node = onnx.helper.make_node(
'Add', 'Add',
inputs=['abs1', 'abs1'], inputs=['abs1', 'abs1'],
outputs=['sum3'], outputs=['sum3'],
name='Add3', name='Add3',
) )
Abs_node = onnx.helper.make_node( Abs_node = onnx.helper.make_node(
'Abs', 'Abs',
inputs=['sum2'], inputs=['sum2'],
outputs=['abs1'], outputs=['abs1'],
name='Abs' name='Abs'
) )
Round_node = onnx.helper.make_node( Round_node = onnx.helper.make_node(
'Round', 'Round',
inputs=['sum3'], inputs=['sum3'],
outputs=['out1'], outputs=['out1'],
name='Round', name='Round',
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The names of the inputs and outputs of the nodes give already an idea of the structure of the resulting graph. In order to integrate the nodes into a graph environment, the inputs and outputs of the graph have to be specified first. In ONNX all data edges are processed as tensors. So with onnx helper function tensors value infos are created for the input and output tensors of the graph. Float from ONNX is used as data type. The names of the inputs and outputs of the nodes give already an idea of the structure of the resulting graph. In order to integrate the nodes into a graph environment, the inputs and outputs of the graph have to be specified first. In ONNX all data edges are processed as tensors. So with onnx helper function tensors value infos are created for the input and output tensors of the graph. Float from ONNX is used as data type.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
in1 = onnx.helper.make_tensor_value_info("in1", onnx.TensorProto.FLOAT, [4, 4]) in1 = onnx.helper.make_tensor_value_info("in1", onnx.TensorProto.FLOAT, [4, 4])
in2 = onnx.helper.make_tensor_value_info("in2", onnx.TensorProto.FLOAT, [4, 4]) in2 = onnx.helper.make_tensor_value_info("in2", onnx.TensorProto.FLOAT, [4, 4])
in3 = onnx.helper.make_tensor_value_info("in3", onnx.TensorProto.FLOAT, [4, 4]) in3 = onnx.helper.make_tensor_value_info("in3", onnx.TensorProto.FLOAT, [4, 4])
out1 = onnx.helper.make_tensor_value_info("out1", onnx.TensorProto.FLOAT, [4, 4]) out1 = onnx.helper.make_tensor_value_info("out1", onnx.TensorProto.FLOAT, [4, 4])
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now the graph can be built. First all nodes are passed. Here it is to be noted that it requires a certain sequence. The nodes must be instantiated in their dependencies to each other. This means Add2 must not be listed before Add1, because Add2 depends on the result of Add1. A name is then assigned to the graph. This is followed by the inputs and outputs. Now the graph can be built. First all nodes are passed. Here it is to be noted that it requires a certain sequence. The nodes must be instantiated in their dependencies to each other. This means Add2 must not be listed before Add1, because Add2 depends on the result of Add1. A name is then assigned to the graph. This is followed by the inputs and outputs.
`value_info` of the graph contains the remaining tensors within the graph. When creating the nodes we have already defined names for the inner data edges and now these are assigned tensors of the datatype float and a certain shape. `value_info` of the graph contains the remaining tensors within the graph. When creating the nodes we have already defined names for the inner data edges and now these are assigned tensors of the datatype float and a certain shape.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
graph = onnx.helper.make_graph( graph = onnx.helper.make_graph(
nodes=[ nodes=[
Add1_node, Add1_node,
Add2_node, Add2_node,
Abs_node, Abs_node,
Add3_node, Add3_node,
Round_node, Round_node,
], ],
name="simple_graph", name="simple_graph",
inputs=[in1, in2, in3], inputs=[in1, in2, in3],
outputs=[out1], outputs=[out1],
value_info=[ value_info=[
onnx.helper.make_tensor_value_info("sum1", onnx.TensorProto.FLOAT, [4, 4]), onnx.helper.make_tensor_value_info("sum1", onnx.TensorProto.FLOAT, [4, 4]),
onnx.helper.make_tensor_value_info("sum2", onnx.TensorProto.FLOAT, [4, 4]), onnx.helper.make_tensor_value_info("sum2", onnx.TensorProto.FLOAT, [4, 4]),
onnx.helper.make_tensor_value_info("abs1", onnx.TensorProto.FLOAT, [4, 4]), onnx.helper.make_tensor_value_info("abs1", onnx.TensorProto.FLOAT, [4, 4]),
onnx.helper.make_tensor_value_info("sum3", onnx.TensorProto.FLOAT, [4, 4]), onnx.helper.make_tensor_value_info("sum3", onnx.TensorProto.FLOAT, [4, 4]),
], ],
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
**Important**: In our example, the shape of the tensors does not change during the calculation. This is not always the case. So you have to make sure that you specify the shape correctly. **Important**: In our example, the shape of the tensors does not change during the calculation. This is not always the case. So you have to make sure that you specify the shape correctly.
Now a model can be created from the graph and saved using the `.save` function. The model is saved in .onnx format and can be reloaded with `onnx.load()`. This also means that you can easily share your own model in .onnx format with others. Now a model can be created from the graph and saved using the `.save` function. The model is saved in .onnx format and can be reloaded with `onnx.load()`. This also means that you can easily share your own model in .onnx format with others.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
onnx_model = onnx.helper.make_model(graph, producer_name="simple-model") onnx_model = onnx.helper.make_model(graph, producer_name="simple-model")
onnx.save(onnx_model, '/tmp/simple_model.onnx') onnx.save(onnx_model, '/tmp/simple_model.onnx')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
To visualize the created model, [netron](https://github.com/lutzroeder/netron) can be used. Netron is a visualizer for neural network, deep learning and machine learning models. FINN provides a utility function for visualization with netron, which we import and use in the following. To visualize the created model, [netron](https://github.com/lutzroeder/netron) can be used. Netron is a visualizer for neural network, deep learning and machine learning models. FINN provides a utility function for visualization with netron, which we import and use in the following.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from finn.util.visualization import showInNetron from finn.util.visualization import showInNetron
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
showInNetron('/tmp/simple_model.onnx') showInNetron('/tmp/simple_model.onnx')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Netron also allows you to interactively explore the model. If you click on a node, the node attributes will be displayed. Netron also allows you to interactively explore the model. If you click on a node, the node attributes will be displayed.
In order to test the resulting model, a function is first written in Python that calculates the expected output. Because numpy arrays are to be used, numpy is imported first. In order to test the resulting model, a function is first written in Python that calculates the expected output. Because numpy arrays are to be used, numpy is imported first.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import numpy as np import numpy as np
def expected_output(in1, in2, in3): def expected_output(in1, in2, in3):
sum1 = np.add(in1, in2) sum1 = np.add(in1, in2)
sum2 = np.add(sum1, in3) sum2 = np.add(sum1, in3)
abs1 = np.absolute(sum2) abs1 = np.absolute(sum2)
sum3 = np.add(abs1, abs1) sum3 = np.add(abs1, abs1)
return np.round(sum3) return np.round(sum3)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Then the values for the three inputs are calculated. Random numbers are used. Then the values for the three inputs are calculated. Random numbers are used.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
in1_values =np.asarray(np.random.uniform(low=-5, high=5, size=(4,4)), dtype=np.float32) in1_values =np.asarray(np.random.uniform(low=-5, high=5, size=(4,4)), dtype=np.float32)
in2_values = np.asarray(np.random.uniform(low=-5, high=5, size=(4,4)), dtype=np.float32) in2_values = np.asarray(np.random.uniform(low=-5, high=5, size=(4,4)), dtype=np.float32)
in3_values = np.asarray(np.random.uniform(low=-5, high=5, size=(4,4)), dtype=np.float32) in3_values = np.asarray(np.random.uniform(low=-5, high=5, size=(4,4)), dtype=np.float32)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
We can easily pass the values to the function we just wrote to calculate the expected result. For the created model the inputs must be summarized in a dictionary, which is then passed on to the model. We can easily pass the values to the function we just wrote to calculate the expected result. For the created model the inputs must be summarized in a dictionary, which is then passed on to the model.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
input_dict = {} input_dict = {}
input_dict["in1"] = in1_values input_dict["in1"] = in1_values
input_dict["in2"] = in2_values input_dict["in2"] = in2_values
input_dict["in3"] = in3_values input_dict["in3"] = in3_values
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
To run the model and calculate the output, [onnxruntime](https://github.com/microsoft/onnxruntime) can be used. ONNX Runtime is a performance-focused complete scoring engine for ONNX models from Microsoft. The `.InferenceSession` function is used to create a session of the model and `.run` is used to execute the model. To run the model and calculate the output, [onnxruntime](https://github.com/microsoft/onnxruntime) can be used. ONNX Runtime is a performance-focused complete scoring engine for ONNX models from Microsoft. The `.InferenceSession` function is used to create a session of the model and `.run` is used to execute the model.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import onnxruntime as rt import onnxruntime as rt
sess = rt.InferenceSession(onnx_model.SerializeToString()) sess = rt.InferenceSession(onnx_model.SerializeToString())
output = sess.run(None, input_dict) output = sess.run(None, input_dict)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The input values are also transferred to the reference function. Now the output of the execution of the model can be compared with that of the reference. The input values are also transferred to the reference function. Now the output of the execution of the model can be compared with that of the reference.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
ref_output= expected_output(in1_values, in2_values, in3_values) ref_output= expected_output(in1_values, in2_values, in3_values)
print("The output of the ONNX model is: \n{}".format(output[0])) print("The output of the ONNX model is: \n{}".format(output[0]))
print("\nThe output of the reference function is: \n{}".format(ref_output)) print("\nThe output of the reference function is: \n{}".format(ref_output))
if (output[0] == ref_output).all(): if (output[0] == ref_output).all():
print("\nThe results are the same!") print("\nThe results are the same!")
else: else:
raise Exception("Something went wrong, the output of the model doesn't match the expected output!") raise Exception("Something went wrong, the output of the model doesn't match the expected output!")
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now that we have verified that the model works as we expected it to, we can continue working with the graph. Now that we have verified that the model works as we expected it to, we can continue working with the graph.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### How to manipulate an ONNX model ### How to manipulate an ONNX model
In the model there are two successive adder nodes. An adder node in ONNX can only add two inputs, but there is also the [**sum**](https://github.com/onnx/onnx/blob/master/docs/Operators.md#Sum) node, which can process more than two inputs. So it would be a reasonable change of the graph to combine the two successive adder nodes to one sum node. In the model there are two successive adder nodes. An adder node in ONNX can only add two inputs, but there is also the [**sum**](https://github.com/onnx/onnx/blob/master/docs/Operators.md#Sum) node, which can process more than two inputs. So it would be a reasonable change of the graph to combine the two successive adder nodes to one sum node.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
In the following we assume that we do not know the appearance of the model, so we first try to identify whether there are two consecutive adders in the graph and then convert them into a sum node. In the following we assume that we do not know the appearance of the model, so we first try to identify whether there are two consecutive adders in the graph and then convert them into a sum node.
Here we make use of FINN. FINN provides a thin wrapper around the model which provides several additional helper functions to manipulate the graph. The code can be found [here](https://github.com/Xilinx/finn/blob/master/src/finn/core/modelwrapper.py). Here we make use of FINN. FINN provides a thin wrapper around the model which provides several additional helper functions to manipulate the graph. The so called `ModelWrapper` can be found in the QONNX repository which contains a lot of functionality that is used by FINN, you can find it [here](https://github.com/fastmachinelearning/qonnx/blob/main/src/qonnx/core/modelwrapper.py).
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from qonnx.core.modelwrapper import ModelWrapper from qonnx.core.modelwrapper import ModelWrapper
finn_model = ModelWrapper(onnx_model) finn_model = ModelWrapper(onnx_model)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
As explained in the previous section, it is important that the nodes are listed in the correct order. If a new node has to be inserted or an old node has to be replaced, it is important to do that in the appropriate position. The following function serves this purpose. It returns a dictionary, which contains the node name as key and the respective node index as value. As explained in the previous section, it is important that the nodes are listed in the correct order. If a new node has to be inserted or an old node has to be replaced, it is important to do that in the appropriate position. The following function serves this purpose. It returns a dictionary, which contains the node name as key and the respective node index as value.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def get_node_id(model): def get_node_id(model):
node_index = {} node_index = {}
node_ind = 0 node_ind = 0
for node in model.graph.node: for node in model.graph.node:
node_index[node.name] = node_ind node_index[node.name] = node_ind
node_ind += 1 node_ind += 1
return node_index return node_index
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The function scans the list of nodes and stores a run index (`node_ind`) as node index in the dictionary for every node name. The function scans the list of nodes and stores a run index (`node_ind`) as node index in the dictionary for every node name.
Another helper function is being implemented that searches for adder nodes in the graph and returns the found nodes. This is needed to determine if and which adder nodes are in the given model. Another helper function is being implemented that searches for adder nodes in the graph and returns the found nodes. This is needed to determine if and which adder nodes are in the given model.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def identify_adder_nodes(model): def identify_adder_nodes(model):
add_nodes = [] add_nodes = []
for node in model.graph.node: for node in model.graph.node:
if node.op_type == "Add": if node.op_type == "Add":
add_nodes.append(node) add_nodes.append(node)
return add_nodes return add_nodes
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The function iterates over all nodes of the model and if the operation type is `"Add"` the node will be stored in `add_nodes`. At the end `add_nodes` is returned. The function iterates over all nodes of the model and if the operation type is `"Add"` the node will be stored in `add_nodes`. At the end `add_nodes` is returned.
If we apply this to our model, three nodes should be returned. If we apply this to our model, three nodes should be returned.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
add_nodes = identify_adder_nodes(finn_model) add_nodes = identify_adder_nodes(finn_model)
for node in add_nodes: for node in add_nodes:
print("Found adder node: {}".format(node.name)) print("Found adder node: {}".format(node.name))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Among other helper functions, `ModelWrapper` offers two functions that can help to determine the preceding and succeeding node of a node. However, these functions are not getting a node as input, but can determine the consumer or producer of a tensor. We write two functions that uses these helper functions to determine the previous and the next node of a node. Among other helper functions, `ModelWrapper` offers two functions that can help to determine the preceding and succeeding node of a node: `find_direct_successors` and `find_direct_predecessors`. So we can use one of them to define a function to find adder pairs.
%% Cell type:code id: tags:
``` python
def find_predecessor(model, node):
predecessors = []
for i in range(len(node.input)):
producer = model.find_producer(node.input[i])
predecessors.append(producer)
return predecessors
def find_successor(model, node):
successors = []
for i in range(len(node.output)):
consumer = model.find_consumer(node.output[i])
successors.append(consumer)
return successors
```
%% Cell type:markdown id: tags:
The first function uses `find_producer` from `ModelWrapper` to create a list of the producers of the inputs of the given node. So the returned list is indirectly filled with the predecessors of the node. The second function works in a similar way, `find_consumer` from `ModelWrapper` is used to find the consumers of the output tensors of the node and so a list with the successors can be created.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def adder_pair(model, node): def adder_pair(model, node):
adder_pairs = [] adder_pairs = []
node_pair = [] node_pair = []
successor_list = find_successor(model, node) successor_list = model.find_direct_successors(node)
for successor in successor_list: for successor in successor_list:
if successor.op_type == "Add": if successor.op_type == "Add":
node_pair.append(node) node_pair.append(node)
node_pair.append(successor) node_pair.append(successor)
adder_pairs.append((node_pair)) adder_pairs.append((node_pair))
node_pair = [] node_pair = []
return adder_pairs return adder_pairs
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The function gets a node and the model as input. Two empty lists are created to be filled with a list of adder node pairs that can be returned as result of the function. Then the function `find_successor` is used to return all of the successors of the node. If one of the successors is an adder node, the node is saved in `node_pair` together with the successive adder node and put in the list `adder_pairs`. Then the temporary list is cleaned and can be filled with the next adder node pair. Since it is theoretically possible for an adder node to have more than one subsequent adder node, a list of lists is created. This list of the node with all its successive adder nodes is returned. The function gets a node and the model as input. Two empty lists are created to be filled with a list of adder node pairs that can be returned as result of the function. Then the function `find_direct_successors` is used to return all of the successors of the node. If one of the successors is an adder node, the node is saved in `node_pair` together with the successive adder node and put in the list `adder_pairs`. Then the temporary list is cleaned and can be filled with the next adder node pair. Since it is theoretically possible for an adder node to have more than one subsequent adder node, a list of lists is created. This list of the node with all its successive adder nodes is returned.
So now we can find out which adder node has an adder node as successor. Since the model is known, one adder pair (Add1+Add2) should be found when applying the function to the previously determined adder node list (`add_nodes`). So now we can find out which adder node has an adder node as successor. Since the model is known, one adder pair (Add1+Add2) should be found when applying the function to the previously determined adder node list (`add_nodes`).
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
for node in add_nodes: for node in add_nodes:
add_pairs = adder_pair(finn_model, node) add_pairs = adder_pair(finn_model, node)
if len(add_pairs) != 0: if len(add_pairs) != 0:
for i in range(len(add_pairs)): for i in range(len(add_pairs)):
substitute_pair = add_pairs[i] substitute_pair = add_pairs[i]
print("Found following pair that could be replaced by a sum node:") print("Found following pair that could be replaced by a sum node:")
for node_pair in add_pairs: for node_pair in add_pairs:
for node in node_pair: for node in node_pair:
print(node.name) print(node.name)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now that the pair to be replaced has been identified (`substitute_pair`), a sum node can be instantiated and inserted into the graph at the correct position. Now that the pair to be replaced has been identified (`substitute_pair`), a sum node can be instantiated and inserted into the graph at the correct position.
First of all, the inputs must be determined. For this the adder nodes inputs are used minus the input, which corresponds to the output of the other adder node. First of all, the inputs must be determined. For this the adder nodes inputs are used minus the input, which corresponds to the output of the other adder node.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
input_list = [] input_list = []
for i in range(len(substitute_pair)): for i in range(len(substitute_pair)):
if i == 0: if i == 0:
for j in range(len(substitute_pair[i].input)): for j in range(len(substitute_pair[i].input)):
if substitute_pair[i].input[j] != substitute_pair[i+1].output[0]: if substitute_pair[i].input[j] != substitute_pair[i+1].output[0]:
input_list.append(substitute_pair[i].input[j]) input_list.append(substitute_pair[i].input[j])
else: else:
for j in range(len(substitute_pair[i].input)): for j in range(len(substitute_pair[i].input)):
if substitute_pair[i].input[j] != substitute_pair[i-1].output[0]: if substitute_pair[i].input[j] != substitute_pair[i-1].output[0]:
input_list.append(substitute_pair[i].input[j]) input_list.append(substitute_pair[i].input[j])
print("The new node gets the following inputs: \n{}".format(input_list)) print("The new node gets the following inputs: \n{}".format(input_list))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The output of the sum node matches the output of the second adder node and can therefore be taken over directly. The output of the sum node matches the output of the second adder node and can therefore be taken over directly.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
sum_output = substitute_pair[1].output[0] sum_output = substitute_pair[1].output[0]
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The summary node can be created with this information. The sum node can be created with this information.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
Sum_node = onnx.helper.make_node( Sum_node = onnx.helper.make_node(
'Sum', 'Sum',
inputs=input_list, inputs=input_list,
outputs=[sum_output], outputs=[sum_output],
name="Sum" name="Sum"
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The node can now be inserted into the graph and the old nodes are removed. The node can now be inserted into the graph and the old nodes are removed.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
node_ids = get_node_id(finn_model) node_ids = get_node_id(finn_model)
node_ind = node_ids[substitute_pair[0].name] node_ind = node_ids[substitute_pair[0].name]
graph.node.insert(node_ind, Sum_node) graph.node.insert(node_ind, Sum_node)
for node in substitute_pair: for node in substitute_pair:
graph.node.remove(node) graph.node.remove(node)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
To insert the node in the right place, the index of the first node of the substitute_pair is used as node index for the sum node and embedded into the graph using `.insert`. Then the two elements in `substitute_pair` are deleted using `.remove`. `.insert` and `.remove` are functions provided by ONNX. To insert the node in the right place, the index of the first node of the substitute_pair is used as node index for the sum node and embedded into the graph using `.insert`. Then the two elements in `substitute_pair` are deleted using `.remove`. `.insert` and `.remove` are functions provided by ONNX.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
The new graph is saved as ONNX model and can be visualized with Netron. The new graph is saved as ONNX model and can be visualized with Netron.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
onnx_model1 = onnx.helper.make_model(graph, producer_name="simple-model1") onnx_model1 = onnx.helper.make_model(graph, producer_name="simple-model1")
onnx.save(onnx_model1, '/tmp/simple_model1.onnx') onnx.save(onnx_model1, '/tmp/simple_model1.onnx')
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
showInNetron('/tmp/simple_model1.onnx') showInNetron('/tmp/simple_model1.onnx')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Through the visualization it can already be seen that the insertion was successful, but it is still to be checked whether the result remains the same. Therefore the result of the reference function written in the previous section is used and the new model with the input values is simulated. At this point onnxruntime can be used again. The simulation is analogous to the one of the first model in the previous section. Through the visualization it can already be seen that the insertion was successful, but it is still to be checked whether the result remains the same. Therefore the result of the reference function written in the previous section is used and the new model with the input values is simulated. At this point onnxruntime can be used again. The simulation is analogous to the one of the first model in the previous section.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
sess = rt.InferenceSession(onnx_model1.SerializeToString()) sess = rt.InferenceSession(onnx_model1.SerializeToString())
output = sess.run(None, input_dict) output = sess.run(None, input_dict)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print("The output of the manipulated ONNX model is: \n{}".format(output[0])) print("The output of the manipulated ONNX model is: \n{}".format(output[0]))
print("\nThe output of the reference function is: \n{}".format(ref_output)) print("\nThe output of the reference function is: \n{}".format(ref_output))
if (output[0] == ref_output).all(): if (output[0] == ref_output).all():
print("\nThe results are the same!") print("\nThe results are the same!")
else: else:
raise Exception("Something went wrong, the output of the model doesn't match the expected output!") raise Exception("Something went wrong, the output of the model doesn't match the expected output!")
``` ```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment