Open nihui opened 1 year ago
Hi, I had a similar issue to yours, and I solved it.
Traceback (most recent call last):
File "d:\onnx2torch\convert.py", line 6, in <module>
torch_model = convert(model)
File "c:\Python\Python39\pyenv\lib\site-packages\onnx2torch\converter.py", line 110, in convert
torch_module, onnx_mapping = converter(onnx_node, onnx_graph)
File "c:\Python\Python39\pyenv\lib\site-packages\onnx2torch\node_converters\conv.py", line 29, in _
weights = graph.initializers[weights_value_name]
KeyError: 'conv2d_0.w_0'
I found that if a node is trainable, its category must be 'Initializer' rather than 'Constant' in ONNX. Therefore, I changed the trainable node, which was in the 'Constant' category, to 'Initializer,' and the issue was resolved.
Could you check you node's category if Constant or not? You can use netron check the node
If you need to change the category of a node, you can follow these steps:
onnx.helper.make_tensor
to creat a tensorgraph.initializer.extend
to extend the tensorgraph.node.remove
to original nodeonnx.checker.check_model
check your onnx modela demo for you:
import onnx
import numpy as np
from onnx import helper
model_path = "Orinigal.onnx"
NewModel_path = "New.onnx"
onnx_model = onnx.load(model_path)
graph = onnx_model.graph
for node in graph.node:
if node.name == "TargetNode":
for attr in node.attribute:
initializer_node = helper.make_tensor(
name=attr.t.name,
data_type = attr.t.data_type,
dims = attr.t.dims,
vals= np.frombuffer(attr.t.raw_data, np.float32)
)
graph.initializer.extend([initializer_node])
graph.node.remove(node)
onnx.checker.check_model(onnx_model)
onnx.save(onnx_model, NewModel_path)
PS: it's just demo, so you may change code and test. If there is any question, please let me know.
python 3.11 torch-2.0.0+cpu