xref: /aosp_15_r20/external/executorch/kernels/portable/cpu/op_relu.cpp (revision 523fa7a60841cd1ecfb9cc4201f1ca8b03ed023a)
1 /*
2  * Copyright (c) Meta Platforms, Inc. and affiliates.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD-style license found in the
6  * LICENSE file in the root directory of this source tree.
7  */
8 
9 #include <cmath>
10 
11 #include <executorch/kernels/portable/cpu/util/functional_util.h>
12 #include <executorch/runtime/kernel/kernel_includes.h>
13 #include <executorch/runtime/platform/assert.h>
14 
15 namespace torch {
16 namespace executor {
17 namespace native {
18 
19 using Tensor = exec_aten::Tensor;
20 using ScalarType = exec_aten::ScalarType;
21 
relu_out(KernelRuntimeContext & ctx,const Tensor & in,Tensor & out)22 Tensor& relu_out(KernelRuntimeContext& ctx, const Tensor& in, Tensor& out) {
23   (void)ctx;
24 
25   // Resize for dynamic shape
26   ET_KERNEL_CHECK_MSG(
27       ctx,
28       resize_tensor(out, in.sizes()) == Error::Ok,
29       InvalidArgument,
30       out,
31       "Failed to resize output tensor.");
32 
33   ET_KERNEL_CHECK(
34       ctx, tensors_have_same_shape_and_dtype(in, out), InvalidArgument, out);
35 
36   ET_KERNEL_CHECK(ctx, tensor_is_real_type(out), InvalidArgument, out);
37 
38   ET_KERNEL_CHECK(
39       ctx, tensors_have_same_dim_order(in, out), InvalidArgument, out);
40 
41   ET_SWITCH_REAL_TYPES(in.scalar_type(), ctx, "relu.out", CTYPE, [&]() {
42     apply_unary_map_fn(
43         [](const CTYPE val_in) {
44           return (std::isnan(val_in) || val_in >= CTYPE(0)) ? val_in : CTYPE(0);
45         },
46         in.const_data_ptr<CTYPE>(),
47         out.mutable_data_ptr<CTYPE>(),
48         in.numel());
49   });
50 
51   return out;
52 }
53 
54 } // namespace native
55 } // namespace executor
56 } // namespace torch
57