Skip to content

Commit ca30f97

Browse files
cccclaifacebook-github-bot
authored andcommitted
Add backend option
Summary: Introduce backend option as discussed in #10216 Differential Revision: D75770142
1 parent ce8359d commit ca30f97

File tree

4 files changed

+288
-1
lines changed

4 files changed

+288
-1
lines changed

runtime/backend/backend_option.h

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
#include <cstddef>
2+
#include <cstring>
3+
#include <executorch/runtime/core/error.h>
4+
5+
using executorch::runtime::Error;
6+
7+
namespace executorch {
8+
namespace ET_RUNTIME_NAMESPACE {
9+
10+
// Strongly-typed option key template
11+
// Wraps a string key with type information for type-safe option access
12+
template <typename T>
13+
struct OptionKey {
14+
const char* key; // String identifier for the option
15+
constexpr explicit OptionKey(const char* k) : key(k) {}
16+
};
17+
18+
// Supported option data types
19+
enum class OptionType { BOOL, INT, STRING };
20+
21+
// Union-like container for option values (only one member is valid per option)
22+
struct OptionValue {
23+
bool bool_value; // Storage for boolean values
24+
int int_value; // Storage for integer values
25+
const char* string_value; // Storage for string values
26+
};
27+
28+
// Represents a single backend configuration option
29+
struct BackendOption {
30+
const char* key; // Name of the option
31+
OptionType type; // Data type of the option
32+
OptionValue value; // Current value of the option
33+
};
34+
35+
// Fixed-capacity container for backend options with type-safe access
36+
// MaxCapacity: Maximum number of options this container can hold
37+
template <size_t MaxCapacity>
38+
class BackendOptions {
39+
public:
40+
// Initialize with zero options
41+
BackendOptions() : size(0) {}
42+
43+
// Type-safe setters ---------------------------------------------------
44+
45+
/// Sets or updates a boolean option
46+
/// @param key: Typed option key
47+
/// @param value: Boolean value to set
48+
void set_option(OptionKey<bool> key, bool value) {
49+
set_option_internal(key.key, OptionType::BOOL, {.bool_value = value});
50+
}
51+
52+
/// Sets or updates an integer option
53+
/// @param key: Typed option key
54+
/// @param value: Integer value to set
55+
void set_option(OptionKey<int> key, int value) {
56+
set_option_internal(key.key, OptionType::INT, {.int_value = value});
57+
}
58+
59+
/// Sets or updates a string option
60+
/// @param key: Typed option key
61+
/// @param value: Null-terminated string value to set
62+
void set_option(OptionKey<const char*> key, const char* value) {
63+
set_option_internal(key.key, OptionType::STRING, {.string_value = value});
64+
}
65+
66+
// Type-safe getters ---------------------------------------------------
67+
68+
/// Retrieves a boolean option value
69+
/// @param key: Typed option key
70+
/// @param out_value: Reference to store retrieved value
71+
/// @return: Error code (Ok on success)
72+
Error get_option(OptionKey<bool> key, bool& out_value) const {
73+
OptionValue val;
74+
Error err = get_option_internal(key.key, OptionType::BOOL, val);
75+
if (err == Error::Ok) out_value = val.bool_value;
76+
return err;
77+
}
78+
79+
/// Retrieves an integer option value
80+
/// @param key: Typed option key
81+
/// @param out_value: Reference to store retrieved value
82+
/// @return: Error code (Ok on success)
83+
Error get_option(OptionKey<int> key, int& out_value) const {
84+
OptionValue val;
85+
Error err = get_option_internal(key.key, OptionType::INT, val);
86+
if (err == Error::Ok) out_value = val.int_value;
87+
return err;
88+
}
89+
90+
/// Retrieves a string option value
91+
/// @param key: Typed option key
92+
/// @param out_value: Reference to store retrieved pointer
93+
/// @return: Error code (Ok on success)
94+
Error get_option(OptionKey<const char*> key, const char*& out_value) const {
95+
OptionValue val;
96+
Error err = get_option_internal(key.key, OptionType::STRING, val);
97+
if (err == Error::Ok) out_value = val.string_value;
98+
return err;
99+
}
100+
101+
private:
102+
BackendOption options[MaxCapacity]; // Storage for options
103+
size_t size; // Current number of options
104+
105+
// Internal helper to set/update an option
106+
void set_option_internal(const char* key, OptionType type, OptionValue value) {
107+
// Update existing key if found
108+
for (size_t i = 0; i < size; ++i) {
109+
if (strcmp(options[i].key, key) == 0) {
110+
options[i].type = type;
111+
options[i].value = value;
112+
return;
113+
}
114+
}
115+
// Add new option if capacity allows
116+
if (size < MaxCapacity) {
117+
options[size++] = {key, type, value};
118+
}
119+
}
120+
121+
// Internal helper to get an option value with type checking
122+
Error get_option_internal(const char* key, OptionType expected_type, OptionValue& out) const {
123+
for (size_t i = 0; i < size; ++i) {
124+
if (strcmp(options[i].key, key) == 0) {
125+
// Verify type matches expectation
126+
if (options[i].type != expected_type) {
127+
return Error::InvalidArgument;
128+
}
129+
out = options[i].value;
130+
return Error::Ok;
131+
}
132+
}
133+
return Error::NotFound; // Key not found
134+
}
135+
};
136+
137+
// Helper functions for creating typed option keys --------------------------
138+
139+
/// Creates a boolean option key
140+
constexpr OptionKey<bool> BoolKey(const char* k) { return OptionKey<bool>(k); }
141+
142+
/// Creates an integer option key
143+
constexpr OptionKey<int> IntKey(const char* k) { return OptionKey<int>(k); }
144+
145+
/// Creates a string option key
146+
constexpr OptionKey<const char*> StrKey(const char* k) { return OptionKey<const char*>(k); }
147+
}
148+
}

