xref: /aosp_15_r20/external/executorch/kernels/portable/cpu/op_mean.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/kernel_ops_util.h>
10 #include <executorch/kernels/portable/cpu/util/reduce_util.h>
11 #include <executorch/runtime/kernel/kernel_includes.h>
12 #include <executorch/runtime/platform/assert.h>
13 
14 namespace torch {
15 namespace executor {
16 namespace native {
17 
18 using Tensor = exec_aten::Tensor;
19 using ScalarType = exec_aten::ScalarType;
20 
mean_dim_out(KernelRuntimeContext & ctx,const Tensor & in,optional<ArrayRef<int64_t>> dim_list,bool keepdim,optional<ScalarType> dtype,Tensor & out)21 Tensor& mean_dim_out(
22     KernelRuntimeContext& ctx,
23     const Tensor& in,
24     optional<ArrayRef<int64_t>> dim_list,
25     bool keepdim,
26     optional<ScalarType> dtype,
27     Tensor& out) {
28   (void)ctx;
29 
30   ET_KERNEL_CHECK(
31       ctx,
32       check_mean_dim_args(in, dim_list, keepdim, dtype, out),
33       InvalidArgument,
34       out);
35 
36   ET_KERNEL_CHECK(
37       ctx, tensors_have_same_dim_order(in, out), InvalidArgument, out);
38 
39   ET_KERNEL_CHECK(ctx, tensor_is_default_dim_order(in), InvalidArgument, out);
40 
41   ET_KERNEL_CHECK(
42       ctx,
43       resize_reduction_out(in, dim_list, keepdim, out) == Error::Ok,
44       InvalidArgument,
45       out);
46 
47   ET_SWITCH_REALHB_TYPES(in.scalar_type(), ctx, "mean.out", CTYPE_IN, [&] {
48     ET_SWITCH_FLOATH_TYPES(out.scalar_type(), ctx, "mean.out", CTYPE_OUT, [&] {
49       CTYPE_OUT* out_data = out.mutable_data_ptr<CTYPE_OUT>();
50       const size_t num = get_reduced_dim_product(in, dim_list);
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 / static_cast<float>(num);
62       }
63     });
64   });
65 
66   return out;
67 }
68 
69 } // namespace native
70 } // namespace executor
71 } // namespace torch
72