Skip to content

Commit 8697346

Browse files
committed
[1/N] Add BackendOptions class
Pull Request resolved: #11389 Introduce backend option as discussed in #10216 Step 1: Introducd Backend Option class In later stage, it will be plugged in with the rest of the stack. ghstack-source-id: 288753951 Differential Revision: [D75993712](https://our.internmc.facebook.com/intern/diff/D75993712/)
1 parent b4bd556 commit 8697346

File tree

4 files changed

+317
-1
lines changed

4 files changed

+317
-1
lines changed

runtime/backend/backend_options.h

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
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+
#pragma once
10+
#include <executorch/runtime/core/error.h>
11+
#include <cstddef>
12+
#include <cstring>
13+
14+
namespace executorch {
15+
namespace runtime {
16+
17+
// Strongly-typed option key template
18+
template <typename T>
19+
struct OptionKey {
20+
const char* key;
21+
constexpr explicit OptionKey(const char* k) : key(k) {}
22+
};
23+
24+
enum class OptionType { BOOL, INT, STRING };
25+
26+
// Union for option values
27+
union OptionValue {
28+
bool bool_value;
29+
int64_t int_value;
30+
const char* string_value;
31+
};
32+
33+
struct BackendOption {
34+
const char* key;
35+
OptionType type;
36+
OptionValue value;
37+
};
38+
39+
template <size_t MaxCapacity>
40+
class BackendOptions {
41+
public:
42+
// Initialize with zero options
43+
BackendOptions() : size_(0) {}
44+
45+
// Type-safe setters ---------------------------------------------------
46+
47+
/// Sets or updates a boolean option
48+
/// @param key: Typed option key
49+
/// @param value: Boolean value to set
50+
void set_option(OptionKey<bool> key, bool value) {
51+
OptionValue v;
52+
v.bool_value = value; // Direct member assignment
53+
set_option_internal(key.key, OptionType::BOOL, v);
54+
}
55+
56+
/// Sets or updates an integer option
57+
/// @param key: Typed option key
58+
/// @param value: Integer value to set
59+
void set_option(OptionKey<int64_t> key, int64_t value) {
60+
OptionValue v;
61+
v.int_value = value; // Direct member assignment
62+
set_option_internal(key.key, OptionType::INT, v);
63+
}
64+
65+
/// Sets or updates a string option
66+
/// @param key: Typed option key
67+
/// @param value: Null-terminated string value to set
68+
void set_option(OptionKey<const char*> key, const char* value) {
69+
OptionValue v;
70+
v.string_value = value; // Direct member assignment
71+
set_option_internal(key.key, OptionType::STRING, v);
72+
}
73+
74+
// Type-safe getters ---------------------------------------------------
75+
76+
/// Retrieves a boolean option value
77+
/// @param key: Typed option key
78+
/// @param out_value: Reference to store retrieved value
79+
/// @return: Error code (Ok on success)
80+
executorch::runtime::Error get_option(OptionKey<bool> key, bool& out_value)
81+
const {
82+
OptionValue val;
83+
executorch::runtime::Error err =
84+
get_option_internal(key.key, OptionType::BOOL, val);
85+
if (err == executorch::runtime::Error::Ok) {
86+
out_value = val.bool_value;
87+
}
88+
return err;
89+
}
90+
91+
/// Retrieves an integer option value
92+
/// @param key: Typed option key
93+
/// @param out_value: Reference to store retrieved value
94+
/// @return: Error code (Ok on success)
95+
executorch::runtime::Error get_option(
96+
OptionKey<int64_t> key,
97+
int64_t& out_value) const {
98+
OptionValue val;
99+
executorch::runtime::Error err =
100+
get_option_internal(key.key, OptionType::INT, val);
101+
if (err == executorch::runtime::Error::Ok) {
102+
out_value = val.int_value;
103+
}
104+
return err;
105+
}
106+
107+
/// Retrieves an string option value
108+
/// @param key: Typed option key
109+
/// @param out_value: Reference to store retrieved value
110+
/// @return: Error code (Ok on success)
111+
executorch::runtime::Error get_option(
112+
OptionKey<const char*> key,
113+
const char*& out_value) const {
114+
OptionValue val;
115+
executorch::runtime::Error err =
116+
get_option_internal(key.key, OptionType::STRING, val);
117+
if (err == executorch::runtime::Error::Ok) {
118+
out_value = val.string_value;
119+
}
120+
return err;
121+
}
122+
123+
private:
124+
BackendOption options_[MaxCapacity]{};
125+
size_t size_;
126+
127+
// Internal helper to set/update an option
128+
void
129+
set_option_internal(const char* key, OptionType type, OptionValue value) {
130+
// Update existing key if found
131+
for (size_t i = 0; i < size_; ++i) {
132+
if (strcmp(options_[i].key, key) == 0) {
133+
options_[i].type = type;
134+
options_[i].value = value;
135+
return;
136+
}
137+
}
138+
// Add new option if capacity allows
139+
if (size_ < MaxCapacity) {
140+
options_[size_] = BackendOption{key, type, value};
141+
size_++;
142+
}
143+
}
144+
145+
// Internal helper to get an option value with type checking
146+
executorch::runtime::Error get_option_internal(
147+
const char* key,
148+
OptionType expected_type,
149+
OptionValue& out) const {
150+
for (size_t i = 0; i < size_; ++i) {
151+
if (strcmp(options_[i].key, key) == 0) {
152+
if (options_[i].type != expected_type) {
153+
return executorch::runtime::Error::InvalidArgument;
154+
}
155+
out = options_[i].value;
156+
return executorch::runtime::Error::Ok;
157+
}
158+
}
159+
return executorch::runtime::Error::NotFound;
160+
}
161+
};
162+
163+
// Helper functions for creating typed option keys --------------------------
164+
constexpr OptionKey<bool> BoolKey(const char* k) {
165+
return OptionKey<bool>(k);
166+
}
167+
168+
constexpr OptionKey<int64_t> IntKey(const char* k) {
169+
return OptionKey<int64_t>(k);
170+
}
171+
172+
constexpr OptionKey<const char*> StrKey(const char* k) {
173+
return OptionKey<const char*>(k);
174+
}
175+
} // namespace runtime
176+
} // namespace executorch

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_options.h",
2021
"interface.h",
2122
],
2223
preprocessor_flags = ["-DUSE_ATEN_LIB"] if aten_mode else [],
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
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_options.h>
10+
#include <executorch/runtime/platform/runtime.h>
11+
12+
#include <gtest/gtest.h>
13+
14+
using namespace ::testing;
15+
using executorch::runtime::BackendOptions;
16+
using executorch::runtime::BoolKey;
17+
using executorch::runtime::Error;
18+
using executorch::runtime::IntKey;
19+
using executorch::runtime::OptionKey;
20+
using executorch::runtime::StrKey;
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+
int64_t num_threads = 0;
63+
EXPECT_EQ(options.get_option(IntKey("num_threads"), num_threads), Error::Ok);
64+
EXPECT_EQ(num_threads, 256);
65+
}
66+
67+
// Test error conditions
68+
TEST_F(BackendOptionsTest, HandlesErrors) {
69+
// Non-existent key
70+
bool dummy_bool;
71+
EXPECT_EQ(
72+
options.get_option(BoolKey("missing"), dummy_bool), Error::NotFound);
73+
74+
// Type mismatch
75+
options.set_option(IntKey("threshold"), 100);
76+
const char* dummy_str = nullptr;
77+
EXPECT_EQ(
78+
options.get_option(StrKey("threshold"), dummy_str),
79+
Error::InvalidArgument);
80+
81+
// Null value handling
82+
options.set_option(StrKey("nullable"), nullptr);
83+
EXPECT_EQ(options.get_option(StrKey("nullable"), dummy_str), Error::Ok);
84+
EXPECT_EQ(dummy_str, nullptr);
85+
}
86+
87+
// Test capacity limits
88+
TEST_F(BackendOptionsTest, HandlesCapacity) {
89+
// Use persistent storage for keys
90+
std::vector<std::string> keys = {"key0", "key1", "key2", "key3", "key4"};
91+
92+
// Fill to capacity with persistent keys
93+
for (int i = 0; i < 5; i++) {
94+
options.set_option(IntKey(keys[i].c_str()), i);
95+
}
96+
97+
// Verify all exist
98+
int64_t value;
99+
for (int i = 0; i < 5; i++) {
100+
EXPECT_EQ(options.get_option(IntKey(keys[i].c_str()), value), Error::Ok);
101+
EXPECT_EQ(value, i);
102+
}
103+
104+
// Add beyond capacity - should fail
105+
const char* overflow_key = "overflow";
106+
options.set_option(IntKey(overflow_key), 99);
107+
EXPECT_EQ(options.get_option(IntKey(overflow_key), value), Error::NotFound);
108+
109+
// Update existing within capacity
110+
options.set_option(IntKey(keys[2].c_str()), 222);
111+
EXPECT_EQ(options.get_option(IntKey(keys[2].c_str()), value), Error::Ok);
112+
EXPECT_EQ(value, 222);
113+
}
114+
115+
// Test type-specific keys
116+
TEST_F(BackendOptionsTest, EnforcesKeyTypes) {
117+
// Same key name - later set operations overwrite earlier ones
118+
options.set_option(BoolKey("flag"), true);
119+
options.set_option(IntKey("flag"), 123); // Overwrites the boolean entry
120+
121+
bool bval;
122+
int64_t ival;
123+
124+
// Boolean get should fail - type was overwritten to INT
125+
EXPECT_EQ(options.get_option(BoolKey("flag"), bval), Error::InvalidArgument);
126+
127+
// Integer get should succeed with correct value
128+
EXPECT_EQ(options.get_option(IntKey("flag"), ival), Error::Ok);
129+
EXPECT_EQ(ival, 123);
130+
}

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_options_test",
11+
srcs = ["backend_options_test.cpp"],
12+
deps = [
13+
"//executorch/runtime/core:core",
14+
"//executorch/runtime/backend:interface",
15+
],
16+
)

0 commit comments

Comments
 (0)