@huggingface/transformers 3.0.0-alpha.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.
Files changed (96) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +376 -0
  3. package/dist/ort-wasm-simd-threaded.jsep.wasm +0 -0
  4. package/dist/transformers.cjs +30741 -0
  5. package/dist/transformers.cjs.map +1 -0
  6. package/dist/transformers.js +33858 -0
  7. package/dist/transformers.js.map +1 -0
  8. package/dist/transformers.min.cjs +173 -0
  9. package/dist/transformers.min.cjs.map +1 -0
  10. package/dist/transformers.min.js +231 -0
  11. package/dist/transformers.min.js.map +1 -0
  12. package/package.json +92 -0
  13. package/src/backends/onnx.js +151 -0
  14. package/src/configs.js +360 -0
  15. package/src/env.js +152 -0
  16. package/src/generation/configuration_utils.js +381 -0
  17. package/src/generation/logits_process.js +716 -0
  18. package/src/generation/logits_sampler.js +204 -0
  19. package/src/generation/parameters.js +35 -0
  20. package/src/generation/stopping_criteria.js +156 -0
  21. package/src/generation/streamers.js +212 -0
  22. package/src/models/whisper/common_whisper.js +151 -0
  23. package/src/models/whisper/generation_whisper.js +89 -0
  24. package/src/models.js +7028 -0
  25. package/src/ops/registry.js +92 -0
  26. package/src/pipelines.js +3341 -0
  27. package/src/processors.js +2614 -0
  28. package/src/tokenizers.js +4395 -0
  29. package/src/transformers.js +28 -0
  30. package/src/utils/audio.js +704 -0
  31. package/src/utils/constants.js +2 -0
  32. package/src/utils/core.js +149 -0
  33. package/src/utils/data-structures.js +445 -0
  34. package/src/utils/devices.js +11 -0
  35. package/src/utils/dtypes.js +62 -0
  36. package/src/utils/generic.js +35 -0
  37. package/src/utils/hub.js +671 -0
  38. package/src/utils/image.js +745 -0
  39. package/src/utils/maths.js +1050 -0
  40. package/src/utils/tensor.js +1378 -0
  41. package/types/backends/onnx.d.ts +26 -0
  42. package/types/backends/onnx.d.ts.map +1 -0
  43. package/types/configs.d.ts +59 -0
  44. package/types/configs.d.ts.map +1 -0
  45. package/types/env.d.ts +106 -0
  46. package/types/env.d.ts.map +1 -0
  47. package/types/generation/configuration_utils.d.ts +320 -0
  48. package/types/generation/configuration_utils.d.ts.map +1 -0
  49. package/types/generation/logits_process.d.ts +354 -0
  50. package/types/generation/logits_process.d.ts.map +1 -0
  51. package/types/generation/logits_sampler.d.ts +51 -0
  52. package/types/generation/logits_sampler.d.ts.map +1 -0
  53. package/types/generation/parameters.d.ts +47 -0
  54. package/types/generation/parameters.d.ts.map +1 -0
  55. package/types/generation/stopping_criteria.d.ts +81 -0
  56. package/types/generation/stopping_criteria.d.ts.map +1 -0
  57. package/types/generation/streamers.d.ts +81 -0
  58. package/types/generation/streamers.d.ts.map +1 -0
  59. package/types/models/whisper/common_whisper.d.ts +8 -0
  60. package/types/models/whisper/common_whisper.d.ts.map +1 -0
  61. package/types/models/whisper/generation_whisper.d.ts +76 -0
  62. package/types/models/whisper/generation_whisper.d.ts.map +1 -0
  63. package/types/models.d.ts +3845 -0
  64. package/types/models.d.ts.map +1 -0
  65. package/types/ops/registry.d.ts +11 -0
  66. package/types/ops/registry.d.ts.map +1 -0
  67. package/types/pipelines.d.ts +2403 -0
  68. package/types/pipelines.d.ts.map +1 -0
  69. package/types/processors.d.ts +917 -0
  70. package/types/processors.d.ts.map +1 -0
  71. package/types/tokenizers.d.ts +999 -0
  72. package/types/tokenizers.d.ts.map +1 -0
  73. package/types/transformers.d.ts +13 -0
  74. package/types/transformers.d.ts.map +1 -0
  75. package/types/utils/audio.d.ts +130 -0
  76. package/types/utils/audio.d.ts.map +1 -0
  77. package/types/utils/constants.d.ts +2 -0
  78. package/types/utils/constants.d.ts.map +1 -0
  79. package/types/utils/core.d.ts +91 -0
  80. package/types/utils/core.d.ts.map +1 -0
  81. package/types/utils/data-structures.d.ts +236 -0
  82. package/types/utils/data-structures.d.ts.map +1 -0
  83. package/types/utils/devices.d.ts +8 -0
  84. package/types/utils/devices.d.ts.map +1 -0
  85. package/types/utils/dtypes.d.ts +22 -0
  86. package/types/utils/dtypes.d.ts.map +1 -0
  87. package/types/utils/generic.d.ts +11 -0
  88. package/types/utils/generic.d.ts.map +1 -0
  89. package/types/utils/hub.d.ts +191 -0
  90. package/types/utils/hub.d.ts.map +1 -0
  91. package/types/utils/image.d.ts +119 -0
  92. package/types/utils/image.d.ts.map +1 -0
  93. package/types/utils/maths.d.ts +280 -0
  94. package/types/utils/maths.d.ts.map +1 -0
  95. package/types/utils/tensor.d.ts +392 -0
  96. package/types/utils/tensor.d.ts.map +1 -0