runtime/backend/targets.bzl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ def define_common_targets():
1717
exported_headers = [
1818
"backend_execution_context.h",
1919
"backend_init_context.h",
20+
"backend_option.h",
2021
"interface.h",
2122
],
2223
preprocessor_flags = ["-DUSE_ATEN_LIB"] if aten_mode else [],
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
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/runtime/backend/backend_option.h>
10+
#include <executorch/runtime/platform/runtime.h>
11+
12+
#include <gtest/gtest.h>
13+
14+
using namespace ::testing;
15+
using executorch::runtime::Error;
16+
using executorch::ET_RUNTIME_NAMESPACE::BackendOptions;
17+
using executorch::ET_RUNTIME_NAMESPACE::OptionKey;
18+
using executorch::ET_RUNTIME_NAMESPACE::BoolKey;
19+
using executorch::ET_RUNTIME_NAMESPACE::StrKey;
20+
using executorch::ET_RUNTIME_NAMESPACE::IntKey;
21+
22+
class BackendOptionsTest : public ::testing::Test {
23+
protected:
24+
void SetUp() override {
25+
// Since these tests cause ET_LOG to be called, the PAL must be initialized
26+
// first.
27+
executorch::runtime::runtime_init();
28+
}
29+
BackendOptions<5> options; // Capacity of 5 for testing limits
30+
};
31+
32+
// Test basic string functionality
33+
TEST_F(BackendOptionsTest, HandlesStringOptions) {
34+
// Set and retrieve valid string
35+
options.set_option(StrKey("backend_type"), "GPU");
36+
const char* result = nullptr;
37+
EXPECT_EQ(options.get_option(StrKey("backend_type"), result), Error::Ok);
38+
EXPECT_STREQ(result, "GPU");
39+
40+
// Update existing key
41+
options.set_option(StrKey("backend_type"), "CPU");
42+
EXPECT_EQ(options.get_option(StrKey("backend_type"), result), Error::Ok);
43+
EXPECT_STREQ(result, "CPU");
44+
}
45+
46+
// Test boolean options
47+
TEST_F(BackendOptionsTest, HandlesBoolOptions) {
48+
options.set_option(BoolKey("debug"), true);
49+
bool debug = false;
50+
EXPECT_EQ(options.get_option(BoolKey("debug"), debug), Error::Ok);
51+
EXPECT_TRUE(debug);
52+
53+
// Test false value
54+
options.set_option(BoolKey("verbose"), false);
55+
EXPECT_EQ(options.get_option(BoolKey("verbose"), debug), Error::Ok);
56+
EXPECT_FALSE(debug);
57+
}
58+
59+
// Test integer options
60+
TEST_F(BackendOptionsTest, HandlesIntOptions) {
61+
options.set_option(IntKey("num_threads"), 256);
62+
int size = 0;
63+
EXPECT_EQ(options.get_option(IntKey("num_threads"), size), Error::Ok);
64+
EXPECT_EQ(size, 256);
65+
}
66+
67+
// Test error conditions
68+
TEST_F(BackendOptionsTest, HandlesErrors) {
69+
// Non-existent key
70+
bool dummy_bool;
71+
EXPECT_EQ(options.get_option(BoolKey("missing"), dummy_bool), Error::NotFound);
72+
73+
// Type mismatch
74+
options.set_option(IntKey("threshold"), 100);
75+
const char* dummy_str = nullptr;
76+
EXPECT_EQ(options.get_option(StrKey("threshold"), dummy_str), Error::InvalidArgument);
77+
78+
// Null value handling
79+
options.set_option(StrKey("nullable"), nullptr);
80+
EXPECT_EQ(options.get_option(StrKey("nullable"), dummy_str), Error::Ok);
81+
EXPECT_EQ(dummy_str, nullptr);
82+
}
83+
84+
// Test capacity limits
85+
TEST_F(BackendOptionsTest, HandlesCapacity) {
86+
// Use persistent storage for keys
87+
std::vector<std::string> keys = {
88+
"key0", "key1", "key2", "key3", "key4"
89+
};
90+
91+
// Fill to capacity with persistent keys
92+
for(int i = 0; i < 5; i++) {
93+
options.set_option(IntKey(keys[i].c_str()), i);
94+
}
95+
96+
// Verify all exist
97+
int value;
98+
for(int i = 0; i < 5; i++) {
99+
EXPECT_EQ(options.get_option(IntKey(keys[i].c_str()), value), Error::Ok);
100+
EXPECT_EQ(value, i);
101+
}
102+
103+
// Add beyond capacity - should fail
104+
const char* overflow_key = "overflow";
105+
options.set_option(IntKey(overflow_key), 99);
106+
EXPECT_EQ(options.get_option(IntKey(overflow_key), value), Error::NotFound);
107+
108+
// Update existing within capacity
109+
options.set_option(IntKey(keys[2].c_str()), 222);
110+
EXPECT_EQ(options.get_option(IntKey(keys[2].c_str()), value), Error::Ok);
111+
EXPECT_EQ(value, 222);
112+
}
113+
114+
// Test type-specific keys
115+
TEST_F(BackendOptionsTest, EnforcesKeyTypes) {
116+
// Same key name - later set operations overwrite earlier ones
117+
options.set_option(BoolKey("flag"), true);
118+
options.set_option(IntKey("flag"), 123); // Overwrites the boolean entry
119+
120+
bool bval;
121+
int ival;
122+
123+
// Boolean get should fail - type was overwritten to INT
124+
EXPECT_EQ(options.get_option(BoolKey("flag"), bval), Error::InvalidArgument);
125+
126+
// Integer get should succeed with correct value
127+
EXPECT_EQ(options.get_option(IntKey("flag"), ival), Error::Ok);
128+
EXPECT_EQ(ival, 123);
129+
}

runtime/backend/test/targets.bzl

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,16 @@
1+
load("@fbsource//xplat/executorch/build:runtime_wrapper.bzl", "runtime")
2+
13
def define_common_targets():
24
"""Defines targets that should be shared between fbcode and xplat.
35
46
The directory containing this targets.bzl file should also contain both
57
TARGETS and BUCK files that call this function.
68
"""
7-
pass
9+
runtime.cxx_test(
10+
name = "backend_option_test",
11+
srcs = ["backend_option_test.cpp"],
12+
deps = [
13+
"//executorch/runtime/core:core",
14+
"//executorch/runtime/backend:interface",
15+
],
16+
)

0 commit comments

Comments
 (0)