|
| 1 | +import os |
| 2 | +import sys |
| 3 | +import imp |
| 4 | +import torch |
| 5 | + |
| 6 | + |
| 7 | +# load the custom_op_library and register the custom ops |
| 8 | +lib_dir = os.path.join(os.path.dirname(__file__), '..') |
| 9 | +file, path, description = imp.find_module("_custom_ops", [lib_dir]) |
| 10 | +torch.ops.load_library(path) |
| 11 | + |
| 12 | + |
| 13 | +def register_custom_op(): |
| 14 | + from torch.onnx.symbolic_helper import parse_args, scalar_type_to_onnx |
| 15 | + from torch.onnx.symbolic_opset9 import select, unsqueeze, squeeze, _cast_Long, reshape |
| 16 | + |
| 17 | + @parse_args('v', 'v', 'f') |
| 18 | + def symbolic_multi_label_nms(g, boxes, scores, iou_threshold): |
| 19 | + boxes = unsqueeze(g, boxes, 0) |
| 20 | + scores = unsqueeze(g, unsqueeze(g, scores, 0), 0) |
| 21 | + max_output_per_class = g.op('Constant', value_t=torch.tensor([sys.maxsize], dtype=torch.long)) |
| 22 | + iou_threshold = g.op('Constant', value_t=torch.tensor([iou_threshold], dtype=torch.float)) |
| 23 | + nms_out = g.op('NonMaxSuppression', boxes, scores, max_output_per_class, iou_threshold) |
| 24 | + return squeeze(g, select(g, nms_out, 1, g.op('Constant', value_t=torch.tensor([2], dtype=torch.long))), 1) |
| 25 | + |
| 26 | + @parse_args('v', 'v', 'f', 'i', 'i', 'i') |
| 27 | + def roi_align(g, input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio): |
| 28 | + batch_indices = _cast_Long(g, squeeze(g, select(g, rois, 1, g.op('Constant', |
| 29 | + value_t=torch.tensor([0], dtype=torch.long))), 1), False) |
| 30 | + rois = select(g, rois, 1, g.op('Constant', value_t=torch.tensor([1, 2, 3, 4], dtype=torch.long))) |
| 31 | + return g.op('RoiAlign', input, rois, batch_indices, spatial_scale_f=spatial_scale, |
| 32 | + output_height_i=pooled_height, output_width_i=pooled_width, sampling_ratio_i=sampling_ratio) |
| 33 | + |
| 34 | + @parse_args('v', 'v', 'f', 'i', 'i') |
| 35 | + def roi_pool(g, input, rois, spatial_scale, pooled_height, pooled_width): |
| 36 | + roi_pool = g.op('MaxRoiPool', input, rois, |
| 37 | + pooled_shape_i=(pooled_height, pooled_width), spatial_scale_f=spatial_scale) |
| 38 | + return roi_pool, None |
| 39 | + |
| 40 | + from torch.onnx import register_custom_op_symbolic |
| 41 | + register_custom_op_symbolic('torchvision::nms', symbolic_multi_label_nms, 10) |
| 42 | + register_custom_op_symbolic('torchvision::roi_align', roi_align, 10) |
| 43 | + register_custom_op_symbolic('torchvision::roi_pool', roi_pool, 10) |
| 44 | + |
| 45 | + |
| 46 | +register_custom_op() |
0 commit comments