Skip to content
This repository has been archived by the owner on May 22, 2023. It is now read-only.

Commit

Permalink
[Util] NestedMsg: MapNestedMsg (#410)
Browse files Browse the repository at this point in the history
This PR brings a new util function (`MapNestedMsg`) for NestedMsg:

* `MapNestedMsg` recurses into an input NestedMsg and maps the leaves
according to the provided mapping function.

One corresponding unit test is provided.
  • Loading branch information
MasterJH5574 authored Feb 7, 2023
1 parent 83adb87 commit 1123675
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
26 changes: 26 additions & 0 deletions include/tvm/relax/nested_msg.h
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,32 @@ NestedMsg<T> CombineNestedMsg(NestedMsg<T> lhs, NestedMsg<T> rhs, FType fcombine
}
}

/*!
* \brief Recursively map a nested message to another one, with leaf mapped by the input fmapleaf.
* \param msg The nested message to be mapped.
* \param fmapleaf The leaf map function, with signature NestedMsg<T> fmapleaf(T msg)
* \tparam T The content type of nested message.
* \tparam FType The leaf map function type.
* \return The new nested message.
*/
template <typename T, typename FType>
NestedMsg<T> MapNestedMsg(NestedMsg<T> msg, FType fmapleaf) {
if (msg.IsNull()) {
return msg;
} else if (msg.IsLeaf()) {
return fmapleaf(msg.LeafValue());
} else {
ICHECK(msg.IsNested());
Array<NestedMsg<T>> arr = msg.NestedArray();
Array<NestedMsg<T>> res;
res.reserve(arr.size());
for (int i = 0; i < static_cast<int>(arr.size()); ++i) {
res.push_back(MapNestedMsg(arr[i], fmapleaf));
}
return NestedMsg<T>(res);
}
}

/*!
* \brief Recursively decompose the tuple structure in expr and msg along with it.
*
Expand Down
23 changes: 23 additions & 0 deletions tests/cpp/nested_msg_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,29 @@ TEST(NestedMsg, CombineNestedMsg) {
[](Integer lhs, Integer rhs) -> bool { return lhs->value == rhs->value; }));
}

TEST(NestedMsg, MapNestedMsg) {
auto c0 = Integer(0);
auto c1 = Integer(1);
auto c2 = Integer(2);
auto c3 = Integer(3);

NestedMsg<Integer> msg = {c0, {c0, c1}, NullOpt, {c0, {c2, c1}}};
NestedMsg<Integer> expected = {c3, {c3, NullOpt}, NullOpt, {c3, {c2, NullOpt}}};

auto output = MapNestedMsg(msg, [](Integer x) {
if (x->value == 0) {
return NestedMsg<Integer>(Integer(3));
} else if (x->value == 1) {
return NestedMsg<Integer>();
} else {
return NestedMsg<Integer>(x);
}
});

EXPECT_TRUE(Equal(output, expected,
[](Integer lhs, Integer rhs) -> bool { return lhs->value == rhs->value; }));
}

TEST(NestedMsg, TransformTupleLeaf) {
auto c0 = Integer(0);
auto c1 = Integer(1);
Expand Down

0 comments on commit 1123675

Please sign in to comment.