Using torch.onnx.export came across "collections. OrderedDict' object is not callable”

Hello, I have some problems, can anyone help me?

I am using my trained Resnet34 network, and my attempt to convert the trained network to ONNX model fails, and the error is as follows.

Traceback (most recent call last):
  File "/home/private/hrrp/NanHu/resnetV2/model.py", line 216, in <module>
    torch.onnx.export(model,
  File "/home/private/anaconda3/envs/resnet34/lib/python3.8/site-packages/torch/onnx/utils.py", line 504, in export
    _export(
  File "/home/private/anaconda3/envs/resnet34/lib/python3.8/site-packages/torch/onnx/utils.py", line 1506, in _export
    with exporter_context(model, training, verbose):
  File "/home/private/anaconda3/envs/resnet34/lib/python3.8/contextlib.py", line 113, in __enter__
    return next(self.gen)
  File "/home/private/anaconda3/envs/resnet34/lib/python3.8/site-packages/torch/onnx/utils.py", line 176, in exporter_context
    with select_model_mode_for_export(
  File "/home/private/anaconda3/envs/resnet34/lib/python3.8/contextlib.py", line 113, in __enter__
    return next(self.gen)
  File "/home/private/anaconda3/envs/resnet34/lib/python3.8/site-packages/torch/onnx/utils.py", line 137, in disable_apex_o2_state_dict_hook
    for module in model.modules():
TypeError: 'collections.OrderedDict' object is not callable

Then I tried the official sample code and the same error.

import torch
import torchvision


dummy_input = torch.randn(10, 3, 224, 224, device="cuda")
model = torchvision.models.alexnet(pretrained=True).cuda()

input_names = [ "actual_input_1" ] + [ "learned_%d" % i for i in range(16) ]
output_names = [ "output1" ]

torch.onnx.export(model, dummy_input, "alexnet.onnx", verbose=True, input_names=input_names, output_names=output_names)

My Pytorch is 1.13.1。

I cannot reproduce the issue using torch==2.0.0+cu118 and onnx==1.13.1 and get:

dummy_input = torch.randn(10, 3, 224, 224, device="cuda")
model = torchvision.models.alexnet(pretrained=True).cuda()

input_names = [ "actual_input_1" ] + [ "learned_%d" % i for i in range(16) ]
output_names = [ "output1" ]

torch.onnx.export(model, dummy_input, "alexnet.onnx", verbose=True, input_names=input_names, output_names=output_names)

import onnx

model = onnx.load("alexnet.onnx")
onnx.checker.check_model(model)
# Print a human readable representation of the graph
print(onnx.helper.printable_graph(model.graph))
# graph torch_jit (
#   %actual_input_1[FLOAT, 10x3x224x224]
# ) initializers (
#   %learned_0[FLOAT, 64x3x11x11]
#   %learned_1[FLOAT, 64]
#   %learned_2[FLOAT, 192x64x5x5]
# ...
1 Like

Thank you, I found out that my pytorch was not installed completely for some reason, and it can be used after I reinstall it.