Tianxiaomo / pytorch-YOLOv4

PyTorch ,ONNX and TensorRT implementation of YOLOv4
Apache License 2.0
4.46k stars 1.49k forks source link

Error in function "transform_to_onnx(cfgfile, weightfile, batch_size=1)" #490

Open GrabitThais opened 2 years ago

GrabitThais commented 2 years ago

def transform_to_onnx(cfgfile, weightfile, batch_size=1): model = Darknet(cfgfile)

model.print_network()
model.load_weights(weightfile)
print('Loading weights from %s... Done!' % (weightfile))

dynamic = False
if batch_size <= 0:
    dynamic = True
print(".....70")
input_names = ["input"]
print(".....80")
output_names = ['boxes', 'confs']
print(".....90")
if dynamic:
    x = torch.randn((1, 3, model.height, model.width), requires_grad=True)
    print(".....91")
    onnx_file_name = "yolov4_-1_3_{}_{}_dynamic.onnx".format(model.height, model.width)
    dynamic_axes = {"input": {0: "batch_size"}, "boxes": {0: "batch_size"}, "confs": {0: "batch_size"}}
    print(".....92")
    # Export the model
    print('Export the onnx model ...')
    torch.onnx.export(model,
                      x,
                      onnx_file_name,
                      export_params=True,
                      opset_version=11,
                      do_constant_folding=True,
                      input_names=input_names, output_names=output_names,
                      dynamic_axes=dynamic_axes)

    print('Onnx model exporting done')
    return onnx_file_name

else:
    x = torch.randn((batch_size, 3, model.height, model.width), requires_grad=True)
    print(".....93")
    onnx_file_name = "yolov4_{}_3_{}_{}_static.onnx".format(batch_size, model.height, model.width)
    print("onnx_file_nam",onnx_file_name)
    print("height",model.height)
    print("width",model.width)

    print(".....94")
    torch.onnx.export(model,
                      x,
                      onnx_file_name,
                      export_params=True,
                      opset_version=11,
                      do_constant_folding=True,
                      input_names=input_names, output_names=output_names,
                      dynamic_axes=None)
    print(".....95")

    print('Onnx model exporting done')
    return onnx_file_name

I have this error: .....94 /pytorch-YOLOv4/tool/yolo_layer.py:227: TracerWarning: torch.tensor results are registered as constants in the trace. You can safely ignore this warning if you use this function to create tensors out of constant variables that would be the same every time you call this function. In any other case, this might cause the trace to be incorrect. bx = bxy[:, ii : ii + 1] + torch.tensor(grid_x, device=device, dtype=torch.float32) # grid_x.to(device=device, dtype=torch.float32) Killed