You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In the [Running an ExecuTorch Model in C++ Tutorial](running-a-model-cpp-tutorial.md), we explored the lower-level ExecuTorch APIs for running an exported model. While these APIs offer zero overhead, great flexibility, and control, they can be verbose and complex for regular use. To simplify this and resemble PyTorch's eager mode in Python, we introduce the Module facade APIs over the regular ExecuTorch runtime APIs. The Module APIs provide the same flexibility but default to commonly used components like `DataLoader` and `MemoryAllocator`, hiding most intricate details.
5
+
In the [Running an ExecuTorch Model in C++ Tutorial](running-a-model-cpp-tutorial.md), we explored the lower-level ExecuTorch APIs for running an exported model. While these APIs offer zero overhead, great flexibility, and control, they can be verbose and complex for regular use. To simplify this and resemble PyTorch's eager mode in Python, we introduce the `Module` facade APIs over the regular ExecuTorch runtime APIs. The `Module` APIs provide the same flexibility but default to commonly used components like `DataLoader` and `MemoryAllocator`, hiding most intricate details.
6
6
7
7
## Example
8
8
@@ -37,7 +37,7 @@ The code now boils down to creating a `Module` and calling `forward()` on it, wi
37
37
38
38
### Creating a Module
39
39
40
-
Creating a `Module` object is an extremely fast operation that does not involve significant processing time or memory allocation. The actual loading of a `Program` and a `Method` happens lazily on the first inference unless explicitly requested with a dedicated API.
40
+
Creating a `Module` object is a fast operation that does not involve significant processing time or memory allocation. The actual loading of a `Program` and a `Method` happens lazily on the first inference unless explicitly requested with a dedicated API.
41
41
42
42
```cpp
43
43
Module module("/path/to/model.pte");
@@ -60,31 +60,32 @@ const auto error = module.load_method("forward");
60
60
61
61
assert(module.is_method_loaded("forward"));
62
62
```
63
-
Note: the `Program` is loaded automatically before any `Method` is loaded. Subsequent attemps to load them have no effect if one of the previous attemps was successful.
64
63
65
-
You can also force-load the "forward" method with a convenience syntax:
64
+
You can also use the convenience function to load the `forward` method:
66
65
67
66
```cpp
68
67
constauto error = module.load_forward();
69
68
70
69
assert(module.is_method_loaded("forward"));
71
70
```
72
71
72
+
**Note:** The `Program` is loaded automatically before any `Method` is loaded. Subsequent attempts to load them have no effect if a previous attempt was successful.
73
+
73
74
### Querying for Metadata
74
75
75
-
Get a set of method names that a Module contains udsing the `method_names()` function:
76
+
Get a set of method names that a `Module` contains using the `method_names()` function:
76
77
77
78
```cpp
78
79
const auto method_names = module.method_names();
79
80
80
81
if (method_names.ok()) {
81
-
assert(method_names.count("forward"));
82
+
assert(method_names->count("forward"));
82
83
}
83
84
```
84
85
85
-
Note: `method_names()` will try to force-load the `Program` when called the first time.
86
+
**Note:**`method_names()` will force-load the `Program` when called for the first time.
86
87
87
-
Introspect miscellaneous metadata about a particular method via `MethodMeta` struct returned by `method_meta()` function:
88
+
To introspect miscellaneous metadata about a particular method, use the `method_meta()` function, which returns a `MethodMeta` struct:
const auto output_meta = meta->output_tensor_meta(0);
102
101
102
+
const auto output_meta = method_meta->output_tensor_meta(0);
103
103
if (output_meta.ok()) {
104
104
assert(output_meta->sizes().size() == 1);
105
105
}
106
106
}
107
107
```
108
108
109
-
Note: `method_meta()` will try to force-load the `Method`when called for the first time.
109
+
**Note:**`method_meta()` will also force-load the `Method` the first time it is called.
110
110
111
-
### Perform an Inference
111
+
### Performing an Inference
112
112
113
-
Assuming that the `Program`'s method names and their input format is known ahead of time, we rarely need to query for those and can run the methods directly by name using the `execute()` function:
113
+
Assuming the `Program`'s method names and their input format are known ahead of time, you can run methods directly by name using the `execute()` function:
114
114
115
115
```cpp
116
-
constauto result = module.execute("forward", Tensor(&tensor));
116
+
constauto result = module.execute("forward", tensor);
117
+
```
118
+
119
+
For the standard `forward()` method, the above can be simplified:
120
+
121
+
```cpp
122
+
constauto result = module.forward(tensor);
117
123
```
118
124
119
-
Which can also be simplified for the standard `forward()` method name as:
125
+
**Note:**`execute()` or `forward()` will load the `Program` and the `Method` the first time they are called. Therefore, the first inference will take longer, as the model is loaded lazily and prepared for execution unless it was explicitly loaded earlier.
126
+
127
+
### Setting Input and Output
128
+
129
+
You can set individual input and output values for methods with the following APIs.
130
+
131
+
#### Setting Inputs
132
+
133
+
Inputs can be any `EValue`, which includes tensors, scalars, lists, and other supported types. To set a specific input value for a method:
**Note:** You can skip the method name argument for the `forward()` method.
156
+
157
+
By pre-setting all inputs, you can perform an inference without passing any arguments:
120
158
121
159
```cpp
122
-
constauto result = module.forward(Tensor(&tensor));
160
+
const auto result = module.forward();
123
161
```
124
162
125
-
Note: `execute()` or `forward()` will try to force load the `Program` and the `Method` when called for the first time. Therefore, the first inference will take more time than subsequent ones as it loads the model lazily and prepares it for execution unless the `Program` or `Method` was loaded explicitly earlier using the corresponding functions.
163
+
Or just setting and then passing the inputs partially:
164
+
165
+
```cpp
166
+
// Set the second input ahead of time.
167
+
module.set_input(input_value_1, 1);
168
+
169
+
// Execute the method, providing the first input at call time.
170
+
constauto result = module.forward(input_value_0);
171
+
```
172
+
173
+
**Note:** The pre-set inputs are stored in the `Module` and can be reused multiple times for the next executions.
174
+
175
+
Don't forget to clear or reset the inputs if you don't need them anymore by setting them to default-constructed `EValue`:
176
+
177
+
```cpp
178
+
module.set_input(runtime::EValue(), 1);
179
+
```
180
+
181
+
#### Setting Outputs
182
+
183
+
Only outputs of type Tensor can be set at runtime, and they must not be memory-planned at model export time. Memory-planned tensors are preallocated during model export and cannot be replaced.
-`output_tensor` is an `EValue` containing the tensor you want to set as the output.
192
+
-`output_index` is the zero-based index of the output to set.
193
+
194
+
**Note:** Ensure that the output tensor you're setting matches the expected shape and data type of the method's output.
195
+
196
+
You can skip the method name for `forward()` and the index for the first output:
197
+
198
+
```cpp
199
+
module.set_output(output_tensor);
200
+
```
201
+
202
+
**Note:** The pre-set outputs are stored in the `Module` and can be reused multiple times for the next executions, just like inputs.
126
203
127
204
### Result and Error Types
128
205
129
-
Most of the ExecuTorch APIs, including those described above, return either `Result` or `Error` types. Let's understand what those are:
206
+
Most of the ExecuTorch APIsreturn either `Result` or `Error` types:
130
207
131
-
*[`Error`](https://github.com/pytorch/executorch/blob/main/runtime/core/error.h) is a C++ enum containing a collection of valid error codes, where the default is `Error::Ok`, denoting success.
208
+
-[`Error`](https://github.com/pytorch/executorch/blob/main/runtime/core/error.h) is a C++ enum containing valid error codes. The default is `Error::Ok`, denoting success.
132
209
133
-
*[`Result`](https://github.com/pytorch/executorch/blob/main/runtime/core/result.h) can hold either an `Error` if the operation has failed or a payload, i.e., the actual result of the operation like an `EValue` wrapping a `Tensor`or any other standard C++ data type if the operation succeeded. To check if `Result`has a valid value, call the `ok()` function. To get the `Error` use the `error()` function, and to get the actual data, use the overloaded `get()`function or dereferencing pointer operators like `*` and `->`.
210
+
-[`Result`](https://github.com/pytorch/executorch/blob/main/runtime/core/result.h) can hold either an `Error` if the operation fails, or a payload such as an `EValue` wrapping a `Tensor` if successful. To check if a `Result`is valid, call `ok()`. To retrieve the `Error`, use `error()`, and to get the data, use `get()` or dereference operators like `*` and `->`.
134
211
135
-
### Profile the Module
212
+
### Profiling the Module
136
213
137
-
Use [ExecuTorch Dump](etdump.md) to trace model execution. Create an instance of the `ETDumpGen`class and pass it to the `Module` constructor. After executing a method, save the `ETDump` to a file for further analysis. You can capture multiple executions in a single trace if desired.
214
+
Use [ExecuTorch Dump](etdump.md) to trace model execution. Create an `ETDumpGen`instance and pass it to the `Module` constructor. After executing a method, save the `ETDump`data to a file for further analysis:
138
215
139
216
```cpp
140
217
#include<fstream>
@@ -147,7 +224,7 @@ using namespace ::executorch::extension;
// Execute a method, e.g. module.forward(...); or module.execute("my_method", ...);
227
+
// Execute a method, e.g., module.forward(...); or module.execute("my_method", ...);
151
228
152
229
if (auto* etdump = dynamic_cast<ETDumpGen*>(module.event_tracer())) {
153
230
const auto trace = etdump->get_etdump_data();
@@ -162,3 +239,7 @@ if (auto* etdump = dynamic_cast<ETDumpGen*>(module.event_tracer())) {
162
239
}
163
240
}
164
241
```
242
+
243
+
# Conclusion
244
+
245
+
The `Module` APIs provide a simplified interface for running ExecuTorch models in C++, closely resembling the experience of PyTorch's eager mode. By abstracting away the complexities of the lower-level runtime APIs, developers can focus on model execution without worrying about the underlying details.
0 commit comments