• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/scalar_utils.h>
10 #include <executorch/runtime/kernel/kernel_includes.h>
11 
12 namespace torch {
13 namespace executor {
14 namespace native {
15 
16 using Tensor = exec_aten::Tensor;
17 using ScalarType = exec_aten::ScalarType;
18 
full_like_out(KernelRuntimeContext & ctx,const Tensor & in,const Scalar & fill_value,optional<MemoryFormat> memory_format,Tensor & out)19 Tensor& full_like_out(
20     KernelRuntimeContext& ctx,
21     const Tensor& in,
22     const Scalar& fill_value,
23     optional<MemoryFormat> memory_format,
24     Tensor& out) {
25   (void)ctx;
26 
27   if (memory_format.has_value()) {
28     ET_KERNEL_CHECK_MSG(
29         ctx,
30         memory_format.value() == MemoryFormat::Contiguous ||
31             memory_format.value() == MemoryFormat::Preserve,
32         InvalidArgument,
33         out,
34         "memory_format must be contiguous");
35   }
36 
37   ET_KERNEL_CHECK(
38       ctx, tensors_have_same_dim_order(in, out), InvalidArgument, out);
39 
40   ET_KERNEL_CHECK(ctx, tensor_is_default_dim_order(in), InvalidArgument, out);
41 
42   // Resize for dynamic shape
43   ET_KERNEL_CHECK_MSG(
44       ctx,
45       resize_tensor(out, in.sizes()) == Error::Ok,
46       InvalidArgument,
47       out,
48       "Failed to resize output tensor.");
49 
50   ScalarType val_type = utils::get_scalar_dtype(fill_value);
51   ScalarType out_type = out.scalar_type();
52 
53   constexpr auto name = "scalar_tensor.out";
54 
55   ET_SWITCH_REALB_TYPES(val_type, ctx, name, CTYPE_VAL, [&] {
56     CTYPE_VAL val;
57     utils::extract_scalar(fill_value, &val);
58 
59     ET_SWITCH_REALHB_TYPES(out_type, ctx, name, CTYPE_OUT, [&] {
60       CTYPE_OUT val_casted = static_cast<CTYPE_OUT>(val);
61       auto data_out = out.mutable_data_ptr<CTYPE_OUT>();
62       for (size_t i = 0; i < out.numel(); ++i) {
63         data_out[i] = val_casted;
64       }
65     });
66   });
67 
68   return out;
69 }
70 
71 } // namespace native
72 } // namespace executor
73 } // namespace torch
74