xref: /aosp_15_r20/external/executorch/kernels/portable/cpu/op_sum.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/reduce_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 Tensor = exec_aten::Tensor;
18 using ScalarType = exec_aten::ScalarType;
19 
sum_dim_out(KernelRuntimeContext & ctx,const Tensor & in,optional<ArrayRef<int64_t>> dim_list,bool keepdim,optional<ScalarType> dtype,Tensor & out)20 Tensor& sum_dim_out(
21     KernelRuntimeContext& ctx,
22     const Tensor& in,
23     optional<ArrayRef<int64_t>> dim_list,
24     bool keepdim,
25     optional<ScalarType> dtype,
26     Tensor& out) {
27   (void)ctx;
28 
29   ET_KERNEL_CHECK(
30       ctx,
31       check_reduction_args(in, dim_list, keepdim, dtype, out),
32       InvalidArgument,
33       out);
34 
35   ET_KERNEL_CHECK(
36       ctx,
37       resize_reduction_out(in, dim_list, keepdim, out) == Error::Ok,
38       InvalidArgument,
39       out);
40 
41   ET_KERNEL_CHECK(
42       ctx, tensors_have_same_dim_order(in, out), InvalidArgument, out);
43 
44   ET_KERNEL_CHECK(ctx, tensor_is_default_dim_order(in), InvalidArgument, out);
45 
46   ET_SWITCH_REAL_TYPES_AND(
47       Bool, in.scalar_type(), ctx, "sum.IntList_out", CTYPE_IN, [&] {
48         ET_SWITCH_REAL_TYPES_AND(
49             Bool, out.scalar_type(), ctx, "sum.IntList_out", CTYPE_OUT, [&] {
50               CTYPE_OUT* out_data = out.mutable_data_ptr<CTYPE_OUT>();
51               for (size_t out_ix = 0; out_ix < out.numel(); ++out_ix) {
52                 CTYPE_OUT sum = 0;
53                 if (in.numel() > 0) {
54                   sum = map_reduce_over_dim_list<CTYPE_IN, CTYPE_OUT>(
55                       [](CTYPE_IN v) { return static_cast<CTYPE_OUT>(v); },
56                       [](CTYPE_OUT outv, CTYPE_OUT acc) { return acc + outv; },
57                       in,
58                       dim_list,
59                       out_ix);
60                 }
61                 out_data[out_ix] = sum;
62               }
63             });
64       });
65 
66   return out;
67 }
68 
69 } // namespace native
70 } // namespace executor
71 } // namespace torch
72