xref: /aosp_15_r20/external/executorch/extension/runner_util/inputs.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/extension/runner_util/inputs.h>
10 
11 #include <executorch/runtime/executor/method.h>
12 #include <executorch/runtime/executor/method_meta.h>
13 #include <executorch/runtime/platform/log.h>
14 
15 using executorch::runtime::Error;
16 using executorch::runtime::Method;
17 using executorch::runtime::MethodMeta;
18 using executorch::runtime::Result;
19 using executorch::runtime::Tag;
20 using executorch::runtime::TensorInfo;
21 
22 namespace executorch {
23 namespace extension {
24 
prepare_input_tensors(Method & method)25 Result<BufferCleanup> prepare_input_tensors(Method& method) {
26   MethodMeta method_meta = method.method_meta();
27   size_t num_inputs = method_meta.num_inputs();
28   size_t num_allocated = 0;
29   void** inputs = (void**)malloc(num_inputs * sizeof(void*));
30 
31   for (size_t i = 0; i < num_inputs; i++) {
32     auto tag = method_meta.input_tag(i);
33     if (!tag.ok()) {
34       BufferCleanup cleanup({inputs, num_allocated});
35       return tag.error();
36     }
37     if (tag.get() != Tag::Tensor) {
38       ET_LOG(Debug, "Skipping non-tensor input %zu", i);
39       continue;
40     }
41     Result<TensorInfo> tensor_meta = method_meta.input_tensor_meta(i);
42     if (!tensor_meta.ok()) {
43       return tensor_meta.error();
44     }
45     // This input is a tensor. Allocate a buffer for it.
46     void* data_ptr = malloc(tensor_meta->nbytes());
47     inputs[num_allocated++] = data_ptr;
48 
49     // Create the tensor and set it as the input.
50     Error err =
51         internal::fill_and_set_input(method, tensor_meta.get(), i, data_ptr);
52     if (err != Error::Ok) {
53       ET_LOG(
54           Error, "Failed to prepare input %zu: 0x%" PRIx32, i, (uint32_t)err);
55       // The BufferCleanup will free the inputs when it goes out of scope.
56       BufferCleanup cleanup({inputs, num_allocated});
57       return err;
58     }
59   }
60   return BufferCleanup({inputs, num_allocated});
61 }
62 
63 } // namespace extension
64 } // namespace executorch
65