@mailwoman/sentencepiece-wasm 8.4.0
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.
- package/binding.cpp +119 -0
- package/build.sh +86 -0
- package/index.d.ts +68 -0
- package/package.json +34 -0
- package/sentencepiece.mjs +0 -0
package/binding.cpp
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Embind wrapper for google/sentencepiece v0.2.2 — the mailwoman tokenizer's WASM core (task #26,
|
|
7
|
+
* the SP 0.2.2 native-offsets lever from the 2026-07-30 Latin tokenizer survey).
|
|
8
|
+
*
|
|
9
|
+
* Why this exists: the previous runtime (`@sctg/sentencepiece-js`, an emscripten build of an older
|
|
10
|
+
* sentencepiece) exposed pieces + ids but never bound the offset-carrying proto API, forcing
|
|
11
|
+
* `neural/tokenizer.ts` to RECONSTRUCT char offsets by re-walking the input — the source of the
|
|
12
|
+
* byte-fallback desync class and the documented surrogate-pair deferral. SentencePiece itself has
|
|
13
|
+
* always known the answer: `Encode(text, &SentencePieceText)` yields per-piece `begin`/`end` BYTE
|
|
14
|
+
* offsets with the documented invariant `text.substr(begin, end - begin) == surface` and
|
|
15
|
+
* contiguity between consecutive pieces. This wrapper binds exactly that.
|
|
16
|
+
*
|
|
17
|
+
* API surface (deliberately minimal — one class, three methods):
|
|
18
|
+
*
|
|
19
|
+
* - `loadFromSerializedProto(bytes)` — load a `tokenizer.model` from bytes; returns "" on success,
|
|
20
|
+
* the status message on failure (no exceptions across the WASM boundary).
|
|
21
|
+
* - `encodeWithOffsets(text)` — returns { pieces: string[], ids: Int32Array-like, begins, ends }
|
|
22
|
+
* where begins/ends are UTF-8 BYTE offsets into the input. The TS layer owns the byte→UTF-16
|
|
23
|
+
* conversion (exact, via a code-point walk — see neural/tokenizer.ts).
|
|
24
|
+
* - `decodeIds(ids)` — detokenize back to a string.
|
|
25
|
+
*
|
|
26
|
+
* Build: `./build.sh` (fetches sentencepiece at the pinned tag, emcmake+emmake, links this file
|
|
27
|
+
* with embind, emits the committed single-file ESM artifact `sentencepiece.mjs`).
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
#include <emscripten/bind.h>
|
|
31
|
+
#include <emscripten/val.h>
|
|
32
|
+
|
|
33
|
+
#include <cstdint>
|
|
34
|
+
#include <string>
|
|
35
|
+
#include <vector>
|
|
36
|
+
|
|
37
|
+
#include "builtin_pb/sentencepiece.pb.h"
|
|
38
|
+
#include "sentencepiece_processor.h"
|
|
39
|
+
|
|
40
|
+
namespace {
|
|
41
|
+
|
|
42
|
+
class SentencePieceWASM {
|
|
43
|
+
public:
|
|
44
|
+
/**
|
|
45
|
+
* Load a tokenizer.model from its serialized-proto bytes (a JS Uint8Array). Returns "" on
|
|
46
|
+
* success, the status message on failure — errors cross the WASM boundary as values, never
|
|
47
|
+
* exceptions. NOTE the parameter is emscripten::val, NOT std::string: embind marshals JS
|
|
48
|
+
* strings to std::string as UTF-8, which corrupts arbitrary binary — the exact trap that made
|
|
49
|
+
* the first smoke fail to parse the model proto.
|
|
50
|
+
*/
|
|
51
|
+
std::string loadFromSerializedProto(const emscripten::val& data) {
|
|
52
|
+
const std::vector<uint8_t> bytes = emscripten::convertJSArrayToNumberVector<uint8_t>(data);
|
|
53
|
+
const auto status = processor_.LoadFromSerializedProto(
|
|
54
|
+
absl::string_view(reinterpret_cast<const char*>(bytes.data()), bytes.size()));
|
|
55
|
+
return status.ok() ? std::string() : std::string(status.message());
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Encode with native offsets. Returns a JS object:
|
|
60
|
+
* { pieces: string[], ids: number[], begins: number[], ends: number[] } — begins/ends are byte
|
|
61
|
+
* offsets into the UTF-8 encoding of `text` (the exact bytes embind marshalled in).
|
|
62
|
+
*/
|
|
63
|
+
emscripten::val encodeWithOffsets(const std::string& text) const {
|
|
64
|
+
sentencepiece::SentencePieceText spt;
|
|
65
|
+
const auto status = processor_.Encode(text, &spt);
|
|
66
|
+
|
|
67
|
+
emscripten::val result = emscripten::val::object();
|
|
68
|
+
|
|
69
|
+
if (!status.ok()) {
|
|
70
|
+
result.set("error", std::string(status.message()));
|
|
71
|
+
return result;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const int n = spt.pieces_size();
|
|
75
|
+
emscripten::val pieces = emscripten::val::array();
|
|
76
|
+
emscripten::val ids = emscripten::val::array();
|
|
77
|
+
emscripten::val begins = emscripten::val::array();
|
|
78
|
+
emscripten::val ends = emscripten::val::array();
|
|
79
|
+
|
|
80
|
+
for (int i = 0; i < n; i++) {
|
|
81
|
+
const auto& p = spt.pieces(i);
|
|
82
|
+
pieces.set(i, p.piece());
|
|
83
|
+
ids.set(i, p.id());
|
|
84
|
+
begins.set(i, p.begin());
|
|
85
|
+
ends.set(i, p.end());
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
result.set("pieces", pieces);
|
|
89
|
+
result.set("ids", ids);
|
|
90
|
+
result.set("begins", begins);
|
|
91
|
+
result.set("ends", ends);
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Detokenize ids back to text. Invalid ids surface as the empty string plus the error field on
|
|
97
|
+
* the wrapper's contract being violated upstream — the TS layer validates lengths.
|
|
98
|
+
*/
|
|
99
|
+
std::string decodeIds(const std::vector<int>& ids) const {
|
|
100
|
+
std::string out;
|
|
101
|
+
const auto status = processor_.Decode(ids, &out);
|
|
102
|
+
return status.ok() ? out : std::string();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private:
|
|
106
|
+
sentencepiece::SentencePieceProcessor processor_;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
} // namespace
|
|
110
|
+
|
|
111
|
+
EMSCRIPTEN_BINDINGS(sentencepiece_wasm) {
|
|
112
|
+
emscripten::register_vector<int>("IntVector");
|
|
113
|
+
|
|
114
|
+
emscripten::class_<SentencePieceWASM>("SentencePieceProcessor")
|
|
115
|
+
.constructor<>()
|
|
116
|
+
.function("loadFromSerializedProto", &SentencePieceWASM::loadFromSerializedProto)
|
|
117
|
+
.function("encodeWithOffsets", &SentencePieceWASM::encodeWithOffsets)
|
|
118
|
+
.function("decodeIds", &SentencePieceWASM::decodeIds);
|
|
119
|
+
}
|
package/build.sh
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
#
|
|
3
|
+
# @copyright Sister Software
|
|
4
|
+
# @license AGPL-3.0
|
|
5
|
+
# @author Teffen Ellis, et al.
|
|
6
|
+
#
|
|
7
|
+
# Build the committed `sentencepiece.mjs` artifact: google/sentencepiece at the PINNED tag below,
|
|
8
|
+
# compiled to WASM with emscripten and linked against binding.cpp (the embind wrapper exposing
|
|
9
|
+
# native per-piece byte offsets — task #26).
|
|
10
|
+
#
|
|
11
|
+
# The artifact is COMMITTED (like core/data's reference blobs): consumers import
|
|
12
|
+
# `@mailwoman/sentencepiece-wasm` as a plain dependency and never need emscripten. Re-run this
|
|
13
|
+
# script only to bump the sentencepiece tag or change the binding; commit the regenerated .mjs in
|
|
14
|
+
# the same PR and note the tag bump in the header of index.d.ts.
|
|
15
|
+
#
|
|
16
|
+
# Prereqs: emsdk activated (`source ~/tools/emsdk/emsdk_env.sh`), cmake, git. The sentencepiece
|
|
17
|
+
# checkout is cached OUTSIDE the repo (a toolchain input, not a repo artifact).
|
|
18
|
+
#
|
|
19
|
+
# Single-file output on purpose: -sSINGLE_FILE=1 embeds the wasm as base64 in the .mjs, matching
|
|
20
|
+
# how the previous runtime (@sctg/sentencepiece-js) shipped — no separate .wasm delivery path to
|
|
21
|
+
# thread through neural-web, the docs demo, or the drop-in APIs. The size cost (~4/3× the wasm) is
|
|
22
|
+
# accepted; the artifact is fetched once and cached.
|
|
23
|
+
|
|
24
|
+
set -euo pipefail
|
|
25
|
+
|
|
26
|
+
# The pin. corpus-python trains with `sentencepiece>=0.2.2` — the runtime MUST tokenize
|
|
27
|
+
# byte-identically to the trainer, so the tags travel together (see project-tokenizer-mismatch).
|
|
28
|
+
SP_TAG="v0.2.2"
|
|
29
|
+
|
|
30
|
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
31
|
+
SP_SRC="${SENTENCEPIECE_SRC:-$HOME/tools/sentencepiece}"
|
|
32
|
+
BUILD_DIR="$SP_SRC/build-wasm"
|
|
33
|
+
|
|
34
|
+
command -v emcc > /dev/null || {
|
|
35
|
+
echo "emcc not found — source the emsdk env first (see header)." >&2
|
|
36
|
+
exit 1
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if [ ! -d "$SP_SRC" ]; then
|
|
40
|
+
git clone https://github.com/google/sentencepiece.git "$SP_SRC"
|
|
41
|
+
fi
|
|
42
|
+
|
|
43
|
+
git -C "$SP_SRC" fetch --tags
|
|
44
|
+
git -C "$SP_SRC" checkout "$SP_TAG"
|
|
45
|
+
|
|
46
|
+
# Static library build. SPM_ENABLE_SHARED=OFF is required under emscripten; the TCMalloc probe is
|
|
47
|
+
# meaningless in WASM.
|
|
48
|
+
emcmake cmake -S "$SP_SRC" -B "$BUILD_DIR" \
|
|
49
|
+
-DCMAKE_BUILD_TYPE=Release \
|
|
50
|
+
-DSPM_ENABLE_SHARED=OFF \
|
|
51
|
+
-DSPM_ENABLE_TCMALLOC=OFF > /dev/null
|
|
52
|
+
|
|
53
|
+
# Full build (not just sentencepiece-static): v0.2.2 links against the vendored abseil-cpp, whose
|
|
54
|
+
# ~90 small static libs only materialize with the default target set.
|
|
55
|
+
cmake --build "$BUILD_DIR" -j "$(nproc)" > /dev/null
|
|
56
|
+
|
|
57
|
+
# Every abseil archive joins the link line — wasm-ld's resolution across this many inter-dependent
|
|
58
|
+
# archives is handled by listing them all; the dead ones are dropped by -Oz + gc-sections anyway.
|
|
59
|
+
ABSL_LIBS=$(find "$BUILD_DIR/third_party/abseil-cpp" -name "*.a" | sort)
|
|
60
|
+
|
|
61
|
+
# Link the binding. Notes on the flags:
|
|
62
|
+
# - MODULARIZE + EXPORT_ES6: the artifact default-exports an async factory (createSentencePiece).
|
|
63
|
+
# - SINGLE_FILE: wasm embedded as base64 (see header).
|
|
64
|
+
# - ENVIRONMENT=web,webview,worker,node: every consumer surface (browser demo, workers, Node CLI).
|
|
65
|
+
# - ALLOW_MEMORY_GROWTH: tokenizer.model is ~1.6MB and encode allocations scale with input length.
|
|
66
|
+
# - DISABLE_EXCEPTION_CATCHING=0: protobuf-lite + sentencepiece throw in cold error paths; without
|
|
67
|
+
# catching enabled a bad model file ABORTS the runtime instead of returning a status.
|
|
68
|
+
# - FILESYSTEM=0: only LoadFromSerializedProto is bound — no FS use anywhere.
|
|
69
|
+
emcc "$SCRIPT_DIR/binding.cpp" \
|
|
70
|
+
-I "$SP_SRC/src" -I "$SP_SRC" -I "$SP_SRC/third_party/abseil-cpp" -I "$SP_SRC/third_party/protobuf-lite" -I "$SP_SRC/src/builtin_pb" -I "$BUILD_DIR" \
|
|
71
|
+
"$BUILD_DIR/src/libsentencepiece.a" \
|
|
72
|
+
$ABSL_LIBS \
|
|
73
|
+
-Oz \
|
|
74
|
+
-lembind \
|
|
75
|
+
-sMODULARIZE=1 \
|
|
76
|
+
-sEXPORT_ES6=1 \
|
|
77
|
+
-sEXPORT_NAME=createSentencePiece \
|
|
78
|
+
-sSINGLE_FILE=1 \
|
|
79
|
+
-sALLOW_MEMORY_GROWTH=1 \
|
|
80
|
+
-sENVIRONMENT=web,webview,worker,node \
|
|
81
|
+
-sDISABLE_EXCEPTION_CATCHING=0 \
|
|
82
|
+
-sFILESYSTEM=0 \
|
|
83
|
+
-o "$SCRIPT_DIR/sentencepiece.mjs"
|
|
84
|
+
|
|
85
|
+
echo "Built $SCRIPT_DIR/sentencepiece.mjs from sentencepiece $SP_TAG:"
|
|
86
|
+
ls -la "$SCRIPT_DIR/sentencepiece.mjs"
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Type surface of the committed `sentencepiece.mjs` artifact — google/sentencepiece **v0.2.2**
|
|
7
|
+
* compiled to WASM with the native-offsets embind wrapper (`binding.cpp`, task #26). Rebuilt only
|
|
8
|
+
* by `build.sh`; bump the tag there and note it here.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* One encode result. `begins`/`ends` are UTF-8 BYTE offsets into the encoded input with the upstream invariant
|
|
13
|
+
* `utf8(text).slice(begins[i], ends[i])` = the piece's surface, and contiguity between consecutive pieces. The TS
|
|
14
|
+
* tokenizer layer owns byte→UTF-16 conversion.
|
|
15
|
+
*/
|
|
16
|
+
export interface EncodeWithOffsetsResult {
|
|
17
|
+
pieces: string[]
|
|
18
|
+
ids: number[]
|
|
19
|
+
begins: number[]
|
|
20
|
+
ends: number[]
|
|
21
|
+
/**
|
|
22
|
+
* Present INSTEAD of the arrays when encoding failed (errors cross the boundary as values).
|
|
23
|
+
*/
|
|
24
|
+
error?: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The bound processor. Construct via the module factory, then `loadFromSerializedProto` once.
|
|
29
|
+
*/
|
|
30
|
+
export declare class SentencePieceProcessor {
|
|
31
|
+
constructor()
|
|
32
|
+
/**
|
|
33
|
+
* Load a `tokenizer.model` from its serialized-proto bytes. Takes a `Uint8Array` — the binding deliberately does NOT
|
|
34
|
+
* accept a string (embind marshals JS strings to `std::string` as UTF-8, which corrupts arbitrary binary). Returns
|
|
35
|
+
* `""` on success, the sentencepiece status message on failure.
|
|
36
|
+
*/
|
|
37
|
+
loadFromSerializedProto(serialized: Uint8Array): string
|
|
38
|
+
encodeWithOffsets(text: string): EncodeWithOffsetsResult
|
|
39
|
+
decodeIds(ids: IntVector): string
|
|
40
|
+
/**
|
|
41
|
+
* Embind object lifetime: the processor owns WASM-heap memory — call when done (long-lived singletons in practice
|
|
42
|
+
* never do).
|
|
43
|
+
*/
|
|
44
|
+
delete(): void
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Embind-registered `std::vector<int>` — build with `module.IntVector`, `push_back` ids, and `delete()` after use.
|
|
49
|
+
*/
|
|
50
|
+
export declare class IntVector {
|
|
51
|
+
constructor()
|
|
52
|
+
push_back(value: number): void
|
|
53
|
+
size(): number
|
|
54
|
+
get(index: number): number
|
|
55
|
+
delete(): void
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface SentencePieceModule {
|
|
59
|
+
SentencePieceProcessor: typeof SentencePieceProcessor
|
|
60
|
+
IntVector: typeof IntVector
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The emscripten MODULARIZE factory — resolves once the embedded WASM is instantiated.
|
|
65
|
+
*/
|
|
66
|
+
declare function createSentencePiece(): Promise<SentencePieceModule>
|
|
67
|
+
|
|
68
|
+
export default createSentencePiece
|
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@mailwoman/sentencepiece-wasm",
|
|
3
|
+
"version": "8.4.0",
|
|
4
|
+
"description": "google/sentencepiece v0.2.2 compiled to WASM with a native-offsets binding — the tokenizer core for @mailwoman/neural. Single-file ESM (wasm embedded), no runtime deps; per-piece byte offsets come from SentencePiece itself instead of TS-side reconstruction.",
|
|
5
|
+
"license": "AGPL-3.0-only OR LicenseRef-Commercial",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/sister-software/mailwoman.git",
|
|
9
|
+
"directory": "sentencepiece-wasm"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"sentencepiece.mjs",
|
|
13
|
+
"index.d.ts",
|
|
14
|
+
"binding.cpp",
|
|
15
|
+
"build.sh"
|
|
16
|
+
],
|
|
17
|
+
"type": "module",
|
|
18
|
+
"exports": {
|
|
19
|
+
"./package.json": "./package.json",
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./index.d.ts",
|
|
22
|
+
"default": "./sentencepiece.mjs"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"exports": {
|
|
27
|
+
"./package.json": "./package.json",
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./index.d.ts",
|
|
30
|
+
"default": "./sentencepiece.mjs"
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
Binary file
|