xref: /aosp_15_r20/external/executorch/kernels/portable/cpu/op_sign.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 #include <cstring>
11 
12 #include <executorch/kernels/portable/cpu/util/functional_util.h>
13 #include <executorch/runtime/kernel/kernel_includes.h>
14 #include <executorch/runtime/platform/assert.h>
15 
16 namespace torch {
17 namespace executor {
18 namespace native {
19 
20 using exec_aten::Tensor;
21 
sign_out(KernelRuntimeContext & ctx,const Tensor & in,Tensor & out)22 Tensor& sign_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_dim_order(in, out), InvalidArgument, out);
35 
36   ET_KERNEL_CHECK(
37       ctx, tensors_have_same_shape_and_dtype(in, out), InvalidArgument, out);
38 
39   if (in.scalar_type() == exec_aten::ScalarType::Bool) {
40     memcpy(out.mutable_data_ptr(), in.const_data_ptr(), in.nbytes());
41   } else {
42     ET_SWITCH_REAL_TYPES(in.scalar_type(), ctx, "sign.out", CTYPE, [&] {
43       apply_unary_map_fn(
44           [](const CTYPE val_in) {
45             if (std::isnan(val_in)) {
46               return val_in;
47             } else {
48               return static_cast<CTYPE>((val_in > 0) - (val_in < 0));
49             }
50           },
51           in.const_data_ptr<CTYPE>(),
52           out.mutable_data_ptr<CTYPE>(),
53           in.numel());
54     });
55   }
56 
57   return out;
58 }
59 
60 } // namespace native
61 } // namespace executor
62 } // namespace torch
63