react-native-executorch 0.5.1-rc.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/README.md +132 -0
  2. package/common/rnexecutorch/models/speech_to_text/SpeechToText.cpp +4 -10
  3. package/common/rnexecutorch/models/speech_to_text/SpeechToText.h +1 -1
  4. package/common/rnexecutorch/models/speech_to_text/SpeechToTextStrategy.h +3 -2
  5. package/common/rnexecutorch/models/speech_to_text/WhisperStrategy.cpp +16 -4
  6. package/common/rnexecutorch/models/speech_to_text/WhisperStrategy.h +2 -2
  7. package/lib/Error.d.ts +30 -0
  8. package/lib/Error.js +50 -0
  9. package/lib/constants/directories.d.ts +1 -0
  10. package/lib/constants/directories.js +2 -0
  11. package/lib/constants/llmDefaults.d.ts +6 -0
  12. package/lib/constants/llmDefaults.js +16 -0
  13. package/lib/constants/modelUrls.d.ts +217 -83
  14. package/lib/constants/modelUrls.js +304 -98
  15. package/lib/constants/ocr/models.d.ts +882 -0
  16. package/lib/constants/ocr/models.js +182 -0
  17. package/lib/constants/ocr/symbols.d.ts +75 -0
  18. package/lib/constants/ocr/symbols.js +139 -0
  19. package/lib/{typescript/constants → constants}/sttDefaults.d.ts +0 -1
  20. package/lib/constants/sttDefaults.js +12 -10
  21. package/lib/controllers/LLMController.d.ts +47 -0
  22. package/lib/controllers/LLMController.js +14 -11
  23. package/lib/controllers/OCRController.d.ts +23 -0
  24. package/lib/controllers/OCRController.js +12 -5
  25. package/lib/controllers/SpeechToTextController.d.ts +8 -4
  26. package/lib/controllers/SpeechToTextController.js +15 -9
  27. package/lib/controllers/VerticalOCRController.d.ts +25 -0
  28. package/lib/controllers/VerticalOCRController.js +75 -0
  29. package/lib/hooks/computer_vision/useClassification.d.ts +15 -0
  30. package/lib/hooks/computer_vision/useClassification.js +7 -0
  31. package/lib/hooks/computer_vision/useImageEmbeddings.d.ts +15 -0
  32. package/lib/hooks/computer_vision/useImageEmbeddings.js +7 -0
  33. package/lib/hooks/computer_vision/useImageSegmentation.d.ts +38 -0
  34. package/lib/hooks/computer_vision/useImageSegmentation.js +7 -0
  35. package/lib/hooks/computer_vision/useOCR.d.ts +20 -0
  36. package/lib/hooks/computer_vision/useOCR.js +42 -0
  37. package/lib/hooks/computer_vision/useObjectDetection.d.ts +15 -0
  38. package/lib/hooks/computer_vision/useObjectDetection.js +7 -0
  39. package/lib/hooks/computer_vision/useStyleTransfer.d.ts +15 -0
  40. package/lib/hooks/computer_vision/useStyleTransfer.js +7 -0
  41. package/lib/hooks/computer_vision/useVerticalOCR.d.ts +21 -0
  42. package/lib/hooks/computer_vision/useVerticalOCR.js +45 -0
  43. package/lib/hooks/general/useExecutorchModule.d.ts +13 -0
  44. package/lib/hooks/general/useExecutorchModule.js +7 -0
  45. package/lib/hooks/natural_language_processing/useLLM.d.ts +10 -0
  46. package/lib/hooks/natural_language_processing/useLLM.js +78 -0
  47. package/lib/hooks/natural_language_processing/useSpeechToText.d.ts +27 -0
  48. package/lib/hooks/natural_language_processing/useSpeechToText.js +19 -14
  49. package/lib/hooks/natural_language_processing/useTextEmbeddings.d.ts +16 -0
  50. package/lib/hooks/natural_language_processing/useTextEmbeddings.js +7 -0
  51. package/lib/hooks/natural_language_processing/useTokenizer.d.ts +17 -0
  52. package/lib/hooks/natural_language_processing/useTokenizer.js +52 -0
  53. package/lib/hooks/useModule.d.ts +17 -0
  54. package/lib/hooks/useModule.js +45 -0
  55. package/lib/hooks/useNonStaticModule.d.ts +20 -0
  56. package/lib/hooks/useNonStaticModule.js +49 -0
  57. package/lib/index.d.ts +1 -1
  58. package/lib/index.js +3 -2
  59. package/lib/module/constants/modelUrls.js +61 -36
  60. package/lib/module/constants/modelUrls.js.map +1 -1
  61. package/lib/module/constants/ocr/models.js +1 -1
  62. package/lib/module/hooks/natural_language_processing/useSpeechToText.js +71 -34
  63. package/lib/module/hooks/natural_language_processing/useSpeechToText.js.map +1 -1
  64. package/lib/module/index.js +2 -3
  65. package/lib/module/index.js.map +1 -1
  66. package/lib/module/modules/natural_language_processing/SpeechToTextModule.js +72 -31
  67. package/lib/module/modules/natural_language_processing/SpeechToTextModule.js.map +1 -1
  68. package/lib/module/types/stt.js +1 -85
  69. package/lib/module/types/stt.js.map +1 -1
  70. package/lib/module/utils/ResourceFetcher.js +6 -8
  71. package/lib/module/utils/ResourceFetcher.js.map +1 -1
  72. package/lib/module/utils/ResourceFetcherUtils.js +20 -20
  73. package/lib/module/utils/ResourceFetcherUtils.js.map +1 -1
  74. package/lib/module/utils/SpeechToTextModule/ASR.js +191 -0
  75. package/lib/module/utils/SpeechToTextModule/ASR.js.map +1 -0
  76. package/lib/module/utils/SpeechToTextModule/OnlineProcessor.js +73 -0
  77. package/lib/module/utils/SpeechToTextModule/OnlineProcessor.js.map +1 -0
  78. package/lib/module/utils/SpeechToTextModule/hypothesisBuffer.js +56 -0
  79. package/lib/module/utils/SpeechToTextModule/hypothesisBuffer.js.map +1 -0
  80. package/lib/modules/BaseModule.d.ts +8 -0
  81. package/lib/modules/BaseModule.js +25 -0
  82. package/lib/modules/BaseNonStaticModule.d.ts +9 -0
  83. package/lib/modules/BaseNonStaticModule.js +14 -0
  84. package/lib/modules/computer_vision/ClassificationModule.d.ts +8 -0
  85. package/lib/modules/computer_vision/ClassificationModule.js +17 -0
  86. package/lib/modules/computer_vision/ImageEmbeddingsModule.d.ts +8 -0
  87. package/lib/modules/computer_vision/ImageEmbeddingsModule.js +17 -0
  88. package/lib/modules/computer_vision/ImageSegmentationModule.d.ts +11 -0
  89. package/lib/modules/computer_vision/ImageSegmentationModule.js +27 -0
  90. package/lib/modules/computer_vision/OCRModule.d.ts +15 -0
  91. package/lib/modules/computer_vision/OCRModule.js +20 -0
  92. package/lib/modules/computer_vision/ObjectDetectionModule.d.ts +9 -0
  93. package/lib/modules/computer_vision/ObjectDetectionModule.js +17 -0
  94. package/lib/modules/computer_vision/StyleTransferModule.d.ts +8 -0
  95. package/lib/modules/computer_vision/StyleTransferModule.js +17 -0
  96. package/lib/modules/computer_vision/VerticalOCRModule.d.ts +15 -0
  97. package/lib/modules/computer_vision/VerticalOCRModule.js +22 -0
  98. package/lib/modules/general/ExecutorchModule.d.ts +7 -0
  99. package/lib/modules/general/ExecutorchModule.js +14 -0
  100. package/lib/modules/natural_language_processing/LLMModule.d.ts +28 -0
  101. package/lib/modules/natural_language_processing/LLMModule.js +45 -0
  102. package/lib/modules/natural_language_processing/SpeechToTextModule.d.ts +18 -8
  103. package/lib/modules/natural_language_processing/SpeechToTextModule.js +21 -15
  104. package/lib/modules/natural_language_processing/TextEmbeddingsModule.d.ts +9 -0
  105. package/lib/modules/natural_language_processing/TextEmbeddingsModule.js +21 -0
  106. package/lib/modules/natural_language_processing/TokenizerModule.d.ts +12 -0
  107. package/lib/modules/natural_language_processing/TokenizerModule.js +5 -4
  108. package/lib/native/NativeETInstaller.d.ts +6 -0
  109. package/lib/native/NativeETInstaller.js +2 -0
  110. package/lib/native/NativeOCR.d.ts +8 -0
  111. package/lib/native/NativeOCR.js +2 -0
  112. package/lib/native/NativeVerticalOCR.d.ts +8 -0
  113. package/lib/native/NativeVerticalOCR.js +2 -0
  114. package/lib/types/common.d.ts +31 -0
  115. package/lib/types/common.js +25 -0
  116. package/lib/types/imageSegmentation.d.ts +24 -0
  117. package/lib/types/imageSegmentation.js +26 -0
  118. package/lib/types/llm.d.ts +46 -0
  119. package/lib/types/llm.js +9 -0
  120. package/lib/types/objectDetection.d.ts +104 -0
  121. package/lib/types/objectDetection.js +94 -0
  122. package/lib/types/ocr.d.ts +11 -0
  123. package/lib/types/ocr.js +1 -0
  124. package/lib/types/stt.d.ts +94 -0
  125. package/lib/types/stt.js +85 -0
  126. package/lib/typescript/constants/modelUrls.d.ts +24 -7
  127. package/lib/typescript/constants/modelUrls.d.ts.map +1 -1
  128. package/lib/typescript/constants/ocr/models.d.ts +126 -126
  129. package/lib/typescript/hooks/natural_language_processing/useSpeechToText.d.ts +15 -24
  130. package/lib/typescript/hooks/natural_language_processing/useSpeechToText.d.ts.map +1 -1
  131. package/lib/typescript/index.d.ts +2 -3
  132. package/lib/typescript/index.d.ts.map +1 -1
  133. package/lib/typescript/modules/natural_language_processing/SpeechToTextModule.d.ts +19 -22
  134. package/lib/typescript/modules/natural_language_processing/SpeechToTextModule.d.ts.map +1 -1
  135. package/lib/typescript/types/stt.d.ts +17 -91
  136. package/lib/typescript/types/stt.d.ts.map +1 -1
  137. package/lib/typescript/utils/ResourceFetcher.d.ts.map +1 -1
  138. package/lib/typescript/utils/ResourceFetcherUtils.d.ts.map +1 -1
  139. package/lib/typescript/utils/SpeechToTextModule/ASR.d.ts +27 -0
  140. package/lib/typescript/utils/SpeechToTextModule/ASR.d.ts.map +1 -0
  141. package/lib/typescript/utils/SpeechToTextModule/OnlineProcessor.d.ts +23 -0
  142. package/lib/typescript/utils/SpeechToTextModule/OnlineProcessor.d.ts.map +1 -0
  143. package/lib/typescript/utils/SpeechToTextModule/hypothesisBuffer.d.ts +13 -0
  144. package/lib/typescript/utils/SpeechToTextModule/hypothesisBuffer.d.ts.map +1 -0
  145. package/lib/utils/ResourceFetcher.d.ts +24 -0
  146. package/lib/utils/ResourceFetcher.js +305 -0
  147. package/lib/utils/ResourceFetcherUtils.d.ts +54 -0
  148. package/lib/utils/ResourceFetcherUtils.js +9 -0
  149. package/lib/utils/llm.d.ts +6 -0
  150. package/lib/utils/llm.js +1 -0
  151. package/lib/utils/stt.d.ts +1 -0
  152. package/lib/utils/stt.js +21 -0
  153. package/package.json +5 -3
  154. package/src/constants/modelUrls.ts +70 -37
  155. package/src/constants/ocr/models.ts +1 -1
  156. package/src/hooks/natural_language_processing/useSpeechToText.ts +87 -92
  157. package/src/index.ts +6 -8
  158. package/src/modules/natural_language_processing/SpeechToTextModule.ts +81 -69
  159. package/src/types/stt.ts +97 -92
  160. package/src/utils/ResourceFetcher.ts +9 -7
  161. package/src/utils/ResourceFetcherUtils.ts +15 -17
  162. package/src/utils/SpeechToTextModule/ASR.ts +303 -0
  163. package/src/utils/SpeechToTextModule/OnlineProcessor.ts +87 -0
  164. package/src/utils/SpeechToTextModule/hypothesisBuffer.ts +79 -0
  165. package/common/rnexecutorch/models/speech_to_text/MoonshineStrategy.cpp +0 -31
  166. package/common/rnexecutorch/models/speech_to_text/MoonshineStrategy.h +0 -21
  167. package/lib/module/constants/sttDefaults.js +0 -74
  168. package/lib/module/constants/sttDefaults.js.map +0 -1
  169. package/lib/module/controllers/SpeechToTextController.js +0 -320
  170. package/lib/module/controllers/SpeechToTextController.js.map +0 -1
  171. package/lib/typescript/constants/sttDefaults.d.ts.map +0 -1
  172. package/lib/typescript/controllers/SpeechToTextController.d.ts +0 -57
  173. package/lib/typescript/controllers/SpeechToTextController.d.ts.map +0 -1
  174. package/src/constants/sttDefaults.ts +0 -82
  175. package/src/controllers/SpeechToTextController.ts +0 -471
  176. package/third-party/ios/ExecutorchLib/ExecutorchLib.xcodeproj/project.xcworkspace/contents.xcworkspacedata +0 -7
  177. package/third-party/ios/ExecutorchLib/ExecutorchLib.xcodeproj/project.xcworkspace/xcuserdata/norbertklockiewicz.xcuserdatad/UserInterfaceState.xcuserstate +0 -0
  178. package/third-party/ios/ExecutorchLib/ExecutorchLib.xcodeproj/xcuserdata/norbertklockiewicz.xcuserdatad/xcschemes/xcschememanagement.plist +0 -14
