Skip to content

Commit de5a630

Browse files
authored
Share the Native vision runner across CPU and Vulkan engines (#23936)
Summary: Move classification package loading, FP32 I/O, labels, constant-byte reporting, and reference comparison into `ClassificationRunner`, following the HF LLM runner's engine factory pattern. Add `run_classification_cpu`; `run_classification` remains the Vulkan command, and `run_classification_vulkan` is a Buck `command_alias` for it rather than a second build of the same binary. Share the runner implementation in Buck and CMake, with engine-specific entry points. `EXECUTORCH_BUILD_NATIVE_VISION_RUNNER` accepts CPU, Vulkan, or both; the CPU engine and its CMake libraries come from the preceding commit. The runner's I/O contract and exit codes are documented in the Native README. Authored with OpenAI Codex and Claude Code. Reviewed By: SS-JIA Differential Revision: D125540991 Pull Request resolved: #23936
1 parent aa342dd commit de5a630

9 files changed

Lines changed: 337 additions & 197 deletions

File tree

‎backends/native/README.md‎

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -252,29 +252,44 @@ prefix (or the corresponding `CMAKE_INSTALL_DATADIR` location).
252252
CPU engine tests, including quantized linear execution, graph caching, and
253253
mutable buffers.
254254

255-
### Vision classification runner
255+
### Vision classification runners
256256

257-
Enable `EXECUTORCH_BUILD_NATIVE_VISION_RUNNER=ON` together with
258-
`EXECUTORCH_BUILD_NATIVE_VULKAN=ON` to build `run_classification` from
259-
`examples/vision`. The runner additionally requires gflags; an OSS build uses
260-
the vendored copy, and other builds resolve an installed gflags package.
261-
Running the runner requires a Vulkan device.
257+
`examples/vision` shares model loading, FP32 input/output handling, top-5 display,
258+
and eager-reference comparison between the CPU and Vulkan engines.
259+
`run_classification_cpu` uses the CPU engine and `run_classification` the Vulkan
260+
engine; `run_classification_vulkan` is a Buck alias for `run_classification`.
261+
262+
For a CPU-only CMake build:
262263

263264
```sh
264265
cmake -S . -B cmake-out -DCMAKE_BUILD_TYPE=Release \
265-
-DEXECUTORCH_BUILD_NATIVE=ON -DEXECUTORCH_BUILD_NATIVE_VULKAN=ON \
266+
-DEXECUTORCH_BUILD_NATIVE=ON -DEXECUTORCH_BUILD_NATIVE_CPU=ON \
267+
-DEXECUTORCH_BUILD_XNNPACK=ON \
268+
-DEXECUTORCH_BUILD_KERNELS_OPTIMIZED=ON \
266269
-DEXECUTORCH_BUILD_NATIVE_VISION_RUNNER=ON
267-
cmake --build cmake-out --target run_classification
270+
cmake --build cmake-out --target run_classification_cpu
268271
cmake --install cmake-out --prefix install
269-
install/bin/run_classification \
272+
install/bin/run_classification_cpu \
270273
--package mv2.ptn --input mv2_input.bin \
271274
--expected mv2_expected.bin --categories categories.txt
272275
```
273276

277+
`EXECUTORCH_BUILD_NATIVE_CPU` provides `native_cpu_engine`, using
278+
XNNPACK and the Reference provider with optimized/portable operator registrations.
279+
The CPU build does not need a Vulkan SDK or device. Enable
280+
`EXECUTORCH_BUILD_NATIVE_VULKAN=ON` to also build `run_classification`, which
281+
runs on the host's Vulkan device; both engines can be enabled together. The
282+
runners require gflags.
283+
274284
Export the `.ptn`, input, reference logits, and labels with
275-
[`export.py`](../../examples/native/vision/export.py). The runner prints the
276-
top-5 logits and, when `--expected` is given, exits nonzero if the logits
277-
differ from the reference beyond `--rtol`/`--atol` (both default to `1e-3`).
285+
[`export.py`](../../examples/native/vision/export.py). The same package and FP32
286+
artifacts are accepted by either runner, subject to each engine's supported
287+
operators. Each runner expects a model with one FP32 input and one FP32 output,
288+
and prints the selected engine and device and the top-5 logits. When
289+
`--expected` is given, it compares the logits with the reference using
290+
`--rtol`/`--atol` (both default to `1e-3`). Exit codes are 0 on success, 1 for
291+
invalid arguments, 2 for a loading or execution error, and 3 for a reference
292+
mismatch.
278293

279294
## Native LLM runner
280295

‎backends/native/examples/vision/BUCK‎

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,47 @@ load("@fbsource//xplat/executorch/build:runtime_wrapper.bzl", "runtime")
33

44
oncall("executorch")
55

6-
# Run an exported .ptn on the Vulkan engine and check the logits against the
7-
# eager reference. Runs on the host's system Vulkan device.
8-
fbcode_target(
9-
_kind = runtime.cxx_binary,
10-
name = "run_classification",
11-
srcs = ["run_classification.cpp"],
6+
runtime.cxx_library(
7+
name = "classification_runner",
8+
srcs = ["ClassificationRunner.cpp"],
9+
exported_headers = ["ClassificationRunner.h"],
10+
exported_deps = ["//executorch/backends/native/runtime/engine:engine"],
1211
deps = [
1312
"//executorch/backends/native/examples/runner_utils:runner_utils",
1413
"//executorch/backends/native/runtime:runtime",
1514
"//executorch/backends/native/runtime/deserialize:package",
16-
"//executorch/backends/native/runtime/engine:engine",
1715
"//executorch/backends/native/runtime/graph:scalar_type",
16+
],
17+
external_deps = ["gflags"],
18+
visibility = ["PUBLIC"],
19+
)
20+
21+
runtime.cxx_binary(
22+
name = "run_classification_cpu",
23+
srcs = ["run_classification_cpu.cpp"],
24+
deps = [
25+
":classification_runner",
26+
"//executorch/backends/native/runtime/cpu:cpu_engine",
27+
],
28+
external_deps = ["gflags"],
29+
visibility = ["PUBLIC"],
30+
)
31+
32+
fbcode_target(
33+
_kind = runtime.cxx_binary,
34+
name = "run_classification",
35+
srcs = ["run_classification.cpp"],
36+
deps = [
37+
":classification_runner",
1838
"//executorch/backends/native/runtime/vulkan:vulkan_engine",
1939
],
2040
external_deps = ["gflags"],
2141
visibility = ["PUBLIC"],
2242
)
43+
44+
fbcode_target(
45+
_kind = runtime.command_alias,
46+
name = "run_classification_vulkan",
47+
exe = ":run_classification",
48+
visibility = ["PUBLIC"],
49+
)

‎backends/native/examples/vision/CMakeLists.txt‎

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
1313
set(EXECUTORCH_ROOT "${executorch_native_PREFIX}/include/executorch")
1414
add_subdirectory(../runner_utils runner_utils)
1515
set(_native_vision_runtime executorch_native::runtime)
16+
set(_native_vision_vulkan_engine executorch_native::runtime)
17+
set(EXECUTORCH_BUILD_NATIVE_VULKAN ON)
1618

1719
if(NOT TARGET gflags AND NOT TARGET gflags::gflags)
1820
find_package(gflags REQUIRED)
@@ -23,19 +25,43 @@ if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
2325
set(_native_runner_gflags gflags)
2426
endif()
2527
else()
26-
set(_native_vision_runtime native_engine native_package native_runtime
27-
native_vulkan_engine
28-
)
28+
set(_native_vision_runtime native_engine)
29+
set(_native_vision_vulkan_engine native_vulkan_engine)
2930
endif()
3031

31-
add_executable(run_classification run_classification.cpp)
32+
add_library(native_classification_runner STATIC ClassificationRunner.cpp)
3233
target_link_libraries(
33-
run_classification PRIVATE ${_native_runner_gflags} native_runner_utils
34-
${_native_vision_runtime}
34+
native_classification_runner
35+
PUBLIC ${_native_vision_runtime}
36+
PRIVATE ${_native_runner_gflags} native_runner_utils
3537
)
3638
target_compile_options(
37-
run_classification PRIVATE $<$<CXX_COMPILER_ID:MSVC>:/EHsc>
38-
$<$<NOT:$<CXX_COMPILER_ID:MSVC>>:-fexceptions>
39+
native_classification_runner
40+
PRIVATE $<$<CXX_COMPILER_ID:MSVC>:/EHsc>
41+
$<$<NOT:$<CXX_COMPILER_ID:MSVC>>:-fexceptions>
3942
)
4043

41-
install(TARGETS run_classification RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
44+
function(add_native_classification_runner target source engine)
45+
add_executable(${target} ${source})
46+
target_link_libraries(
47+
${target} PRIVATE native_classification_runner ${_native_runner_gflags}
48+
${engine}
49+
)
50+
target_compile_options(
51+
${target} PRIVATE $<$<CXX_COMPILER_ID:MSVC>:/EHsc>
52+
$<$<NOT:$<CXX_COMPILER_ID:MSVC>>:-fexceptions>
53+
)
54+
install(TARGETS ${target} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
55+
endfunction()
56+
57+
if(EXECUTORCH_BUILD_NATIVE_VULKAN)
58+
add_native_classification_runner(
59+
run_classification run_classification.cpp ${_native_vision_vulkan_engine}
60+
)
61+
endif()
62+
63+
if(EXECUTORCH_BUILD_NATIVE_CPU)
64+
add_native_classification_runner(
65+
run_classification_cpu run_classification_cpu.cpp native_cpu_engine
66+
)
67+
endif()
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
// All rights reserved.
3+
//
4+
// This source code is licensed under the BSD-style license found in the
5+
// LICENSE file in the root directory of this source tree.
6+
7+
#include <executorch/backends/native/examples/vision/ClassificationRunner.h>
8+
9+
#include <cstdint>
10+
#include <cstdio>
11+
#include <exception>
12+
#include <memory>
13+
#include <string>
14+
#include <vector>
15+
16+
#include <executorch/backends/native/examples/runner_utils/runner_utils.h>
17+
#include <executorch/backends/native/runtime/Program.h>
18+
#include <executorch/backends/native/runtime/deserialize/Package.h>
19+
#include <executorch/backends/native/runtime/engine/Engine.h>
20+
#include <executorch/backends/native/runtime/graph/ScalarType.h>
21+
#include <gflags/gflags.h>
22+
23+
DEFINE_string(package, "", "Path to the *.ptn to run. Required.");
24+
DEFINE_string(input, "", "Path to the input tensor, raw float32. Required.");
25+
DEFINE_string(
26+
expected,
27+
"",
28+
"Reference logits to compare against, raw float32.");
29+
DEFINE_string(categories, "", "Newline-separated class labels, for display.");
30+
DEFINE_string(method, "", "Method to run. Defaults to the first one.");
31+
DEFINE_double(rtol, 1e-3, "Relative tolerance for the logits comparison.");
32+
DEFINE_double(atol, 1e-3, "Absolute tolerance for the logits comparison.");
33+
namespace {
34+
35+
std::string label_of(const std::vector<std::string>& labels, int index) {
36+
if (index >= 0 && index < static_cast<int>(labels.size())) {
37+
return labels[index];
38+
}
39+
return "class_" + std::to_string(index);
40+
}
41+
42+
void print_top5(
43+
const std::vector<float>& logits,
44+
const std::vector<std::string>& labels) {
45+
const std::vector<int> order = ptn::runner_utils::top_k(logits, 5);
46+
std::printf("top-5 (class : logit):\n");
47+
for (const int index : order) {
48+
std::printf(
49+
" %4d %-28s %10.4f\n",
50+
index,
51+
label_of(labels, index).c_str(),
52+
logits[index]);
53+
}
54+
}
55+
56+
} // namespace
57+
58+
namespace ptn {
59+
60+
int run_classification(
61+
const std::function<std::unique_ptr<EngineHost>()>& make_host,
62+
const std::function<ConstantBytes(const EngineContext&)>& constant_bytes) {
63+
if (FLAGS_package.empty() || FLAGS_input.empty()) {
64+
std::fprintf(stderr, "error: --package and --input are required\n");
65+
return 1;
66+
}
67+
68+
try {
69+
const auto package =
70+
std::make_shared<const ptn::Package>(ptn::Package::load(FLAGS_package));
71+
const ptn::ByteSpan program_bytes = package->program_bytes();
72+
const auto program = std::make_shared<const ptn::Program>(
73+
ptn::Program::load(program_bytes.data(), program_bytes.size()));
74+
75+
const std::vector<std::string> names = program->method_names();
76+
if (names.empty()) {
77+
std::fprintf(stderr, "error: package holds no methods\n");
78+
return 2;
79+
}
80+
const std::string method_name =
81+
FLAGS_method.empty() ? names[0] : FLAGS_method;
82+
std::printf(
83+
"package: %s (program %zu bytes, %zu constants / %zu bytes)\n",
84+
FLAGS_package.c_str(),
85+
program_bytes.size(),
86+
package->keys().size(),
87+
package->constant_bytes());
88+
89+
const auto host = make_host();
90+
const auto context = host->create_context(program, package);
91+
std::printf(
92+
"engine: %s on %s\n",
93+
host->name().c_str(),
94+
host->device_name().c_str());
95+
96+
const std::unique_ptr<ptn::EngineExecutable> executable =
97+
context->compile(method_name);
98+
std::printf(
99+
"method: %s (%zu inputs, %zu outputs)\n",
100+
method_name.c_str(),
101+
executable->num_inputs(),
102+
executable->num_outputs());
103+
const ConstantBytes constants = constant_bytes(*context);
104+
std::printf(
105+
"constants: %zu unique source bytes, %zu materialized\n",
106+
constants.unique,
107+
constants.materialized);
108+
109+
if (executable->num_inputs() != 1 || executable->num_outputs() != 1) {
110+
std::fprintf(
111+
stderr,
112+
"error: expected 1 input and 1 output, got %zu and %zu\n",
113+
executable->num_inputs(),
114+
executable->num_outputs());
115+
return 2;
116+
}
117+
if (executable->input_dtype(0) != ptn::kFloat ||
118+
executable->output_dtype(0) != ptn::kFloat) {
119+
std::fprintf(stderr, "error: this runner handles fp32 models only\n");
120+
return 2;
121+
}
122+
123+
const std::vector<int64_t> in_sizes = executable->input_sizes(0);
124+
const std::vector<int64_t> out_sizes = executable->output_sizes(0);
125+
std::printf(
126+
" input: %s\n output: %s\n",
127+
ptn::runner_utils::shape_str(in_sizes).c_str(),
128+
ptn::runner_utils::shape_str(out_sizes).c_str());
129+
130+
const std::vector<float> input =
131+
ptn::runner_utils::read_floats(FLAGS_input);
132+
if (static_cast<int64_t>(input.size()) !=
133+
ptn::runner_utils::numel_of(in_sizes)) {
134+
std::fprintf(
135+
stderr,
136+
"error: input has %zu floats, the model wants %lld\n",
137+
input.size(),
138+
static_cast<long long>(ptn::runner_utils::numel_of(in_sizes)));
139+
return 2;
140+
}
141+
142+
executable->set_input(0, input.data(), input.size(), ptn::kFloat);
143+
executable->execute();
144+
145+
std::vector<float> logits(
146+
static_cast<size_t>(ptn::runner_utils::numel_of(out_sizes)));
147+
executable->get_output(0, logits.data(), logits.size(), ptn::kFloat);
148+
if (logits.empty()) {
149+
std::fprintf(stderr, "error: model produced no logits\n");
150+
return 2;
151+
}
152+
153+
std::vector<std::string> labels;
154+
if (!FLAGS_categories.empty()) {
155+
labels = ptn::runner_utils::read_lines(FLAGS_categories);
156+
}
157+
print_top5(logits, labels);
158+
const int argmax = ptn::runner_utils::top_k(logits, 1).front();
159+
std::printf(
160+
"argmax: %d (%s)\n", argmax, label_of(labels, argmax).c_str());
161+
162+
if (FLAGS_expected.empty()) {
163+
std::printf("result: ran (no reference given)\n");
164+
return 0;
165+
}
166+
const std::vector<float> reference =
167+
ptn::runner_utils::read_floats(FLAGS_expected);
168+
const bool pass = ptn::runner_utils::compare_floats(
169+
logits, reference, FLAGS_rtol, FLAGS_atol);
170+
std::printf("result: %s\n", pass ? "PASS" : "FAIL");
171+
return pass ? 0 : 3;
172+
} catch (const std::exception& e) {
173+
std::fprintf(stderr, "error: %s\n", e.what());
174+
return 2;
175+
}
176+
}
177+
178+
} // namespace ptn
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
// All rights reserved.
3+
//
4+
// This source code is licensed under the BSD-style license found in the
5+
// LICENSE file in the root directory of this source tree.
6+
7+
#pragma once
8+
9+
#include <cstddef>
10+
#include <functional>
11+
#include <memory>
12+
13+
#include <executorch/backends/native/runtime/engine/Engine.h>
14+
15+
namespace ptn {
16+
17+
struct ConstantBytes {
18+
size_t unique = 0;
19+
size_t materialized = 0;
20+
};
21+
22+
template <typename Context>
23+
ConstantBytes constant_bytes(const EngineContext& context) {
24+
const auto& typed = dynamic_cast<const Context&>(context);
25+
return {typed.unique_constant_bytes(), typed.materialized_constant_bytes()};
26+
}
27+
28+
int run_classification(
29+
const std::function<std::unique_ptr<EngineHost>()>& make_host,
30+
const std::function<ConstantBytes(const EngineContext&)>& constant_bytes);
31+
32+
} // namespace ptn

0 commit comments

Comments
 (0)