Skip to content

Commit b4e1d24

Browse files
committed
feat: add support for ExtractImagePatches
Signed-off-by: Nanoskript <96655713+nanoskript@users.noreply.github.com>
1 parent b27aa05 commit b4e1d24

File tree

4 files changed

+106
-0
lines changed

4 files changed

+106
-0
lines changed

tests/test_backend.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@
7272
matrix_diag_part = tf.compat.v1.matrix_diag_part
7373
fake_quant_with_min_max_args = tf.quantization.fake_quant_with_min_max_args
7474
fake_quant_with_min_max_vars = tf.quantization.fake_quant_with_min_max_vars
75+
extract_image_patches = tf.image.extract_patches
7576
elif Version(tf.__version__) >= Version("1.13"):
7677
conv2d_backprop_input = tf.compat.v1.nn.conv2d_backprop_input
7778
conv3d_transpose = tf.compat.v1.nn.conv3d_transpose
@@ -94,6 +95,7 @@
9495
matrix_diag_part = tf.compat.v1.matrix_diag_part
9596
fake_quant_with_min_max_args = tf.compat.v1.quantization.fake_quant_with_min_max_args
9697
fake_quant_with_min_max_vars = tf.compat.v1.quantization.fake_quant_with_min_max_vars
98+
extract_image_patches = tf.compat.v1.extract_image_patches
9799
else:
98100
conv2d_backprop_input = tf.nn.conv2d_backprop_input
99101
conv3d_transpose = tf.nn.conv3d_transpose
@@ -111,6 +113,7 @@
111113
is_inf = tf.is_inf
112114
floormod = tf.floormod
113115
matrix_diag_part = tf.matrix_diag_part
116+
extract_image_patches = tf.extract_image_patches
114117

115118

116119
def make_xval(shape):
@@ -6248,5 +6251,21 @@ def func(tensor, indices, updates):
62486251
self._run_test_case(func, [_OUTPUT], {_INPUT: tensor_val, _INPUT1: indices_val, _INPUT2: updates_val})
62496252
self._run_test_case(func, [_OUTPUT], {_INPUT: tensor_val, _INPUT1: indices64_val, _INPUT2: updates_val})
62506253

6254+
def test_extract_image_patches(self):
6255+
for rates in [[1, 1], [1, 4], [4, 1], [3, 3]]:
6256+
for _, padding, x_shape, sizes, strides in get_conv_getdata():
6257+
def func(x):
6258+
return extract_image_patches(
6259+
x,
6260+
sizes=sizes,
6261+
strides=strides,
6262+
rates=[1] + rates + [1],
6263+
padding=padding,
6264+
name=_TFOUTPUT
6265+
)
6266+
6267+
x_val = make_xval(x_shape)
6268+
self._run_test_case(func, [_OUTPUT], {_INPUT: x_val})
6269+
62516270
if __name__ == '__main__':
62526271
unittest_main()

tf2onnx/rewriter/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from tf2onnx.rewriter.lstm_tf2_rewriter import rewriter_lstm_tf2
2525
from tf2onnx.rewriter.gru_tf2_rewriter import rewrite_gru_tf2
2626
from tf2onnx.rewriter.fused_op_rewriter import rewrite_fused_ops
27+
from tf2onnx.rewriter.extract_image_patches_rewriter import rewrite_extract_image_patches
2728

2829

