|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | + |
| 3 | + |
| 4 | +""" |
| 5 | +tf2onnx.rewriter.depthwise_conv_dilations_rewriter - Rewrites the patten used to represent dilations |
| 6 | +pat = SpaceToBatchND->DepthwiseConv2dNative->BatchToSpaceND |
| 7 | +""" |
| 8 | + |
| 9 | +from tf2onnx.graph_matcher import OpTypePattern, GraphMatcher |
| 10 | + |
| 11 | +# pylint: disable=invalid-name,unused-argument,missing-docstring, unused-variable |
| 12 | + |
| 13 | + |
| 14 | +def rewrite_depthwise_conv_dilations(g, ops): |
| 15 | + pattern1 = \ |
| 16 | + OpTypePattern("BatchToSpaceND", name="batch_to_space", inputs=[ |
| 17 | + OpTypePattern("DepthwiseConv2dNative", name="depthwise_conv", inputs=[ |
| 18 | + OpTypePattern("SpaceToBatchND", name="space_to_batch", inputs=[ |
| 19 | + OpTypePattern("*"), |
| 20 | + OpTypePattern("Const|ConstV2"), |
| 21 | + OpTypePattern("Const|ConstV2"), |
| 22 | + ]), |
| 23 | + OpTypePattern("*"), |
| 24 | + ]), |
| 25 | + OpTypePattern("Const|ConstV2"), |
| 26 | + OpTypePattern("Const|ConstV2"), |
| 27 | + ]) |
| 28 | + |
| 29 | + for pattern in [pattern1]: |
| 30 | + matcher = GraphMatcher(pattern, allow_reorder=False) |
| 31 | + match_results = list(matcher.match_ops(ops)) |
| 32 | + for match_result in match_results: |
| 33 | + space_to_batch = match_result.get_op("space_to_batch") |
| 34 | + depthwise_conv = match_result.get_op("depthwise_conv") |
| 35 | + batch_to_space = match_result.get_op("batch_to_space") |
| 36 | + |
| 37 | + block_shape1 = space_to_batch.inputs[1].get_tensor_value(as_list=True) |
| 38 | + paddings = space_to_batch.inputs[2].get_tensor_value(as_list=False).flatten().tolist() |
| 39 | + block_shape2 = batch_to_space.inputs[1].get_tensor_value(as_list=True) |
| 40 | + crops = batch_to_space.inputs[2].get_tensor_value(as_list=True) |
| 41 | + if block_shape1 != block_shape2: |
| 42 | + continue |
| 43 | + if depthwise_conv.get_attr_value("dilations", [1, 1, 1, 1]) != [1, 1, 1, 1]: |
| 44 | + continue |
| 45 | + if depthwise_conv.get_attr_value("strides", [1, 1, 1, 1]) != [1, 1, 1, 1]: |
| 46 | + continue |
| 47 | + if depthwise_conv.get_attr_value("data_format", b"NHWC") != b"NHWC": |
| 48 | + continue |
| 49 | + if depthwise_conv.get_attr_value("padding") != b"VALID": |
| 50 | + continue |
| 51 | + if crops != [[0, 0], [0, 0]]: |
| 52 | + continue |
| 53 | + |
| 54 | + inp = space_to_batch.input[0] |
| 55 | + kernel = depthwise_conv.input[1] |
| 56 | + |
| 57 | + g.replace_inputs(depthwise_conv, [inp, kernel]) |
| 58 | + depthwise_conv.set_attr("dilations", [1] + block_shape1 + [1]) |
| 59 | + depthwise_conv.set_attr("explicit_paddings", [0, 0] + paddings + [0, 0]) |
| 60 | + depthwise_conv.set_attr("padding", "EXPLICIT") |
| 61 | + g.copy_shape(batch_to_space.output[0], depthwise_conv.output[0]) |
| 62 | + g.replace_all_inputs(batch_to_space.output[0], depthwise_conv.output[0]) |
| 63 | + |
| 64 | + return g.get_nodes() |
0 commit comments