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
15 changes: 14 additions & 1 deletion src/target/intrin_rule.cc
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,18 @@ namespace codegen {
namespace intrin {
using tirx::FLowerIntrinsic;

// `tirx.round` is ties-to-even (see include/tvm/tirx/op.h), and constant
// folding implements it with std::nearbyint. The C library's round()/roundf()
// is ties-AWAY-from-zero, so lowering through FloatSuffix would disagree with
// the folder and with every other backend. Rename to nearbyint before the
// float suffix is applied, as the CUDA rule already does.
struct FloatSuffixTiesToEven {
std::string operator()(const PrimType& ty, std::string name) const {
if (name == "round") name = "nearbyint";
return FloatSuffix()(ty, name);
}
};

TVM_REGISTER_OP("tirx.exp")
.set_attr<FLowerIntrinsic>("default.FLowerIntrinsic", DispatchPureExtern<FloatSuffix>);

Expand Down Expand Up @@ -115,7 +127,8 @@ TVM_REGISTER_OP("tirx.ceil")
.set_attr<FLowerIntrinsic>("default.FLowerIntrinsic", DispatchPureExtern<FloatSuffix>);

TVM_REGISTER_OP("tirx.round")
.set_attr<FLowerIntrinsic>("default.FLowerIntrinsic", DispatchPureExtern<FloatSuffix>);
.set_attr<FLowerIntrinsic>("default.FLowerIntrinsic",
DispatchPureExtern<FloatSuffixTiesToEven>);

TVM_REGISTER_OP("tirx.nearbyint")
.set_attr<FLowerIntrinsic>("default.FLowerIntrinsic", DispatchPureExtern<FloatSuffix>);
Expand Down
12 changes: 11 additions & 1 deletion tests/python/codegen/test_target_codegen_c_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,17 @@ def check_c():
fround = m["test_round"]
dev = tvm.cpu(0)
n = nn
a = tvm.runtime.tensor(np.random.rand(n).astype("float32"), dev)
# Exact midpoints first: this is where ties-to-even (np.round, and the
# semantics every other backend and the constant folder use) differs
# from ties-away-from-zero. np.random.rand never produces them, so the
# random tail alone cannot exercise the tie rule.
midpoints = np.array(
[0.5, 1.5, 2.5, 3.5, -0.5, -1.5, -2.5, -3.5], dtype="float32"
)
a_np = np.concatenate(
[midpoints, np.random.rand(n - len(midpoints)).astype("float32")]
).astype("float32")
a = tvm.runtime.tensor(a_np, dev)
b = tvm.runtime.tensor(np.zeros(n, dtype="float32"), dev)
fround(a, b)
tvm.testing.assert_allclose(b.numpy(), (np.round(a.numpy()).view("float32")))
Expand Down