2

I have 2 ONNX model, the model1 is like: (conv1-pooling1), the model2 is like: (conv2-pooling2-fc2). How can I generate a new model3, which is (conv1-pooling1-fc2), weights of conv1-pooling1 are from model1 and weights of fc2 are from model2.

Philokey
  • 491
  • 2
  • 5
  • 14

1 Answers1

0

here is how I managed to do it. I hope it will help others, the documentation of ONNX is really poor.

onnx1 = "/workspace/OUTPUT/onnx/decoder_net.onnx"
onnx2 = "/workspace/OUTPUT/onnx/reste_net.onnx"
model_1 = onnx.load(onnx1)
model_2 = onnx.load(onnx2)
out_onnx = "/workspace/OUTPUT/onnx/decoder_reste_fusionnes.onnx"


output_names_model_1 = [output.name for output in model_1.graph.output]
for output_name in output_names_model_1: # on ne veut garder ici aucune sortie intermédiaire en sortie finale
    model_1.graph.output.remove(next(output for output in model_1.graph.output if output.name == output_name))
input_names_model_2 = [input_.name for input_ in model_2.graph.input]

for node in model_2.graph.node:
    for i,nom_input_noeud in enumerate(node.input):
        try:
            from_model_1 = input_names_model_2.index(nom_input_noeud)
            node.input[i] = output_names_model_1[from_model_1] # on espere qu'ils soient dans le mm ordre
        except ValueError: # is not in list
            node.input[i] += "_model2"
    for i,nom_output_noeud in enumerate(node.output):
        node.output[i] += "_model2" # unicite pour ne pas avoir de noms de variables en doublons avec l'autre modele
    node.name += "_model2"
    model_1.graph.node.extend([node])
for sortie in model_2.graph.output:
    sortie.name += "_model2"
model_1.graph.output.extend(model_2.graph.output)  
for poids in model_2.graph.initializer:
    poids.name += "_model2"
    model_1.graph.initializer.append(poids)
onnx.checker.check_model(model_1)
onnx.save(model_1, out_onnx)
Robin maltaros
  • 211
  • 3
  • 5