@@ -0,0 +1,2 @@
1
+
2
+ export const GITHUB_ISSUE_URL = 'https://github.com/xenova/transformers.js/issues/new/choose';
@@ -0,0 +1,149 @@
1
+
2
+ /**
3
+ * @file Core utility functions/classes for Transformers.js.
4
+ *
5
+ * These are only used internally, meaning an end-user shouldn't
6
+ * need to access anything here.
7
+ *
8
+ * @module utils/core
9
+ */
10
+
11
+ /**
12
+ * Helper function to dispatch progress callbacks.
13
+ *
14
+ * @param {Function} progress_callback The progress callback function to dispatch.
15
+ * @param {any} data The data to pass to the progress callback function.
16
+ * @returns {void}
17
+ * @private
18
+ */
19
+ export function dispatchCallback(progress_callback, data) {
20
+ if (progress_callback) progress_callback(data);
21
+ }
22
+
23
+ /**
24
+ * Reverses the keys and values of an object.
25
+ *
26
+ * @param {Object} data The object to reverse.
27
+ * @returns {Object} The reversed object.
28
+ * @see https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
29
+ */
30
+ export function reverseDictionary(data) {
31
+ // https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
32
+ return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));
33
+ }
34
+
35
+ /**
36
+ * Escapes regular expression special characters from a string by replacing them with their escaped counterparts.
37
+ *
38
+ * @param {string} string The string to escape.
39
+ * @returns {string} The escaped string.
40
+ */
41
+ export function escapeRegExp(string) {
42
+ return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
43
+ }
44
+
45
+ /**
46
+ * Check if a value is a typed array.
47
+ * @param {*} val The value to check.
48
+ * @returns {boolean} True if the value is a `TypedArray`, false otherwise.
49
+ *
50
+ * Adapted from https://stackoverflow.com/a/71091338/13989043
51
+ */
52
+ export function isTypedArray(val) {
53
+ return val?.prototype?.__proto__?.constructor?.name === 'TypedArray';
54
+ }
55
+
56
+
57
+ /**
58
+ * Check if a value is an integer.
59
+ * @param {*} x The value to check.
60
+ * @returns {boolean} True if the value is a string, false otherwise.
61
+ */
62
+ export function isIntegralNumber(x) {
63
+ return Number.isInteger(x) || typeof x === 'bigint'
64
+ }
65
+
66
+ /**
67
+ * Calculates the dimensions of a nested array.
68
+ *
69
+ * @param {any[]} arr The nested array to calculate dimensions for.
70
+ * @returns {number[]} An array containing the dimensions of the input array.
71
+ */
72
+ export function calculateDimensions(arr) {
73
+ const dimensions = [];
74
+ let current = arr;
75
+ while (Array.isArray(current)) {
76
+ dimensions.push(current.length);
77
+ current = current[0];
78
+ }
79
+ return dimensions;
80
+ }
81
+
82
+ /**
83
+ * Replicate python's .pop() method for objects.
84
+ * @param {Object} obj The object to pop from.
85
+ * @param {string} key The key to pop.
86
+ * @param {*} defaultValue The default value to return if the key does not exist.
87
+ * @returns {*} The value of the popped key.
88
+ * @throws {Error} If the key does not exist and no default value is provided.
89
+ */
90
+ export function pop(obj, key, defaultValue = undefined) {
91
+ const value = obj[key];
92
+ if (value !== undefined) {
93
+ delete obj[key];
94
+ return value;
95
+ }
96
+ if (defaultValue === undefined) {
97
+ throw Error(`Key ${key} does not exist in object.`)
98
+ }
99
+ return defaultValue;
100
+ }
101
+
102
+ /**
103
+ * Efficiently merge arrays, creating a new copy.
104
+ * Adapted from https://stackoverflow.com/a/6768642/13989043
105
+ * @param {Array[]} arrs Arrays to merge.
106
+ * @returns {Array} The merged array.
107
+ */
108
+ export function mergeArrays(...arrs) {
109
+ return Array.prototype.concat.apply([], arrs);
110
+ }
111
+
112
+ /**
113
+ * Compute the Cartesian product of given arrays
114
+ * @param {...Array} a Arrays to compute the product
115
+ * @returns {Array} Returns the computed Cartesian product as an array
116
+ * @private
117
+ */
118
+ export function product(...a) {
119
+ // Cartesian product of items
120
+ // Adapted from https://stackoverflow.com/a/43053803
121
+ return a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e])));
122
+ }
123
+
124
+ /**
125
+ * Calculates the index offset for a given index and window size.
126
+ * @param {number} i The index.
127
+ * @param {number} w The window size.
128
+ * @returns {number} The index offset.
129
+ */
130
+ export function calculateReflectOffset(i, w) {
131
+ return Math.abs((i + w) % (2 * w) - w);
132
+ }
133
+
134
+ /**
135
+ *
136
+ * @param {Object} o
137
+ * @param {string[]} props
138
+ * @returns {Object}
139
+ */
140
+ export function pick(o, props) {
141
+ return Object.assign(
142
+ {},
143
+ ...props.map((prop) => {
144
+ if (o[prop] !== undefined) {
145
+ return { [prop]: o[prop] };
146
+ }
147
+ })
148
+ );
149
+ }
@@ -0,0 +1,445 @@
1
+
2
+ /**
3
+ * @file Custom data structures.
4
+ *
5
+ * These are only used internally, meaning an end-user shouldn't
6
+ * need to access anything here.
7
+ *
8
+ * @module utils/data-structures
9
+ */
10
+
11
+
12
+ /**
13
+ * Efficient Heap-based Implementation of a Priority Queue.
14
+ * It uses an array-based binary heap, where the root is at index `0`, and the
15
+ * children of node `i` are located at indices `2i + 1` and `2i + 2`, respectively.
16
+ *
17
+ * Adapted from the following sources:
18
+ * - https://stackoverflow.com/a/42919752/13989043 (original)
19
+ * - https://github.com/belladoreai/llama-tokenizer-js (minor improvements)
20
+ */
21
+ export class PriorityQueue {
22
+
23
+ /**
24
+ * Create a new PriorityQueue.
25
+ * @param {function(any, any): boolean} comparator Comparator function to determine priority. Defaults to a MaxHeap.
26
+ */
27
+ constructor(comparator = (a, b) => a > b, maxSize = Infinity) {
28
+ this._heap = [];
29
+ this._comparator = comparator;
30
+ this._maxSize = maxSize;
31
+ }
32
+
33
+ /**
34
+ * The size of the queue
35
+ */
36
+ get size() {
37
+ return this._heap.length;
38
+ }
39
+
40
+ /**
41
+ * Check if the queue is empty.
42
+ * @returns {boolean} `true` if the queue is empty, `false` otherwise.
43
+ */
44
+ isEmpty() {
45
+ return this.size === 0;
46
+ }
47
+
48
+ /**
49
+ * Return the element with the highest priority in the queue.
50
+ * @returns {any} The highest priority element in the queue.
51
+ */
52
+ peek() {
53
+ return this._heap[0];
54
+ }
55
+
56
+ /**
57
+ * Add one or more elements to the queue.
58
+ * @param {...any} values The values to push into the queue.
59
+ * @returns {number} The new size of the queue.
60
+ */
61
+ push(...values) {
62
+ return this.extend(values);
63
+ }
64
+
65
+ /**
66
+ * Add multiple elements to the queue.
67
+ * @param {any[]} values The values to push into the queue.
68
+ * @returns {number} The new size of the queue.
69
+ */
70
+ extend(values) {
71
+ for (const value of values) {
72
+ if (this.size < this._maxSize) {
73
+ this._heap.push(value);
74
+ this._siftUp();
75
+ } else {
76
+ // Get index of value with the lowest priority
77
+ const smallest = this._smallest();
78
+
79
+ // If the new value has higher priority than the smallest value in the heap
80
+ // then replace the smallest value with the new value and update the heap
81
+ if (this._comparator(value, this._heap[smallest])) {
82
+ this._heap[smallest] = value;
83
+ this._siftUpFrom(smallest);
84
+ }
85
+ }
86
+ }
87
+ return this.size;
88
+ }
89
+
90
+ /**
91
+ * Remove and return the element with the highest priority in the queue.
92
+ * @returns {any} The element with the highest priority in the queue.
93
+ */
94
+ pop() {
95
+ const poppedValue = this.peek();
96
+ const bottom = this.size - 1;
97
+ if (bottom > 0) {
98
+ this._swap(0, bottom);
99
+ }
100
+ this._heap.pop();
101
+ this._siftDown();
102
+ return poppedValue;
103
+ }
104
+
105
+ /**
106
+ * Replace the element with the highest priority in the queue with a new value.
107
+ * @param {*} value The new value.
108
+ * @returns {*} The replaced value.
109
+ */
110
+ replace(value) {
111
+ const replacedValue = this.peek();
112
+ this._heap[0] = value;
113
+ this._siftDown();
114
+ return replacedValue;
115
+ }
116
+
117
+ /**
118
+ * Compute the index for the parent of the node at index `i`.
119
+ * @param {number} i The index of the node to get the parent of.
120
+ * @returns {number} The index of the parent node.
121
+ * @private
122
+ */
123
+ _parent(i) {
124
+ return ((i + 1) >>> 1) - 1;
125
+ }
126
+
127
+ /**
128
+ * Compute the index for the left child of the node at index `i`.
129
+ * @param {number} i The index of the node to get the left child of.
130
+ * @returns {number} The index of the left child.
131
+ * @private
132
+ */
133
+ _left(i) {
134
+ return (i << 1) + 1;
135
+ }
136
+
137
+ /**
138
+ * Compute the index for the right child of the node at index `i`.
139
+ * @param {number} i The index of the node to get the right child of.
140
+ * @returns {number} The index of the right child.
141
+ * @private
142
+ */
143
+ _right(i) {
144
+ return (i + 1) << 1;
145
+ }
146
+
147
+ /**
148
+ * Check if the element at index `i` is greater than the element at index `j`.
149
+ * @param {number} i The index of the first element to compare.
150
+ * @param {number} j The index of the second element to compare.
151
+ * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.
152
+ * @private
153
+ */
154
+ _greater(i, j) {
155
+ return this._comparator(this._heap[i], this._heap[j]);
156
+ }
157
+
158
+ /**
159
+ * Swap the elements at indices `i` and `j`.
160
+ * @param {number} i The index of the first element to swap.
161
+ * @param {number} j The index of the second element to swap.
162
+ * @private
163
+ */
164
+ _swap(i, j) {
165
+ const temp = this._heap[i];
166
+ this._heap[i] = this._heap[j];
167
+ this._heap[j] = temp;
168
+ }
169
+
170
+ /**
171
+ * Maintain the heap property by updating positions in the heap,
172
+ * starting at the last element and moving up the heap.
173
+ * @private
174
+ */
175
+ _siftUp() {
176
+ this._siftUpFrom(this.size - 1);
177
+ }
178
+
179
+ /**
180
+ * Helper function to sift up from a given node.
181
+ * @param {number} node The index of the node to start sifting up from.
182
+ */
183
+ _siftUpFrom(node) {
184
+ while (node > 0 && this._greater(node, this._parent(node))) {
185
+ this._swap(node, this._parent(node));
186
+ node = this._parent(node);
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Maintain the heap property by updating positions in the heap,
192
+ * starting at the first element and moving down the heap.
193
+ * @private
194
+ */
195
+ _siftDown() {
196
+ let node = 0;
197
+ while (
198
+ (this._left(node) < this.size && this._greater(this._left(node), node)) ||
199
+ (this._right(node) < this.size && this._greater(this._right(node), node))
200
+ ) {
201
+ const maxChild = (this._right(node) < this.size && this._greater(this._right(node), this._left(node)))
202
+ ? this._right(node)
203
+ : this._left(node);
204
+ this._swap(node, maxChild);
205
+ node = maxChild;
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Get the index of the smallest element in the heap. Since we use an array-based heap,
211
+ * the index can be computed without needing to traverse the heap.
212
+ * @private
213
+ */
214
+ _smallest() {
215
+ return (2 ** (Math.floor(Math.log2(this.size))) - 1);
216
+ }
217
+ }
218
+
219
+ /**
220
+ * A trie structure to efficiently store and search for strings.
221
+ */
222
+ export class CharTrie {
223
+ constructor() {
224
+ this.root = CharTrieNode.default();
225
+ }
226
+
227
+ /**
228
+ * Adds one or more `texts` to the trie.
229
+ * @param {string[]} texts The strings to add to the trie.
230
+ */
231
+ extend(texts) {
232
+ for (let text of texts) {
233
+ this.push(text);
234
+ }
235
+ }
236
+
237
+ /**
238
+ * Adds text to the trie.
239
+ * @param {string} text The string to add to the trie.
240
+ */
241
+ push(text) {
242
+ let node = this.root;
243
+ for (let ch of text) {
244
+ let child = node.children.get(ch);
245
+ if (child === undefined) {
246
+ child = CharTrieNode.default();
247
+ node.children.set(ch, child);
248
+ }
249
+ node = child;
250
+ }
251
+ node.isLeaf = true;
252
+ }
253
+
254
+ /**
255
+ * Searches the trie for all strings with a common prefix of `text`.
256
+ * @param {string} text The common prefix to search for.
257
+ * @yields {string} Each string in the trie that has `text` as a prefix.
258
+ */
259
+ *commonPrefixSearch(text) {
260
+ let node = this.root;
261
+ let prefix = "";
262
+ for (let i = 0; i < text.length && node !== undefined; ++i) {
263
+ const ch = text[i];
264
+ prefix += ch;
265
+ node = node.children.get(ch);
266
+ if (node !== undefined && node.isLeaf) {
267
+ yield prefix;
268
+ }
269
+ }
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Represents a node in a character trie.
275
+ */
276
+ class CharTrieNode {
277
+ /**
278
+ * Create a new CharTrieNode.
279
+ * @param {boolean} isLeaf Whether the node is a leaf node or not.
280
+ * @param {Map<string, CharTrieNode>} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.
281
+ */
282
+ constructor(isLeaf, children) {
283
+ this.isLeaf = isLeaf;
284
+ this.children = children;
285
+ }
286
+
287
+ /**
288
+ * Returns a new `CharTrieNode` instance with default values.
289
+ * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.
290
+ */
291
+ static default() {
292
+ return new CharTrieNode(false, new Map());
293
+ }
294
+ }
295
+
296
+ /**
297
+ * A lattice data structure to be used for tokenization.
298
+ */
299
+ export class TokenLattice {
300
+ /**
301
+ * Creates a new TokenLattice instance.
302
+ *
303
+ * @param {string} sentence The input sentence to be tokenized.
304
+ * @param {number} bosTokenId The beginning-of-sequence token ID.
305
+ * @param {number} eosTokenId The end-of-sequence token ID.
306
+ */
307
+ constructor(sentence, bosTokenId, eosTokenId) {
308
+ this.sentence = sentence;
309
+ this.len = sentence.length;
310
+ this.bosTokenId = bosTokenId;
311
+ this.eosTokenId = eosTokenId;
312
+ this.nodes = [];
313
+ this.beginNodes = Array.from({ length: this.len + 1 }, () => []);
314
+ this.endNodes = Array.from({ length: this.len + 1 }, () => []);
315
+
316
+ const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0);
317
+ const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0);
318
+ this.nodes.push(bos.clone());
319
+ this.nodes.push(eos.clone());
320
+ this.beginNodes[this.len].push(eos);
321
+ this.endNodes[0].push(bos);
322
+ }
323
+
324
+ /**
325
+ * Inserts a new token node into the token lattice.
326
+ *
327
+ * @param {number} pos The starting position of the token.
328
+ * @param {number} length The length of the token.
329
+ * @param {number} score The score of the token.
330
+ * @param {number} tokenId The token ID of the token.
331
+ */
332
+ insert(pos, length, score, tokenId) {
333
+ const nodeId = this.nodes.length;
334
+ const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score);
335
+ this.beginNodes[pos].push(node);
336
+ this.endNodes[pos + length].push(node);
337
+ this.nodes.push(node);
338
+ }
339
+
340
+ /**
341
+ * Implements the Viterbi algorithm to compute the most likely sequence of tokens.
342
+ *
343
+ * @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens.
344
+ */
345
+ viterbi() {
346
+ const len = this.len;
347
+ let pos = 0;
348
+ while (pos <= len) {
349
+ if (this.beginNodes[pos].length == 0) {
350
+ return [];
351
+ }
352
+ for (let rnode of this.beginNodes[pos]) {
353
+ rnode.prev = null;
354
+ let bestScore = 0.0;
355
+ let bestNode = null;
356
+ for (let lnode of this.endNodes[pos]) {
357
+ const score = lnode.backtraceScore + rnode.score;
358
+ if (bestNode === null || score > bestScore) {
359
+ bestNode = lnode.clone();
360
+ bestScore = score;
361
+ }
362
+ }
363
+
364
+ if (bestNode !== null) {
365
+ rnode.prev = bestNode;
366
+ rnode.backtraceScore = bestScore;
367
+ } else {
368
+ return [];
369
+ }
370
+ }
371
+ ++pos;
372
+ }
373
+
374
+ const results = [];
375
+ const root = this.beginNodes[len][0];
376
+ const prev = root.prev;
377
+ if (prev === null) {
378
+ return [];
379
+ }
380
+
381
+ let node = prev.clone();
382
+ while (node.prev !== null) {
383
+ results.push(node.clone());
384
+ const n = node.clone();
385
+ node = n.prev.clone();
386
+ }
387
+
388
+ results.reverse();
389
+ return results;
390
+ }
391
+
392
+ /**
393
+ * @param {TokenLatticeNode} node
394
+ * @returns {string} The array of nodes representing the most likely sequence of tokens.
395
+ */
396
+ piece(node) {
397
+ return this.sentence.slice(node.pos, node.pos + node.length);
398
+ }
399
+
400
+ /**
401
+ * @returns {Array} The array of nodes representing the most likely sequence of tokens.
402
+ */
403
+ tokens() {
404
+ const nodes = this.viterbi();
405
+ return nodes.map(x => this.piece(x));
406
+ }
407
+
408
+ /**
409
+ * @returns {Array} The array of nodes representing the most likely sequence of tokens.
410
+ */
411
+ tokenIds() {
412
+ const nodes = this.viterbi();
413
+ return nodes.map(x => x.tokenId);
414
+ }
415
+ }
416
+ class TokenLatticeNode {
417
+ /**
418
+ * Represents a node in a token lattice for a given sentence.
419
+ * @param {number} tokenId The ID of the token associated with this node.
420
+ * @param {number} nodeId The ID of this node.
421
+ * @param {number} pos The starting position of the token in the sentence.
422
+ * @param {number} length The length of the token.
423
+ * @param {number} score The score associated with the token.
424
+ */
425
+ constructor(tokenId, nodeId, pos, length, score) {
426
+ this.tokenId = tokenId;
427
+ this.nodeId = nodeId;
428
+ this.pos = pos;
429
+ this.length = length;
430
+ this.score = score;
431
+ this.prev = null;
432
+ this.backtraceScore = 0.0;
433
+ }
434
+
435
+ /**
436
+ * Returns a clone of this node.
437
+ * @returns {TokenLatticeNode} A clone of this node.
438
+ */
439
+ clone() {
440
+ const n = new TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score);
441
+ n.prev = this.prev;
442
+ n.backtraceScore = this.backtraceScore;
443
+ return n;
444
+ }
445
+ }
@@ -0,0 +1,11 @@
1
+
2
+ export const DEVICE_TYPES = Object.freeze({
3
+ cpu: 'cpu',
4
+ gpu: 'gpu',
5
+ wasm: 'wasm',
6
+ webgpu: 'webgpu',
7
+ });
8
+
9
+ /**
10
+ * @typedef {keyof typeof DEVICE_TYPES} DeviceType
11
+ */
@@ -0,0 +1,62 @@
1
+ import { apis } from "../env.js";
2
+
3
+ import { DEVICE_TYPES } from "./devices.js";
4
+
5
+ // TODO: Use the adapter from `env.backends.onnx.webgpu.adapter` to check for `shader-f16` support,
6
+ // when available in https://github.com/microsoft/onnxruntime/pull/19940.
7
+ // For more information, see https://github.com/microsoft/onnxruntime/pull/19857#issuecomment-1999984753
8
+
9
+ /**
10
+ * Checks if WebGPU fp16 support is available in the current environment.
11
+ */
12
+ export const isWebGpuFp16Supported = (function () {
13
+ /** @type {boolean} */
14
+ let cachedResult;
15
+
16
+ return async function () {
17
+ if (cachedResult === undefined) {
18
+ if (!apis.IS_WEBGPU_AVAILABLE) {
19
+ cachedResult = false;
20
+ } else {
21
+ try {
22
+ const adapter = await navigator.gpu.requestAdapter();
23
+ cachedResult = adapter.features.has('shader-f16');
24
+ } catch (e) {
25
+ cachedResult = false;
26
+ }
27
+ }
28
+ }
29
+ return cachedResult;
30
+ };
31
+ })();
32
+
33
+ export const DATA_TYPES = Object.freeze({
34
+ fp32: 'fp32',
35
+ fp16: 'fp16',
36
+ q8: 'q8',
37
+ int8: 'int8',
38
+ uint8: 'uint8',
39
+ q4: 'q4',
40
+ bnb4: 'bnb4',
41
+ q4f16: 'q4f16', // fp16 model with int4 block weight quantization
42
+ });
43
+ /** @typedef {keyof typeof DATA_TYPES} DataType */
44
+
45
+ export const DEFAULT_DEVICE_DTYPE_MAPPING = Object.freeze({
46
+ [DEVICE_TYPES.cpu]: DATA_TYPES.q8,
47
+ [DEVICE_TYPES.gpu]: DATA_TYPES.fp32,
48
+ [DEVICE_TYPES.wasm]: DATA_TYPES.q8,
49
+ [DEVICE_TYPES.webgpu]: DATA_TYPES.fp32,
50
+ });
51
+
52
+ /** @type {Record<DataType, string>} */
53
+ export const DEFAULT_DTYPE_SUFFIX_MAPPING = Object.freeze({
54
+ [DATA_TYPES.fp32]: '',
55
+ [DATA_TYPES.fp16]: '_fp16',
56
+ [DATA_TYPES.int8]: '_int8',
57
+ [DATA_TYPES.uint8]: '_uint8',
58
+ [DATA_TYPES.q8]: '_quantized',
59
+ [DATA_TYPES.q4]: '_q4',
60
+ [DATA_TYPES.q4f16]: '_q4f16',
61
+ [DATA_TYPES.bnb4]: '_bnb4',
62
+ });
@@ -0,0 +1,35 @@
1
+
2
+ /**
3
+ * A base class for creating callable objects.
4
+ * See [here](https://stackoverflow.com/q/76073890) for more information.
5
+ *
6
+ * @type {new () => {(...args: any[]): any, _call(...args: any[]): any}}
7
+ */
8
+ export const Callable = /** @type {any} */ (class {
9
+ /**
10
+ * Creates a new instance of the Callable class.
11
+ */
12
+ constructor() {
13
+ /**
14
+ * Creates a closure that delegates to a private method '_call' with the given arguments.
15
+ * @type {any}
16
+ * @param {...any} args Zero or more arguments to pass to the '_call' method.
17
+ * @returns {*} The result of calling the '_call' method.
18
+ */
19
+ let closure = function (...args) {
20
+ return closure._call(...args)
21
+ }
22
+ return Object.setPrototypeOf(closure, new.target.prototype)
23
+ }
24
+
25
+ /**
26
+ * This method should be implemented in subclasses to provide the
27
+ * functionality of the callable object.
28
+ *
29
+ * @param {any[]} args
30
+ * @throws {Error} If the subclass does not implement the `_call` method.
31
+ */
32
+ _call(...args) {
33
+ throw Error('Must implement _call method in subclass')
34
+ }
35
+ });