package/README.md ADDED
@@ -0,0 +1,132 @@
1
+ <div align="right">
2
+ <h1 align="left" style="display:inline-block">React Native ExecuTorch
3
+ <!-- Discord Badge -->
4
+ <a href="https://discord.gg/ZGqqY55qkP">
5
+ <img src="https://img.shields.io/badge/Discord-Join%20Us-00008B?logo=discord&logoColor=white&style=for-the-badge" alt="Join our Discord community">
6
+ </a>
7
+ </h1>
8
+ </div>
9
+
10
+ ![Software Mansion banner](https://github.com/user-attachments/assets/fa2c4735-e75c-4cc1-970d-88905d95e3a4)
11
+
12
+ **React Native ExecuTorch** provides a declarative way to run AI models on-device using React Native, powered by **ExecuTorch** :rocket:. It offers out-of-the-box support for a wide range of LLMs, computer vision models, and more. Visit our [HuggingFace](https://huggingface.co/software-mansion) page to explore these models.
13
+
14
+ **ExecuTorch**, developed by Meta, is a novel framework allowing AI model execution on devices like mobile phones or microcontrollers.
15
+
16
+ React Native ExecuTorch bridges the gap between React Native and native platform capabilities, enabling developers to efficiently run local AI models on mobile devices. This can be achieved without the need for extensive expertise in native programming or machine learning.
17
+
18
+ [![npm version](https://img.shields.io/npm/v/react-native-executorch?color=00008B)](https://www.npmjs.com/package/react-native-executorch)
19
+ [![CI](https://github.com/software-mansion/react-native-executorch/actions/workflows/ci.yml/badge.svg)](https://github.com/software-mansion/react-native-executorch/actions/workflows/ci.yml)
20
+
21
+ **Table of contents:**
22
+
23
+ - [:yin_yang: Supported versions](#yin_yang-supported-versions)
24
+ - [:robot: Ready-made models](#robot-ready-made-models)
25
+ - [:books: Documentation](#books-documentation)
26
+ - [:llama: Quickstart - Running Llama](#llama-quickstart---running-llama)
27
+ - [:calling: Examples](#calling-examples)
28
+ - [:balance_scale: License](#balance_scale-license)
29
+ - [:soon: What's next?](#soon-whats-next)
30
+
31
+ ## :yin_yang: Supported versions
32
+
33
+ The minimal supported version are:
34
+ * iOS 17.0
35
+ * Android 13
36
+ * React Native 0.76
37
+
38
+ > [!IMPORTANT]
39
+ > React Native Executorch supports only the [New React Native architecture](https://reactnative.dev/architecture/landing-page).
40
+
41
+ ## :robot: Ready-made models
42
+
43
+ Our library has a number of ready-to-use AI models; a complete list is available in the documentation. If you're interested in running your own AI model, you need to first export it to the `.pte` format. Instructions on how to do this are available in the [Python API](https://pypi.org/project/executorch/).
44
+
45
+ ## :books: Documentation
46
+
47
+ Check out how our library can help you build your React Native AI features by visiting our docs:
48
+ https://docs.swmansion.com/react-native-executorch
49
+
50
+ ## :llama: **Quickstart - Running Llama**
51
+
52
+ **Get started with AI-powered text generation in 3 easy steps!**
53
+
54
+ ### :one: **Installation**
55
+
56
+ ```bash
57
+ # Install the package
58
+ yarn add react-native-executorch
59
+ # Depending on the platform, choose either iOS or Android
60
+ yarn expo run:< ios | android >
61
+ ```
62
+
63
+ ### :two: **Setup & Initialization**
64
+
65
+ Add this to your component file:
66
+
67
+ ```tsx
68
+ import {
69
+ useLLM,
70
+ LLAMA3_2_1B,
71
+ Message
72
+ } from 'react-native-executorch';
73
+
74
+ function MyComponent() {
75
+ // Initialize the model 🚀
76
+ const llm = useLLM({ model: LLAMA3_2_1B });
77
+ // ... rest of your component
78
+ }
79
+ ```
80
+
81
+ ### :three: **Run the model!**
82
+
83
+ ```tsx
84
+ const handleGenerate = async () => {
85
+ const chat: Message[] = [
86
+ { role: 'system', content: 'You are a helpful assistant' },
87
+ { role: 'user', content: 'What is the meaning of life?' }
88
+ ];
89
+
90
+ // Chat completion
91
+ await llm.generate(chat);
92
+ console.log('Llama says:', llm.response);
93
+ };
94
+ ```
95
+
96
+ ## :calling: Examples
97
+
98
+ We currently host a few example [apps](https://github.com/software-mansion/react-native-executorch/tree/main/apps) demonstrating use cases of our library:
99
+
100
+ - `llm` - Chat application showcasing use of LLMs
101
+ - `speech-to-text` - Whisper and Moonshine models ready for transcription tasks
102
+ - `computer-vision` - Computer vision related tasks
103
+ - `text-embeddings` - Computing text representations for semantic search
104
+
105
+ If you would like to run demo app, navigate to its project directory and install dependencies with:
106
+
107
+ ```bash
108
+ yarn
109
+ ```
110
+
111
+ Then, depending on the platform, choose either iOS or Android:
112
+
113
+ ```bash
114
+ yarn expo run:< ios | android >
115
+ ```
116
+
117
+ > [!WARNING]
118
+ > Running LLMs requires a significant amount of RAM. If you are encountering unexpected app crashes, try to increase the amount of RAM allocated to the emulator.
119
+
120
+ ## :balance_scale: License
121
+
122
+ This library is licensed under [The MIT License](./LICENSE).
123
+
124
+ ## :soon: What's next?
125
+
126
+ To learn about our upcoming plans and developments, please visit our [milestones](https://github.com/software-mansion/react-native-executorch/milestones).
127
+
128
+ ## React Native ExecuTorch is created by Software Mansion
129
+
130
+ Since 2012, [Software Mansion](https://swmansion.com) is a software agency with experience in building web and mobile apps. We are Core React Native Contributors and experts in dealing with all kinds of React Native issues. We can help you build your next dream product – [Hire us](https://swmansion.com/contact/projects?utm_source=react-native-executorch&utm_medium=readme).
131
+
132
+ [![swm](https://logo.swmansion.com/logo?color=white&variant=desktop&width=150&tag=react-native-executorch-github 'Software Mansion')](https://swmansion.com)
@@ -1,4 +1,3 @@
1
- #include <rnexecutorch/models/speech_to_text/MoonshineStrategy.h>
2
1
  #include <rnexecutorch/models/speech_to_text/SpeechToText.h>
3
2
  #include <rnexecutorch/models/speech_to_text/WhisperStrategy.h>
4
3
  #include <stdexcept>
@@ -19,11 +18,9 @@ SpeechToText::SpeechToText(const std::string &encoderPath,
19
18
  void SpeechToText::initializeStrategy() {
20
19
  if (modelName == "whisper") {
21
20
  strategy = std::make_unique<WhisperStrategy>();
22
- } else if (modelName == "moonshine") {
23
- strategy = std::make_unique<MoonshineStrategy>();
24
21
  } else {
25
22
  throw std::runtime_error("Unsupported STT model: " + modelName +
26
- ". Only 'whisper' and 'moonshine' are supported.");
23
+ ". Only 'whisper' is supported.");
27
24
  }
28
25
  }
29
26
 
@@ -40,7 +37,8 @@ void SpeechToText::encode(std::span<float> waveform) {
40
37
  encoderOutput = result.get().at(0);
41
38
  }
42
39
 
43
- int64_t SpeechToText::decode(std::vector<int64_t> prevTokens) {
40
+ std::shared_ptr<OwningArrayBuffer>
41
+ SpeechToText::decode(std::vector<int64_t> prevTokens) {
44
42
  if (encoderOutput.isNone()) {
45
43
  throw std::runtime_error("Empty encodings on decode call, make sure to "
46
44
  "call encode() prior to decode()!");
@@ -49,9 +47,6 @@ int64_t SpeechToText::decode(std::vector<int64_t> prevTokens) {
49
47
  const auto prevTokensTensor = strategy->prepareTokenInput(prevTokens);
50
48
 
51
49
  const auto decoderMethod = strategy->getDecoderMethod();
52
- // BEWARE!!!
53
- // Moonshine will fail with invalid input if you pass large tokens i.e.
54
- // Whisper's BOS/EOS
55
50
  const auto decoderResult =
56
51
  decoder_->execute(decoderMethod, {prevTokensTensor, encoderOutput});
57
52
 
@@ -63,8 +58,7 @@ int64_t SpeechToText::decode(std::vector<int64_t> prevTokens) {
63
58
 
64
59
  const auto decoderOutputTensor = decoderResult.get().at(0).toTensor();
65
60
  const auto innerDim = decoderOutputTensor.size(1);
66
- return strategy->extractOutputToken(decoderOutputTensor.const_data_ptr(),
67
- innerDim);
61
+ return strategy->extractOutputToken(decoderOutputTensor);
68
62
  }
69
63
 
70
64
  } // namespace rnexecutorch
@@ -18,7 +18,7 @@ public:
18
18
  const std::string &modelName,
19
19
  std::shared_ptr<react::CallInvoker> callInvoker);
20
20
  void encode(std::span<float> waveform);
21
- int64_t decode(std::vector<int64_t> prevTokens);
21
+ std::shared_ptr<OwningArrayBuffer> decode(std::vector<int64_t> prevTokens);
22
22
 
23
23
  private:
24
24
  const std::string modelName;
@@ -1,6 +1,7 @@
1
1
  #pragma once
2
2
 
3
3
  #include "executorch/extension/tensor/tensor_ptr.h"
4
+ #include <rnexecutorch/host_objects/JSTensorViewOut.h>
4
5
  #include <span>
5
6
  #include <vector>
6
7
 
@@ -19,8 +20,8 @@ public:
19
20
 
20
21
  virtual std::string getDecoderMethod() const = 0;
21
22
 
22
- virtual int64_t extractOutputToken(const void *outputPtr,
23
- size_t innerDim) const = 0;
23
+ virtual std::shared_ptr<OwningArrayBuffer> extractOutputToken(
24
+ const executorch::aten::Tensor &decoderOutputTensor) const = 0;
24
25
  };
25
26
 
26
27
  } // namespace rnexecutorch
@@ -29,10 +29,22 @@ WhisperStrategy::prepareTokenInput(const std::vector<int64_t> &prevTokens) {
29
29
  return make_tensor_ptr(std::move(tensorSizes), std::move(tokens32));
30
30
  }
31
31
 
32
- int64_t WhisperStrategy::extractOutputToken(const void *outputPtr,
33
- size_t innerDim) const {
34
- const auto *data = static_cast<const int32_t *>(outputPtr);
35
- return static_cast<int64_t>(data[innerDim - 1]);
32
+ std::shared_ptr<OwningArrayBuffer> WhisperStrategy::extractOutputToken(
33
+ const executorch::aten::Tensor &decoderOutputTensor) const {
34
+ const auto innerDim = decoderOutputTensor.size(1);
35
+ const auto dictSize = decoderOutputTensor.size(2);
36
+ auto outputNumel = decoderOutputTensor.numel();
37
+ auto dataPtr =
38
+ static_cast<const float *>(decoderOutputTensor.const_data_ptr()) +
39
+ (innerDim - 1) * dictSize;
40
+
41
+ std::span<const float> modelOutput(dataPtr, outputNumel / innerDim);
42
+ auto createBuffer = [](const auto &data, size_t size) {
43
+ auto buffer = std::make_shared<OwningArrayBuffer>(size);
44
+ std::memcpy(buffer->data(), data, size);
45
+ return buffer;
46
+ };
47
+ return createBuffer(modelOutput.data(), modelOutput.size_bytes());
36
48
  }
37
49
 
38
50
  } // namespace rnexecutorch
@@ -14,8 +14,8 @@ public:
14
14
 
15
15
  std::string getDecoderMethod() const override { return "forward"; }
16
16
 
17
- int64_t extractOutputToken(const void *outputPtr,
18
- size_t innerDim) const override;
17
+ std::shared_ptr<OwningArrayBuffer> extractOutputToken(
18
+ const executorch::aten::Tensor &decoderOutputTensor) const override;
19
19
 
20
20
  private:
21
21
  std::vector<float> preprocessedData;
package/lib/Error.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ export declare enum ETError {
2
+ UndefinedError = 101,
3
+ ModuleNotLoaded = 102,
4
+ FileWriteFailed = 103,
5
+ ModelGenerating = 104,
6
+ LanguageNotSupported = 105,
7
+ InvalidModelSource = 255,
8
+ MultilingualConfiguration = 160,
9
+ MissingDataChunk = 161,
10
+ StreamingNotStarted = 162,
11
+ Ok = 0,
12
+ Internal = 1,
13
+ InvalidState = 2,
14
+ EndOfMethod = 3,
15
+ NotSupported = 16,
16
+ NotImplemented = 17,
17
+ InvalidArgument = 18,
18
+ InvalidType = 19,
19
+ OperatorMissing = 20,
20
+ NotFound = 32,
21
+ MemoryAllocationFailed = 33,
22
+ AccessFailed = 34,
23
+ InvalidProgram = 35,
24
+ InvalidExternalData = 36,
25
+ OutOfResources = 37,
26
+ DelegateInvalidCompatibility = 48,
27
+ DelegateMemoryAllocationFailed = 49,
28
+ DelegateInvalidHandle = 50
29
+ }
30
+ export declare const getError: (e: unknown | ETError | Error) => string;
package/lib/Error.js ADDED
@@ -0,0 +1,50 @@
1
+ export var ETError;
2
+ (function (ETError) {
3
+ // React-native-ExecuTorch errors
4
+ ETError[ETError["UndefinedError"] = 101] = "UndefinedError";
5
+ ETError[ETError["ModuleNotLoaded"] = 102] = "ModuleNotLoaded";
6
+ ETError[ETError["FileWriteFailed"] = 103] = "FileWriteFailed";
7
+ ETError[ETError["ModelGenerating"] = 104] = "ModelGenerating";
8
+ ETError[ETError["LanguageNotSupported"] = 105] = "LanguageNotSupported";
9
+ ETError[ETError["InvalidModelSource"] = 255] = "InvalidModelSource";
10
+ // SpeechToText errors
11
+ ETError[ETError["MultilingualConfiguration"] = 160] = "MultilingualConfiguration";
12
+ ETError[ETError["MissingDataChunk"] = 161] = "MissingDataChunk";
13
+ ETError[ETError["StreamingNotStarted"] = 162] = "StreamingNotStarted";
14
+ // ExecuTorch mapped errors
15
+ // Based on: https://github.com/pytorch/executorch/blob/main/runtime/core/error.h
16
+ // System errors
17
+ ETError[ETError["Ok"] = 0] = "Ok";
18
+ ETError[ETError["Internal"] = 1] = "Internal";
19
+ ETError[ETError["InvalidState"] = 2] = "InvalidState";
20
+ ETError[ETError["EndOfMethod"] = 3] = "EndOfMethod";
21
+ // Logical errors
22
+ ETError[ETError["NotSupported"] = 16] = "NotSupported";
23
+ ETError[ETError["NotImplemented"] = 17] = "NotImplemented";
24
+ ETError[ETError["InvalidArgument"] = 18] = "InvalidArgument";
25
+ ETError[ETError["InvalidType"] = 19] = "InvalidType";
26
+ ETError[ETError["OperatorMissing"] = 20] = "OperatorMissing";
27
+ // Resource errors
28
+ ETError[ETError["NotFound"] = 32] = "NotFound";
29
+ ETError[ETError["MemoryAllocationFailed"] = 33] = "MemoryAllocationFailed";
30
+ ETError[ETError["AccessFailed"] = 34] = "AccessFailed";
31
+ ETError[ETError["InvalidProgram"] = 35] = "InvalidProgram";
32
+ ETError[ETError["InvalidExternalData"] = 36] = "InvalidExternalData";
33
+ ETError[ETError["OutOfResources"] = 37] = "OutOfResources";
34
+ // Delegate errors
35
+ ETError[ETError["DelegateInvalidCompatibility"] = 48] = "DelegateInvalidCompatibility";
36
+ ETError[ETError["DelegateMemoryAllocationFailed"] = 49] = "DelegateMemoryAllocationFailed";
37
+ ETError[ETError["DelegateInvalidHandle"] = 50] = "DelegateInvalidHandle";
38
+ })(ETError || (ETError = {}));
39
+ export const getError = (e) => {
40
+ if (typeof e === 'number') {
41
+ return ETError[e] ?? ETError[ETError.UndefinedError];
42
+ }
43
+ // try to extract number from message (can contain false positives)
44
+ const error = e;
45
+ const errorCode = parseInt(error.message, 10);
46
+ if (Number.isNaN(errorCode)) {
47
+ return error.message;
48
+ }
49
+ return ETError[errorCode] ?? ETError[ETError.UndefinedError];
50
+ };
@@ -0,0 +1 @@
1
+ export declare const RNEDirectory: string;
@@ -0,0 +1,2 @@
1
+ import { documentDirectory } from 'expo-file-system';
2
+ export const RNEDirectory = `${documentDirectory}react-native-executorch/`;
@@ -0,0 +1,6 @@
1
+ import { ChatConfig, Message } from '../types/llm';
2
+ export declare const DEFAULT_SYSTEM_PROMPT = "You are a knowledgeable, efficient, and direct AI assistant. Provide concise answers, focusing on the key information needed. Offer suggestions tactfully when appropriate to improve outcomes. Engage in productive collaboration with the user. Don't return too much text.";
3
+ export declare const DEFAULT_STRUCTURED_OUTPUT_PROMPT: (structuredOutputSchema: string) => string;
4
+ export declare const DEFAULT_MESSAGE_HISTORY: Message[];
5
+ export declare const DEFAULT_CONTEXT_WINDOW_LENGTH = 5;
6
+ export declare const DEFAULT_CHAT_CONFIG: ChatConfig;
@@ -0,0 +1,16 @@
1
+ export const DEFAULT_SYSTEM_PROMPT = "You are a knowledgeable, efficient, and direct AI assistant. Provide concise answers, focusing on the key information needed. Offer suggestions tactfully when appropriate to improve outcomes. Engage in productive collaboration with the user. Don't return too much text.";
2
+ export const DEFAULT_STRUCTURED_OUTPUT_PROMPT = (structuredOutputSchema) => `The output should be formatted as a JSON instance that conforms to the JSON schema below.
3
+
4
+ As an example, for the schema {"properties": {"foo": {"title": "Foo", "description": "a list of strings", "type": "array", "items": {"type": "string"}}}, "required": ["foo"]}
5
+ the object {"foo": ["bar", "baz"]} is a well-formatted instance of the schema. The object {"properties": {"foo": ["bar", "baz"]}} is not well-formatted.
6
+
7
+ Here is the output schema:
8
+ ${structuredOutputSchema}
9
+ `;
10
+ export const DEFAULT_MESSAGE_HISTORY = [];
11
+ export const DEFAULT_CONTEXT_WINDOW_LENGTH = 5;
12
+ export const DEFAULT_CHAT_CONFIG = {
13
+ systemPrompt: DEFAULT_SYSTEM_PROMPT,
14
+ initialMessageHistory: DEFAULT_MESSAGE_HISTORY,
15
+ contextWindowLength: DEFAULT_CONTEXT_WINDOW_LENGTH,
16
+ };