|
| 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 <emscripten.h> |
| 10 | +#include <emscripten/bind.h> |
| 11 | +#include <executorch/runtime/platform/compiler.h> |
| 12 | +#include <pytorch/tokenizers/hf_tokenizer.h> |
| 13 | +#include <pytorch/tokenizers/llama2c_tokenizer.h> |
| 14 | +#include <pytorch/tokenizers/sentencepiece.h> |
| 15 | +#include <pytorch/tokenizers/tekken.h> |
| 16 | +#include <pytorch/tokenizers/tiktoken.h> |
| 17 | +#include <cstdio> |
| 18 | + |
| 19 | +using namespace emscripten; |
| 20 | +using tokenizers::Error; |
| 21 | +using tokenizers::HFTokenizer; |
| 22 | +using tokenizers::Llama2cTokenizer; |
| 23 | +using tokenizers::SPTokenizer; |
| 24 | +using tokenizers::Tekken; |
| 25 | +using tokenizers::Tiktoken; |
| 26 | +using tokenizers::Tokenizer; |
| 27 | + |
| 28 | +#define THROW_JS_ERROR(errorType, message, ...) \ |
| 29 | + ({ \ |
| 30 | + char msg_buf[256]; \ |
| 31 | + int len = snprintf(msg_buf, sizeof(msg_buf), message, ##__VA_ARGS__); \ |
| 32 | + if (len < sizeof(msg_buf)) { \ |
| 33 | + EM_ASM(throw new errorType(UTF8ToString($0)), msg_buf); \ |
| 34 | + } else { \ |
| 35 | + std::string msg; \ |
| 36 | + msg.resize(len); \ |
| 37 | + snprintf(&msg[0], len + 1, message, ##__VA_ARGS__); \ |
| 38 | + EM_ASM(throw new errorType(UTF8ToString($0)), msg.c_str()); \ |
| 39 | + } \ |
| 40 | + __builtin_unreachable(); \ |
| 41 | + }) |
| 42 | + |
| 43 | +/// Throws a JavaScript Error with the provided message if `error` is not `Ok`. |
| 44 | +#define THROW_IF_ERROR(error, message, ...) \ |
| 45 | + ({ \ |
| 46 | + if ET_UNLIKELY ((error) != Error::Ok) { \ |
| 47 | + THROW_JS_ERROR(Error, message, ##__VA_ARGS__); \ |
| 48 | + } \ |
| 49 | + }) |
| 50 | + |
| 51 | +namespace executorch { |
| 52 | +namespace extension { |
| 53 | +namespace wasm { |
| 54 | +namespace tokenizers { |
| 55 | + |
| 56 | +namespace { |
| 57 | + |
| 58 | +#define JS_FORALL_TOKENIZERS(_) \ |
| 59 | + _(HFTokenizer) \ |
| 60 | + _(Tiktoken) \ |
| 61 | + _(SPTokenizer) \ |
| 62 | + _(Llama2cTokenizer) \ |
| 63 | + _(Tekken) |
| 64 | + |
| 65 | +/** |
| 66 | + * EXPERIMENTAL: JavaScript wrapper for Tokenizer. |
| 67 | + */ |
| 68 | +template <typename T> |
| 69 | +class ET_EXPERIMENTAL JsTokenizer { |
| 70 | + static_assert( |
| 71 | + std::is_base_of<Tokenizer, T>::value, |
| 72 | + "T must be a subclass of Tokenizer"); |
| 73 | + |
| 74 | + public: |
| 75 | + JsTokenizer() : tokenizer_(std::make_unique<T>()) {} |
| 76 | + JsTokenizer(const JsTokenizer&) = delete; |
| 77 | + JsTokenizer& operator=(const JsTokenizer&) = delete; |
| 78 | + JsTokenizer(JsTokenizer&&) = default; |
| 79 | + JsTokenizer& operator=(JsTokenizer&&) = default; |
| 80 | + |
| 81 | + void load_from_uint8_array(val data) { |
| 82 | + // Tokenizer API can't load from a buffer, so we need to write the buffer to |
| 83 | + // a temporary file and load from there. |
| 84 | + static const char* tmpFileName = "tokenizer_input_buffer.tmp"; |
| 85 | + FILE* tmp_file = fopen(tmpFileName, "wb"); |
| 86 | + if (tmp_file == nullptr) { |
| 87 | + THROW_JS_ERROR(Error, "Failed to open file"); |
| 88 | + } |
| 89 | + size_t length = data["length"].as<size_t>(); |
| 90 | + std::vector<uint8_t> buffer(length); |
| 91 | + val memory_view = val(typed_memory_view(length, buffer.data())); |
| 92 | + memory_view.call<void>("set", data); |
| 93 | + fwrite(buffer.data(), sizeof(uint8_t), length, tmp_file); |
| 94 | + fclose(tmp_file); |
| 95 | + Error error = tokenizer_->load(tmpFileName); |
| 96 | + THROW_IF_ERROR(error, "Failed to load tokenizer"); |
| 97 | + remove(tmpFileName); |
| 98 | + } |
| 99 | + |
| 100 | + void load(val data) { |
| 101 | + if (data.isString()) { |
| 102 | + Error error = tokenizer_->load(data.as<std::string>()); |
| 103 | + THROW_IF_ERROR(error, "Failed to load tokenizer"); |
| 104 | + } else if (data.instanceof (val::global("Uint8Array"))) { |
| 105 | + return load_from_uint8_array(data); |
| 106 | + } else if (data.instanceof (val::global("ArrayBuffer"))) { |
| 107 | + return load_from_uint8_array(val::global("Uint8Array").new_(data)); |
| 108 | + } else { |
| 109 | + THROW_JS_ERROR( |
| 110 | + TypeError, |
| 111 | + "Unsupported data type: %s", |
| 112 | + data.typeOf().as<std::string>().c_str()); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + val encode(const std::string& text, int8_t bos, int8_t eos) const { |
| 117 | + auto res = tokenizer_->encode(text, bos, eos); |
| 118 | + THROW_IF_ERROR(res.error(), "Failed to encode text"); |
| 119 | + return val::array(res.get().begin(), res.get().end()); |
| 120 | + } |
| 121 | + |
| 122 | + val encode(const std::string& text, int8_t bos) const { |
| 123 | + return encode(text, bos, 0); |
| 124 | + } |
| 125 | + |
| 126 | + val encode(const std::string& text) const { |
| 127 | + return encode(text, 0); |
| 128 | + } |
| 129 | + |
| 130 | + std::string decode(uint64_t prev, uint64_t current) const { |
| 131 | + auto res = tokenizer_->decode(prev, current); |
| 132 | + THROW_IF_ERROR(res.error(), "Failed to decode token"); |
| 133 | + return res.get(); |
| 134 | + } |
| 135 | + |
| 136 | + uint64_t vocab_size() const { |
| 137 | + return tokenizer_->vocab_size(); |
| 138 | + } |
| 139 | + |
| 140 | + uint64_t bos_tok() const { |
| 141 | + return tokenizer_->bos_tok(); |
| 142 | + } |
| 143 | + |
| 144 | + uint64_t eos_tok() const { |
| 145 | + return tokenizer_->eos_tok(); |
| 146 | + } |
| 147 | + |
| 148 | + bool is_loaded() const { |
| 149 | + return tokenizer_->is_loaded(); |
| 150 | + } |
| 151 | + |
| 152 | + private: |
| 153 | + std::unique_ptr<T> tokenizer_; |
| 154 | +}; |
| 155 | + |
| 156 | +} // namespace |
| 157 | + |
| 158 | +EMSCRIPTEN_BINDINGS(TokenizerModule) { |
| 159 | +#define JS_BIND_TOKENIZER(NAME) \ |
| 160 | + class_<JsTokenizer<NAME>>(#NAME) \ |
| 161 | + .constructor<>() \ |
| 162 | + .function("load", &JsTokenizer<NAME>::load) \ |
| 163 | + .function( \ |
| 164 | + "encode", \ |
| 165 | + select_overload<val(const std::string&) const>( \ |
| 166 | + &JsTokenizer<NAME>::encode)) \ |
| 167 | + .function( \ |
| 168 | + "encode", \ |
| 169 | + select_overload<val(const std::string&, int8_t) const>( \ |
| 170 | + &JsTokenizer<NAME>::encode)) \ |
| 171 | + .function( \ |
| 172 | + "encode", \ |
| 173 | + select_overload<val(const std::string&, int8_t, int8_t) const>( \ |
| 174 | + &JsTokenizer<NAME>::encode)) \ |
| 175 | + .function("decode", &JsTokenizer<NAME>::decode) \ |
| 176 | + .property("vocabSize", &JsTokenizer<NAME>::vocab_size) \ |
| 177 | + .property("bosTok", &JsTokenizer<NAME>::bos_tok) \ |
| 178 | + .property("eosTok", &JsTokenizer<NAME>::eos_tok) \ |
| 179 | + .property("isLoaded", &JsTokenizer<NAME>::is_loaded); |
| 180 | + JS_FORALL_TOKENIZERS(JS_BIND_TOKENIZER) |
| 181 | +} |
| 182 | + |
| 183 | +} // namespace tokenizers |
| 184 | +} // namespace wasm |
| 185 | +} // namespace extension |
| 186 | +} // namespace executorch |
0 commit comments