Hi again,
i´m trying to get a custom NN working, i´m struggeling implementing the morphology.open.
Does someone know how to fix this or where to look further?
custom nn for cv2.morphologyEx(thresh, cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (22, 22))):
#!/usr/bin/env python3
from pathlib import Path
import torch
from torch import nn
import kornia
import onnx
from onnxsim import simplify
import blobconverter
# Name of the model
name = 'threshold'
# Define the model class
class Model(nn.Module):
def forward(self, image):
# Define structuring element (kernel) for morphological operation
kernel_size = (22, 22)
# Create an empty tensor to represent the elliptical structuring element
structuring_element = torch.zeros(*kernel_size)
# Calculate the coordinates of the center of the ellipse
center_x = kernel_size[1] // 2
center_y = kernel_size[0] // 2
# Set the values inside the ellipse to 1
for i in range(kernel_size[0]):
for j in range(kernel_size[1]):
if ((j - center_x) / (kernel_size[1] // 2)) ** 2 + ((i - center_y) / (kernel_size[0] // 2)) ** 2 <= 1:
structuring_element[i, j] = 1
# Perform morphology operation (opening) using Kornia
blob = kornia.morphology.opening(image, structuring_element)
return blob
# Define the expected input shape (dummy input)
shape = (1, 3, 300, 300) # Example input shape
model = Model()
X = torch.ones(shape, dtype=torch.float32)
# Create output directory if it doesn't exist
path = Path("out/")
path.mkdir(parents=True, exist_ok=True)
# Export the model to ONNX format
onnx_path = str(path / (name + '.onnx'))
print(f"Exporting model to {onnx_path}")
torch.onnx.export(
model,
X,
onnx_path,
opset_version=12,
do_constant_folding=True,
)
# Simplify the ONNX model
onnx_simplified_path = str(path / (name + '_simplified.onnx'))
print(f"Simplifying model to {onnx_simplified_path}")
onnx_model = onnx.load(onnx_path)
model_simp, check = simplify(onnx_model)
onnx.save(model_simp, onnx_simplified_path)
# Convert ONNX model to blob format
print("Converting ONNX model to blob format...")
blobconverter.from_onnx(
model=onnx_simplified_path,
data_type="FP16",
shaves=6,
use_cache=False,
output_dir="../models",
optimizer_params=[]
)
print("Conversion completed.")
error log:
Traceback (most recent call last):
File "C:\Users\lh\Documents\DEV\OAK Projects\depthai-experiments\gen2-custom-models\generate_model\kornia_threashold.py", line 49, in <module>
torch.onnx.export(
File "C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\utils.py", line 516, in export
_export(
File "C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\utils.py", line 1613, in _export
graph, params_dict, torch_out = _model_to_graph(
File "C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\utils.py", line 1139, in _model_to_graph
graph = _optimize_graph(
File "C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\utils.py", line 677, in _optimize_graph
graph = _C._jit_pass_onnx(graph, operator_export_type)
File "C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\utils.py", line 1957, in _run_symbolic_function
return symbolic_fn(graph_context, *inputs, **attrs)
File "C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\symbolic_helper.py", line 306, in wrapper
return fn(g, *args, **kwargs)
File "C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\symbolic_opset12.py", line 331, in unfold
return opset9.unfold(g, input, dimension, const_size, const_step)
File "C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\symbolic_helper.py", line 306, in wrapper
return fn(g, *args, **kwargs)
File "C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\symbolic_opset9.py", line 3149, in unfold
return symbolic_helper._unimplemented(
File "C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\symbolic_helper.py", line 612, in _unimplemented
_onnx_unsupported(f"{op}, {msg}", value)
File "C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\symbolic_helper.py", line 623, in _onnx_unsupported
raise errors.SymbolicValueError(
torch.onnx.errors.SymbolicValueError: Unsupported: ONNX export of operator Unfold, input size not accessible. Please feel free to request support or submit a pull request on PyTorch GitHub: https://github.com/pytorch/pytorch/issues [Caused by the value '18839 defined in (%18839 : Float(*, *, *, *, strides=[309123, 103041, 321, 1], requires_grad=0, device=cpu) = onnx::Pad[mode="constant"](%image, %18837, %18838), scope: __main__.Model:: # C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\nn\functional.py:4495:0
)' (type 'Tensor') in the TorchScript graph. The containing node has kind 'onnx::Pad'.]
(node defined in C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\nn\functional.py(4495): pad
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\kornia\morphology\morphology.py(174): erosion
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\kornia\morphology\morphology.py(259): opening
C:\Users\lh\Documents\DEV\OAK Projects\depthai-experiments\gen2-custom-models\generate_model\kornia_threashold.py(34): forward
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\nn\modules\module.py(1501): _slow_forward
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\nn\modules\module.py(1520): _call_impl
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\nn\modules\module.py(1511): _wrapped_call_impl
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\jit\_trace.py(129): wrapper
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\jit\_trace.py(138): forward
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\nn\modules\module.py(1520): _call_impl
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\nn\modules\module.py(1511): _wrapped_call_impl
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\jit\_trace.py(1296): _get_trace_graph
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\utils.py(915): _trace_and_get_graph_from_model
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\utils.py(1011): _create_jit_graph
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\utils.py(1135): _model_to_graph
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\utils.py(1613): _export
C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\onnx\utils.py(516): export
C:\Users\lh\Documents\DEV\OAK Projects\depthai-experiments\gen2-custom-models\generate_model\kornia_threashold.py(49): <module>
)
Inputs:
#0: image defined in (%image : Float(1, 3, 300, 300, strides=[270000, 90000, 300, 1], requires_grad=0, device=cpu) = prim::Param()
) (type 'Tensor')
#1: 18837 defined in (%18837 : Long(8, strides=[1], device=cpu) = onnx::Cast[to=7](%18836), scope: __main__.Model:: # C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\nn\functional.py:4495:0
) (type 'Tensor')
#2: 18838 defined in (%18838 : Float(device=cpu) = onnx::Constant[value={10000}](), scope: __main__.Model:: # C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\nn\functional.py:4495:0
) (type 'Tensor')
Outputs:
#0: 18839 defined in (%18839 : Float(*, *, *, *, strides=[309123, 103041, 321, 1], requires_grad=0, device=cpu) = onnx::Pad[mode="constant"](%image, %18837, %18838), scope: __main__.Model:: # C:\Users\lh\anaconda3\envs\depthai-experiments\lib\site-packages\torch\nn\functional.py:4495:0
) (type 'Tensor')
Process finished with exit code 1
Does this mean that the onnx export does not support Unfold or something with onnx: Pad. How would i get arround this? Would i need to ask Pytorch ONNX people for help here?
Thanks a lot for any clues 🙂