-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathModelHostObject.h
More file actions
241 lines (217 loc) · 10.1 KB
/
ModelHostObject.h
File metadata and controls
241 lines (217 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#pragma once
#include <cstdio>
#include <string>
#include <tuple>
#include <type_traits>
#include <vector>
#include <ReactCommon/CallInvoker.h>
#include <rnexecutorch/TokenizerModule.h>
#include <rnexecutorch/host_objects/JSTensorViewOut.h>
#include <rnexecutorch/host_objects/JsiConversions.h>
#include <rnexecutorch/jsi/JsiHostObject.h>
#include <rnexecutorch/jsi/Promise.h>
#include <rnexecutorch/metaprogramming/FunctionHelpers.h>
#include <rnexecutorch/metaprogramming/TypeConcepts.h>
#include <rnexecutorch/models/BaseModel.h>
#include <rnexecutorch/models/llm/LLM.h>
namespace rnexecutorch {
template <typename Model> class ModelHostObject : public JsiHostObject {
public:
explicit ModelHostObject(const std::shared_ptr<Model> &model,
std::shared_ptr<react::CallInvoker> callInvoker)
: model(model), callInvoker(callInvoker) {
if constexpr (meta::DerivedFromOrSameAs<Model, BaseModel>) {
addFunctions(
JSI_EXPORT_FUNCTION(ModelHostObject<Model>, unload, "unload"));
}
if constexpr (meta::DerivedFromOrSameAs<Model, BaseModel>) {
addFunctions(JSI_EXPORT_FUNCTION(ModelHostObject<Model>,
promiseHostFunction<&Model::forwardJS>,
"forward"));
}
if constexpr (meta::DerivedFromOrSameAs<Model, BaseModel>) {
addFunctions(JSI_EXPORT_FUNCTION(
ModelHostObject<Model>, promiseHostFunction<&Model::getInputShape>,
"getInputShape"));
}
if constexpr (meta::HasGenerate<Model>) {
addFunctions(JSI_EXPORT_FUNCTION(ModelHostObject<Model>,
promiseHostFunction<&Model::generate>,
"generate"));
}
if constexpr (meta::HasEncode<Model>) {
addFunctions(JSI_EXPORT_FUNCTION(ModelHostObject<Model>,
promiseHostFunction<&Model::encode>,
"encode"));
}
if constexpr (meta::SameAs<Model, TokenizerModule>) {
addFunctions(JSI_EXPORT_FUNCTION(ModelHostObject<Model>,
promiseHostFunction<&Model::encode>,
"encode"));
addFunctions(JSI_EXPORT_FUNCTION(ModelHostObject<Model>,
promiseHostFunction<&Model::decode>,
"decode"));
addFunctions(JSI_EXPORT_FUNCTION(
ModelHostObject<Model>, promiseHostFunction<&Model::getVocabSize>,
"getVocabSize"));
addFunctions(JSI_EXPORT_FUNCTION(ModelHostObject<Model>,
promiseHostFunction<&Model::idToToken>,
"idToToken"));
addFunctions(JSI_EXPORT_FUNCTION(ModelHostObject<Model>,
promiseHostFunction<&Model::tokenToId>,
"tokenToId"));
}
if constexpr (meta::SameAs<Model, LLM>) {
addFunctions(JSI_EXPORT_FUNCTION(ModelHostObject<Model>,
promiseHostFunction<&Model::generate>,
"generate"));
addFunctions(JSI_EXPORT_FUNCTION(
ModelHostObject<Model>, synchronousHostFunction<&Model::interrupt>,
"interrupt"));
addFunctions(
JSI_EXPORT_FUNCTION(ModelHostObject<Model>, unload, "unload"));
}
}
// A generic host function that runs synchronously, works analogously to the
// generic promise host function.
template <auto FnPtr> JSI_HOST_FUNCTION(synchronousHostFunction) {
constexpr std::size_t functionArgCount = meta::getArgumentCount(FnPtr);
if (functionArgCount != count) {
char errorMessage[100];
std::snprintf(errorMessage, sizeof(errorMessage),
"Argument count mismatch, was expecting: %zu but got: %zu",
functionArgCount, count);
throw jsi::JSError(runtime, errorMessage);
}
try {
auto argsConverted = meta::createArgsTupleFromJsi(FnPtr, args, runtime);
if constexpr (std::is_void_v<decltype(std::apply(
std::bind_front(FnPtr, model), argsConverted))>) {
// For void functions, just call the function and return undefined
std::apply(std::bind_front(FnPtr, model), std::move(argsConverted));
return jsi::Value::undefined();
} else {
// For non-void functions, capture the result and convert it
auto result =
std::apply(std::bind_front(FnPtr, model), std::move(argsConverted));
return jsiconversion::getJsiValue(std::move(result), runtime);
}
} catch (const std::runtime_error &e) {
// This catch should be merged with the next one
// (std::runtime_error inherits from std::exception) HOWEVER react
// native has broken RTTI which breaks proper exception type
// checking. Remove when the following change is present in our
// version:
// https://github.com/facebook/react-native/commit/3132cc88dd46f95898a756456bebeeb6c248f20e
throw jsi::JSError(runtime, e.what());
} catch (const std::exception &e) {
throw jsi::JSError(runtime, e.what());
} catch (...) {
throw jsi::JSError(runtime, "Unknown error in synchronous function");
}
}
// A generic host function that resolves a promise with a result of a
// function. JSI arguments are converted to the types provided in the function
// signature, and the return value is converted back to JSI before resolving.
template <auto FnPtr> JSI_HOST_FUNCTION(promiseHostFunction) {
auto promise = Promise::createPromise(
runtime, callInvoker,
[this, count, args, &runtime](std::shared_ptr<Promise> promise) {
constexpr std::size_t functionArgCount =
meta::getArgumentCount(FnPtr);
if (functionArgCount != count) {
char errorMessage[100];
std::snprintf(
errorMessage, sizeof(errorMessage),
"Argument count mismatch, was expecting: %zu but got: %zu",
functionArgCount, count);
promise->reject(errorMessage);
return;
}
try {
auto argsConverted =
meta::createArgsTupleFromJsi(FnPtr, args, runtime);
// We need to dispatch a thread if we want the function to be
// asynchronous. In this thread all accesses to jsi::Runtime need to
// be done via the callInvoker.
std::thread([this, promise,
argsConverted = std::move(argsConverted)]() {
try {
if constexpr (std::is_void_v<decltype(std::apply(
std::bind_front(FnPtr, model),
argsConverted))>) {
// For void functions, just call the function and resolve with
// undefined
std::apply(std::bind_front(FnPtr, model),
std::move(argsConverted));
callInvoker->invokeAsync([promise](jsi::Runtime &runtime) {
promise->resolve(jsi::Value::undefined());
});
} else {
// For non-void functions, capture the result and convert it
auto result = std::apply(std::bind_front(FnPtr, model),
std::move(argsConverted));
// The result is copied. It should either be quickly copiable,
// or passed with a shared_ptr.
callInvoker->invokeAsync([promise,
result](jsi::Runtime &runtime) {
promise->resolve(
jsiconversion::getJsiValue(std::move(result), runtime));
});
}
} catch (const std::runtime_error &e) {
// This catch should be merged with the next two
// (std::runtime_error and jsi::JSError inherits from
// std::exception) HOWEVER react native has broken RTTI which
// breaks proper exception type checking. Remove when the
// following change is present in our version:
// https://github.com/facebook/react-native/commit/3132cc88dd46f95898a756456bebeeb6c248f20e
callInvoker->invokeAsync([e = std::move(e), promise]() {
promise->reject(e.what());
});
return;
} catch (const jsi::JSError &e) {
callInvoker->invokeAsync([e = std::move(e), promise]() {
promise->reject(e.what());
});
return;
} catch (const std::exception &e) {
callInvoker->invokeAsync([e = std::move(e), promise]() {
promise->reject(e.what());
});
return;
} catch (...) {
callInvoker->invokeAsync(
[promise]() { promise->reject("Unknown error"); });
return;
}
}).detach();
} catch (...) {
promise->reject("Couldn't parse JS arguments in a native function");
}
});
return promise;
}
JSI_HOST_FUNCTION(unload) {
try {
model->unload();
} catch (const std::runtime_error &e) {
// This catch should be merged with the next one
// (std::runtime_error inherits from std::exception) HOWEVER react
// native has broken RTTI which breaks proper exception type
// checking. Remove when the following change is present in our
// version:
// https://github.com/facebook/react-native/commit/3132cc88dd46f95898a756456bebeeb6c248f20e
throw jsi::JSError(runtime, e.what());
} catch (const std::exception &e) {
throw jsi::JSError(runtime, e.what());
} catch (...) {
throw jsi::JSError(runtime, "Unknown error while unloading a model");
}
return jsi::Value::undefined();
}
private:
std::shared_ptr<Model> model;
std::shared_ptr<react::CallInvoker> callInvoker;
};
} // namespace rnexecutorch