xref: /aosp_15_r20/external/executorch/kernels/portable/cpu/op_abs.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 <executorch/kernels/portable/cpu/util/functional_util.h>
10 #include <executorch/runtime/kernel/kernel_includes.h>
11 #include <executorch/runtime/platform/assert.h>
12 
13 namespace torch {
14 namespace executor {
15 namespace native {
16 
17 using exec_aten::Tensor;
18 
abs_out(KernelRuntimeContext & ctx,const Tensor & in,Tensor & out)19 Tensor& abs_out(KernelRuntimeContext& ctx, const Tensor& in, Tensor& out) {
20   (void)ctx;
21 
22   // Resize for dynamic shape
23   ET_KERNEL_CHECK_MSG(
24       ctx,
25       resize_tensor(out, in.sizes()) == Error::Ok,
26       InvalidArgument,
27       out,
28       "Failed to resize output tensor.");
29 
30   ET_KERNEL_CHECK(ctx, tensors_have_same_dtype(in, out), InvalidArgument, out);
31   ET_KERNEL_CHECK(
32       ctx, tensors_have_same_dim_order(in, out), InvalidArgument, out);
33 
34   ET_SWITCH_REAL_TYPES(in.scalar_type(), ctx, "abs.out", CTYPE, [&] {
35     apply_unary_map_fn(
36         [](const CTYPE val_in) {
37           if (val_in < 0) {
38             return static_cast<CTYPE>(-val_in);
39           } else {
40             return static_cast<CTYPE>(val_in);
41           }
42         },
43         in.const_data_ptr<CTYPE>(),
44         out.mutable_data_ptr<CTYPE>(),
45         in.numel());
46   });
47 
48   return out;
49 }
50 
51 } // namespace native
52 } // namespace executor
53 } // namespace torch
54