Skip to content
Merged
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
11 changes: 9 additions & 2 deletions kernels/portable/cpu/op_hardtanh.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,15 @@ Tensor& hardtanh_out(
ET_KERNEL_CHECK(ctx, in_type == out_type, InvalidArgument, out);

ET_SWITCH_REALHBF16_TYPES(in_type, ctx, "hardtanh.out", CTYPE, [&]() {
const CTYPE min_casted = utils::scalar_to<CTYPE>(min);
const CTYPE max_casted = utils::scalar_to<CTYPE>(max);
auto opt_min_casted =
utils::internal::check_overflow_scalar_cast<CTYPE>(min);
ET_KERNEL_CHECK(ctx, opt_min_casted.has_value(), InvalidArgument, );
auto min_casted = opt_min_casted.value();

auto opt_max_casted =
utils::internal::check_overflow_scalar_cast<CTYPE>(max);
ET_KERNEL_CHECK(ctx, opt_max_casted.has_value(), InvalidArgument, );
auto max_casted = opt_max_casted.value();

apply_unary_map_fn(
[min_casted, max_casted](const CTYPE val_in) {
Expand Down
18 changes: 18 additions & 0 deletions kernels/test/op_hardtanh_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/

#include <executorch/kernels/test/FunctionHeaderWrapper.h> // Declares the operator
#include <executorch/kernels/test/ScalarOverflowTestMacros.h>
#include <executorch/kernels/test/TestUtil.h>
#include <executorch/runtime/core/exec_aten/exec_aten.h>
#include <executorch/runtime/core/exec_aten/testing_util/tensor_factory.h>
Expand Down Expand Up @@ -51,10 +52,27 @@ class OpHardTanhTest : public OperatorTest {
EXPECT_TENSOR_EQ(out, ret);
EXPECT_TENSOR_EQ(out, tf.make({2, 2}, {lower_bound, 0, 1, 2}));
}

template <ScalarType DTYPE>
void expect_bad_scalar_value_dies(const Scalar& bad_value) {
TensorFactory<DTYPE> tf;
Tensor in = tf.ones({2, 2});
Tensor out = tf.zeros({2, 2});

// Test overflow for min parameter (using valid max)
ET_EXPECT_KERNEL_FAILURE(
context_, op_hardtanh_out(in, bad_value, 1.0, out));

// Test overflow for max parameter (using valid min)
ET_EXPECT_KERNEL_FAILURE(
context_, op_hardtanh_out(in, -1.0, bad_value, out));
}
};

TEST_F(OpHardTanhTest, SanityCheck) {
#define TEST_ENTRY(ctype, dtype) test_dtype<ctype, ScalarType::dtype>();
ET_FORALL_REALHBF16_TYPES(TEST_ENTRY);
#undef TEST_ENTRY
}

GENERATE_SCALAR_OVERFLOW_TESTS(OpHardTanhTest)
Loading