Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions python/tvm/relax/frontend/onnx/onnx_frontend.py
Original file line number Diff line number Diff line change
Expand Up @@ -2759,6 +2759,38 @@ def _impl_v11(cls, bb, inputs, attr, params):
# edge mode - replicate border values
return bb.emit_te(topi.nn.replicate_pad, inputs[0], pad_before, pad_after)

@classmethod
def _impl_v19(cls, bb, inputs, attr, params):
pads = get_constant(inputs[1], params)
constant_value = get_constant(inputs[2], params)
if constant_value is not None:
constant_value = constant_value.data.numpy().item()
else:
constant_value = 0.0

if isinstance(pads, relax.Constant):
pad_before, pad_after = _np.split(pads.data.numpy(), 2)
pad_before = _np.ndarray.tolist(pad_before)
pad_after = _np.ndarray.tolist(pad_after)
else:
raise ValueError("Dynamic pads are not supported yet.")

pad_mode = attr.get("mode", b"constant").decode("utf-8")
if pad_mode not in ["constant", "edge", "reflect", "wrap"]:
raise tvm.error.OpAttributeInvalid(
"Value " + pad_mode + ' in attribute "mode" is invalid for operator Pad.'
)

if pad_mode == "constant":
return bb.emit_te(topi.nn.pad, inputs[0], pad_before, pad_after, constant_value)
elif pad_mode == "reflect":
return bb.emit_te(topi.nn.mirror_pad, inputs[0], pad_before, pad_after, "REFLECT")
elif pad_mode == "wrap":
return bb.emit_te(topi.nn.circular_pad, inputs[0], pad_before, pad_after)
else:
# edge mode - replicate border values
return bb.emit_te(topi.nn.replicate_pad, inputs[0], pad_before, pad_after)

Comment on lines +2762 to +2793

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The implementation of _impl_v19 is almost identical to _impl_v11, introducing significant code duplication. Since the only difference is the support for mode="wrap", we can simplify _impl_v19 by handling the "wrap" mode directly and delegating all other modes to _impl_v11. This reduces duplication and improves maintainability.

    @classmethod
    def _impl_v19(cls, bb, inputs, attr, params):
        pad_mode = attr.get("mode", b"constant").decode("utf-8")
        if pad_mode == "wrap":
            pads = get_constant(inputs[1], params)
            if isinstance(pads, relax.Constant):
                pad_before, pad_after = _np.split(pads.data.numpy(), 2)
                pad_before = _np.ndarray.tolist(pad_before)
                pad_after = _np.ndarray.tolist(pad_after)
            else:
                raise ValueError("Dynamic pads are not supported yet.")
            return bb.emit_te(topi.nn.circular_pad, inputs[0], pad_before, pad_after)

        return cls._impl_v11(bb, inputs, attr, params)


class Tile(OnnxOpConverter):
"""Converts an onnx Tile node into an equivalent Relax expression."""
Expand Down
7 changes: 4 additions & 3 deletions tests/python/relax/test_frontend_onnx.py
Original file line number Diff line number Diff line change
Expand Up @@ -3656,14 +3656,14 @@ def test_pad(dynamic):
if dynamic:
pytest.skip("Dynamic pad not supported")

def verify_pad(input_shape, pads, mode="constant", value=0.0):
def verify_pad(input_shape, pads, mode="constant", value=0.0, opset=14):
indata = np.random.normal(size=input_shape).astype(np.float32)
# numpy expect result
len_dim = len(pads) // 2
np_pads = [(pads[i], pads[i + len_dim]) for i in range(len_dim)]
pads = np.array(pads)
# onnx graph
if mode in ["edge", "reflect"]:
if mode in ["edge", "reflect", "wrap"]:
outdata = np.pad(indata, pad_width=np_pads, mode=mode)
node = helper.make_node("Pad", inputs=["input", "pads"], outputs=["output"], mode=mode)
graph = helper.make_graph(
Expand Down Expand Up @@ -3700,14 +3700,15 @@ def verify_pad(input_shape, pads, mode="constant", value=0.0):
],
)
model = helper.make_model(graph, producer_name="pad_test")
check_correctness(model)
check_correctness(model, opset=opset)

verify_pad((2, 2), [0, 1, 0, 0], "constant", 0.0)
verify_pad((2, 3), [1, 0, 0, 1], "constant", 0.0)
verify_pad((3, 2), [0, 0, 1, 0], "constant", 5.0)
verify_pad((1, 3, 4, 5), [0, 1, 1, 1, 0, 0, 1, 1], "reflect")
verify_pad((2, 3), [1, 1, 1, 1], "edge")
verify_pad((1, 3, 4, 5), [0, 1, 1, 1, 0, 0, 1, 1], "edge")
verify_pad((1, 3, 4, 5), [0, 1, 1, 1, 0, 0, 1, 1], "wrap", opset=19)


@pytest.mark.parametrize("dynamic", [True, False])
Expand Down