2930
__all__ = [
@@ -53,4 +54,5 @@
5354
"rewriter_lstm_tf2",
5455
"rewrite_gru_tf2",
5556
"rewrite_fused_ops",
57+
"rewrite_extract_image_patches",
5658
]
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# SPDX-License-Identifier: Apache-2.0
2+
3+
4+
"""
5+
tf2onnx.rewriter.extract_image_patches_rewriter - Rewrites ExtractImagePatches into supported operations.
6+
"""
7+
8+
import numpy as np
9+
from tf2onnx import utils
10+
from tf2onnx.graph_matcher import OpTypePattern, GraphMatcher
11+
12+
13+
def rewrite_extract_image_patches(g, ops):
14+
pattern = OpTypePattern("ExtractImagePatches", name="extract_image_patches")
15+
matcher = GraphMatcher(pattern)
16+
match_results = list(matcher.match_ops(ops))
17+
for match_result in match_results:
18+
operation = match_result.get_op("extract_image_patches")
19+
input_shape = g.get_shape(operation.input[0])
20+
output_shape = operation.output_shapes[0]
21+
22+
sizes = operation.get_attr_value("ksizes")
23+
strides = operation.get_attr_value("strides")
24+
rates = operation.get_attr_value("rates")
25+
padding = operation.get_attr_str("padding")
26+
27+
# Our constraints.
28+
utils.make_sure(0 not in output_shape, "Empty ExtractImagePatches output is unsupported.")
29+
[_, size_rows, size_cols, _] = sizes
30+
31+
# Transform input into [N * C, H, W, 1].
32+
transformed_input = g.make_node("Reshape", inputs=[
33+
g.make_node("Transpose", inputs=operation.input, attr=dict(perm=[0, 3, 1, 2])).output[0],
34+
g.make_const(utils.make_name("new_shape"), np.int64([
35+
input_shape[0] * input_shape[3],
36+
input_shape[1],
37+
input_shape[2],
38+
1,
39+
])).output[0],
40+
])
41+
42+
# Create identity kernel.
43+
k = size_rows * size_cols
44+
identity_kernel = g.make_node("Reshape", inputs=[
45+
g.make_node("EyeLike", inputs=[
46+
g.make_node("ConstantOfShape", inputs=[
47+
g.make_const(utils.make_name("eye_size"), np.array([k, k], dtype=np.int64)).output[0],
48+
]).output[0],
49+
]).output[0],
50+
g.make_const(utils.make_name("new_shape"), np.array([
51+
size_rows,
52+
size_cols,
53+
1,
54+
k,
55+
], dtype=np.int64)).output[0],
56+
])
57+
58+
# Convolve into [N * C, ?H, ?W, K].
59+
convolution = g.make_node("Conv2D", inputs=[transformed_input.output[0], identity_kernel.output[0]],
60+
attr=dict(strides=strides, dilations=rates, padding=padding, data_format="NHWC"),
61+
shapes=[[input_shape[0] * input_shape[3], output_shape[1], output_shape[2], k]],
62+
dtypes=operation.output_dtypes, skip_conversion=False)
63+
64+
# Transform into [N, ?H, ?W, C * K].
65+
output_node = g.make_node("Reshape", inputs=[
66+
g.make_node("Transpose", inputs=[
67+
g.make_node("Reshape", inputs=[
68+
convolution.output[0],
69+
g.make_const(utils.make_name("new_shape"), np.array([
70+
input_shape[0],
71+
input_shape[3],
72+
output_shape[1],
73+
output_shape[2],
74+
k,
75+
], dtype=np.int64)).output[0],
76+
]).output[0],
77+
], attr=dict(perm=[0, 2, 3, 4, 1])).output[0],
78+
g.make_const(utils.make_name("new_shape"), np.array(output_shape, dtype=np.int64)).output[0],
79+
])
80+
81+
# Replace node.
82+
g.replace_all_inputs(operation.output[0], output_node.output[0])
83+
g.remove_node(operation.name)
84+
return g.get_nodes()

tf2onnx/tfonnx.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -598,6 +598,7 @@ def compat_handler(ctx, node, **kwargs):
598598
rewriter_lstm_tf2,
599599
rewrite_gru_tf2,
600600
rewrite_single_direction_lstm,
601+
rewrite_extract_image_patches,
601602
# bi-directional
602603
rewrite_bi_direction_lstm,
603604
rewrite_single_direction_gru,

0 commit comments

Comments
 (0)