parakeet.js 0.0.2 → 0.0.3

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 (160) hide show
  1. package/.gitmodules +3 -0
  2. package/README.md +240 -239
  3. package/examples/hf-spaces-demo/README.md +6 -9
  4. package/examples/hf-spaces-demo/package.json +1 -1
  5. package/examples/hf-spaces-demo/src/App.js +307 -316
  6. package/examples/react-demo/package.json +19 -19
  7. package/examples/react-demo/src/App.jsx +324 -326
  8. package/examples/react-demo-dev/src/App.jsx +23 -24
  9. package/package.json +1 -1
  10. package/publish.ps1 +65 -0
  11. package/src/hub.js +235 -241
  12. package/src/parakeet.js +15 -8
  13. package/src/preprocessor.js +75 -68
  14. package/docs/parakeet-transformers-js/.gitattributes +0 -2
  15. package/docs/parakeet-transformers-js/.prettierignore +0 -8
  16. package/docs/parakeet-transformers-js/.prettierrc +0 -10
  17. package/docs/parakeet-transformers-js/.tmp_features.json +0 -1
  18. package/docs/parakeet-transformers-js/LICENSE +0 -202
  19. package/docs/parakeet-transformers-js/README.md +0 -448
  20. package/docs/parakeet-transformers-js/assets/nemo128.onnx +0 -0
  21. package/docs/parakeet-transformers-js/assets/nemo80.onnx +0 -0
  22. package/docs/parakeet-transformers-js/debug_test.js +0 -84
  23. package/docs/parakeet-transformers-js/dev/inspect_decoder.cjs +0 -9
  24. package/docs/parakeet-transformers-js/dev/inspect_joiner.cjs +0 -9
  25. package/docs/parakeet-transformers-js/dev/js_step_by_step.js +0 -249
  26. package/docs/parakeet-transformers-js/dev/parakeet_cli.js +0 -91
  27. package/docs/parakeet-transformers-js/jest.config.mjs +0 -194
  28. package/docs/parakeet-transformers-js/js_preprocessing.json +0 -225
  29. package/docs/parakeet-transformers-js/js_step_by_step.json +0 -837
  30. package/docs/parakeet-transformers-js/js_step_by_step_v2.json +0 -450
  31. package/docs/parakeet-transformers-js/js_step_by_step_v3.json +0 -450
  32. package/docs/parakeet-transformers-js/js_steps.json +0 -821
  33. package/docs/parakeet-transformers-js/package-lock.json +0 -12251
  34. package/docs/parakeet-transformers-js/package.json +0 -96
  35. package/docs/parakeet-transformers-js/src/audio_features.js +0 -178
  36. package/docs/parakeet-transformers-js/src/backends/onnx.js +0 -210
  37. package/docs/parakeet-transformers-js/src/base/feature_extraction_utils.js +0 -54
  38. package/docs/parakeet-transformers-js/src/base/image_processors_utils.js +0 -1105
  39. package/docs/parakeet-transformers-js/src/base/processing_utils.js +0 -173
  40. package/docs/parakeet-transformers-js/src/configs.js +0 -455
  41. package/docs/parakeet-transformers-js/src/env.js +0 -167
  42. package/docs/parakeet-transformers-js/src/generation/configuration_utils.js +0 -388
  43. package/docs/parakeet-transformers-js/src/generation/logits_process.js +0 -727
  44. package/docs/parakeet-transformers-js/src/generation/logits_sampler.js +0 -204
  45. package/docs/parakeet-transformers-js/src/generation/parameters.js +0 -35
  46. package/docs/parakeet-transformers-js/src/generation/stopping_criteria.js +0 -156
  47. package/docs/parakeet-transformers-js/src/generation/streamers.js +0 -225
  48. package/docs/parakeet-transformers-js/src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js +0 -85
  49. package/docs/parakeet-transformers-js/src/models/auto/feature_extraction_auto.js +0 -25
  50. package/docs/parakeet-transformers-js/src/models/auto/image_processing_auto.js +0 -29
  51. package/docs/parakeet-transformers-js/src/models/auto/processing_auto.js +0 -85
  52. package/docs/parakeet-transformers-js/src/models/beit/image_processing_beit.js +0 -5
  53. package/docs/parakeet-transformers-js/src/models/bit/image_processing_bit.js +0 -5
  54. package/docs/parakeet-transformers-js/src/models/chinese_clip/image_processing_chinese_clip.js +0 -5
  55. package/docs/parakeet-transformers-js/src/models/clap/feature_extraction_clap.js +0 -159
  56. package/docs/parakeet-transformers-js/src/models/clip/image_processing_clip.js +0 -6
  57. package/docs/parakeet-transformers-js/src/models/convnext/image_processing_convnext.js +0 -46
  58. package/docs/parakeet-transformers-js/src/models/dac/feature_extraction_dac.js +0 -3
  59. package/docs/parakeet-transformers-js/src/models/deit/image_processing_deit.js +0 -6
  60. package/docs/parakeet-transformers-js/src/models/detr/image_processing_detr.js +0 -52
  61. package/docs/parakeet-transformers-js/src/models/donut/image_processing_donut.js +0 -31
  62. package/docs/parakeet-transformers-js/src/models/dpt/image_processing_dpt.js +0 -6
  63. package/docs/parakeet-transformers-js/src/models/efficientnet/image_processing_efficientnet.js +0 -14
  64. package/docs/parakeet-transformers-js/src/models/encodec/feature_extraction_encodec.js +0 -32
  65. package/docs/parakeet-transformers-js/src/models/feature_extractors.js +0 -17
  66. package/docs/parakeet-transformers-js/src/models/florence2/processing_florence2.js +0 -131
  67. package/docs/parakeet-transformers-js/src/models/gemma3n/feature_extraction_gemma3n.js +0 -97
  68. package/docs/parakeet-transformers-js/src/models/gemma3n/processing_gemma3n.js +0 -74
  69. package/docs/parakeet-transformers-js/src/models/glpn/image_processing_glpn.js +0 -5
  70. package/docs/parakeet-transformers-js/src/models/grounding_dino/image_processing_grounding_dino.js +0 -29
  71. package/docs/parakeet-transformers-js/src/models/grounding_dino/processing_grounding_dino.js +0 -101
  72. package/docs/parakeet-transformers-js/src/models/idefics3/image_processing_idefics3.js +0 -232
  73. package/docs/parakeet-transformers-js/src/models/idefics3/processing_idefics3.js +0 -136
  74. package/docs/parakeet-transformers-js/src/models/image_processors.js +0 -40
  75. package/docs/parakeet-transformers-js/src/models/janus/image_processing_janus.js +0 -27
  76. package/docs/parakeet-transformers-js/src/models/janus/processing_janus.js +0 -123
  77. package/docs/parakeet-transformers-js/src/models/jina_clip/image_processing_jina_clip.js +0 -26
  78. package/docs/parakeet-transformers-js/src/models/jina_clip/processing_jina_clip.js +0 -24
  79. package/docs/parakeet-transformers-js/src/models/llava/processing_llava.js +0 -44
  80. package/docs/parakeet-transformers-js/src/models/llava_onevision/image_processing_llava_onevision.js +0 -5
  81. package/docs/parakeet-transformers-js/src/models/mask2former/image_processing_mask2former.js +0 -5
  82. package/docs/parakeet-transformers-js/src/models/maskformer/image_processing_maskformer.js +0 -18
  83. package/docs/parakeet-transformers-js/src/models/mgp_str/processing_mgp_str.js +0 -172
  84. package/docs/parakeet-transformers-js/src/models/mobilenet_v1/image_processing_mobilenet_v1.js +0 -7
  85. package/docs/parakeet-transformers-js/src/models/mobilenet_v2/image_processing_mobilenet_v2.js +0 -7
  86. package/docs/parakeet-transformers-js/src/models/mobilenet_v3/image_processing_mobilenet_v3.js +0 -7
  87. package/docs/parakeet-transformers-js/src/models/mobilenet_v4/image_processing_mobilenet_v4.js +0 -7
  88. package/docs/parakeet-transformers-js/src/models/mobilevit/image_processing_mobilevit.js +0 -6
  89. package/docs/parakeet-transformers-js/src/models/moonshine/feature_extraction_moonshine.js +0 -26
  90. package/docs/parakeet-transformers-js/src/models/moonshine/processing_moonshine.js +0 -20
  91. package/docs/parakeet-transformers-js/src/models/nougat/image_processing_nougat.js +0 -5
  92. package/docs/parakeet-transformers-js/src/models/owlv2/image_processing_owlv2.js +0 -5
  93. package/docs/parakeet-transformers-js/src/models/owlvit/image_processing_owlvit.js +0 -12
  94. package/docs/parakeet-transformers-js/src/models/owlvit/processing_owlvit.js +0 -7
  95. package/docs/parakeet-transformers-js/src/models/paligemma/processing_paligemma.js +0 -83
  96. package/docs/parakeet-transformers-js/src/models/parakeet/feature_extraction_parakeet.js +0 -3
  97. package/docs/parakeet-transformers-js/src/models/parakeet/modeling_parakeet.js +0 -3
  98. package/docs/parakeet-transformers-js/src/models/parakeet/processing_parakeet.js +0 -3
  99. package/docs/parakeet-transformers-js/src/models/parakeet/tokenization_parakeet.js +0 -3
  100. package/docs/parakeet-transformers-js/src/models/phi3_v/image_processing_phi3_v.js +0 -163
  101. package/docs/parakeet-transformers-js/src/models/phi3_v/processing_phi3_v.js +0 -53
  102. package/docs/parakeet-transformers-js/src/models/processors.js +0 -22
  103. package/docs/parakeet-transformers-js/src/models/pvt/image_processing_pvt.js +0 -5
  104. package/docs/parakeet-transformers-js/src/models/pyannote/feature_extraction_pyannote.js +0 -85
  105. package/docs/parakeet-transformers-js/src/models/pyannote/processing_pyannote.js +0 -24
  106. package/docs/parakeet-transformers-js/src/models/qwen2_vl/image_processing_qwen2_vl.js +0 -52
  107. package/docs/parakeet-transformers-js/src/models/qwen2_vl/processing_qwen2_vl.js +0 -53
  108. package/docs/parakeet-transformers-js/src/models/rt_detr/image_processing_rt_detr.js +0 -12
  109. package/docs/parakeet-transformers-js/src/models/sam/image_processing_sam.js +0 -242
  110. package/docs/parakeet-transformers-js/src/models/sam/processing_sam.js +0 -20
  111. package/docs/parakeet-transformers-js/src/models/sapiens/image_processing_sapiens.js +0 -13
  112. package/docs/parakeet-transformers-js/src/models/seamless_m4t/feature_extraction_seamless_m4t.js +0 -175
  113. package/docs/parakeet-transformers-js/src/models/segformer/image_processing_segformer.js +0 -13
  114. package/docs/parakeet-transformers-js/src/models/siglip/image_processing_siglip.js +0 -5
  115. package/docs/parakeet-transformers-js/src/models/smolvlm/image_processing_smolvlm.js +0 -2
  116. package/docs/parakeet-transformers-js/src/models/smolvlm/processing_smolvlm.js +0 -2
  117. package/docs/parakeet-transformers-js/src/models/snac/feature_extraction_snac.js +0 -3
  118. package/docs/parakeet-transformers-js/src/models/speecht5/feature_extraction_speecht5.js +0 -4
  119. package/docs/parakeet-transformers-js/src/models/speecht5/processing_speecht5.js +0 -17
  120. package/docs/parakeet-transformers-js/src/models/swin2sr/image_processing_swin2sr.js +0 -24
  121. package/docs/parakeet-transformers-js/src/models/ultravox/processing_ultravox.js +0 -54
  122. package/docs/parakeet-transformers-js/src/models/vit/image_processing_vit.js +0 -7
  123. package/docs/parakeet-transformers-js/src/models/vitmatte/image_processing_vitmatte.js +0 -50
  124. package/docs/parakeet-transformers-js/src/models/vitpose/image_processing_vitpose.js +0 -89
  125. package/docs/parakeet-transformers-js/src/models/wav2vec2/feature_extraction_wav2vec2.js +0 -44
  126. package/docs/parakeet-transformers-js/src/models/wav2vec2/processing_wav2vec2.js +0 -17
  127. package/docs/parakeet-transformers-js/src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js +0 -17
  128. package/docs/parakeet-transformers-js/src/models/wespeaker/feature_extraction_wespeaker.js +0 -95
  129. package/docs/parakeet-transformers-js/src/models/whisper/common_whisper.js +0 -157
  130. package/docs/parakeet-transformers-js/src/models/whisper/feature_extraction_whisper.js +0 -92
  131. package/docs/parakeet-transformers-js/src/models/whisper/generation_whisper.js +0 -89
  132. package/docs/parakeet-transformers-js/src/models/whisper/processing_whisper.js +0 -21
  133. package/docs/parakeet-transformers-js/src/models/yolos/image_processing_yolos.js +0 -12
  134. package/docs/parakeet-transformers-js/src/models.js +0 -8644
  135. package/docs/parakeet-transformers-js/src/ops/registry.js +0 -133
  136. package/docs/parakeet-transformers-js/src/ort_env.js +0 -8
  137. package/docs/parakeet-transformers-js/src/parakeet.js +0 -792
  138. package/docs/parakeet-transformers-js/src/pipelines.js +0 -3540
  139. package/docs/parakeet-transformers-js/src/processors.js +0 -16
  140. package/docs/parakeet-transformers-js/src/tokenizers.js +0 -4432
  141. package/docs/parakeet-transformers-js/src/transformers.js +0 -50
  142. package/docs/parakeet-transformers-js/src/utils/audio.js +0 -893
  143. package/docs/parakeet-transformers-js/src/utils/constants.js +0 -9
  144. package/docs/parakeet-transformers-js/src/utils/core.js +0 -259
  145. package/docs/parakeet-transformers-js/src/utils/data-structures.js +0 -574
  146. package/docs/parakeet-transformers-js/src/utils/devices.js +0 -22
  147. package/docs/parakeet-transformers-js/src/utils/dtypes.js +0 -63
  148. package/docs/parakeet-transformers-js/src/utils/generic.js +0 -35
  149. package/docs/parakeet-transformers-js/src/utils/hub.js +0 -780
  150. package/docs/parakeet-transformers-js/src/utils/image.js +0 -834
  151. package/docs/parakeet-transformers-js/src/utils/maths.js +0 -1061
  152. package/docs/parakeet-transformers-js/src/utils/tensor.js +0 -1539
  153. package/docs/parakeet-transformers-js/src/utils/video.js +0 -128
  154. package/docs/parakeet-transformers-js/test/decoder.test.js +0 -114
  155. package/docs/parakeet-transformers-js/test/encoder.test.js +0 -108
  156. package/docs/parakeet-transformers-js/test/preprocessor.test.js +0 -85
  157. package/docs/parakeet-transformers-js/test/tokenizer.test.js +0 -24
  158. package/docs/parakeet-transformers-js/test/transcribe.js +0 -89
  159. package/docs/parakeet-transformers-js/tsconfig.json +0 -21
  160. package/docs/parakeet-transformers-js/webpack.config.js +0 -223
@@ -1,4432 +0,0 @@
1
-
2
- /**
3
- * @file Tokenizers are used to prepare textual inputs for a model.
4
- *
5
- * **Example:** Create an `AutoTokenizer` and use it to tokenize a sentence.
6
- * This will automatically detect the tokenizer type based on the tokenizer class defined in `tokenizer.json`.
7
- * ```javascript
8
- * import { AutoTokenizer } from '@huggingface/transformers';
9
- *
10
- * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');
11
- * const { input_ids } = await tokenizer('I love transformers!');
12
- * // Tensor {
13
- * // data: BigInt64Array(6) [101n, 1045n, 2293n, 19081n, 999n, 102n],
14
- * // dims: [1, 6],
15
- * // type: 'int64',
16
- * // size: 6,
17
- * // }
18
- * ```
19
- *
20
- * @module tokenizers
21
- */
22
- import {
23
- Callable,
24
- } from './utils/generic.js';
25
-
26
- import {
27
- reverseDictionary,
28
- escapeRegExp,
29
- isIntegralNumber,
30
- mergeArrays,
31
- len,
32
- } from './utils/core.js';
33
-
34
- import {
35
- getModelJSON,
36
- } from './utils/hub.js';
37
-
38
- import { max, min, round } from './utils/maths.js';
39
- import { Tensor } from './utils/tensor.js';
40
-
41
- import {
42
- PriorityQueue,
43
- TokenLattice,
44
- CharTrie,
45
- DictionarySplitter,
46
- LRUCache,
47
- } from './utils/data-structures.js';
48
-
49
- import { Template } from '@huggingface/jinja';
50
-
51
- import {
52
- WHISPER_LANGUAGE_MAPPING
53
- } from './models/whisper/common_whisper.js';
54
-
55
- /**
56
- * @typedef {Object} TokenizerProperties Additional tokenizer-specific properties.
57
- * @property {boolean} [legacy=false] Whether or not the `legacy` behavior of the tokenizer should be used.
58
- * @typedef {import('./utils/hub.js').PretrainedOptions & TokenizerProperties} PretrainedTokenizerOptions
59
- */
60
-
61
- /**
62
- * Loads a tokenizer from the specified path.
63
- * @param {string} pretrained_model_name_or_path The path to the tokenizer directory.
64
- * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
65
- * @returns {Promise<any[]>} A promise that resolves with information about the loaded tokenizer.
66
- */
67
- async function loadTokenizer(pretrained_model_name_or_path, options) {
68
-
69
- const info = await Promise.all([
70
- getModelJSON(pretrained_model_name_or_path, 'tokenizer.json', true, options),
71
- getModelJSON(pretrained_model_name_or_path, 'tokenizer_config.json', true, options),
72
- ])
73
-
74
- // Override legacy option if `options.legacy` is not null
75
- if (options.legacy !== null) {
76
- info[1].legacy = options.legacy;
77
- }
78
- return info;
79
- }
80
-
81
-
82
- /**
83
- * Helper function to split a string on a regex, but keep the delimiters.
84
- * This is required, because the JavaScript `.split()` method does not keep the delimiters,
85
- * and wrapping in a capturing group causes issues with existing capturing groups (due to nesting).
86
- * @param {string} text The text to split.
87
- * @param {RegExp} regex The regex to split on.
88
- * @returns {string[]} The split string.
89
- */
90
- function regexSplit(text, regex) {
91
- const result = [];
92
- let prev = 0;
93
- for (const match of text.matchAll(regex)) {
94
- const fullMatch = match[0];
95
- if (prev < match.index) {
96
- result.push(text.slice(prev, match.index));
97
- }
98
- if (fullMatch.length > 0) {
99
- result.push(fullMatch);
100
- }
101
- prev = match.index + fullMatch.length;
102
- }
103
- if (prev < text.length) {
104
- result.push(text.slice(prev));
105
- }
106
- return result;
107
- }
108
-
109
-
110
- /**
111
- * Helper method to construct a pattern from a config object.
112
- * @param {Object} pattern The pattern object.
113
- * @param {boolean} invert Whether to invert the pattern.
114
- * @returns {RegExp|null} The compiled pattern.
115
- */
116
- function createPattern(pattern, invert = true) {
117
-
118
- if (pattern.Regex !== undefined) {
119
- // In certain cases, the pattern may contain unnecessary escape sequences (e.g., \# or \& or \~).
120
- // i.e., valid in Python (where the patterns are exported from) but invalid in JavaScript (where the patterns are parsed).
121
- // This isn't an issue when creating the regex w/o the 'u' flag, but it is when the 'u' flag is used.
122
- // For this reason, it is necessary to remove these backslashes before creating the regex.
123
- // See https://stackoverflow.com/a/63007777/13989043 for more information
124
- let regex = pattern.Regex.replace(/\\([#&~])/g, '$1'); // TODO: add more characters to this list if necessary
125
-
126
- // We also handle special cases where the regex contains invalid (non-JS compatible) syntax.
127
- for (const [key, value] of PROBLEMATIC_REGEX_MAP) {
128
- regex = regex.replaceAll(key, value);
129
- }
130
-
131
- return new RegExp(regex, 'gu');
132
-
133
- } else if (pattern.String !== undefined) {
134
- const escaped = escapeRegExp(pattern.String);
135
- // NOTE: if invert is true, we wrap the pattern in a group so that it is kept when performing .split()
136
- return new RegExp(invert ? escaped : `(${escaped})`, 'gu');
137
-
138
- } else {
139
- console.warn('Unknown pattern type:', pattern)
140
- return null;
141
- }
142
- }
143
-
144
- /**
145
- * Helper function to convert an Object to a Map
146
- * @param {Object} obj The object to convert.
147
- * @returns {Map<string, any>} The map.
148
- */
149
- function objectToMap(obj) {
150
- return new Map(Object.entries(obj));
151
- }
152
-
153
- /**
154
- * Helper function to convert a tensor to a list before decoding.
155
- * @param {Tensor} tensor The tensor to convert.
156
- * @returns {number[]} The tensor as a list.
157
- */
158
- function prepareTensorForDecode(tensor) {
159
- const dims = tensor.dims;
160
- switch (dims.length) {
161
- case 1:
162
- return tensor.tolist();
163
- case 2:
164
- if (dims[0] !== 1) {
165
- throw new Error('Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.');
166
- }
167
- return tensor.tolist()[0];
168
- default:
169
- throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`)
170
- }
171
- }
172
-
173
- /**
174
- * Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms
175
- * @param {string} text The text to clean up.
176
- * @returns {string} The cleaned up text.
177
- */
178
- function clean_up_tokenization(text) {
179
- // Clean up a list of simple English tokenization artifacts
180
- // like spaces before punctuations and abbreviated forms
181
- return text.replace(/ \./g, '.')
182
- .replace(/ \?/g, '?')
183
- .replace(/ \!/g, '!')
184
- .replace(/ ,/g, ',')
185
- .replace(/ \' /g, "'")
186
- .replace(/ n\'t/g, "n't")
187
- .replace(/ \'m/g, "'m")
188
- .replace(/ \'s/g, "'s")
189
- .replace(/ \'ve/g, "'ve")
190
- .replace(/ \'re/g, "'re");
191
- }
192
-
193
- /**
194
- * Helper function to remove accents from a string.
195
- * @param {string} text The text to remove accents from.
196
- * @returns {string} The text with accents removed.
197
- */
198
- function remove_accents(text) {
199
- return text.replace(/\p{M}/gu, '');
200
- }
201
-
202
- /**
203
- * Helper function to lowercase a string and remove accents.
204
- * @param {string} text The text to lowercase and remove accents from.
205
- * @returns {string} The lowercased text with accents removed.
206
- */
207
- function lowercase_and_remove_accent(text) {
208
- return remove_accents(text.toLowerCase());
209
- }
210
-
211
-
212
- /**
213
- * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character.
214
- *
215
- * A "chinese character" is defined as anything in the CJK Unicode block:
216
- * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
217
- *
218
- * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name.
219
- * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana.
220
- * Those alphabets are used to write space-separated words, so they are not treated specially
221
- * and are handled like all other languages.
222
- *
223
- * @param {number|bigint} cp The Unicode codepoint to check.
224
- * @returns {boolean} True if the codepoint represents a CJK character, false otherwise.
225
- */
226
- export function is_chinese_char(cp) {
227
- return (
228
- (cp >= 0x4E00 && cp <= 0x9FFF)
229
- || (cp >= 0x3400 && cp <= 0x4DBF)
230
- || (cp >= 0x20000 && cp <= 0x2A6DF)
231
- || (cp >= 0x2A700 && cp <= 0x2B73F)
232
- || (cp >= 0x2B740 && cp <= 0x2B81F)
233
- || (cp >= 0x2B820 && cp <= 0x2CEAF)
234
- || (cp >= 0xF900 && cp <= 0xFAFF)
235
- || (cp >= 0x2F800 && cp <= 0x2FA1F)
236
- )
237
- }
238
-
239
- /**
240
- * Helper function to fuse consecutive unknown tokens.
241
- * @param {string[]} arr The list of input tokens
242
- * @param {Map<string, any>} tokens_to_ids The mapping from tokens to token ids.
243
- * @param {number} unk_token_id The value to fuse on.
244
- * @private
245
- */
246
- function fuse_unk(arr, tokens_to_ids, unk_token_id) {
247
- const fused = [];
248
- let i = 0;
249
- while (i < arr.length) {
250
- fused.push(arr[i])
251
- if ((tokens_to_ids.get(arr[i]) ?? unk_token_id) !== unk_token_id) {
252
- ++i;
253
- continue;
254
- }
255
-
256
- while (++i < arr.length && (tokens_to_ids.get(arr[i]) ?? unk_token_id) === unk_token_id) {
257
- if (tokens_to_ids.get(fused.at(-1)) !== unk_token_id) {
258
- fused[fused.length - 1] += arr[i];
259
- }
260
- }
261
- }
262
-
263
- return fused;
264
- }
265
-
266
- /**
267
- * Split a string on whitespace.
268
- * @param {string} text The text to split.
269
- * @returns {string[]} The split string.
270
- */
271
- function whitespace_split(text) {
272
- return text.match(/\S+/g) || [];
273
- }
274
-
275
- const PUNCTUATION_REGEX = '\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E';
276
- const PUNCTUATION_ONLY_REGEX = new RegExp(`^[${PUNCTUATION_REGEX}]+$`, 'gu');
277
- const BLOOM_SPLIT_CHARS = '.,!?\u2026\u3002\uff0c\u3001\u0964\u06d4\u060c';
278
-
279
- // A mapping of regex patterns to their equivalent (but possibly longer) JS-compatible versions.
280
- const PROBLEMATIC_REGEX_MAP = new Map([
281
- // This uses the case insensitive group modifier, which is not supported in JavaScript.
282
- // When parsing the regex, an "Invalid group" error is thrown.
283
- ["(?i:'s|'t|'re|'ve|'m|'ll|'d)", "(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],
284
-
285
- // Used to override the default (invalid) regex of the bloom pretokenizer.
286
- // For more information, see https://github.com/huggingface/transformers.js/issues/94
287
- [` ?[^(\\s|[${BLOOM_SPLIT_CHARS}])]+`, ` ?[^\\s${BLOOM_SPLIT_CHARS}]+`],
288
- ])
289
-
290
-
291
- /**
292
- * Represent a token added by the user on top of the existing Model vocabulary.
293
- * AddedToken can be configured to specify the behavior they should have in various situations like:
294
- * - Whether they should only match single words
295
- * - Whether to include any whitespace on its left or right
296
- */
297
- class AddedToken {
298
- /**
299
- * Creates a new instance of AddedToken.
300
- * @param {Object} config Added token configuration object.
301
- * @param {string} config.content The content of the added token.
302
- * @param {number} config.id The id of the added token.
303
- * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words.
304
- * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left.
305
- * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right.
306
- * @param {boolean} [config.normalized=false] Whether this token should be normalized.
307
- * @param {boolean} [config.special=false] Whether this token is special.
308
- */
309
- constructor(config) {
310
- this.content = config.content;
311
- this.id = config.id;
312
- this.single_word = config.single_word ?? false;
313
- this.lstrip = config.lstrip ?? false;
314
- this.rstrip = config.rstrip ?? false;
315
- this.special = config.special ?? false;
316
- this.normalized = config.normalized ?? null;
317
- }
318
- }
319
-
320
- /**
321
- * Abstract base class for tokenizer models.
322
- *
323
- * @extends Callable
324
- */
325
- export class TokenizerModel extends Callable {
326
- /**
327
- * Creates a new instance of TokenizerModel.
328
- * @param {Object} config The configuration object for the TokenizerModel.
329
- */
330
- constructor(config) {
331
- super();
332
- this.config = config;
333
-
334
- /** @type {string[]} */
335
- this.vocab = [];
336
-
337
- /**
338
- * A mapping of tokens to ids.
339
- * @type {Map<string, number>}
340
- */
341
- this.tokens_to_ids = new Map();
342
-
343
- this.unk_token_id = undefined;
344
- this.unk_token = undefined;
345
- this.end_of_word_suffix = undefined;
346
-
347
- /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */
348
- this.fuse_unk = this.config.fuse_unk ?? false;
349
- }
350
-
351
- /**
352
- * Instantiates a new TokenizerModel instance based on the configuration object provided.
353
- * @param {Object} config The configuration object for the TokenizerModel.
354
- * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor.
355
- * @returns {TokenizerModel} A new instance of a TokenizerModel.
356
- * @throws Will throw an error if the TokenizerModel type in the config is not recognized.
357
- */
358
- static fromConfig(config, ...args) {
359
- switch (config.type) {
360
- case 'WordPiece':
361
- return new WordPieceTokenizer(config);
362
- case 'Unigram':
363
- // @ts-ignore
364
- return new Unigram(config, ...args);
365
- case 'BPE':
366
- return new BPE(config);
367
-
368
- default:
369
- // Some older tokenizers, like `google-t5/t5-small`, `openai-community/gpt2`, and `distilbert/distilbert-base-uncased`, do not have a `type` field.
370
- // In this case, we can infer the tokenizer type based on the structure of the `vocab` field and other properties.
371
- if (config.vocab) {
372
- if (Array.isArray(config.vocab)) {
373
- // config.vocab is of type `[string, number][]`
374
- // @ts-ignore
375
- return new Unigram(config, ...args);
376
- } else if (Object.hasOwn(config, 'continuing_subword_prefix') && Object.hasOwn(config, 'unk_token')) {
377
- if (Object.hasOwn(config, 'merges')) {
378
- return new BPE(config);
379
- } else {
380
- return new WordPieceTokenizer(config);
381
- }
382
- } else {
383
- // @ts-ignore
384
- return new LegacyTokenizerModel(config, ...args);
385
- }
386
- }
387
- throw new Error(`Unknown TokenizerModel type: ${config.type}`);
388
- }
389
- }
390
-
391
- /**
392
- * Internal function to call the TokenizerModel instance.
393
- * @param {string[]} tokens The tokens to encode.
394
- * @returns {string[]} The encoded tokens.
395
- */
396
- _call(tokens) {
397
- tokens = this.encode(tokens);
398
- if (this.fuse_unk) {
399
- // Fuse unknown tokens
400
- tokens = fuse_unk(tokens, this.tokens_to_ids, this.unk_token_id);
401
- }
402
- return tokens;
403
- }
404
-
405
- /**
406
- * Encodes a list of tokens into a list of token IDs.
407
- * @param {string[]} tokens The tokens to encode.
408
- * @returns {string[]} The encoded tokens.
409
- * @throws Will throw an error if not implemented in a subclass.
410
- */
411
- encode(tokens) {
412
- throw Error("encode should be implemented in subclass.")
413
- }
414
-
415
- /**
416
- * Converts a list of tokens into a list of token IDs.
417
- * @param {string[]} tokens The tokens to convert.
418
- * @returns {number[]} The converted token IDs.
419
- */
420
- convert_tokens_to_ids(tokens) {
421
- return tokens.map(t => this.tokens_to_ids.get(t) ?? this.unk_token_id);
422
- }
423
-
424
- /**
425
- * Converts a list of token IDs into a list of tokens.
426
- * @param {number[]|bigint[]} ids The token IDs to convert.
427
- * @returns {string[]} The converted tokens.
428
- */
429
- convert_ids_to_tokens(ids) {
430
- return ids.map(i => this.vocab[i] ?? this.unk_token);
431
- }
432
- }
433
-
434
- /**
435
- * A subclass of TokenizerModel that uses WordPiece encoding to encode tokens.
436
- * @extends TokenizerModel
437
- */
438
- class WordPieceTokenizer extends TokenizerModel {
439
- /**
440
- * @param {Object} config The configuration object.
441
- * @param {Object} config.vocab A mapping of tokens to ids.
442
- * @param {string} config.unk_token The unknown token string.
443
- * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords.
444
- * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word.
445
- */
446
- constructor(config) {
447
- super(config);
448
- /**
449
- * A mapping of tokens to ids.
450
- * @type {Map<string, number>}
451
- */
452
- this.tokens_to_ids = objectToMap(config.vocab);
453
-
454
- /**
455
- * The id of the unknown token.
456
- * @type {number}
457
- */
458
- this.unk_token_id = this.tokens_to_ids.get(config.unk_token);
459
-
460
- /**
461
- * The unknown token string.
462
- * @type {string}
463
- */
464
- this.unk_token = config.unk_token;
465
-
466
- /**
467
- * The maximum number of characters allowed per word.
468
- * @type {number}
469
- */
470
- this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100;
471
-
472
- /**
473
- * An array of tokens.
474
- * @type {string[]}
475
- */
476
- this.vocab = new Array(this.tokens_to_ids.size);
477
- for (const [key, value] of this.tokens_to_ids) {
478
- this.vocab[value] = key;
479
- }
480
- }
481
-
482
- /**
483
- * Encodes an array of tokens using WordPiece encoding.
484
- * @param {string[]} tokens The tokens to encode.
485
- * @returns {string[]} An array of encoded tokens.
486
- */
487
- encode(tokens) {
488
- const outputTokens = [];
489
- for (const token of tokens) {
490
- const chars = [...token];
491
- if (chars.length > this.max_input_chars_per_word) {
492
- outputTokens.push(this.unk_token);
493
- continue;
494
- }
495
-
496
- let isUnknown = false;
497
- let start = 0;
498
- const subTokens = [];
499
-
500
- while (start < chars.length) {
501
- let end = chars.length;
502
- let currentSubstring = null;
503
- while (start < end) {
504
- let substr = chars.slice(start, end).join('');
505
-
506
- if (start > 0) {
507
- substr = this.config.continuing_subword_prefix + substr;
508
- }
509
- if (this.tokens_to_ids.has(substr)) {
510
- currentSubstring = substr;
511
- break;
512
- }
513
-
514
- --end;
515
- }
516
- if (currentSubstring === null) {
517
- isUnknown = true;
518
- break;
519
- }
520
- subTokens.push(currentSubstring);
521
- start = end;
522
- }
523
- if (isUnknown) {
524
- outputTokens.push(this.unk_token);
525
- } else {
526
- outputTokens.push(...subTokens);
527
- }
528
- }
529
-
530
- return outputTokens;
531
- }
532
-
533
- }
534
-
535
- /**
536
- * Class representing a Unigram tokenizer model.
537
- * @extends TokenizerModel
538
- */
539
- class Unigram extends TokenizerModel {
540
- /**
541
- * Create a new Unigram tokenizer model.
542
- * @param {Object} config The configuration object for the Unigram model.
543
- * @param {number} config.unk_id The ID of the unknown token
544
- * @param {[string, number][]} config.vocab A 2D array representing a mapping of tokens to scores.
545
- * @param {Object} moreConfig Additional configuration object for the Unigram model.
546
- */
547
- constructor(config, moreConfig) {
548
- super(config);
549
-
550
- const vocabSize = config.vocab.length;
551
- this.vocab = new Array(vocabSize);
552
- /** @type {number[]} */
553
- this.scores = new Array(vocabSize);
554
- for (let i = 0; i < vocabSize; ++i) {
555
- [this.vocab[i], this.scores[i]] = config.vocab[i];
556
- }
557
-
558
- this.unk_token_id = config.unk_id;
559
- this.unk_token = this.vocab[config.unk_id];
560
-
561
- this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i]));
562
- this.bos_token = ' '; // beginning of a sentence token
563
-
564
- this.bos_token_id = this.tokens_to_ids.get(this.bos_token); // NOTE: may be undefined
565
- this.eos_token = moreConfig.eos_token;
566
-
567
- this.eos_token_id = this.tokens_to_ids.get(this.eos_token);
568
- this.unk_token = this.vocab[this.unk_token_id];
569
-
570
- this.minScore = min(this.scores)[0];
571
-
572
- this.unk_score = this.minScore - 10.0;
573
- this.scores[this.unk_token_id] = this.unk_score;
574
-
575
- this.trie = new CharTrie();
576
- this.trie.extend(this.vocab);
577
-
578
- // NOTE: `fuse_unk` is hardcoded to true for Unigram models
579
- // See: https://github.com/huggingface/tokenizers/blob/b58227c7f1ccf8b73ee2268354336da56d91e492/tokenizers/src/models/unigram/model.rs#L119
580
- this.fuse_unk = true;
581
- }
582
-
583
- /**
584
- * Populates lattice nodes.
585
- * @param {TokenLattice} lattice The token lattice to populate with nodes.
586
- */
587
- populateNodes(lattice) {
588
- const chars = lattice.chars;
589
- const mblen = 1;
590
- let beginPos = 0;
591
- while (beginPos < chars.length) {
592
- let hasSingleNode = false;
593
-
594
- const tokens = [];
595
- const sliced = chars.slice(beginPos).join('');
596
- const prefixedTokens = this.trie.commonPrefixSearch(sliced);
597
- for (const token of prefixedTokens) {
598
- tokens.push(token);
599
- const tokenId = this.tokens_to_ids.get(token);
600
- const tokenScore = this.scores[tokenId];
601
- const n = len(token);
602
- lattice.insert(beginPos, n, tokenScore, tokenId);
603
- if (!hasSingleNode && n === mblen) {
604
- hasSingleNode = true;
605
- }
606
- }
607
- if (!hasSingleNode) {
608
- lattice.insert(beginPos, mblen, this.unk_score, this.unk_token_id);
609
- }
610
- beginPos += mblen;
611
- }
612
- }
613
-
614
- /**
615
- * Encodes an array of tokens into an array of subtokens using the unigram model.
616
- *
617
- * @param {string} normalized The normalized string.
618
- * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model.
619
- */
620
- tokenize(normalized) {
621
- const lattice = new TokenLattice(normalized, this.bos_token_id, this.eos_token_id);
622
- this.populateNodes(lattice);
623
- return lattice.tokens();
624
- }
625
-
626
- /**
627
- * Encodes an array of tokens using Unigram encoding.
628
- * @param {string[]} tokens The tokens to encode.
629
- * @returns {string[]} An array of encoded tokens.
630
- */
631
- encode(tokens) {
632
- const toReturn = [];
633
- for (const token of tokens) {
634
- const tokenized = this.tokenize(token);
635
- toReturn.push(...tokenized);
636
- }
637
- return toReturn;
638
- }
639
-
640
- }
641
-
642
- /**
643
- * Returns list of utf-8 byte and a mapping to unicode strings.
644
- * Specifically avoids mapping to whitespace/control characters the BPE code barfs on.
645
- * @returns {Object} Object with utf-8 byte keys and unicode string values.
646
- */
647
- const BYTES_TO_UNICODE = (() => {
648
- // Returns list of utf-8 byte and a mapping to unicode strings.
649
- // We specifically avoids mapping to whitespace/control characters
650
- // the bpe code barfs on.
651
-
652
- const bs = [
653
- ...Array.from({ length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, (_, i) => i + "!".charCodeAt(0)),
654
- ...Array.from({ length: "¬".charCodeAt(0) - "¡".charCodeAt(0) + 1 }, (_, i) => i + "¡".charCodeAt(0)),
655
- ...Array.from({ length: "ÿ".charCodeAt(0) - "®".charCodeAt(0) + 1 }, (_, i) => i + "®".charCodeAt(0)),
656
- ];
657
- const cs = bs.slice();
658
- let n = 0;
659
- for (let b = 0; b < 256; ++b) {
660
- if (!bs.includes(b)) {
661
- bs.push(b);
662
- cs.push(256 + n);
663
- n += 1;
664
- }
665
- }
666
- const ccs = cs.map(n => String.fromCharCode(n));
667
- return Object.fromEntries(bs.map((b, i) => [b, ccs[i]]));
668
- })();
669
-
670
- const UNICODE_TO_BYTES = reverseDictionary(BYTES_TO_UNICODE);
671
-
672
-
673
- /**
674
- * @typedef {Object} BPENode
675
- * @property {string} token The token associated with the node
676
- * @property {number} bias A positional bias for the node.
677
- * @property {number} [score] The score of the node.
678
- * @property {BPENode} [prev] The previous node in the linked list.
679
- * @property {BPENode} [next] The next node in the linked list.
680
- */
681
-
682
- /**
683
- * BPE class for encoding text into Byte-Pair-Encoding (BPE) tokens.
684
- * @extends TokenizerModel
685
- */
686
- class BPE extends TokenizerModel {
687
- /**
688
- * Create a BPE instance.
689
- * @param {Object} config The configuration object for BPE.
690
- * @param {Object} config.vocab A mapping of tokens to ids.
691
- * @param {string[]|[string, string][]} config.merges An array of BPE merges as strings.
692
- * @param {string} config.unk_token The unknown token used for out of vocabulary words.
693
- * @param {string} config.end_of_word_suffix The suffix to place at the end of each word.
694
- * @param {string} [config.continuing_subword_suffix] The suffix to insert between words.
695
- * @param {boolean} [config.byte_fallback=false] Whether to use spm byte-fallback trick (defaults to False)
696
- * @param {boolean} [config.ignore_merges=false] Whether or not to match tokens with the vocab before using merges.
697
- */
698
- constructor(config) {
699
- super(config);
700
-
701
- /** @type {Map<string, number>} */
702
- this.tokens_to_ids = objectToMap(config.vocab);
703
-
704
- this.unk_token_id = this.tokens_to_ids.get(config.unk_token);
705
- this.unk_token = config.unk_token;
706
-
707
- this.vocab = new Array(this.tokens_to_ids.size);
708
- for (const [key, value] of this.tokens_to_ids) {
709
- this.vocab[value] = key;
710
- }
711
-
712
- // Tokenizers >= 0.20.0 serializes BPE merges as a [string, string][] instead of a string[],
713
- // which resolves the ambiguity for merges containing spaces.
714
- const use_new_merge_format = Array.isArray(config.merges[0]);
715
-
716
- /** @type {[string, string][]} */
717
- this.merges = use_new_merge_format
718
- ? /** @type {[string, string][]} */(config.merges)
719
- : (/** @type {string[]} */(config.merges)).map(x => /** @type {[string, string]} */(x.split(' ', 2)));
720
- this.bpe_ranks = new Map(this.merges.map((x, i) => [JSON.stringify(x), i]));
721
-
722
- this.end_of_word_suffix = config.end_of_word_suffix;
723
-
724
- // NOTE: `continuing_subword_suffix` is custom (to support `BlenderbotSmallTokenizer`)
725
- this.continuing_subword_suffix = config.continuing_subword_suffix ?? null;
726
-
727
- this.byte_fallback = this.config.byte_fallback ?? false;
728
-
729
- if (this.byte_fallback) {
730
- this.text_encoder = new TextEncoder();
731
- }
732
-
733
- this.ignore_merges = this.config.ignore_merges ?? false;
734
-
735
- /**
736
- * The maximum length we should cache in a model.
737
- * Strings that are too long have minimal chances to cache hit anyway
738
- */
739
- this.max_length_to_cache = 256;
740
-
741
- /**
742
- * The default capacity for a `BPE`'s internal cache.
743
- */
744
- this.cache_capacity = 10000;
745
- this.cache = new LRUCache(this.cache_capacity);
746
- }
747
-
748
- /**
749
- * Clears the cache.
750
- */
751
- clear_cache() {
752
- this.cache.clear();
753
- }
754
-
755
- /**
756
- * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority
757
- * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js.
758
- * @param {string} token The token to encode.
759
- * @returns {string[]} The BPE encoded tokens.
760
- */
761
- bpe(token) {
762
- if (token.length === 0) {
763
- return [];
764
- }
765
-
766
- const cached = this.cache.get(token);
767
- if (cached !== undefined) {
768
- return cached;
769
- }
770
-
771
- const word = Array.from(token);
772
- if (this.end_of_word_suffix) {
773
- word[word.length - 1] += this.end_of_word_suffix;
774
- }
775
-
776
- let result = [];
777
- if (word.length > 1) {
778
- // Create a priority queue to store the nodes that will be merged.
779
- // The comparator function compares the scores of the nodes.
780
- const queue = new PriorityQueue((a, b) => a.score < b.score);
781
-
782
- // Construct a doubly-linked list of nodes that will be inserted into the priority queue,
783
- // starting with the individual characters. We also populate each node with a positional
784
- // bias to break ties in the priority queue.
785
- let startingNode = {
786
- token: word[0],
787
- bias: 0,
788
- prev: null,
789
- next: null,
790
- }
791
-
792
- let previousNode = startingNode
793
- for (let i = 1; i < word.length; ++i) {
794
- const currentNode = {
795
- bias: i / word.length, // Add fractional component to break ties
796
- token: word[i],
797
- prev: previousNode,
798
- next: null,
799
- }
800
- previousNode.next = currentNode
801
- this._add_node(queue, previousNode)
802
- previousNode = currentNode
803
- }
804
-
805
- while (!queue.isEmpty()) {
806
- // Get the next node with the highest priority
807
- const node = queue.pop();
808
-
809
- // Check that this merge is still possible
810
- if (node.deleted || !node.next || node.next.deleted) continue;
811
-
812
- // Here, we mark the current node (left side of the merge) and the next node (right side of the merge) as deleted.
813
- // This is because they will both be replaced by a new node representing the merge result.
814
- node.deleted = true;
815
- node.next.deleted = true;
816
-
817
- // Next, we fix the node that comes before the current node (i.e., left side of the merge).
818
- if (node.prev) {
819
-
820
- // Make a shallow copy of the previous node
821
- const newPreviousNode = { ...node.prev };
822
-
823
- // Mark the old previous node as deleted. This avoids erroneous merges later,
824
- // because there may still be references to this node in the priority queue.
825
- node.prev.deleted = true;
826
- node.prev = newPreviousNode;
827
-
828
- // Update the reference of the previous node, by pointing its previous node to this new previous node.
829
- if (newPreviousNode.prev) {
830
- newPreviousNode.prev.next = newPreviousNode;
831
- } else {
832
- // If the previous of the previous node does not exist, it means that
833
- // `newPreviousNode` must be the new `startingNode`.
834
- startingNode = newPreviousNode;
835
- }
836
- }
837
-
838
- // Create a new node which represents the result of the merge.
839
- const merged = {
840
- token: node.token + node.next.token,
841
- bias: node.bias,
842
- prev: node.prev,
843
- next: node.next.next,
844
- }
845
-
846
- // We now consider where we can add the new merged node to the priority queue:
847
- // 1. prev <-> merged
848
- if (merged.prev) {
849
- merged.prev.next = merged;
850
- this._add_node(queue, merged.prev);
851
- } else {
852
- // If `merged.prev` does not exist, then `merged` must be the new `startingNode`.
853
- startingNode = merged;
854
- }
855
-
856
- // 2. merged <-> next
857
- if (merged.next) {
858
- merged.next.prev = merged;
859
- this._add_node(queue, merged);
860
- }
861
- }
862
-
863
- // Traverse the linked list, starting from the `startingNode`, and collect the tokens.
864
- for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) {
865
- result.push(currentNode.token);
866
- }
867
- } else {
868
- result = word;
869
- }
870
-
871
- // Possibly append suffix
872
- if (this.continuing_subword_suffix) {
873
- // Do not append suffix to the last token
874
- for (let i = 0; i < result.length - 1; ++i) {
875
- result[i] += this.continuing_subword_suffix;
876
- }
877
- }
878
-
879
- if (token.length < this.max_length_to_cache) {
880
- // Save the result to the cache
881
- this.cache.put(token, result);
882
- }
883
-
884
- return result;
885
- }
886
-
887
-
888
- /**
889
- * Helper function to add a node to the priority queue.
890
- * @param {PriorityQueue} queue
891
- * @param {BPENode} node
892
- * @private
893
- */
894
- _add_node(queue, node) {
895
- // `score` is a measure of the merge priority: lower means higher priority
896
- // We use the BPE rank as a measure of priority (i.e., the local of the merge in the merges list)
897
- // We also add a fractional component to the score to break ties (with the earlier character having higher priority)
898
- const rank = this.bpe_ranks.get(JSON.stringify([node.token, node.next.token]));
899
- if (rank !== undefined) {
900
- node.score = rank + node.bias;
901
- queue.push(node);
902
- }
903
- }
904
-
905
- /**
906
- * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens.
907
- * @param {string[]} tokens The input sequence of tokens to encode.
908
- * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens.
909
- */
910
- encode(tokens) {
911
- const outputTokens = [];
912
-
913
- for (const token of tokens) {
914
- if (this.ignore_merges && this.tokens_to_ids.has(token)) {
915
- outputTokens.push(token);
916
- continue;
917
- }
918
- const bpe_token_list = this.bpe(token);
919
-
920
- for (const t of bpe_token_list) {
921
- if (this.tokens_to_ids.has(t)) {
922
- outputTokens.push(t);
923
- } else if (this.byte_fallback) {
924
- const byteTokens = Array.from(this.text_encoder.encode(t))
925
- .map(x => `<0x${x.toString(16).toUpperCase().padStart(2, '0')}>`);
926
- if (byteTokens.every(x => this.tokens_to_ids.has(x))) {
927
- // Ensure the byte tokens are actually in the vocabulary, otherwise
928
- // we fall back to the unknown token. For more information, see
929
- // https://github.com/huggingface/transformers/issues/28096.
930
- outputTokens.push(...byteTokens);
931
- } else {
932
- outputTokens.push(this.unk_token);
933
- }
934
- } else {
935
- outputTokens.push(this.unk_token);
936
- }
937
- }
938
- }
939
-
940
- return outputTokens;
941
- }
942
-
943
- }
944
-
945
- /**
946
- * Legacy tokenizer class for tokenizers with only a vocabulary.
947
- */
948
- class LegacyTokenizerModel extends TokenizerModel {
949
- /**
950
- * Create a LegacyTokenizerModel instance.
951
- * @param {Object} config The configuration object for LegacyTokenizerModel.
952
- * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids.
953
- * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model.
954
- */
955
- constructor(config, moreConfig) {
956
- super(config);
957
-
958
- /**@type {Map<string, number>} */
959
- this.tokens_to_ids = objectToMap(
960
- moreConfig.target_lang
961
- ? config.vocab[moreConfig.target_lang]
962
- : config.vocab
963
- );
964
-
965
- this.bos_token = moreConfig.bos_token;
966
- this.bos_token_id = this.tokens_to_ids.get(this.bos_token);
967
-
968
- this.eos_token = moreConfig.eos_token;
969
- this.eos_token_id = this.tokens_to_ids.get(this.eos_token);
970
-
971
- this.pad_token = moreConfig.pad_token;
972
- this.pad_token_id = this.tokens_to_ids.get(this.pad_token);
973
-
974
- this.unk_token = moreConfig.unk_token;
975
- this.unk_token_id = this.tokens_to_ids.get(this.unk_token);
976
-
977
- this.vocab = new Array(this.tokens_to_ids.size);
978
- for (const [key, value] of this.tokens_to_ids) {
979
- this.vocab[value] = key;
980
- }
981
- }
982
-
983
- encode(tokens) {
984
- return tokens;
985
- }
986
- }
987
-
988
-
989
- /**
990
- * A base class for text normalization.
991
- * @abstract
992
- */
993
- class Normalizer extends Callable {
994
- /**
995
- * @param {Object} config The configuration object for the normalizer.
996
- */
997
- constructor(config) {
998
- super();
999
- this.config = config;
1000
- }
1001
-
1002
- /**
1003
- * Factory method for creating normalizers from config objects.
1004
- * @static
1005
- * @param {Object} config The configuration object for the normalizer.
1006
- * @returns {Normalizer} A Normalizer object.
1007
- * @throws {Error} If an unknown Normalizer type is specified in the config.
1008
- */
1009
- static fromConfig(config) {
1010
- if (config === null) return null;
1011
- switch (config.type) {
1012
- case 'BertNormalizer':
1013
- return new BertNormalizer(config);
1014
- case 'Precompiled':
1015
- return new Precompiled(config);
1016
- case 'Sequence':
1017
- return new NormalizerSequence(config);
1018
- case 'Replace':
1019
- return new Replace(config);
1020
- case 'NFC':
1021
- return new NFC(config);
1022
- case 'NFD':
1023
- return new NFD(config);
1024
- case 'NFKC':
1025
- return new NFKC(config);
1026
- case 'NFKD':
1027
- return new NFKD(config);
1028
- case 'Strip':
1029
- return new StripNormalizer(config);
1030
- case 'StripAccents':
1031
- return new StripAccents(config);
1032
- case 'Lowercase':
1033
- return new Lowercase(config);
1034
- case 'Prepend':
1035
- return new Prepend(config);
1036
- default:
1037
- throw new Error(`Unknown Normalizer type: ${config.type}`);
1038
- }
1039
- }
1040
-
1041
- /**
1042
- * Normalize the input text.
1043
- * @abstract
1044
- * @param {string} text The text to normalize.
1045
- * @returns {string} The normalized text.
1046
- * @throws {Error} If this method is not implemented in a subclass.
1047
- */
1048
- normalize(text) {
1049
- throw Error("normalize should be implemented in subclass.")
1050
- }
1051
-
1052
- /**
1053
- * Alias for {@link Normalizer#normalize}.
1054
- * @param {string} text The text to normalize.
1055
- * @returns {string} The normalized text.
1056
- */
1057
- _call(text) {
1058
- return this.normalize(text);
1059
- }
1060
-
1061
- }
1062
-
1063
- /**
1064
- * Replace normalizer that replaces occurrences of a pattern with a given string or regular expression.
1065
- * @extends Normalizer
1066
- */
1067
- class Replace extends Normalizer {
1068
- /**
1069
- * Normalize the input text by replacing the pattern with the content.
1070
- * @param {string} text The input text to be normalized.
1071
- * @returns {string} The normalized text after replacing the pattern with the content.
1072
- */
1073
- normalize(text) {
1074
- const pattern = createPattern(this.config.pattern);
1075
- return pattern === null
1076
- ? text
1077
- : text.replaceAll(pattern, this.config.content);
1078
- }
1079
- }
1080
-
1081
- /**
1082
- * A normalizer that applies Unicode normalization to the input text.
1083
- * @extends Normalizer
1084
- * @abstract
1085
- */
1086
- class UnicodeNormalizer extends Normalizer {
1087
- /**
1088
- * @type {string} The Unicode normalization form to apply.
1089
- * Should be one of: 'NFC', 'NFD', 'NFKC', or 'NFKD'.
1090
- */
1091
- form = undefined;
1092
-
1093
- /**
1094
- * Normalize the input text by applying Unicode normalization.
1095
- * @param {string} text The input text to be normalized.
1096
- * @returns {string} The normalized text.
1097
- */
1098
- normalize(text) {
1099
- text = text.normalize(this.form)
1100
- return text;
1101
- }
1102
- }
1103
-
1104
- /**
1105
- * A normalizer that applies Unicode normalization form C (NFC) to the input text.
1106
- * Canonical Decomposition, followed by Canonical Composition.
1107
- * @extends UnicodeNormalizer
1108
- */
1109
- class NFC extends UnicodeNormalizer {
1110
- form = 'NFC';
1111
- }
1112
-
1113
- /**
1114
- * A normalizer that applies Unicode normalization form D (NFD) to the input text.
1115
- * Canonical Decomposition.
1116
- * @extends UnicodeNormalizer
1117
- */
1118
- class NFD extends UnicodeNormalizer {
1119
- form = 'NFD';
1120
- }
1121
-
1122
- /**
1123
- * A normalizer that applies Unicode normalization form KC (NFKC) to the input text.
1124
- * Compatibility Decomposition, followed by Canonical Composition.
1125
- * @extends UnicodeNormalizer
1126
- */
1127
- class NFKC extends UnicodeNormalizer {
1128
- form = 'NFKC';
1129
- }
1130
-
1131
- /**
1132
- * A normalizer that applies Unicode normalization form KD (NFKD) to the input text.
1133
- * Compatibility Decomposition.
1134
- * @extends UnicodeNormalizer
1135
- */
1136
- class NFKD extends UnicodeNormalizer {
1137
- form = 'NFKD';
1138
- }
1139
-
1140
- /**
1141
- * A normalizer that strips leading and/or trailing whitespace from the input text.
1142
- */
1143
- class StripNormalizer extends Normalizer {
1144
- /**
1145
- * Strip leading and/or trailing whitespace from the input text.
1146
- * @param {string} text The input text.
1147
- * @returns {string} The normalized text.
1148
- */
1149
- normalize(text) {
1150
- if (this.config.strip_left && this.config.strip_right) {
1151
- // Fast path to avoid an extra trim call
1152
- text = text.trim();
1153
- } else {
1154
- if (this.config.strip_left) {
1155
- text = text.trimStart();
1156
- }
1157
- if (this.config.strip_right) {
1158
- text = text.trimEnd();
1159
- }
1160
- }
1161
- return text;
1162
- }
1163
- }
1164
-
1165
- /**
1166
- * StripAccents normalizer removes all accents from the text.
1167
- * @extends Normalizer
1168
- */
1169
- class StripAccents extends Normalizer {
1170
- /**
1171
- * Remove all accents from the text.
1172
- * @param {string} text The input text.
1173
- * @returns {string} The normalized text without accents.
1174
- */
1175
- normalize(text) {
1176
- text = remove_accents(text);
1177
- return text;
1178
- }
1179
- }
1180
-
1181
- /**
1182
- * A Normalizer that lowercases the input string.
1183
- * @extends Normalizer
1184
- */
1185
- class Lowercase extends Normalizer {
1186
- /**
1187
- * Lowercases the input string.
1188
- * @param {string} text The text to normalize.
1189
- * @returns {string} The normalized text.
1190
- */
1191
- normalize(text) {
1192
- text = text.toLowerCase();
1193
- return text;
1194
- }
1195
- }
1196
-
1197
- /**
1198
- * A Normalizer that prepends a string to the input string.
1199
- * @extends Normalizer
1200
- */
1201
- class Prepend extends Normalizer {
1202
- /**
1203
- * Prepends the input string.
1204
- * @param {string} text The text to normalize.
1205
- * @returns {string} The normalized text.
1206
- */
1207
- normalize(text) {
1208
- text = this.config.prepend + text;
1209
- return text;
1210
- }
1211
- }
1212
-
1213
- /**
1214
- * A Normalizer that applies a sequence of Normalizers.
1215
- * @extends Normalizer
1216
- */
1217
- class NormalizerSequence extends Normalizer {
1218
- /**
1219
- * Create a new instance of NormalizerSequence.
1220
- * @param {Object} config The configuration object.
1221
- * @param {Object[]} config.normalizers An array of Normalizer configuration objects.
1222
- */
1223
- constructor(config) {
1224
- super(config);
1225
- this.normalizers = config.normalizers.map(x => Normalizer.fromConfig(x));
1226
- }
1227
- /**
1228
- * Apply a sequence of Normalizers to the input text.
1229
- * @param {string} text The text to normalize.
1230
- * @returns {string} The normalized text.
1231
- */
1232
- normalize(text) {
1233
- return this.normalizers.reduce((t, normalizer) => {
1234
- return normalizer.normalize(t);
1235
- }, text);
1236
- }
1237
- }
1238
-
1239
- /**
1240
- * A class representing a normalizer used in BERT tokenization.
1241
- * @extends Normalizer
1242
- */
1243
- class BertNormalizer extends Normalizer {
1244
- /**
1245
- * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text.
1246
- *
1247
- * @param {string} text The input text to tokenize.
1248
- * @returns {string} The tokenized text with whitespace added around CJK characters.
1249
- */
1250
- _tokenize_chinese_chars(text) {
1251
- /* Adds whitespace around any CJK character. */
1252
- const output = [];
1253
- for (let i = 0; i < text.length; ++i) {
1254
- const char = text[i];
1255
- const cp = char.charCodeAt(0);
1256
- if (is_chinese_char(cp)) {
1257
- output.push(" ");
1258
- output.push(char);
1259
- output.push(" ");
1260
- } else {
1261
- output.push(char);
1262
- }
1263
- }
1264
- return output.join("");
1265
- }
1266
-
1267
- /**
1268
- * Strips accents from the given text.
1269
- * @param {string} text The text to strip accents from.
1270
- * @returns {string} The text with accents removed.
1271
- */
1272
- stripAccents(text) {
1273
- // "Mark, Nonspacing" (Mn)
1274
- return text.normalize('NFD').replace(/\p{Mn}/gu, '');
1275
- }
1276
-
1277
-
1278
- /**
1279
- * Checks whether `char` is a control character.
1280
- * @param {string} char The character to check.
1281
- * @returns {boolean} Whether `char` is a control character.
1282
- * @private
1283
- */
1284
- _is_control(char) {
1285
- switch (char) {
1286
- case '\t':
1287
- case '\n':
1288
- case '\r':
1289
- // These are technically control characters but we count them as whitespace characters.
1290
- return false;
1291
-
1292
- default:
1293
- // Check if unicode category starts with C:
1294
- // Cc - Control
1295
- // Cf - Format
1296
- // Co - Private Use
1297
- // Cs - Surrogate
1298
- return /^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(char);
1299
- }
1300
- }
1301
-
1302
- /**
1303
- * Performs invalid character removal and whitespace cleanup on text.
1304
- * @param {string} text The text to clean.
1305
- * @returns {string} The cleaned text.
1306
- * @private
1307
- */
1308
- _clean_text(text) {
1309
- const output = [];
1310
- for (const char of text) {
1311
- const cp = char.charCodeAt(0);
1312
- if (cp === 0 || cp === 0xFFFD || this._is_control(char)) {
1313
- continue;
1314
- }
1315
- if (/^\s$/.test(char)) { // is whitespace
1316
- output.push(" ");
1317
- } else {
1318
- output.push(char);
1319
- }
1320
- }
1321
- return output.join("");
1322
- }
1323
- /**
1324
- * Normalizes the given text based on the configuration.
1325
- * @param {string} text The text to normalize.
1326
- * @returns {string} The normalized text.
1327
- */
1328
- normalize(text) {
1329
- if (this.config.clean_text) {
1330
- text = this._clean_text(text);
1331
- }
1332
-
1333
- if (this.config.handle_chinese_chars) {
1334
- text = this._tokenize_chinese_chars(text);
1335
- }
1336
-
1337
- if (this.config.lowercase) {
1338
- text = text.toLowerCase();
1339
-
1340
- if (this.config.strip_accents !== false) {
1341
- text = this.stripAccents(text);
1342
- }
1343
- } else if (this.config.strip_accents) {
1344
- text = this.stripAccents(text);
1345
- }
1346
-
1347
- return text;
1348
- }
1349
- }
1350
-
1351
- /**
1352
- * A callable class representing a pre-tokenizer used in tokenization. Subclasses
1353
- * should implement the `pre_tokenize_text` method to define the specific pre-tokenization logic.
1354
- * @extends Callable
1355
- */
1356
- class PreTokenizer extends Callable {
1357
- /**
1358
- * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration.
1359
- *
1360
- * @static
1361
- * @param {Object} config A configuration object for the pre-tokenizer.
1362
- * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`.
1363
- * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer.
1364
- */
1365
- static fromConfig(config) {
1366
- if (config === null) return null;
1367
-
1368
- switch (config.type) {
1369
- case 'BertPreTokenizer':
1370
- return new BertPreTokenizer(config);
1371
- case 'Sequence':
1372
- return new PreTokenizerSequence(config);
1373
- case 'Whitespace':
1374
- return new WhitespacePreTokenizer(config);
1375
- case 'WhitespaceSplit':
1376
- return new WhitespaceSplit(config);
1377
- case 'Metaspace':
1378
- return new MetaspacePreTokenizer(config);
1379
-
1380
- case 'ByteLevel':
1381
- return new ByteLevelPreTokenizer(config);
1382
- case 'Split':
1383
- return new SplitPreTokenizer(config);
1384
- case 'Punctuation':
1385
- return new PunctuationPreTokenizer(config);
1386
- case 'Digits':
1387
- return new DigitsPreTokenizer(config);
1388
- case 'Replace':
1389
- return new ReplacePreTokenizer(config);
1390
- default:
1391
- throw new Error(`Unknown PreTokenizer type: ${config.type}`);
1392
- }
1393
- }
1394
-
1395
- /**
1396
- * Method that should be implemented by subclasses to define the specific pre-tokenization logic.
1397
- *
1398
- * @abstract
1399
- * @param {string} text The text to pre-tokenize.
1400
- * @param {Object} [options] Additional options for the pre-tokenization logic.
1401
- * @returns {string[]} The pre-tokenized text.
1402
- * @throws {Error} If the method is not implemented in the subclass.
1403
- */
1404
- pre_tokenize_text(text, options) {
1405
- throw Error("pre_tokenize_text should be implemented in subclass.")
1406
- }
1407
-
1408
- /**
1409
- * Tokenizes the given text into pre-tokens.
1410
- * @param {string|string[]} text The text or array of texts to pre-tokenize.
1411
- * @param {Object} [options] Additional options for the pre-tokenization logic.
1412
- * @returns {string[]} An array of pre-tokens.
1413
- */
1414
- pre_tokenize(text, options) {
1415
- return (Array.isArray(text)
1416
- ? text.map(x => this.pre_tokenize_text(x, options))
1417
- : this.pre_tokenize_text(text, options)
1418
- ).flat();
1419
- }
1420
-
1421
- /**
1422
- * Alias for {@link PreTokenizer#pre_tokenize}.
1423
- * @param {string|string[]} text The text or array of texts to pre-tokenize.
1424
- * @param {Object} [options] Additional options for the pre-tokenization logic.
1425
- * @returns {string[]} An array of pre-tokens.
1426
- */
1427
- _call(text, options) {
1428
- return this.pre_tokenize(text, options);
1429
- }
1430
- }
1431
-
1432
- /**
1433
- * @extends PreTokenizer
1434
- */
1435
- class BertPreTokenizer extends PreTokenizer {
1436
- /**
1437
- * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme
1438
- * similar to that used in the original implementation of BERT.
1439
- *
1440
- * @param {Object} config The configuration object.
1441
- */
1442
- constructor(config) {
1443
- super();
1444
- // Construct a pattern which matches the rust implementation:
1445
- // https://github.com/huggingface/tokenizers/blob/b4fcc9ce6e4ad5806e82826f816acfdfdc4fcc67/tokenizers/src/pre_tokenizers/bert.rs#L11
1446
- // Equivalent to removing whitespace and splitting on punctuation (both \p{P} and other ascii characters)
1447
- this.pattern = new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, 'gu');
1448
- }
1449
- /**
1450
- * Tokenizes a single text using the BERT pre-tokenization scheme.
1451
- *
1452
- * @param {string} text The text to tokenize.
1453
- * @param {Object} [options] Additional options for the pre-tokenization logic.
1454
- * @returns {string[]} An array of tokens.
1455
- */
1456
- pre_tokenize_text(text, options) {
1457
- return text.trim().match(this.pattern) || [];
1458
- }
1459
- }
1460
-
1461
- /**
1462
- * A pre-tokenizer that splits text into Byte-Pair-Encoding (BPE) subwords.
1463
- * @extends PreTokenizer
1464
- */
1465
- class ByteLevelPreTokenizer extends PreTokenizer {
1466
- /**
1467
- * Creates a new instance of the `ByteLevelPreTokenizer` class.
1468
- * @param {Object} config The configuration object.
1469
- */
1470
- constructor(config) {
1471
- super();
1472
- this.config = config;
1473
-
1474
- /**
1475
- * @type {boolean} Whether to add a leading space to the first word.
1476
- * This allows to treat the leading word just as any other word.
1477
- */
1478
- this.add_prefix_space = this.config.add_prefix_space;
1479
-
1480
- /**
1481
- * @type {boolean} Whether the post processing step should trim offsets
1482
- * to avoid including whitespaces.
1483
- * @todo Use this in the pretokenization step.
1484
- */
1485
- this.trim_offsets = this.config.trim_offsets;
1486
-
1487
- /**
1488
- * @type {boolean} Whether to use the standard GPT2 regex for whitespace splitting.
1489
- * Set it to False if you want to use your own splitting. Defaults to true.
1490
- */
1491
- this.use_regex = this.config.use_regex ?? true;
1492
- this.pattern = /'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu;
1493
-
1494
- this.byte_encoder = BYTES_TO_UNICODE;
1495
- this.text_encoder = new TextEncoder();
1496
- }
1497
-
1498
- /**
1499
- * Tokenizes a single piece of text using byte-level tokenization.
1500
- * @param {string} text The text to tokenize.
1501
- * @param {Object} [options] Additional options for the pre-tokenization logic.
1502
- * @returns {string[]} An array of tokens.
1503
- */
1504
- pre_tokenize_text(text, options) {
1505
- // Add a leading space if the option is enabled
1506
- if (this.add_prefix_space && !text.startsWith(' ')) {
1507
- text = ' ' + text;
1508
- }
1509
-
1510
- // Split on whitespace and punctuation
1511
- const tokens = this.use_regex ? (text.match(this.pattern) || []) : [text];
1512
-
1513
- // Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
1514
- return tokens.map(
1515
- token => Array.from(this.text_encoder.encode(token), byte => this.byte_encoder[byte]).join('')
1516
- );
1517
- }
1518
- }
1519
-
1520
- /**
1521
- * @typedef {'removed'|'isolated'|'mergedWithPrevious'|'mergedWithNext'|'contiguous'} SplitDelimiterBehavior
1522
- */
1523
-
1524
- /**
1525
- * Splits text using a given pattern.
1526
- * @extends PreTokenizer
1527
- */
1528
- class SplitPreTokenizer extends PreTokenizer {
1529
- /**
1530
- * @param {Object} config The configuration options for the pre-tokenizer.
1531
- * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.
1532
- * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string.
1533
- * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex.
1534
- * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.
1535
- * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern.
1536
- */
1537
- constructor(config) {
1538
- super();
1539
- this.config = config;
1540
- // TODO support all behaviours (config.behavior)
1541
-
1542
- this.pattern = createPattern(this.config.pattern, this.config.invert);
1543
- }
1544
-
1545
- /**
1546
- * Tokenizes text by splitting it using the given pattern.
1547
- * @param {string} text The text to tokenize.
1548
- * @param {Object} [options] Additional options for the pre-tokenization logic.
1549
- * @returns {string[]} An array of tokens.
1550
- */
1551
- pre_tokenize_text(text, options) {
1552
- if (this.pattern === null) {
1553
- return [];
1554
- }
1555
-
1556
- if (this.config.invert) {
1557
- return text.match(this.pattern) || [];
1558
- } else if (this.config.behavior?.toLowerCase() === 'removed') {
1559
- return text.split(this.pattern).filter(x => x);
1560
- } else {
1561
- return regexSplit(text, this.pattern);
1562
- }
1563
- }
1564
- }
1565
-
1566
- /**
1567
- * Splits text based on punctuation.
1568
- * @extends PreTokenizer
1569
- */
1570
- class PunctuationPreTokenizer extends PreTokenizer {
1571
- /**
1572
- * @param {Object} config The configuration options for the pre-tokenizer.
1573
- * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.
1574
- */
1575
- constructor(config) {
1576
- super();
1577
- this.config = config;
1578
- this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, 'gu');
1579
- }
1580
-
1581
- /**
1582
- * Tokenizes text by splitting it using the given pattern.
1583
- * @param {string} text The text to tokenize.
1584
- * @param {Object} [options] Additional options for the pre-tokenization logic.
1585
- * @returns {string[]} An array of tokens.
1586
- */
1587
- pre_tokenize_text(text, options) {
1588
- return text.match(this.pattern) || [];
1589
- }
1590
- }
1591
-
1592
-
1593
- /**
1594
- * Splits text based on digits.
1595
- * @extends PreTokenizer
1596
- */
1597
- class DigitsPreTokenizer extends PreTokenizer {
1598
- /**
1599
- * @param {Object} config The configuration options for the pre-tokenizer.
1600
- * @param {boolean} config.individual_digits Whether to split on individual digits.
1601
- */
1602
- constructor(config) {
1603
- super();
1604
- this.config = config;
1605
-
1606
- // Construct a pattern which matches the rust implementation:
1607
- const digit_pattern = `[^\\d]+|\\d${this.config.individual_digits ? '' : '+'}`;
1608
- this.pattern = new RegExp(digit_pattern, 'gu');
1609
- }
1610
-
1611
- /**
1612
- * Tokenizes text by splitting it using the given pattern.
1613
- * @param {string} text The text to tokenize.
1614
- * @param {Object} [options] Additional options for the pre-tokenization logic.
1615
- * @returns {string[]} An array of tokens.
1616
- */
1617
- pre_tokenize_text(text, options) {
1618
- return text.match(this.pattern) || [];
1619
- }
1620
- }
1621
-
1622
- /**
1623
- * @typedef {Object} PostProcessedOutput
1624
- * @property {string[]} tokens List of token produced by the post-processor.
1625
- * @property {number[]} [token_type_ids] List of token type ids produced by the post-processor.
1626
- */
1627
-
1628
-
1629
- /**
1630
- * @typedef {Object} EncodingSingle
1631
- * @property {number[]} input_ids List of token ids to be fed to a model.
1632
- * @property {number[]} attention_mask List of token type ids to be fed to a model
1633
- * @property {number[]} [token_type_ids] List of indices specifying which tokens should be attended to by the model
1634
- */
1635
-
1636
-
1637
- /**
1638
- * @extends Callable
1639
- */
1640
- class PostProcessor extends Callable {
1641
-
1642
- /**
1643
- * @param {Object} config The configuration for the post-processor.
1644
- */
1645
- constructor(config) {
1646
- super();
1647
- this.config = config;
1648
- }
1649
-
1650
- /**
1651
- * Factory method to create a PostProcessor object from a configuration object.
1652
- *
1653
- * @param {Object} config Configuration object representing a PostProcessor.
1654
- * @returns {PostProcessor} A PostProcessor object created from the given configuration.
1655
- * @throws {Error} If an unknown PostProcessor type is encountered.
1656
- */
1657
- static fromConfig(config) {
1658
- if (config === null) return null;
1659
- switch (config.type) {
1660
- case 'TemplateProcessing':
1661
- return new TemplateProcessing(config);
1662
-
1663
- case 'ByteLevel':
1664
- return new ByteLevelPostProcessor(config);
1665
-
1666
- case 'RobertaProcessing':
1667
- return new RobertaProcessing(config);
1668
- case 'BertProcessing':
1669
- return new BertProcessing(config);
1670
-
1671
- case 'Sequence':
1672
- return new PostProcessorSequence(config);
1673
- default:
1674
- throw new Error(`Unknown PostProcessor type: ${config.type}`);
1675
- }
1676
- }
1677
-
1678
- /**
1679
- * Method to be implemented in subclass to apply post-processing on the given tokens.
1680
- *
1681
- * @param {Array} tokens The input tokens to be post-processed.
1682
- * @param {...*} args Additional arguments required by the post-processing logic.
1683
- * @returns {PostProcessedOutput} The post-processed tokens.
1684
- * @throws {Error} If the method is not implemented in subclass.
1685
- */
1686
- post_process(tokens, ...args) {
1687
- throw Error("post_process should be implemented in subclass.")
1688
- }
1689
-
1690
- /**
1691
- * Alias for {@link PostProcessor#post_process}.
1692
- * @param {Array} tokens The text or array of texts to post-process.
1693
- * @param {...*} args Additional arguments required by the post-processing logic.
1694
- * @returns {PostProcessedOutput} The post-processed tokens.
1695
- */
1696
- _call(tokens, ...args) {
1697
- return this.post_process(tokens, ...args);
1698
- }
1699
- }
1700
-
1701
- /**
1702
- * A post-processor that adds special tokens to the beginning and end of the input.
1703
- */
1704
- class BertProcessing extends PostProcessor {
1705
- /**
1706
- * @param {Object} config The configuration for the post-processor.
1707
- * @param {string[]} config.cls The special tokens to add to the beginning of the input.
1708
- * @param {string[]} config.sep The special tokens to add to the end of the input.
1709
- */
1710
- constructor(config) {
1711
- super(config);
1712
- // TODO use all of config: add_prefix_space, trim_offsets
1713
-
1714
- this.cls = config.cls[0];
1715
- this.sep = config.sep[0];
1716
- }
1717
-
1718
- /**
1719
- * Adds the special tokens to the beginning and end of the input.
1720
- * @param {string[]} tokens The input tokens.
1721
- * @param {string[]} [tokens_pair=null] An optional second set of input tokens.
1722
- * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end.
1723
- */
1724
- post_process(tokens, tokens_pair = null, {
1725
- add_special_tokens = true,
1726
- } = {}) {
1727
- if (add_special_tokens) {
1728
- tokens = mergeArrays([this.cls], tokens, [this.sep]);
1729
- }
1730
-
1731
- let token_type_ids = new Array(tokens.length).fill(0);
1732
- if (tokens_pair !== null) {
1733
- // NOTE: It is intended to add 2 EOS tokens after the first set of tokens
1734
- // https://github.com/huggingface/tokenizers/issues/983
1735
- const middle = (add_special_tokens && this instanceof RobertaProcessing)
1736
- ? [this.sep]
1737
- : [];
1738
- const after = add_special_tokens ? [this.sep] : [];
1739
-
1740
- tokens = mergeArrays(tokens, middle, tokens_pair, after);
1741
- token_type_ids = mergeArrays(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1));
1742
- }
1743
- return { tokens, token_type_ids };
1744
- }
1745
- }
1746
- class RobertaProcessing extends BertProcessing { } // NOTE: extends BertProcessing
1747
-
1748
- /**
1749
- * Post processor that replaces special tokens in a template with actual tokens.
1750
- * @extends PostProcessor
1751
- */
1752
- class TemplateProcessing extends PostProcessor {
1753
- /**
1754
- * Creates a new instance of `TemplateProcessing`.
1755
- * @param {Object} config The configuration options for the post processor.
1756
- * @param {Array} config.single The template for a single sequence of tokens.
1757
- * @param {Array} config.pair The template for a pair of sequences of tokens.
1758
- */
1759
- constructor(config) {
1760
- super(config);
1761
-
1762
- this.single = config.single;
1763
- this.pair = config.pair;
1764
- }
1765
-
1766
- /**
1767
- * Replaces special tokens in the template with actual tokens.
1768
- * @param {string[]} tokens The list of tokens for the first sequence.
1769
- * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
1770
- * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens.
1771
- */
1772
- post_process(tokens, tokens_pair = null, {
1773
- add_special_tokens = true,
1774
- } = {}) {
1775
- const type = tokens_pair === null ? this.single : this.pair
1776
-
1777
- let processedTokens = [];
1778
- let types = [];
1779
- for (const item of type) {
1780
- if ('SpecialToken' in item) {
1781
- if (add_special_tokens) {
1782
- processedTokens.push(item.SpecialToken.id);
1783
- types.push(item.SpecialToken.type_id);
1784
- }
1785
- } else if ('Sequence' in item) {
1786
- if (item.Sequence.id === 'A') {
1787
- processedTokens = mergeArrays(processedTokens, tokens);
1788
- types = mergeArrays(types, new Array(tokens.length).fill(item.Sequence.type_id));
1789
-
1790
- } else if (item.Sequence.id === 'B') {
1791
- processedTokens = mergeArrays(processedTokens, tokens_pair);
1792
- types = mergeArrays(types, new Array(tokens_pair.length).fill(item.Sequence.type_id));
1793
- }
1794
- }
1795
- }
1796
- return { tokens: processedTokens, token_type_ids: types };
1797
- }
1798
- }
1799
-
1800
- /**
1801
- * A PostProcessor that returns the given tokens as is.
1802
- * @extends PostProcessor
1803
- */
1804
- class ByteLevelPostProcessor extends PostProcessor {
1805
- /**
1806
- * Post process the given tokens.
1807
- * @param {string[]} tokens The list of tokens for the first sequence.
1808
- * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
1809
- * @returns {PostProcessedOutput} An object containing the post-processed tokens.
1810
- */
1811
- post_process(tokens, tokens_pair = null) {
1812
- if (tokens_pair) {
1813
- tokens = mergeArrays(tokens, tokens_pair);
1814
- }
1815
- return { tokens };
1816
- }
1817
- }
1818
-
1819
-
1820
- /**
1821
- * A post-processor that applies multiple post-processors in sequence.
1822
- */
1823
- class PostProcessorSequence extends PostProcessor {
1824
-
1825
- /**
1826
- * Creates a new instance of PostProcessorSequence.
1827
- * @param {Object} config The configuration object.
1828
- * @param {Object[]} config.processors The list of post-processors to apply.
1829
- */
1830
- constructor(config) {
1831
- super(config);
1832
-
1833
- this.processors = config.processors.map(x => PostProcessor.fromConfig(x));
1834
- }
1835
-
1836
- /**
1837
- * Post process the given tokens.
1838
- * @param {string[]} tokens The list of tokens for the first sequence.
1839
- * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
1840
- * @returns {PostProcessedOutput} An object containing the post-processed tokens.
1841
- */
1842
- post_process(tokens, tokens_pair = null, options = {}) {
1843
- let token_type_ids;
1844
- for (const processor of this.processors) {
1845
- if (processor instanceof ByteLevelPostProcessor) {
1846
- // Special case where we need to pass the tokens_pair to the post-processor
1847
- const output = processor.post_process(tokens);
1848
- tokens = output.tokens;
1849
- if (tokens_pair) {
1850
- const pair_output = processor.post_process(tokens_pair);
1851
- tokens_pair = pair_output.tokens;
1852
- }
1853
- } else {
1854
- const output = processor.post_process(tokens, tokens_pair, options);
1855
- tokens = output.tokens;
1856
- token_type_ids = output.token_type_ids;
1857
- }
1858
- }
1859
- return { tokens, token_type_ids };
1860
- }
1861
- }
1862
-
1863
- /**
1864
- * The base class for token decoders.
1865
- * @extends Callable
1866
- */
1867
- class Decoder extends Callable {
1868
-
1869
- /**
1870
- * Creates an instance of `Decoder`.
1871
- *
1872
- * @param {Object} config The configuration object.
1873
- */
1874
- constructor(config) {
1875
- super();
1876
- this.config = config;
1877
-
1878
- /** @type {AddedToken[]} */
1879
- this.added_tokens = [];
1880
- this.end_of_word_suffix = null;
1881
- this.trim_offsets = config.trim_offsets;
1882
- }
1883
-
1884
- /**
1885
- * Creates a decoder instance based on the provided configuration.
1886
- *
1887
- * @param {Object} config The configuration object.
1888
- * @returns {Decoder} A decoder instance.
1889
- * @throws {Error} If an unknown decoder type is provided.
1890
- */
1891
- static fromConfig(config) {
1892
- if (config === null) return null;
1893
- switch (config.type) {
1894
- case 'WordPiece':
1895
- return new WordPieceDecoder(config);
1896
- case 'Metaspace':
1897
- return new MetaspaceDecoder(config);
1898
- case 'ByteLevel':
1899
- return new ByteLevelDecoder(config);
1900
-
1901
- case 'Replace':
1902
- return new ReplaceDecoder(config);
1903
- case 'ByteFallback':
1904
- return new ByteFallback(config);
1905
- case 'Fuse':
1906
- return new FuseDecoder(config);
1907
- case 'Strip':
1908
- return new StripDecoder(config);
1909
-
1910
- case 'Sequence':
1911
- return new DecoderSequence(config);
1912
-
1913
- case 'CTC':
1914
- return new CTCDecoder(config);
1915
- case 'BPEDecoder':
1916
- return new BPEDecoder(config);
1917
- default:
1918
- throw new Error(`Unknown Decoder type: ${config.type}`);
1919
- }
1920
- }
1921
-
1922
- /**
1923
- * Calls the `decode` method.
1924
- *
1925
- * @param {string[]} tokens The list of tokens.
1926
- * @returns {string} The decoded string.
1927
- */
1928
- _call(tokens) {
1929
- return this.decode(tokens);
1930
- }
1931
-
1932
- /**
1933
- * Decodes a list of tokens.
1934
- * @param {string[]} tokens The list of tokens.
1935
- * @returns {string} The decoded string.
1936
- */
1937
- decode(tokens) {
1938
- return this.decode_chain(tokens).join('');
1939
- }
1940
-
1941
- /**
1942
- * Apply the decoder to a list of tokens.
1943
- *
1944
- * @param {string[]} tokens The list of tokens.
1945
- * @returns {string[]} The decoded list of tokens.
1946
- * @throws {Error} If the `decode_chain` method is not implemented in the subclass.
1947
- */
1948
- decode_chain(tokens) {
1949
- throw Error("`decode_chain` should be implemented in subclass.")
1950
- }
1951
-
1952
- }
1953
-
1954
- class ReplaceDecoder extends Decoder {
1955
-
1956
- /** @type {Decoder['decode_chain']} */
1957
- decode_chain(tokens) {
1958
- const pattern = createPattern(this.config.pattern);
1959
- return pattern === null
1960
- ? tokens
1961
- : tokens.map(token => token.replaceAll(pattern, this.config.content))
1962
- }
1963
- }
1964
-
1965
-
1966
- class ByteFallback extends Decoder {
1967
- constructor(config) {
1968
- super(config);
1969
-
1970
- this.text_decoder = new TextDecoder();
1971
- }
1972
-
1973
- /** @type {Decoder['decode_chain']} */
1974
- decode_chain(tokens) {
1975
-
1976
- const new_tokens = [];
1977
- let previous_byte_tokens = [];
1978
-
1979
- for (const token of tokens) {
1980
- let bytes = null;
1981
- if (token.length === 6 && token.startsWith('<0x') && token.endsWith('>')) {
1982
- const byte = parseInt(token.slice(3, 5), 16);
1983
- if (!isNaN(byte)) {
1984
- bytes = byte;
1985
- }
1986
- }
1987
- if (bytes !== null) {
1988
- previous_byte_tokens.push(bytes);
1989
- } else {
1990
- if (previous_byte_tokens.length > 0) {
1991
- const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));
1992
- new_tokens.push(string);
1993
- previous_byte_tokens = [];
1994
- }
1995
- new_tokens.push(token);
1996
- }
1997
- }
1998
- if (previous_byte_tokens.length > 0) {
1999
- const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));
2000
- new_tokens.push(string);
2001
- previous_byte_tokens = [];
2002
- }
2003
-
2004
- return new_tokens;
2005
- }
2006
- }
2007
-
2008
- /**
2009
- * Fuse simply fuses all tokens into one big string.
2010
- * It's usually the last decoding step anyway, but this decoder
2011
- * exists incase some decoders need to happen after that step
2012
- */
2013
- class FuseDecoder extends Decoder {
2014
-
2015
- /** @type {Decoder['decode_chain']} */
2016
- decode_chain(tokens) {
2017
- return [tokens.join('')];
2018
- }
2019
- }
2020
-
2021
-
2022
- class StripDecoder extends Decoder {
2023
- constructor(config) {
2024
- super(config);
2025
-
2026
- this.content = this.config.content;
2027
- this.start = this.config.start;
2028
- this.stop = this.config.stop;
2029
- }
2030
-
2031
- /** @type {Decoder['decode_chain']} */
2032
- decode_chain(tokens) {
2033
- return tokens.map(token => {
2034
- let start_cut = 0;
2035
- for (let i = 0; i < this.start; ++i) {
2036
- if (token[i] === this.content) {
2037
- start_cut = i + 1;
2038
- continue;
2039
- } else {
2040
- break;
2041
- }
2042
- }
2043
-
2044
- let stop_cut = token.length;
2045
- for (let i = 0; i < this.stop; ++i) {
2046
- const index = token.length - i - 1;
2047
- if (token[index] === this.content) {
2048
- stop_cut = index;
2049
- continue;
2050
- } else {
2051
- break;
2052
- }
2053
- }
2054
-
2055
- return token.slice(start_cut, stop_cut)
2056
- });
2057
- }
2058
- }
2059
-
2060
- /**
2061
- * A decoder that decodes a list of WordPiece tokens into a single string.
2062
- * @extends Decoder
2063
- */
2064
- class WordPieceDecoder extends Decoder {
2065
-
2066
- /**
2067
- * Creates a new instance of WordPieceDecoder.
2068
- * @param {Object} config The configuration object.
2069
- * @param {string} config.prefix The prefix used for WordPiece encoding.
2070
- * @param {boolean} config.cleanup Whether to cleanup the decoded string.
2071
- */
2072
- constructor(config) {
2073
- super(config);
2074
- this.cleanup = config.cleanup;
2075
- }
2076
-
2077
- /** @type {Decoder['decode_chain']} */
2078
- decode_chain(tokens) {
2079
- return tokens.map((token, i) => {
2080
- if (i !== 0) {
2081
- if (token.startsWith(this.config.prefix)) {
2082
- // NOTE: .replace() is intended; only replace first occurrence
2083
- token = token.replace(this.config.prefix, '');
2084
- } else {
2085
- token = ' ' + token;
2086
- }
2087
- }
2088
- if (this.cleanup) {
2089
- token = clean_up_tokenization(token)
2090
- }
2091
-
2092
- return token;
2093
- });
2094
- }
2095
- }
2096
-
2097
- /**
2098
- * Byte-level decoder for tokenization output. Inherits from the `Decoder` class.
2099
- * @extends Decoder
2100
- */
2101
- class ByteLevelDecoder extends Decoder {
2102
-
2103
- /**
2104
- * Create a `ByteLevelDecoder` object.
2105
- * @param {Object} config Configuration object.
2106
- */
2107
- constructor(config) {
2108
- super(config);
2109
-
2110
- this.byte_decoder = UNICODE_TO_BYTES;
2111
- this.text_decoder = new TextDecoder("utf-8", {
2112
- fatal: false,
2113
- ignoreBOM: true,
2114
- });
2115
-
2116
- this.end_of_word_suffix = null;
2117
- }
2118
-
2119
- /**
2120
- * Convert an array of tokens to string by decoding each byte.
2121
- * @param {string[]} tokens Array of tokens to be decoded.
2122
- * @returns {string} The decoded string.
2123
- */
2124
- convert_tokens_to_string(tokens) {
2125
- const text = tokens.join('');
2126
- const byteArray = new Uint8Array([...text].map(c => this.byte_decoder[c]));
2127
- const decoded_text = this.text_decoder.decode(byteArray);
2128
- return decoded_text;
2129
- }
2130
-
2131
- /** @type {Decoder['decode_chain']} */
2132
- decode_chain(tokens) {
2133
- // TODO move to base class (like HF)
2134
- // tokens === filtered_tokens
2135
-
2136
- // To avoid mixing byte-level and unicode for byte-level BPT
2137
- // we need to build string separately for added tokens and byte-level tokens
2138
- // cf. https://github.com/huggingface/transformers/issues/1133
2139
- const sub_texts = [];
2140
- let current_sub_text = [];
2141
- for (const token of tokens) {
2142
- // tokens sent here are already filtered, so we don't need to do this
2143
- // if (skip_special_tokens && this.all_special_ids.includes(token)) {
2144
- // continue;
2145
- // }
2146
-
2147
- if (this.added_tokens.find(x => x.content === token) !== undefined) {
2148
- if (current_sub_text.length > 0) {
2149
- sub_texts.push(this.convert_tokens_to_string(current_sub_text));
2150
- current_sub_text = [];
2151
- }
2152
- sub_texts.push(token);
2153
- } else {
2154
- current_sub_text.push(token);
2155
- }
2156
- }
2157
- if (current_sub_text.length > 0) {
2158
- sub_texts.push(this.convert_tokens_to_string(current_sub_text));
2159
- }
2160
-
2161
- // TODO add spaces_between_special_tokens and clean_up_tokenization_spaces options
2162
-
2163
- return sub_texts;
2164
- }
2165
- }
2166
-
2167
- /**
2168
- * The CTC (Connectionist Temporal Classification) decoder.
2169
- * See https://github.com/huggingface/tokenizers/blob/bb38f390a61883fc2f29d659af696f428d1cda6b/tokenizers/src/decoders/ctc.rs
2170
- */
2171
- class CTCDecoder extends Decoder {
2172
-
2173
- constructor(config) {
2174
- super(config);
2175
-
2176
- this.pad_token = this.config.pad_token;
2177
- this.word_delimiter_token = this.config.word_delimiter_token;
2178
- this.cleanup = this.config.cleanup;
2179
- }
2180
- /**
2181
- * Converts a connectionist-temporal-classification (CTC) output tokens into a single string.
2182
- * @param {string[]} tokens Array of tokens to be decoded.
2183
- * @returns {string} The decoded string.
2184
- */
2185
- convert_tokens_to_string(tokens) {
2186
- if (tokens.length === 0) return '';
2187
-
2188
- // group same tokens into non-repeating tokens in CTC style decoding
2189
- const grouped_tokens = [tokens[0]];
2190
- for (let i = 1; i < tokens.length; ++i) {
2191
- if (tokens[i] !== grouped_tokens.at(-1)) {
2192
- grouped_tokens.push(tokens[i]);
2193
- }
2194
- }
2195
-
2196
- // filter self.pad_token which is used as CTC-blank token
2197
- const filtered_tokens = grouped_tokens.filter(token => token !== this.pad_token);
2198
-
2199
- let text = filtered_tokens.join('');
2200
- if (this.cleanup) {
2201
- // cleanup and replace delimiter token
2202
- text = clean_up_tokenization(text)
2203
- .replaceAll(this.word_delimiter_token, ' ')
2204
- .trim();
2205
- }
2206
- return text;
2207
- }
2208
-
2209
-
2210
- /** @type {Decoder['decode_chain']} */
2211
- decode_chain(tokens) {
2212
- return [this.convert_tokens_to_string(tokens)];
2213
- }
2214
- }
2215
-
2216
- /**
2217
- * Apply a sequence of decoders.
2218
- * @extends Decoder
2219
- */
2220
- class DecoderSequence extends Decoder {
2221
-
2222
- /**
2223
- * Creates a new instance of DecoderSequence.
2224
- * @param {Object} config The configuration object.
2225
- * @param {Object[]} config.decoders The list of decoders to apply.
2226
- */
2227
- constructor(config) {
2228
- super(config);
2229
- this.decoders = config.decoders.map(x => Decoder.fromConfig(x));
2230
- }
2231
-
2232
- /** @type {Decoder['decode_chain']} */
2233
- decode_chain(tokens) {
2234
- // Use reduce to apply each decoder to the tokens
2235
- return this.decoders.reduce((toks, decoder) => {
2236
- return decoder.decode_chain(toks);
2237
- }, tokens);
2238
- }
2239
-
2240
- }
2241
-
2242
- class BPEDecoder extends Decoder {
2243
- constructor(config) {
2244
- super(config);
2245
-
2246
- this.suffix = this.config.suffix;
2247
- }
2248
- /** @type {Decoder['decode_chain']} */
2249
- decode_chain(tokens) {
2250
- return tokens.map((token, i) => {
2251
- return token.replaceAll(this.suffix, (i === tokens.length - 1) ? '' : ' ')
2252
- });
2253
- }
2254
- }
2255
-
2256
- // Custom decoder for VITS
2257
- class VitsDecoder extends Decoder {
2258
- /** @type {Decoder['decode_chain']} */
2259
- decode_chain(tokens) {
2260
- let decoded = '';
2261
- for (let i = 1; i < tokens.length; i += 2) {
2262
- decoded += tokens[i];
2263
- }
2264
- return [decoded];
2265
- }
2266
- }
2267
-
2268
-
2269
- /**
2270
- * This PreTokenizer replaces spaces with the given replacement character, adds a prefix space if requested,
2271
- * and returns a list of tokens.
2272
- * @extends PreTokenizer
2273
- */
2274
- class MetaspacePreTokenizer extends PreTokenizer {
2275
- /**
2276
- * @param {Object} config The configuration object for the MetaspacePreTokenizer.
2277
- * @param {boolean} config.add_prefix_space Whether to add a prefix space to the first token.
2278
- * @param {string} config.replacement The character to replace spaces with.
2279
- * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character.
2280
- * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme.
2281
- */
2282
- constructor(config) {
2283
- super();
2284
-
2285
- this.addPrefixSpace = config.add_prefix_space;
2286
- this.replacement = config.replacement;
2287
- this.strRep = config.str_rep || this.replacement;
2288
- this.prepend_scheme = config.prepend_scheme ?? 'always';
2289
- }
2290
-
2291
- /**
2292
- * This method takes a string, replaces spaces with the replacement character,
2293
- * adds a prefix space if requested, and returns a new list of tokens.
2294
- * @param {string} text The text to pre-tokenize.
2295
- * @param {Object} [options] The options for the pre-tokenization.
2296
- * @param {number} [options.section_index] The index of the section to pre-tokenize.
2297
- * @returns {string[]} A new list of pre-tokenized tokens.
2298
- */
2299
- pre_tokenize_text(text, {
2300
- section_index = undefined,
2301
- } = {}) {
2302
-
2303
- let normalized = text.replaceAll(' ', this.strRep);
2304
-
2305
- if (
2306
- // We add a prefix space if:
2307
- // (1) The addPrefixSpace option is enabled and the normalized
2308
- // token does not already start with the replacement character.
2309
- (this.addPrefixSpace && !normalized.startsWith(this.replacement))
2310
-
2311
- // and (2) either:
2312
- // (a) prepend_scheme is 'always'
2313
- // (b) prepend_scheme is 'first' and this is the first section
2314
- && (
2315
- this.prepend_scheme === 'always' ||
2316
- (this.prepend_scheme === 'first' && section_index === 0)
2317
- )
2318
- ) {
2319
- normalized = this.strRep + normalized;
2320
- }
2321
- return [normalized];
2322
- }
2323
- }
2324
-
2325
- /**
2326
- * MetaspaceDecoder class extends the Decoder class and decodes Metaspace tokenization.
2327
- * @extends Decoder
2328
- */
2329
- class MetaspaceDecoder extends Decoder {
2330
- /**
2331
- * Constructs a new MetaspaceDecoder object.
2332
- * @param {Object} config The configuration object for the MetaspaceDecoder.
2333
- * @param {boolean} config.add_prefix_space Whether to add a prefix space to the decoded string.
2334
- * @param {string} config.replacement The string to replace spaces with.
2335
- */
2336
- constructor(config) {
2337
- super(config);
2338
-
2339
- this.addPrefixSpace = config.add_prefix_space;
2340
- this.replacement = config.replacement;
2341
- }
2342
-
2343
- /** @type {Decoder['decode_chain']} */
2344
- decode_chain(tokens) {
2345
- const result = [];
2346
- for (let i = 0; i < tokens.length; ++i) {
2347
- let normalized = tokens[i].replaceAll(this.replacement, ' ');
2348
- if (this.addPrefixSpace && i == 0 && normalized.startsWith(' ')) {
2349
- normalized = normalized.substring(1);
2350
- }
2351
- result.push(normalized);
2352
- }
2353
- return result;
2354
- }
2355
- }
2356
-
2357
- /**
2358
- * A normalizer that applies a precompiled charsmap.
2359
- * This is useful for applying complex normalizations in C++ and exposing them to JavaScript.
2360
- * @extends Normalizer
2361
- * @param {Object} config The configuration object for the Precompiled normalizer.
2362
- * @param {Object} config.precompiled_charsmap The precompiled charsmap object.
2363
- */
2364
- class Precompiled extends Normalizer {
2365
- /**
2366
- * Create a new instance of Precompiled normalizer.
2367
- * @param {Object} config The configuration object.
2368
- * @param {any} config.precompiled_charsmap Precompiled chars mapping.
2369
- */
2370
- constructor(config) {
2371
- super(config);
2372
- this.charsmap = config.precompiled_charsmap;
2373
- }
2374
-
2375
- /**
2376
- * Normalizes the given text by applying the precompiled charsmap.
2377
- * @param {string} text The text to normalize.
2378
- * @returns {string} The normalized text.
2379
- */
2380
- normalize(text) {
2381
- // As stated in the sentencepiece normalization docs (https://github.com/google/sentencepiece/blob/master/doc/normalization.md#use-pre-defined-normalization-rule),
2382
- // there are 5 pre-defined normalization rules:
2383
- // 1. nmt_nfkc: NFKC normalization with some additional normalization around spaces. (default)
2384
- // 2. nfkc: original NFKC normalization.
2385
- // 3. nmt_nfkc_cf: nmt_nfkc + Unicode case folding (mostly lower casing)
2386
- // 4. nfkc_cf: nfkc + Unicode case folding.
2387
- // 5. identity: no normalization
2388
- //
2389
- // For now, we only implement the default (nmt_nfkc).
2390
- // See https://raw.githubusercontent.com/google/sentencepiece/master/data/nmt_nfkc.tsv for the full list of rules.
2391
- // TODO: detect when a different `this.charsmap` is used.
2392
-
2393
- text = text.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm, ''); // Remove control characters
2394
- text = text.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm, '\u0020'); // Replace certain characters with a space
2395
-
2396
- if (text.includes('\uFF5E')) {
2397
- // To match the sentencepiece implementation 100%, we must handle a very strange edge-case.
2398
- // For some reason, the "Fullwidth Tilde" character (\uFF5E) should not be converted to the standard Tilde character (\u007E).
2399
- // However, NFKC normalization does do this conversion. As a result, we split the string on the Fullwidth Tilde character,
2400
- // perform NFKC normalization on each substring, and then join them back together with the Fullwidth Tilde character.
2401
- const parts = text.split('\uFF5E');
2402
- text = parts.map(part => part.normalize('NFKC')).join('\uFF5E');
2403
- } else {
2404
- text = text.normalize('NFKC');
2405
- }
2406
-
2407
- return text;
2408
- }
2409
- }
2410
-
2411
- /**
2412
- * A pre-tokenizer that applies a sequence of pre-tokenizers to the input text.
2413
- * @extends PreTokenizer
2414
- */
2415
- class PreTokenizerSequence extends PreTokenizer {
2416
- /**
2417
- * Creates an instance of PreTokenizerSequence.
2418
- * @param {Object} config The configuration object for the pre-tokenizer sequence.
2419
- * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations.
2420
- */
2421
- constructor(config) {
2422
- super();
2423
- this.tokenizers = config.pretokenizers.map(x => PreTokenizer.fromConfig(x));
2424
- }
2425
-
2426
- /**
2427
- * Applies each pre-tokenizer in the sequence to the input text in turn.
2428
- * @param {string} text The text to pre-tokenize.
2429
- * @param {Object} [options] Additional options for the pre-tokenization logic.
2430
- * @returns {string[]} The pre-tokenized text.
2431
- */
2432
- pre_tokenize_text(text, options) {
2433
- // Use reduce to apply each tokenizer to the text
2434
- return this.tokenizers.reduce((preTokenizedText, tokenizer) => {
2435
- return tokenizer.pre_tokenize(preTokenizedText, options);
2436
- }, [text]);
2437
- }
2438
- }
2439
-
2440
- /**
2441
- * Splits on word boundaries (using the following regular expression: `\w+|[^\w\s]+`).
2442
- */
2443
- class WhitespacePreTokenizer extends PreTokenizer {
2444
- /**
2445
- * Creates an instance of WhitespacePreTokenizer.
2446
- * @param {Object} config The configuration object for the pre-tokenizer.
2447
- */
2448
- constructor(config) {
2449
- super();
2450
- }
2451
- /**
2452
- * Pre-tokenizes the input text by splitting it on word boundaries.
2453
- * @param {string} text The text to be pre-tokenized.
2454
- * @param {Object} [options] Additional options for the pre-tokenization logic.
2455
- * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.
2456
- */
2457
- pre_tokenize_text(text, options) {
2458
- return text.match(/\w+|[^\w\s]+/g) || [];
2459
- }
2460
- }
2461
-
2462
- /**
2463
- * Splits a string of text by whitespace characters into individual tokens.
2464
- * @extends PreTokenizer
2465
- */
2466
- class WhitespaceSplit extends PreTokenizer {
2467
- /**
2468
- * Creates an instance of WhitespaceSplit.
2469
- * @param {Object} config The configuration object for the pre-tokenizer.
2470
- */
2471
- constructor(config) {
2472
- super();
2473
- }
2474
- /**
2475
- * Pre-tokenizes the input text by splitting it on whitespace characters.
2476
- * @param {string} text The text to be pre-tokenized.
2477
- * @param {Object} [options] Additional options for the pre-tokenization logic.
2478
- * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.
2479
- */
2480
- pre_tokenize_text(text, options) {
2481
- return whitespace_split(text);
2482
- }
2483
- }
2484
-
2485
- // NOTE: `ReplacePreTokenizer` is custom (to support `BlenderbotSmallTokenizer`)
2486
- class ReplacePreTokenizer extends PreTokenizer {
2487
- /**
2488
- * @param {Object} config The configuration options for the pre-tokenizer.
2489
- * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.
2490
- * @param {string} config.content What to replace the pattern with.
2491
- */
2492
- constructor(config) {
2493
- super();
2494
- this.config = config;
2495
- this.pattern = createPattern(this.config.pattern);
2496
- this.content = this.config.content;
2497
- }
2498
-
2499
- /**
2500
- * Pre-tokenizes the input text by replacing certain characters.
2501
- * @param {string} text The text to be pre-tokenized.
2502
- * @param {Object} [options] Additional options for the pre-tokenization logic.
2503
- * @returns {string[]} An array of tokens produced by replacing certain characters.
2504
- */
2505
- pre_tokenize_text(text, options) {
2506
- if (this.pattern === null) {
2507
- return [text];
2508
- }
2509
- return [text.replaceAll(this.pattern, this.config.content)];
2510
- }
2511
- }
2512
-
2513
- const SPECIAL_TOKEN_ATTRIBUTES = [
2514
- 'bos_token',
2515
- 'eos_token',
2516
- 'unk_token',
2517
- 'sep_token',
2518
- 'pad_token',
2519
- 'cls_token',
2520
- 'mask_token',
2521
- // additional_special_tokens (TODO)
2522
- ]
2523
-
2524
- /**
2525
- *
2526
- * Helper function for padding values of an object, which are each arrays.
2527
- * NOTE: No additional checks are made here for validity of arguments.
2528
- * @param {Record<string, any[]>} item The input object.
2529
- * @param {number} length The length to pad to.
2530
- * @param {(key: string) => any} value_fn Determine the value to fill the array, based on its key.
2531
- * @param {string} side Which side to pad the array.
2532
- * @private
2533
- */
2534
- function padHelper(item, length, value_fn, side) {
2535
- for (const key of Object.keys(item)) {
2536
- const diff = length - item[key].length;
2537
- const value = value_fn(key);
2538
-
2539
- const padData = new Array(diff).fill(value);
2540
- item[key] = side === 'right'
2541
- ? mergeArrays(item[key], padData)
2542
- : mergeArrays(padData, item[key]);
2543
- }
2544
- }
2545
-
2546
- /**
2547
- * Helper function for truncating values of an object, which are each arrays.
2548
- * NOTE: No additional checks are made here for validity of arguments.
2549
- * @param {Record<string, any[]>} item The input object.
2550
- * @param {number} length The length to truncate to.
2551
- * @private
2552
- */
2553
- function truncateHelper(item, length) {
2554
- // Setting .length to a lower value truncates the array in-place:
2555
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
2556
- for (const key of Object.keys(item)) {
2557
- item[key].length = length;
2558
- }
2559
- }
2560
-
2561
-
2562
- /**
2563
- * @typedef {Object} Message
2564
- * @property {string} role The role of the message (e.g., "user" or "assistant" or "system").
2565
- * @property {string} content The content of the message.
2566
- */
2567
-
2568
- export class PreTrainedTokenizer extends Callable {
2569
- return_token_type_ids = false;
2570
-
2571
- padding_side = 'right';
2572
- /**
2573
- * Create a new PreTrainedTokenizer instance.
2574
- * @param {Object} tokenizerJSON The JSON of the tokenizer.
2575
- * @param {Object} tokenizerConfig The config of the tokenizer.
2576
- */
2577
- constructor(tokenizerJSON, tokenizerConfig) {
2578
- super();
2579
-
2580
- this.config = tokenizerConfig;
2581
-
2582
- // Construct parts of the tokenizer from the JSON
2583
- this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer);
2584
- this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer);
2585
- this.model = TokenizerModel.fromConfig(tokenizerJSON.model, tokenizerConfig);
2586
- this.post_processor = PostProcessor.fromConfig(tokenizerJSON.post_processor);
2587
- this.decoder = Decoder.fromConfig(tokenizerJSON.decoder);
2588
-
2589
- // Add added_tokens to model
2590
- this.special_tokens = [];
2591
- this.all_special_ids = [];
2592
-
2593
- /** @type {AddedToken[]} */
2594
- this.added_tokens = [];
2595
- for (const addedToken of tokenizerJSON.added_tokens) {
2596
- const token = new AddedToken(addedToken);
2597
- this.added_tokens.push(token);
2598
-
2599
- this.model.tokens_to_ids.set(token.content, token.id);
2600
- this.model.vocab[token.id] = token.content;
2601
-
2602
- if (token.special) {
2603
- this.special_tokens.push(token.content);
2604
- this.all_special_ids.push(token.id);
2605
- }
2606
- }
2607
-
2608
- // Update additional_special_tokens
2609
- this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? [];
2610
- this.special_tokens.push(...this.additional_special_tokens);
2611
- this.special_tokens = [...new Set(this.special_tokens)]; // Remove duplicates
2612
-
2613
- if (this.decoder) {
2614
- // Slight hack, but it prevents code duplication:
2615
- this.decoder.added_tokens = this.added_tokens;
2616
-
2617
- // Another slight hack to add `end_of_word_suffix` (if present) to the decoder
2618
- // This is needed for cases where BPE model and ByteLevel decoder are used
2619
- // For more information, see https://github.com/huggingface/transformers.js/issues/74
2620
- // TODO: save this to the decoder when exporting?
2621
- this.decoder.end_of_word_suffix = this.model.end_of_word_suffix;
2622
- }
2623
-
2624
- this.added_tokens_splitter = new DictionarySplitter(
2625
- this.added_tokens.map(x => x.content),
2626
- );
2627
-
2628
- /** @type {Map<string, AddedToken>} */
2629
- this.added_tokens_map = new Map(this.added_tokens.map(x => [x.content, x]))
2630
-
2631
- // Set mask token if present (otherwise will be undefined, which is fine)
2632
- this.mask_token = this.getToken('mask_token');
2633
- this.mask_token_id = this.model.tokens_to_ids.get(this.mask_token);
2634
-
2635
- this.pad_token = this.getToken('pad_token', 'eos_token');
2636
- this.pad_token_id = this.model.tokens_to_ids.get(this.pad_token);
2637
-
2638
- this.sep_token = this.getToken('sep_token');
2639
- this.sep_token_id = this.model.tokens_to_ids.get(this.sep_token);
2640
-
2641
- this.unk_token = this.getToken('unk_token');
2642
- this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token);
2643
-
2644
- this.bos_token = this.getToken('bos_token');
2645
- this.bos_token_id = this.model.tokens_to_ids.get(this.bos_token);
2646
-
2647
- this.eos_token = this.getToken('eos_token');
2648
- this.eos_token_id = this.model.tokens_to_ids.get(this.eos_token);
2649
-
2650
- this.model_max_length = tokenizerConfig.model_max_length;
2651
-
2652
- /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */
2653
- this.remove_space = tokenizerConfig.remove_space;
2654
-
2655
- this.clean_up_tokenization_spaces = tokenizerConfig.clean_up_tokenization_spaces ?? true;
2656
- this.do_lowercase_and_remove_accent = tokenizerConfig.do_lowercase_and_remove_accent ?? false;
2657
-
2658
- if (tokenizerConfig.padding_side) {
2659
- this.padding_side = tokenizerConfig.padding_side;
2660
- }
2661
-
2662
- this.legacy = false;
2663
-
2664
- this.chat_template = tokenizerConfig.chat_template ?? null;
2665
- if (Array.isArray(this.chat_template)) {
2666
- // Chat templates are stored as lists of dicts with fixed key names,
2667
- // we reconstruct that into a single dict while loading them.
2668
- const chat_template = Object.create(null);
2669
- for (const { name, template } of this.chat_template) {
2670
- if (typeof name !== 'string' || typeof template !== 'string') {
2671
- throw new Error('Chat template must be a list of objects with "name" and "template" properties');
2672
- }
2673
- chat_template[name] = template;
2674
- }
2675
- this.chat_template = chat_template;
2676
- }
2677
- this._compiled_template_cache = new Map();
2678
- }
2679
-
2680
- /**
2681
- * Returns the value of the first matching key in the tokenizer config object.
2682
- * @param {...string} keys One or more keys to search for in the tokenizer config object.
2683
- * @returns {string|null} The value associated with the first matching key, or null if no match is found.
2684
- * @throws {Error} If an object is found for a matching key and its __type property is not "AddedToken".
2685
- * @private
2686
- */
2687
- getToken(...keys) {
2688
- for (const key of keys) {
2689
- const item = this.config[key];
2690
-
2691
- if (!item) continue;
2692
-
2693
- if (typeof item === 'object') {
2694
- if (item.__type === 'AddedToken') {
2695
- return item.content;
2696
- } else {
2697
- throw Error(`Unknown token: ${item}`);
2698
- }
2699
- } else {
2700
- return item;
2701
- }
2702
- }
2703
- return null;
2704
- }
2705
-
2706
- /**
2707
- * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`.
2708
- *
2709
- * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer.
2710
- * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
2711
- *
2712
- * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`.
2713
- * @returns {Promise<PreTrainedTokenizer>} A new instance of the `PreTrainedTokenizer` class.
2714
- */
2715
- static async from_pretrained(pretrained_model_name_or_path, {
2716
- progress_callback = null,
2717
- config = null,
2718
- cache_dir = null,
2719
- local_files_only = false,
2720
- revision = 'main',
2721
- legacy = null,
2722
- } = {}) {
2723
-
2724
- const info = await loadTokenizer(pretrained_model_name_or_path, {
2725
- progress_callback,
2726
- config,
2727
- cache_dir,
2728
- local_files_only,
2729
- revision,
2730
- legacy,
2731
- })
2732
-
2733
- // @ts-ignore
2734
- return new this(...info);
2735
- }
2736
-
2737
- /**
2738
- * @typedef {number[]|number[][]|Tensor} BatchEncodingItem
2739
- *
2740
- * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function.
2741
- * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model.
2742
- * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model.
2743
- * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model.
2744
- */
2745
-
2746
- /**
2747
- * Encode/tokenize the given text(s).
2748
- * @param {string|string[]} text The text to tokenize.
2749
- * @param {Object} options An optional object containing the following properties:
2750
- * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text.
2751
- * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences.
2752
- * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
2753
- * @param {boolean} [options.truncation=null] Whether to truncate the input sequences.
2754
- * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length.
2755
- * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays.
2756
- * @param {boolean} [options.return_token_type_ids=null] Whether to return the token type ids.
2757
- * @returns {BatchEncoding} Object to be passed to the model.
2758
- */
2759
- _call(
2760
- // Required positional arguments
2761
- text,
2762
-
2763
- // Optional keyword arguments
2764
- {
2765
- text_pair = null,
2766
- add_special_tokens = true,
2767
- padding = false,
2768
- truncation = null,
2769
- max_length = null,
2770
- return_tensor = true, // Different to HF
2771
- return_token_type_ids = null,
2772
- } = {},
2773
- ) {
2774
-
2775
- const isBatched = Array.isArray(text);
2776
-
2777
- /** @type {EncodingSingle[]} */
2778
- let encodedTokens;
2779
-
2780
- if (isBatched) {
2781
- if (text.length === 0) {
2782
- throw Error('text array must be non-empty')
2783
- }
2784
-
2785
- if (text_pair !== null) {
2786
- if (!Array.isArray(text_pair)) {
2787
- throw Error('text_pair must also be an array')
2788
-
2789
- } else if (text.length !== text_pair.length) {
2790
- throw Error('text and text_pair must have the same length')
2791
- }
2792
-
2793
- encodedTokens = text.map(
2794
- (t, i) => this._encode_plus(t, { text_pair: text_pair[i], add_special_tokens, return_token_type_ids })
2795
- )
2796
-
2797
- } else {
2798
- encodedTokens = text.map(x => this._encode_plus(x, { add_special_tokens, return_token_type_ids }));
2799
- }
2800
-
2801
- } else {
2802
- if (text === null || text === undefined) {
2803
- throw Error('text may not be null or undefined')
2804
- }
2805
-
2806
- if (Array.isArray(text_pair)) {
2807
- throw Error('When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).')
2808
- }
2809
-
2810
- // For single input, we just wrap in an array, and then unwrap later.
2811
- encodedTokens = [this._encode_plus(text, { text_pair, add_special_tokens, return_token_type_ids })];
2812
- }
2813
- // At this point, `encodedTokens` is batched, of shape [batch_size, tokens].
2814
- // However, array may be jagged. So, we may need pad to max_length.
2815
- if (max_length === null) {
2816
- max_length = this.model_max_length;
2817
- } else if (truncation === null) {
2818
- if (padding === true) {
2819
- console.warn(
2820
- "`max_length` is ignored when `padding: true` and there is no truncation strategy. " +
2821
- "To pad to max length, use `padding: 'max_length'`."
2822
- )
2823
- max_length = this.model_max_length;
2824
- } else if (padding === false) {
2825
- console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length.");
2826
- truncation = true;
2827
- }
2828
- }
2829
-
2830
- // padding: 'max_length' doesn't require any additional calculation
2831
- // but padding: true has to calculate max_length from the sequences
2832
- if (padding === true) {
2833
- max_length = Math.min(max(encodedTokens.map(x => x.input_ids.length))[0], max_length ?? Infinity);
2834
- }
2835
-
2836
- // Ensure it is less than model max length
2837
- max_length = Math.min(max_length, this.model_max_length ?? Infinity);
2838
-
2839
- if (padding || truncation) {
2840
-
2841
- // Perform padding and/or truncation
2842
- for (let i = 0; i < encodedTokens.length; ++i) {
2843
- if (encodedTokens[i].input_ids.length === max_length) {
2844
- continue;
2845
-
2846
- } else if (encodedTokens[i].input_ids.length > max_length) {
2847
- // possibly truncate
2848
- if (truncation) {
2849
- truncateHelper(encodedTokens[i], max_length);
2850
- }
2851
-
2852
- } else { // t.length < max_length
2853
- // possibly pad
2854
- if (padding) {
2855
- padHelper(
2856
- encodedTokens[i],
2857
- max_length,
2858
- key => key === 'input_ids' ? this.pad_token_id : 0,
2859
- this.padding_side
2860
- );
2861
- }
2862
- }
2863
- }
2864
- }
2865
-
2866
- const result = {};
2867
-
2868
- if (return_tensor) {
2869
- if (!(padding && truncation)) {
2870
- // Not, guaranteed that all items have same length, so
2871
- // we perform additional check
2872
-
2873
- if (
2874
- encodedTokens.some(x => {
2875
- for (const key of Object.keys(x)) {
2876
- if (x[key].length !== encodedTokens[0][key]?.length) {
2877
- return true;
2878
- }
2879
- }
2880
- return false;
2881
- })
2882
- ) {
2883
- throw Error(
2884
- "Unable to create tensor, you should probably activate truncation and/or padding " +
2885
- "with 'padding=true' and 'truncation=true' to have batched tensors with the same length."
2886
- )
2887
- }
2888
- }
2889
-
2890
- // Now we actually convert to tensor
2891
- // NOTE: In the same way as the python library, we return a batched tensor, regardless of
2892
- // whether we have a single input or multiple inputs.
2893
- const dims = [encodedTokens.length, encodedTokens[0].input_ids.length];
2894
-
2895
- for (const key of Object.keys(encodedTokens[0])) {
2896
- result[key] = new Tensor('int64',
2897
- BigInt64Array.from(encodedTokens.flatMap(x => x[key]).map(BigInt)),
2898
- dims
2899
- );
2900
- }
2901
-
2902
- } else {
2903
- for (const key of Object.keys(encodedTokens[0])) {
2904
- result[key] = encodedTokens.map(x => x[key]);
2905
- }
2906
-
2907
- // If not returning a tensor, we match the input type
2908
- if (!isBatched) {
2909
- // Input was not batched, so we unwrap
2910
- for (const key of Object.keys(result)) {
2911
- result[key] = result[key][0];
2912
- }
2913
- }
2914
- }
2915
-
2916
- return /** @type {BatchEncoding} */(result);
2917
- }
2918
-
2919
- /**
2920
- * Encodes a single text using the preprocessor pipeline of the tokenizer.
2921
- *
2922
- * @param {string|null} text The text to encode.
2923
- * @returns {string[]|null} The encoded tokens.
2924
- */
2925
- _encode_text(text) {
2926
- if (text === null) return null;
2927
-
2928
- // Actual function which does encoding, for a single text
2929
- // First, we take care of special tokens. Needed to avoid issues arising from
2930
- // normalization and/or pretokenization (which may not preserve special tokens)
2931
- const sections = this.added_tokens_splitter.split(text);
2932
-
2933
- // Process left/right stripping of added tokens
2934
- for (let i = 0; i < sections.length; ++i) {
2935
- const addedToken = this.added_tokens_map.get(sections[i]);
2936
- if (addedToken) {
2937
- if (addedToken.lstrip && i > 0) {
2938
- sections[i - 1] = sections[i - 1].trimEnd();
2939
- }
2940
- if (addedToken.rstrip && i < sections.length - 1) {
2941
- sections[i + 1] = sections[i + 1].trimStart();
2942
- }
2943
- }
2944
- }
2945
-
2946
- const tokens = sections.flatMap((x, section_index) => {
2947
- if (x.length === 0) return [];
2948
- if (this.added_tokens_map.has(x)) return [x]; // Return added tokens unchanged
2949
-
2950
- if (this.remove_space === true) {
2951
- x = x.trim().split(/\s+/).join(' ');
2952
- }
2953
- if (this.do_lowercase_and_remove_accent) {
2954
- x = lowercase_and_remove_accent(x);
2955
- }
2956
-
2957
- if (this.normalizer !== null) {
2958
- x = this.normalizer(x);
2959
- }
2960
-
2961
- // If, after normalization, this section is empty (e.g., trimming whitespace),
2962
- // we return an empty array
2963
- if (x.length === 0) {
2964
- return [];
2965
- }
2966
-
2967
- const sectionTokens = (this.pre_tokenizer !== null) ? this.pre_tokenizer(x, {
2968
- section_index,
2969
- }) : [x];
2970
-
2971
- const tokens = this.model(sectionTokens);
2972
-
2973
- return tokens;
2974
- });
2975
-
2976
- return tokens;
2977
- }
2978
-
2979
- /**
2980
- * Encodes a single text or a pair of texts using the model's tokenizer.
2981
- *
2982
- * @param {string} text The text to encode.
2983
- * @param {Object} options An optional object containing the following properties:
2984
- * @param {string} [options.text_pair=null] The optional second text to encode.
2985
- * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
2986
- * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.
2987
- * @returns {EncodingSingle} An object containing the encoded text.
2988
- * @private
2989
- */
2990
- _encode_plus(text, {
2991
- text_pair = null,
2992
- add_special_tokens = true,
2993
- return_token_type_ids = null,
2994
- } = {}) {
2995
-
2996
- const { tokens, token_type_ids } = this._tokenize_helper(text, { pair: text_pair, add_special_tokens });
2997
-
2998
- const input_ids = this.model.convert_tokens_to_ids(tokens);
2999
-
3000
- const result = {
3001
- input_ids,
3002
- attention_mask: new Array(input_ids.length).fill(1),
3003
- }
3004
- if ((return_token_type_ids ?? this.return_token_type_ids) && token_type_ids) {
3005
- result.token_type_ids = token_type_ids;
3006
- }
3007
- return result;
3008
- }
3009
-
3010
- /**
3011
- * Internal helper function to tokenize a text, and optionally a pair of texts.
3012
- * @param {string} text The text to tokenize.
3013
- * @param {Object} options An optional object containing the following properties:
3014
- * @param {string} [options.pair=null] The optional second text to tokenize.
3015
- * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model.
3016
- * @returns {{tokens: string[], token_type_ids?: number[]}} An object containing the tokens and optionally the token type IDs.
3017
- */
3018
- _tokenize_helper(text, {
3019
- pair = null,
3020
- add_special_tokens = false,
3021
- } = {}) {
3022
- const tokens = this._encode_text(text);
3023
- const tokens2 = this._encode_text(pair);
3024
-
3025
- return this.post_processor
3026
- ? this.post_processor(tokens, tokens2, { add_special_tokens })
3027
- : { tokens: mergeArrays(tokens ?? [], tokens2 ?? []) };
3028
- }
3029
-
3030
- /**
3031
- * Converts a string into a sequence of tokens.
3032
- * @param {string} text The sequence to be encoded.
3033
- * @param {Object} options An optional object containing the following properties:
3034
- * @param {string} [options.pair] A second sequence to be encoded with the first.
3035
- * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model.
3036
- * @returns {string[]} The list of tokens.
3037
- */
3038
- tokenize(text, {
3039
- pair = null,
3040
- add_special_tokens = false,
3041
- } = {}) {
3042
- return this._tokenize_helper(text, { pair, add_special_tokens }).tokens;
3043
- }
3044
-
3045
- /**
3046
- * Encodes a single text or a pair of texts using the model's tokenizer.
3047
- *
3048
- * @param {string} text The text to encode.
3049
- * @param {Object} options An optional object containing the following properties:
3050
- * @param {string} [options.text_pair=null] The optional second text to encode.
3051
- * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
3052
- * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.
3053
- * @returns {number[]} An array of token IDs representing the encoded text(s).
3054
- */
3055
- encode(text, {
3056
- text_pair = null,
3057
- add_special_tokens = true,
3058
- return_token_type_ids = null,
3059
- } = {}) {
3060
- return this._encode_plus(text, {
3061
- text_pair,
3062
- add_special_tokens,
3063
- return_token_type_ids,
3064
- }).input_ids;
3065
- }
3066
-
3067
- /**
3068
- * Decode a batch of tokenized sequences.
3069
- * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences.
3070
- * @param {Object} decode_args (Optional) Object with decoding arguments.
3071
- * @returns {string[]} List of decoded sequences.
3072
- */
3073
- batch_decode(batch, decode_args = {}) {
3074
- if (batch instanceof Tensor) {
3075
- batch = batch.tolist();
3076
- }
3077
- return batch.map(x => this.decode(x, decode_args));
3078
- }
3079
-
3080
- /**
3081
- * Decodes a sequence of token IDs back to a string.
3082
- *
3083
- * @param {number[]|bigint[]|Tensor} token_ids List/Tensor of token IDs to decode.
3084
- * @param {Object} [decode_args={}]
3085
- * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string.
3086
- * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed.
3087
- *
3088
- * @returns {string} The decoded string.
3089
- * @throws {Error} If `token_ids` is not a non-empty array of integers.
3090
- */
3091
- decode(
3092
- token_ids,
3093
- decode_args = {},
3094
- ) {
3095
- if (token_ids instanceof Tensor) {
3096
- token_ids = prepareTensorForDecode(token_ids);
3097
- }
3098
-
3099
- if (!Array.isArray(token_ids) || token_ids.length === 0 || !isIntegralNumber(token_ids[0])) {
3100
- throw Error("token_ids must be a non-empty array of integers.");
3101
- }
3102
-
3103
- return this.decode_single(token_ids, decode_args)
3104
- }
3105
-
3106
- /**
3107
- * Decode a single list of token ids to a string.
3108
- * @param {number[]|bigint[]} token_ids List of token ids to decode
3109
- * @param {Object} decode_args Optional arguments for decoding
3110
- * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding
3111
- * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding.
3112
- * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`.
3113
- * @returns {string} The decoded string
3114
- */
3115
- decode_single(
3116
- token_ids,
3117
- {
3118
- skip_special_tokens = false,
3119
- clean_up_tokenization_spaces = null,
3120
- }
3121
- ) {
3122
- let tokens = this.model.convert_ids_to_tokens(token_ids);
3123
- if (skip_special_tokens) {
3124
- tokens = tokens.filter(x => !this.special_tokens.includes(x));
3125
- }
3126
-
3127
- // If `this.decoder` is null, we just join tokens with a space:
3128
- // https://github.com/huggingface/tokenizers/blob/8edec536a737cb04494b454805be16c020abb14f/tokenizers/src/tokenizer/mod.rs#L835
3129
- /** @type {string} */
3130
- let decoded = this.decoder ? this.decoder(tokens) : tokens.join(' ');
3131
-
3132
- // Slight hack, but prevents having to pass `skip_special_tokens` to
3133
- // each call to `decode`, which would lead to code duplication.
3134
- if (this.decoder && this.decoder.end_of_word_suffix) {
3135
- decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, ' ');
3136
- if (skip_special_tokens) {
3137
- decoded = decoded.trim();
3138
- }
3139
- }
3140
-
3141
- if (clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) {
3142
- decoded = clean_up_tokenization(decoded);
3143
- }
3144
-
3145
- return decoded;
3146
- }
3147
-
3148
- /**
3149
- * Retrieve the chat template string used for tokenizing chat messages. This template is used
3150
- * internally by the `apply_chat_template` method and can also be used externally to retrieve the model's chat
3151
- * template for better generation tracking.
3152
- *
3153
- * @param {Object} options An optional object containing the following properties:
3154
- * @param {string} [options.chat_template=null]
3155
- * A Jinja template or the name of a template to use for this conversion.
3156
- * It is usually not necessary to pass anything to this argument,
3157
- * as the model's template will be used by default.
3158
- * @param {Object[]} [options.tools=null]
3159
- * A list of tools (callable functions) that will be accessible to the model. If the template does not
3160
- * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,
3161
- * giving the name, description and argument types for the tool. See our
3162
- * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)
3163
- * for more information.
3164
- * @returns {string} The chat template string.
3165
- */
3166
- get_chat_template({
3167
- chat_template = null,
3168
- tools = null,
3169
- } = {}) {
3170
-
3171
- // First, handle the cases when the model has a dict of multiple templates
3172
- if (this.chat_template && typeof this.chat_template === 'object') {
3173
- const template_dict = this.chat_template;
3174
-
3175
- if (chat_template !== null && Object.hasOwn(template_dict, chat_template)) {
3176
- // The user can pass the name of a template to the chat template argument instead of an entire template
3177
- chat_template = template_dict[chat_template];
3178
- } else if (chat_template === null) {
3179
- if (tools !== null && 'tool_use' in template_dict) {
3180
- chat_template = template_dict['tool_use'];
3181
- } else if ('default' in template_dict) {
3182
- chat_template = template_dict['default'];
3183
- } else {
3184
- throw Error(
3185
- `This model has multiple chat templates with no default specified! Please either pass a chat ` +
3186
- `template or the name of the template you wish to use to the 'chat_template' argument. Available ` +
3187
- `template names are ${Object.keys(template_dict).sort()}.`
3188
- )
3189
- }
3190
- }
3191
- } else if (chat_template === null) {
3192
- // These are the cases when the model has a single template
3193
- // priority: `chat_template` argument > `tokenizer.chat_template`
3194
- if (this.chat_template) {
3195
- chat_template = this.chat_template;
3196
- } else {
3197
- throw Error(
3198
- "Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template " +
3199
- "argument was passed! For information about writing templates and setting the " +
3200
- "tokenizer.chat_template attribute, please see the documentation at " +
3201
- "https://huggingface.co/docs/transformers/main/en/chat_templating"
3202
- )
3203
- }
3204
- }
3205
- return chat_template;
3206
- }
3207
-
3208
- /**
3209
- * Converts a list of message objects with `"role"` and `"content"` keys to a list of token
3210
- * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to
3211
- * determine the format and control tokens to use when converting.
3212
- *
3213
- * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information.
3214
- *
3215
- * **Example:** Applying a chat template to a conversation.
3216
- *
3217
- * ```javascript
3218
- * import { AutoTokenizer } from "@huggingface/transformers";
3219
- *
3220
- * const tokenizer = await AutoTokenizer.from_pretrained("Xenova/mistral-tokenizer-v1");
3221
- *
3222
- * const chat = [
3223
- * { "role": "user", "content": "Hello, how are you?" },
3224
- * { "role": "assistant", "content": "I'm doing great. How can I help you today?" },
3225
- * { "role": "user", "content": "I'd like to show off how chat templating works!" },
3226
- * ]
3227
- *
3228
- * const text = tokenizer.apply_chat_template(chat, { tokenize: false });
3229
- * // "<s>[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today?</s> [INST] I'd like to show off how chat templating works! [/INST]"
3230
- *
3231
- * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false });
3232
- * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793]
3233
- * ```
3234
- *
3235
- * @param {Message[]} conversation A list of message objects with `"role"` and `"content"` keys,
3236
- * representing the chat history so far.
3237
- * @param {Object} options An optional object containing the following properties:
3238
- * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If
3239
- * this is not passed, the model's chat template will be used instead.
3240
- * @param {Object[]} [options.tools=null]
3241
- * A list of tools (callable functions) that will be accessible to the model. If the template does not
3242
- * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,
3243
- * giving the name, description and argument types for the tool. See our
3244
- * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)
3245
- * for more information.
3246
- * @param {Record<string, string>[]} [options.documents=null]
3247
- * A list of dicts representing documents that will be accessible to the model if it is performing RAG
3248
- * (retrieval-augmented generation). If the template does not support RAG, this argument will have no
3249
- * effect. We recommend that each document should be a dict containing "title" and "text" keys. Please
3250
- * see the RAG section of the [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#arguments-for-RAG)
3251
- * for examples of passing documents with chat templates.
3252
- * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate
3253
- * the start of an assistant message. This is useful when you want to generate a response from the model.
3254
- * Note that this argument will be passed to the chat template, and so it must be supported in the
3255
- * template for this argument to have any effect.
3256
- * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string.
3257
- * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false.
3258
- * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false.
3259
- * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false.
3260
- * If not specified, the tokenizer's `max_length` attribute will be used as a default.
3261
- * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false.
3262
- * @param {boolean} [options.return_dict=true] Whether to return a dictionary with named outputs. Has no effect if tokenize is false.
3263
- * @param {Object} [options.tokenizer_kwargs={}] Additional options to pass to the tokenizer.
3264
- * @returns {string | Tensor | number[]| number[][]|BatchEncoding} The tokenized output.
3265
- */
3266
- apply_chat_template(conversation, {
3267
- tools = null,
3268
- documents = null,
3269
- chat_template = null,
3270
- add_generation_prompt = false,
3271
- tokenize = true,
3272
- padding = false,
3273
- truncation = false,
3274
- max_length = null,
3275
- return_tensor = true,
3276
- return_dict = false,
3277
- tokenizer_kwargs = {},
3278
- ...kwargs
3279
- } = {}) {
3280
-
3281
- chat_template = this.get_chat_template({ chat_template, tools });
3282
-
3283
- if (typeof chat_template !== 'string') {
3284
- throw Error(`chat_template must be a string, but got ${typeof chat_template}`);
3285
- }
3286
-
3287
- // Compilation function uses a cache to avoid recompiling the same template
3288
- let compiledTemplate = this._compiled_template_cache.get(chat_template);
3289
- if (compiledTemplate === undefined) {
3290
- compiledTemplate = new Template(chat_template);
3291
- this._compiled_template_cache.set(chat_template, compiledTemplate);
3292
- }
3293
-
3294
- const special_tokens_map = Object.create(null);
3295
- for (const key of SPECIAL_TOKEN_ATTRIBUTES) {
3296
- const value = this.getToken(key);
3297
- if (value) {
3298
- special_tokens_map[key] = value;
3299
- }
3300
- }
3301
-
3302
- const rendered = compiledTemplate.render({
3303
- messages: conversation,
3304
- add_generation_prompt,
3305
- tools,
3306
- documents,
3307
- ...special_tokens_map,
3308
- ...kwargs,
3309
- });
3310
-
3311
- if (tokenize) {
3312
- const out = this._call(rendered, {
3313
- add_special_tokens: false,
3314
- padding,
3315
- truncation,
3316
- max_length,
3317
- return_tensor,
3318
- ...tokenizer_kwargs,
3319
- });
3320
- return return_dict ? out : out.input_ids;
3321
- }
3322
-
3323
- return rendered;
3324
- }
3325
- }
3326
-
3327
- /**
3328
- * BertTokenizer is a class used to tokenize text for BERT models.
3329
- * @extends PreTrainedTokenizer
3330
- */
3331
- export class BertTokenizer extends PreTrainedTokenizer {
3332
- return_token_type_ids = true;
3333
- }
3334
- /**
3335
- * Albert tokenizer
3336
- * @extends PreTrainedTokenizer
3337
- */
3338
- export class AlbertTokenizer extends PreTrainedTokenizer {
3339
- return_token_type_ids = true;
3340
- }
3341
- export class MobileBertTokenizer extends PreTrainedTokenizer {
3342
- return_token_type_ids = true;
3343
- }
3344
- export class SqueezeBertTokenizer extends PreTrainedTokenizer {
3345
- return_token_type_ids = true;
3346
- }
3347
- export class DebertaTokenizer extends PreTrainedTokenizer {
3348
- return_token_type_ids = true;
3349
- }
3350
- export class DebertaV2Tokenizer extends PreTrainedTokenizer {
3351
- return_token_type_ids = true;
3352
- }
3353
- export class HerbertTokenizer extends PreTrainedTokenizer {
3354
- return_token_type_ids = true;
3355
- }
3356
- export class ConvBertTokenizer extends PreTrainedTokenizer {
3357
- return_token_type_ids = true;
3358
- }
3359
- export class RoFormerTokenizer extends PreTrainedTokenizer {
3360
- return_token_type_ids = true;
3361
- }
3362
- export class DistilBertTokenizer extends PreTrainedTokenizer { }
3363
- export class CamembertTokenizer extends PreTrainedTokenizer { }
3364
- export class XLMTokenizer extends PreTrainedTokenizer {
3365
- return_token_type_ids = true;
3366
-
3367
- constructor(tokenizerJSON, tokenizerConfig) {
3368
- super(tokenizerJSON, tokenizerConfig);
3369
- console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')
3370
- }
3371
- }
3372
- export class ElectraTokenizer extends PreTrainedTokenizer {
3373
- return_token_type_ids = true;
3374
- }
3375
-
3376
- export class T5Tokenizer extends PreTrainedTokenizer { }
3377
- export class GPT2Tokenizer extends PreTrainedTokenizer { }
3378
- export class BartTokenizer extends PreTrainedTokenizer { }
3379
- export class MBartTokenizer extends PreTrainedTokenizer {
3380
- constructor(tokenizerJSON, tokenizerConfig) {
3381
- super(tokenizerJSON, tokenizerConfig);
3382
-
3383
- this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/;
3384
- this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));
3385
- this.lang_to_token = x => x; // Identity function
3386
- }
3387
-
3388
- /**
3389
- * Helper function to build translation inputs for an `MBartTokenizer`.
3390
- * @param {string|string[]} raw_inputs The text to tokenize.
3391
- * @param {Object} tokenizer_options Options to be sent to the tokenizer
3392
- * @param {Object} generate_kwargs Generation options.
3393
- * @returns {Object} Object to be passed to the model.
3394
- */
3395
- _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {
3396
- return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);
3397
- }
3398
- }
3399
- export class MBart50Tokenizer extends MBartTokenizer { } // NOTE: extends MBartTokenizer
3400
-
3401
- export class RobertaTokenizer extends PreTrainedTokenizer { }
3402
-
3403
- export class BloomTokenizer extends PreTrainedTokenizer { }
3404
-
3405
- const SPIECE_UNDERLINE = "▁";
3406
-
3407
- export class LlamaTokenizer extends PreTrainedTokenizer {
3408
-
3409
- padding_side = 'left';
3410
-
3411
- constructor(tokenizerJSON, tokenizerConfig) {
3412
- super(tokenizerJSON, tokenizerConfig);
3413
-
3414
- this.legacy = tokenizerConfig.legacy ?? true;
3415
- if (!this.legacy) {
3416
- // See https://github.com/huggingface/transformers/pull/24565 for more information
3417
- this.normalizer = null;
3418
- this.pre_tokenizer = new MetaspacePreTokenizer({
3419
- replacement: SPIECE_UNDERLINE,
3420
- add_prefix_space: true,
3421
- prepend_scheme: "first",
3422
- });
3423
- }
3424
- }
3425
-
3426
- /**
3427
- * Helper function to handle legacy encoding of SPM tokenizers.
3428
- * Adapted from https://github.com/huggingface/transformers/blob/e6dcf8abd6f65bb4b6dfc1831b20d9ba49ce00e2/src/transformers/models/t5/tokenization_t5.py#L374-L387
3429
- * @param {string} text The text to encode.
3430
- * @returns {string[]} The encoded tokens.
3431
- */
3432
- _encode_text(text) {
3433
- if (text === null) return null;
3434
-
3435
- if (this.legacy || text.length === 0) {
3436
- return super._encode_text(text);
3437
- }
3438
-
3439
- let tokens = super._encode_text(SPIECE_UNDERLINE + text.replaceAll(SPIECE_UNDERLINE, " "));
3440
- if (tokens.length > 1 && tokens[0] === SPIECE_UNDERLINE && this.special_tokens.includes(tokens[1])) {
3441
- tokens = tokens.slice(1);
3442
- }
3443
- return tokens;
3444
- }
3445
- }
3446
- export class CodeLlamaTokenizer extends PreTrainedTokenizer { }
3447
-
3448
- export class XLMRobertaTokenizer extends PreTrainedTokenizer { }
3449
- export class MPNetTokenizer extends PreTrainedTokenizer { }
3450
-
3451
- export class FalconTokenizer extends PreTrainedTokenizer { }
3452
-
3453
- export class GPTNeoXTokenizer extends PreTrainedTokenizer { }
3454
-
3455
- export class EsmTokenizer extends PreTrainedTokenizer { }
3456
-
3457
- export class Qwen2Tokenizer extends PreTrainedTokenizer { }
3458
-
3459
- export class GemmaTokenizer extends PreTrainedTokenizer { }
3460
-
3461
- export class Grok1Tokenizer extends PreTrainedTokenizer { }
3462
-
3463
- /**
3464
- * Helper function to build translation inputs for an `NllbTokenizer` or `M2M100Tokenizer`.
3465
- * @param {PreTrainedTokenizer} self The tokenizer instance.
3466
- * @param {string|string[]} raw_inputs The text to tokenize.
3467
- * @param {Object} tokenizer_options Options to be sent to the tokenizer
3468
- * @param {Object} generate_kwargs Generation options.
3469
- * @returns {Object} Object to be passed to the model.
3470
- * @private
3471
- */
3472
- function _build_translation_inputs(self, raw_inputs, tokenizer_options, generate_kwargs) {
3473
- if (!('language_codes' in self) || !Array.isArray(self.language_codes)) {
3474
- throw new Error('Tokenizer must have `language_codes` attribute set and it should be an array of language ids.')
3475
- }
3476
- if (!('languageRegex' in self) || !(self.languageRegex instanceof RegExp)) {
3477
- throw new Error('Tokenizer must have `languageRegex` attribute set and it should be a regular expression.')
3478
- }
3479
- if (!('lang_to_token' in self) || typeof self.lang_to_token !== 'function') {
3480
- throw new Error('Tokenizer must have `lang_to_token` attribute set and it should be a function.')
3481
- }
3482
- const src_lang_token = generate_kwargs.src_lang;
3483
- const tgt_lang_token = generate_kwargs.tgt_lang;
3484
-
3485
- // Check that the target language is valid:
3486
- if (!self.language_codes.includes(tgt_lang_token)) {
3487
- throw new Error(`Target language code "${tgt_lang_token}" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);
3488
- }
3489
-
3490
- // Allow `src_lang` to be optional. If not set, we'll use the tokenizer's default.
3491
- if (src_lang_token !== undefined) {
3492
- // Check that the source language is valid:
3493
- if (!self.language_codes.includes(src_lang_token)) {
3494
- throw new Error(`Source language code "${src_lang_token}" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);
3495
- }
3496
-
3497
- // In the same way as the Python library, we override the post-processor
3498
- // to force the source language to be first:
3499
- for (const item of self.post_processor.config.single) {
3500
- if ('SpecialToken' in item && self.languageRegex.test(item.SpecialToken.id)) {
3501
- item.SpecialToken.id = self.lang_to_token(src_lang_token);
3502
- break;
3503
- }
3504
- }
3505
- // TODO: Do the same for pair?
3506
- }
3507
-
3508
- // Override the `forced_bos_token_id` to force the correct language
3509
- generate_kwargs.forced_bos_token_id = self.model.convert_tokens_to_ids([self.lang_to_token(tgt_lang_token)])[0];
3510
-
3511
- return self._call(raw_inputs, tokenizer_options);
3512
- }
3513
-
3514
- /**
3515
- * The NllbTokenizer class is used to tokenize text for NLLB ("No Language Left Behind") models.
3516
- *
3517
- * No Language Left Behind (NLLB) is a first-of-its-kind, AI breakthrough project
3518
- * that open-sources models capable of delivering high-quality translations directly
3519
- * between any pair of 200+ languages — including low-resource languages like Asturian,
3520
- * Luganda, Urdu and more. It aims to help people communicate with anyone, anywhere,
3521
- * regardless of their language preferences. For more information, check out their
3522
- * [paper](https://huggingface.co/papers/2207.04672).
3523
- *
3524
- * For a list of supported languages (along with their language codes),
3525
- * @see {@link https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200}
3526
- */
3527
- export class NllbTokenizer extends PreTrainedTokenizer {
3528
-
3529
- constructor(tokenizerJSON, tokenizerConfig) {
3530
- super(tokenizerJSON, tokenizerConfig);
3531
-
3532
- this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/;
3533
- this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));
3534
- this.lang_to_token = x => x; // Identity function
3535
- }
3536
-
3537
- /**
3538
- * Helper function to build translation inputs for an `NllbTokenizer`.
3539
- * @param {string|string[]} raw_inputs The text to tokenize.
3540
- * @param {Object} tokenizer_options Options to be sent to the tokenizer
3541
- * @param {Object} generate_kwargs Generation options.
3542
- * @returns {Object} Object to be passed to the model.
3543
- */
3544
- _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {
3545
- return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);
3546
- }
3547
- }
3548
-
3549
- /**
3550
- * The M2M100Tokenizer class is used to tokenize text for M2M100 ("Many-to-Many") models.
3551
- *
3552
- * M2M100 is a multilingual encoder-decoder (seq-to-seq) model trained for Many-to-Many
3553
- * multilingual translation. It was introduced in this [paper](https://huggingface.co/papers/2010.11125)
3554
- * and first released in [this](https://github.com/pytorch/fairseq/tree/master/examples/m2m_100) repository.
3555
- *
3556
- * For a list of supported languages (along with their language codes),
3557
- * @see {@link https://huggingface.co/facebook/m2m100_418M#languages-covered}
3558
- */
3559
- export class M2M100Tokenizer extends PreTrainedTokenizer {
3560
- constructor(tokenizerJSON, tokenizerConfig) {
3561
- super(tokenizerJSON, tokenizerConfig);
3562
-
3563
- this.languageRegex = /^__[a-z]{2,3}__$/;
3564
- this.language_codes = this.special_tokens
3565
- .filter(x => this.languageRegex.test(x))
3566
- .map(x => x.slice(2, -2));
3567
- this.lang_to_token = x => `__${x}__`;
3568
- }
3569
-
3570
- /**
3571
- * Helper function to build translation inputs for an `M2M100Tokenizer`.
3572
- * @param {string|string[]} raw_inputs The text to tokenize.
3573
- * @param {Object} tokenizer_options Options to be sent to the tokenizer
3574
- * @param {Object} generate_kwargs Generation options.
3575
- * @returns {Object} Object to be passed to the model.
3576
- */
3577
- _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {
3578
- return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);
3579
- }
3580
- }
3581
-
3582
- /**
3583
- * WhisperTokenizer tokenizer
3584
- * @extends PreTrainedTokenizer
3585
- */
3586
- export class WhisperTokenizer extends PreTrainedTokenizer {
3587
-
3588
- get timestamp_begin() {
3589
- return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0] + 1;
3590
- }
3591
-
3592
- /**
3593
- * Decodes automatic speech recognition (ASR) sequences.
3594
- * @param {Array<{tokens: bigint[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode.
3595
- * @param {Object} options The options to use for decoding.
3596
- * @returns {Array<string|{chunks?: undefined|Array<{language: string|null, timestamp: Array<number|null>, text: string}>}>} The decoded sequences.
3597
- */
3598
- _decode_asr(sequences, {
3599
- return_timestamps = false,
3600
- return_language = false,
3601
- time_precision = null,
3602
- force_full_sequences = true
3603
- } = {}) {
3604
- // Set force_full_sequences=false if you want streaming
3605
- // TODO add support for `return_language`
3606
-
3607
- // Internal method meant to only be used by asr pipeline.
3608
- // Handles all the little quirks specific to whisper to handle
3609
- // the various options not allowed in other seq2seq models
3610
-
3611
- // =========== Overview ============
3612
- // - iterate over all outputs
3613
- // - all tokens within output
3614
- // - Each token can be
3615
- // - language token
3616
- // - special token
3617
- // - timestamp token
3618
- // - text token
3619
- // - We accumulate the text tokens.
3620
- // - We split on end timestamps
3621
- // - Lots of complexity comes from stride and timestamps
3622
-
3623
- if (time_precision === null) {
3624
- throw Error("Must specify time_precision")
3625
- }
3626
- let last_language = null;
3627
-
3628
- const returnWordTimestamps = return_timestamps === "word";
3629
-
3630
- function new_chunk() {
3631
- return { "language": last_language, "timestamp": [null, null], "text": "" };
3632
- }
3633
-
3634
- // Welcome to the state machine!
3635
- const chunks = [];
3636
- let chunk = new_chunk();
3637
- let time_offset = 0.0;
3638
- const timestamp_begin = this.timestamp_begin;
3639
- // Whisper timestamp tokens start from 0.00 and go to timestamp 30.00 in 0.02 increments.
3640
- // We can calculate the last time stamp token as timestamp_begin plus the number of tokens
3641
- // tokens from 0.00 to 30.00 which is 1500.
3642
- const total_timestamp_tokens = 1500; // (30.00 - 0.00) / 0.02
3643
- const timestamp_end = timestamp_begin + total_timestamp_tokens;
3644
-
3645
- let previous_tokens = [];
3646
- let previous_token_timestamps = [];
3647
-
3648
- let skip = false;
3649
- let right_stride_start = null;
3650
-
3651
-
3652
- const all_special_ids = new Set(this.all_special_ids);
3653
-
3654
- for (const output of sequences) {
3655
- // NOTE: python version has batches, so it uses [0]
3656
- const token_ids = output.tokens;
3657
- const token_timestamps = returnWordTimestamps ? output.token_timestamps : null;
3658
-
3659
- // These keep track of timestamps within strides, which need
3660
- // to be skipped and resolve all tokens in a single chunk.
3661
- let last_timestamp = null;
3662
- let first_timestamp = timestamp_begin;
3663
-
3664
- if ("stride" in output) {
3665
- const [chunk_len, stride_left, stride_right] = output.stride;
3666
-
3667
- // Offset the timings to account for the other `model_outputs`.
3668
- time_offset -= stride_left;
3669
- right_stride_start = chunk_len - stride_right;
3670
-
3671
- // Keeping track of timestamps within strides
3672
- // We're going to NOT split on those, and delay until we're
3673
- // out of BOTH stride. Otherwise lots of issues occur and
3674
- // corner cases
3675
- if (stride_left) {
3676
- first_timestamp = stride_left / time_precision + timestamp_begin;
3677
- }
3678
-
3679
- if (stride_right) {
3680
- for (let i = token_ids.length - 1; i >= 0; --i) {
3681
- const token = Number(token_ids[i]);
3682
- if (token >= timestamp_begin) {
3683
- // There can be several token in the right stride
3684
- // But the last one is ALWAYS going to be skipped
3685
- if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) {
3686
- break;
3687
- }
3688
- last_timestamp = token;
3689
- }
3690
- }
3691
- }
3692
- }
3693
-
3694
- let current_tokens = [];
3695
- let current_token_timestamps = [];
3696
-
3697
- // - all tokens within output
3698
- for (let i = 0; i < token_ids.length; ++i) {
3699
- const token = Number(token_ids[i]);
3700
- // 4 possible states for each token
3701
- // - 1/ Language code
3702
- // - 2/ all other special tokens (which we ignore)
3703
- // - 3/ Timestamp
3704
- // - 4/ Regular text
3705
-
3706
- if (all_special_ids.has(token)) {
3707
- const text = this.decode([token]);
3708
- const language = WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2));
3709
-
3710
- if (language !== undefined) {
3711
- // 1/ Indeed some language
3712
- // TODO Handle when language is different from the previous
3713
- // one, and we cannot use timestamped tokens to create chunks
3714
- if (last_language !== null && language !== last_language && !return_timestamps) {
3715
- previous_tokens.push(current_tokens);
3716
- const resolved_tokens = this.findLongestCommonSequence(previous_tokens)[0];
3717
- const resolved_text = this.decode(resolved_tokens);
3718
- chunk.text = resolved_text;
3719
- chunks.push(chunk);
3720
-
3721
- // Flush all our temporary context
3722
- previous_tokens = [];
3723
- current_tokens = [];
3724
- chunk = new_chunk();
3725
- }
3726
-
3727
- last_language = chunk.language = language;
3728
- } else {
3729
- // 2/ This is a regular special token, ignoring it
3730
- }
3731
- } else if (token >= timestamp_begin && token <= timestamp_end) {
3732
- // 3/ Timestamp token
3733
- const time = (token - timestamp_begin) * time_precision + time_offset;
3734
- const rounded_time = round(time, 2);
3735
-
3736
- if (last_timestamp !== null && token >= last_timestamp) {
3737
- // Whisper outputted a timestamp token, but it falls within
3738
- // our stride, so we're going to skip it for the time being
3739
- // and resolve this later
3740
- // Skip is necessary because timestamp tokens always come
3741
- // by pair, so we need to skip the next one too (which would mark the start of another chunk).
3742
- skip = true;
3743
- } else if (skip || (previous_tokens.length > 0 && token < first_timestamp)) {
3744
- skip = false;
3745
- } else if (chunk.timestamp[0] === null) {
3746
- chunk.timestamp[0] = rounded_time;
3747
- } else {
3748
- // This is the end of the timestamp chunk
3749
- if (rounded_time === chunk.timestamp[0]) {
3750
- // This is a bug in timestamp token output
3751
- // where we're taking the duplicate token
3752
- // as a stop where it should be a start.
3753
- // This is an issue in the underlying model output
3754
- // Let's just skip it so it becomes de-factor a start agin
3755
- } else {
3756
- chunk.timestamp[1] = rounded_time;
3757
-
3758
- // Handling merges
3759
- previous_tokens.push(current_tokens)
3760
-
3761
- if (returnWordTimestamps) {
3762
- previous_token_timestamps.push(current_token_timestamps);
3763
- }
3764
- const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(
3765
- previous_tokens, previous_token_timestamps
3766
- )
3767
-
3768
- const resolved_text = this.decode(resolved_tokens)
3769
- chunk.text = resolved_text
3770
-
3771
- if (returnWordTimestamps) {
3772
- chunk.words = this.collateWordTimestamps(
3773
- resolved_tokens, resolved_token_timestamps, last_language,
3774
- )
3775
- }
3776
-
3777
- chunks.push(chunk)
3778
-
3779
- // Flush all our temporary context
3780
- previous_tokens = []
3781
- current_tokens = []
3782
- previous_token_timestamps = []
3783
- current_token_timestamps = []
3784
- chunk = new_chunk()
3785
- }
3786
- }
3787
-
3788
- } else {
3789
- // 4/ Regular token
3790
- // We just append to the list of all tokens so we can handle
3791
- // merges later and decode into text.
3792
- current_tokens.push(token)
3793
-
3794
- if (returnWordTimestamps) {
3795
- let start_time = round(token_timestamps[i] + time_offset, 2);
3796
-
3797
- let end_time;
3798
- if (i + 1 < token_timestamps.length) {
3799
- end_time = round(token_timestamps[i + 1] + time_offset, 2);
3800
-
3801
- // Do not allow punctuation-only tokens to have a duration.
3802
- // This prevents long pauses from messing up the timestamps.
3803
- const decoded_text = this.decode([token]);
3804
- if (PUNCTUATION_ONLY_REGEX.test(decoded_text)) {
3805
- // Add `time_precision` to avoid overlapping timestamps
3806
- end_time = round(Math.min(start_time + time_precision, end_time), 2);
3807
- }
3808
- } else {
3809
- // should never happen
3810
- end_time = null;
3811
- }
3812
- current_token_timestamps.push([start_time, end_time]);
3813
- }
3814
-
3815
- }
3816
- }
3817
-
3818
- if ('stride' in output) {
3819
- const [chunk_len, stride_left, stride_right] = output.stride;
3820
- time_offset += chunk_len - stride_right
3821
- }
3822
-
3823
- // Leftover tokens
3824
- if (current_tokens.length > 0) {
3825
- previous_tokens.push(current_tokens)
3826
- if (returnWordTimestamps) {
3827
- previous_token_timestamps.push(current_token_timestamps);
3828
- }
3829
- } else if (previous_tokens.every(p => p.length === 0)) {
3830
- // Flushing previous tokens (END)"
3831
- chunk = new_chunk()
3832
- previous_tokens = []
3833
- current_tokens = []
3834
- previous_token_timestamps = [];
3835
- current_token_timestamps = [];
3836
- }
3837
-
3838
- }
3839
-
3840
- if (previous_tokens.length > 0) {
3841
- if (force_full_sequences && return_timestamps) {
3842
- // Last token should always be timestamps, so there shouldn't be
3843
- // leftover
3844
- throw new Error(
3845
- "Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. " +
3846
- "Also make sure WhisperTimeStampLogitsProcessor was used during generation."
3847
- );
3848
- }
3849
-
3850
- // Happens when we don't use timestamps
3851
- const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(previous_tokens, previous_token_timestamps);
3852
-
3853
- // Flushing previous tokens (FINAL)
3854
- const resolved_text = this.decode(resolved_tokens);
3855
- chunk.text = resolved_text;
3856
- if (returnWordTimestamps) {
3857
- chunk.words = this.collateWordTimestamps(
3858
- resolved_tokens, resolved_token_timestamps, last_language,
3859
- )
3860
- }
3861
- chunks.push(chunk);
3862
- }
3863
-
3864
- let optional = Object.create(null);
3865
-
3866
- // Preparing and cleaning up the pipeline output
3867
- const full_text = chunks.map(chunk => chunk.text).join('');
3868
- if (return_timestamps || return_language) {
3869
- for (let i = 0; i < chunks.length; ++i) {
3870
- const chunk = chunks[i];
3871
- if (!return_timestamps) {
3872
- delete chunk["timestamp"];
3873
- }
3874
-
3875
- if (!return_language) {
3876
- delete chunk["language"];
3877
- }
3878
- }
3879
- if (returnWordTimestamps) {
3880
- const new_chunks = [];
3881
- for (const chunk of chunks) {
3882
- for (const word of chunk.words) {
3883
- new_chunks.push(word);
3884
- }
3885
- }
3886
- optional = { "chunks": new_chunks };
3887
- } else {
3888
- optional = { "chunks": chunks };
3889
- }
3890
- }
3891
- return [full_text, optional];
3892
-
3893
- }
3894
-
3895
- /**
3896
- * Finds the longest common sequence among the provided sequences.
3897
- * @param {number[][]} sequences An array of sequences of token ids to compare.
3898
- * @returns {number[][]} The longest common sequence found.
3899
- * @throws {Error} If there is a bug within the function.
3900
- * @private
3901
- */
3902
- findLongestCommonSequence(sequences, token_timestamp_sequences = null) {
3903
- // It would be much harder to do O(n) because of fault tolerance.
3904
- // We actually have a really good property which is that the total sequence
3905
- // MUST be those subsequences in order.
3906
- // If token_timestamp_sequences is provided, will split those sequences in
3907
- // exactly the same way.
3908
- let leftSequence = sequences[0];
3909
- let leftLength = leftSequence.length;
3910
- let totalSequence = [];
3911
-
3912
- const use_token_timestamp_sequences = Array.isArray(token_timestamp_sequences) && token_timestamp_sequences.length > 0;
3913
- let total_token_timestamp_sequence = use_token_timestamp_sequences ? [] : null;
3914
- let left_token_timestamp_sequence = use_token_timestamp_sequences ? token_timestamp_sequences[0] : null;
3915
- for (let i = 1; i < sequences.length; ++i) {
3916
- const rightSequence = sequences[i];
3917
- let max = 0.0;
3918
- let maxIndices = [leftLength, leftLength, 0, 0];
3919
- // Here we're sliding matches
3920
- // [a, b, c, d]
3921
- // [c, d, f]
3922
- // = [c] == [d]
3923
-
3924
- // [a, b, c, d]
3925
- // [c, d, f]
3926
- // = [c, d] == [c, d]
3927
-
3928
-
3929
- // [a, b, c, d]
3930
- // [c, d, f]
3931
-
3932
- // = [b, c, d] == [c, d, f]
3933
-
3934
- // [a, b, c, d]
3935
- // [c, d, f]
3936
-
3937
- // [a, b, c] == [c, d, f]
3938
-
3939
- // [a, b, c, d]
3940
- // [d, f]
3941
-
3942
- // [a, b] == [d, f]
3943
-
3944
- // [a, b, c, d]
3945
- // [f]
3946
-
3947
- // [a] == [f]
3948
-
3949
- const rightLength = rightSequence.length;
3950
- for (let j = 1; j < leftLength + rightLength; ++j) {
3951
- // Slightly convoluted because we don't want out of bound indices
3952
- // This will be necessary for a small conflict resolution optimization
3953
- // later
3954
- const leftStart = Math.max(0, leftLength - j);
3955
- const leftStop = Math.min(leftLength, leftLength + rightLength - j);
3956
- const left = leftSequence.slice(leftStart, leftStop);
3957
- const rightStart = Math.max(0, j - leftLength);
3958
- const rightStop = Math.min(rightLength, j);
3959
- const right = rightSequence.slice(rightStart, rightStop);
3960
- if (left.length !== right.length) {
3961
- throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");
3962
- }
3963
-
3964
- let matches;
3965
- if (use_token_timestamp_sequences) {
3966
- // Get length of longest subsequence of tokens that match
3967
- // and have timestamps that are in order
3968
- matches = left.filter((elem, idx) => (
3969
- elem === right[idx]
3970
- && left_token_timestamp_sequence[leftStart + idx] <= token_timestamp_sequences[i][rightStart + idx]
3971
- )).length;
3972
- } else {
3973
- matches = left.filter((elem, idx) => elem === right[idx]).length;
3974
- }
3975
-
3976
- // epsilon to favor long perfect matches
3977
- const eps = j / 10000.0;
3978
- const matching = matches / j + eps;
3979
- if (matches > 1 && matching > max) {
3980
- max = matching;
3981
- maxIndices = [leftStart, leftStop, rightStart, rightStop];
3982
- }
3983
- }
3984
- const [leftStart, leftStop, rightStart, rightStop] = maxIndices;
3985
- const leftMid = Math.floor((leftStop + leftStart) / 2);
3986
- const rightMid = Math.floor((rightStop + rightStart) / 2);
3987
- totalSequence.push(...leftSequence.slice(0, leftMid));
3988
- leftSequence = rightSequence.slice(rightMid);
3989
- leftLength = leftSequence.length;
3990
-
3991
- if (use_token_timestamp_sequences) {
3992
- total_token_timestamp_sequence.push(...left_token_timestamp_sequence.slice(0, leftMid));
3993
- left_token_timestamp_sequence = token_timestamp_sequences[i].slice(rightMid);
3994
- }
3995
- }
3996
- totalSequence.push(...leftSequence);
3997
-
3998
- if (use_token_timestamp_sequences) {
3999
- total_token_timestamp_sequence.push(...left_token_timestamp_sequence);
4000
- return [totalSequence, total_token_timestamp_sequence];
4001
- } else {
4002
- return [totalSequence, []];
4003
- }
4004
- }
4005
-
4006
- /** @private */
4007
- collateWordTimestamps(tokens, token_timestamps, language) {
4008
-
4009
- const [words, _, token_indices] = this.combineTokensIntoWords(tokens, language);
4010
-
4011
- const timings = [];
4012
- for (let i = 0; i < words.length; ++i) {
4013
- const indices = token_indices[i];
4014
- timings.push({
4015
- text: words[i],
4016
- timestamp: [
4017
- token_timestamps[indices.at(0)][0],
4018
- token_timestamps[indices.at(-1)][1],
4019
- ],
4020
- });
4021
- }
4022
- return timings;
4023
- }
4024
-
4025
- /**
4026
- * Groups tokens by word. Returns a tuple containing a list of strings with the words,
4027
- * and a list of `token_id` sequences with the tokens making up each word.
4028
- * @param {number[]} tokens
4029
- * @param {string} [language]
4030
- * @param {string} prepend_punctionations
4031
- * @param {string} append_punctuations
4032
- *
4033
- * @private
4034
- */
4035
- combineTokensIntoWords(tokens, language, prepend_punctionations = "\"'“¡¿([{-", append_punctuations = "\"'.。,,!!??::”)]}、") {
4036
- language = language ?? 'english';
4037
-
4038
- let words, word_tokens, token_indices;
4039
-
4040
- if (["chinese", "japanese", "thai", "lao", "myanmar"].includes(language)) {
4041
- // These languages don't typically use spaces.
4042
- [words, word_tokens, token_indices] = this.splitTokensOnUnicode(tokens)
4043
- } else {
4044
- [words, word_tokens, token_indices] = this.splitTokensOnSpaces(tokens)
4045
- }
4046
-
4047
- return this.mergePunctuations(words, word_tokens, token_indices, prepend_punctionations, append_punctuations);
4048
- }
4049
-
4050
- /** @type {PreTrainedTokenizer['decode']} */
4051
- decode(
4052
- token_ids,
4053
- decode_args,
4054
- ) {
4055
- let text;
4056
- // @ts-ignore
4057
- if (decode_args?.decode_with_timestamps) {
4058
- if (token_ids instanceof Tensor) {
4059
- token_ids = prepareTensorForDecode(token_ids);
4060
- }
4061
- text = this.decodeWithTimestamps(token_ids, decode_args);
4062
- } else {
4063
- text = super.decode(token_ids, decode_args);
4064
- }
4065
- // TODO: implement offsets
4066
- // if (decode_args.output_offsets) {
4067
- // let offsets = this.computeOffsets
4068
- // }
4069
- return text;
4070
- }
4071
-
4072
- /**
4073
- * @param {number[]|bigint[]} token_ids List of token IDs to decode.
4074
- * @param {Object} decode_args Optional arguments for decoding
4075
- * @private
4076
- */
4077
- decodeWithTimestamps(token_ids, decode_args) {
4078
- const time_precision = decode_args?.time_precision ?? 0.02;
4079
-
4080
- const timestamp_begin = Array.from(this.all_special_ids).at(-1) + 1;
4081
- /**@type {Array} */
4082
- let outputs = [[]];
4083
- for (let token of token_ids) {
4084
- token = Number(token);
4085
- if (token >= timestamp_begin) {
4086
- const timestamp = ((token - timestamp_begin) * time_precision).toFixed(2);
4087
- outputs.push(`<|${timestamp}|>`);
4088
- outputs.push([]);
4089
- } else {
4090
- outputs[outputs.length - 1].push(token);
4091
- }
4092
- }
4093
- outputs = outputs.map(
4094
- s => typeof s === 'string' ? s : super.decode(s, decode_args)
4095
- )
4096
-
4097
- return outputs.join('');
4098
- }
4099
-
4100
- /**
4101
- * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points.
4102
- * @param {number[]} tokens
4103
- * @returns {*}
4104
- * @private
4105
- */
4106
- splitTokensOnUnicode(tokens) {
4107
- const decoded_full = this.decode(tokens, {
4108
- // @ts-ignore
4109
- decode_with_timestamps: true,
4110
- });
4111
- const replacement_char = '\uFFFD';
4112
-
4113
- const words = []
4114
- const word_tokens = []
4115
- const token_indices = []
4116
- let current_tokens = []
4117
- let current_indices = []
4118
- let unicode_offset = 0
4119
-
4120
- for (let token_idx = 0; token_idx < tokens.length; ++token_idx) {
4121
- const token = tokens[token_idx];
4122
-
4123
- current_tokens.push(token);
4124
- current_indices.push(token_idx);
4125
-
4126
- const decoded = this.decode(current_tokens, {
4127
- // @ts-ignore
4128
- decode_with_timestamps: true,
4129
- });
4130
-
4131
- if (!decoded.includes(replacement_char) || decoded_full[unicode_offset + decoded.indexOf(replacement_char)] === replacement_char) {
4132
- words.push(decoded)
4133
- word_tokens.push(current_tokens)
4134
- token_indices.push(current_indices)
4135
- current_tokens = []
4136
- current_indices = []
4137
- unicode_offset += decoded.length;
4138
- }
4139
-
4140
- }
4141
-
4142
- return [words, word_tokens, token_indices]
4143
- }
4144
-
4145
- /**
4146
- * Combine tokens into words by splitting at whitespace and punctuation tokens.
4147
- * @param {number[]} tokens
4148
- * @private
4149
- */
4150
- splitTokensOnSpaces(tokens) {
4151
-
4152
- const [subwords, subword_tokens_list, subword_indices_list] = this.splitTokensOnUnicode(tokens);
4153
-
4154
- const words = []
4155
- const word_tokens = []
4156
- const token_indices = []
4157
-
4158
- const punctuationRegex = new RegExp(`^[${PUNCTUATION_REGEX}]$`, 'gu');
4159
-
4160
- for (let i = 0; i < subwords.length; ++i) {
4161
-
4162
- const subword = subwords[i];
4163
- const subword_tokens = subword_tokens_list[i];
4164
- const subword_indices = subword_indices_list[i];
4165
-
4166
- // @ts-ignore
4167
- const special = subword_tokens[0] >= this.model.tokens_to_ids.get('<|endoftext|>');
4168
- const with_space = subword.startsWith(' ');
4169
- const trimmed = subword.trim();
4170
- const punctuation = punctuationRegex.test(trimmed);
4171
-
4172
- if (special || with_space || punctuation || words.length === 0) {
4173
- words.push(subword);
4174
- word_tokens.push(subword_tokens);
4175
- token_indices.push(subword_indices);
4176
- } else {
4177
- const ix = words.length - 1;
4178
- words[ix] += subword;
4179
- word_tokens[ix].push(...subword_tokens);
4180
- token_indices[ix].push(...subword_indices);
4181
- }
4182
- }
4183
-
4184
- return [words, word_tokens, token_indices];
4185
-
4186
- }
4187
-
4188
- /**
4189
- * Merges punctuation tokens with neighboring words.
4190
- * @param {string[]} words
4191
- * @param {number[][]} tokens
4192
- * @param {number[][]} indices
4193
- * @param {string} prepended
4194
- * @param {string} appended
4195
- * @private
4196
- */
4197
- mergePunctuations(words, tokens, indices, prepended, appended) {
4198
-
4199
- const newWords = structuredClone(words);
4200
- const newTokens = structuredClone(tokens);
4201
- const newIndices = structuredClone(indices);
4202
-
4203
-
4204
- // prepend punctuations
4205
- let i = newWords.length - 2;
4206
- let j = newWords.length - 1;
4207
-
4208
- while (i >= 0) {
4209
- if (newWords[i].startsWith(' ') && prepended.includes(newWords[i].trim())) {
4210
- newWords[j] = newWords[i] + newWords[j];
4211
- newTokens[j] = mergeArrays(newTokens[i], newTokens[j]);
4212
- newIndices[j] = mergeArrays(newIndices[i], newIndices[j]);
4213
- newWords[i] = '';
4214
- newTokens[i] = [];
4215
- newIndices[i] = [];
4216
- } else {
4217
- j = i;
4218
- }
4219
- --i;
4220
- }
4221
-
4222
- // append punctuations
4223
- i = 0;
4224
- j = 1;
4225
- while (j < newWords.length) {
4226
- if (!newWords[i].endsWith(' ') && appended.includes(newWords[j])) {
4227
- newWords[i] += newWords[j];
4228
- newTokens[i] = mergeArrays(newTokens[i], newTokens[j]);
4229
- newIndices[i] = mergeArrays(newIndices[i], newIndices[j]);
4230
- newWords[j] = '';
4231
- newTokens[j] = [];
4232
- newIndices[j] = [];
4233
- } else {
4234
- i = j;
4235
- }
4236
- ++j;
4237
- }
4238
-
4239
- return [
4240
- newWords.filter(x => x),
4241
- newTokens.filter(x => x.length > 0),
4242
- newIndices.filter(x => x.length > 0),
4243
- ]
4244
- }
4245
- }
4246
- export class CodeGenTokenizer extends PreTrainedTokenizer { }
4247
- export class CLIPTokenizer extends PreTrainedTokenizer { }
4248
- export class SiglipTokenizer extends PreTrainedTokenizer { }
4249
-
4250
- /**
4251
- * @todo This model is not yet supported by Hugging Face's "fast" tokenizers library (https://github.com/huggingface/tokenizers).
4252
- * Therefore, this implementation (which is based on fast tokenizers) may produce slightly inaccurate results.
4253
- */
4254
- export class MarianTokenizer extends PreTrainedTokenizer {
4255
- /**
4256
- * Create a new MarianTokenizer instance.
4257
- * @param {Object} tokenizerJSON The JSON of the tokenizer.
4258
- * @param {Object} tokenizerConfig The config of the tokenizer.
4259
- */
4260
- constructor(tokenizerJSON, tokenizerConfig) {
4261
- super(tokenizerJSON, tokenizerConfig);
4262
-
4263
- this.languageRegex = /^(>>\w+<<)\s*/g;
4264
-
4265
- this.supported_language_codes = this.model.vocab.filter(
4266
- x => this.languageRegex.test(x)
4267
- );
4268
-
4269
- console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')
4270
- }
4271
-
4272
- /**
4273
- * Encodes a single text. Overriding this method is necessary since the language codes
4274
- * must be removed before encoding with sentencepiece model.
4275
- * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213
4276
- *
4277
- * @param {string|null} text The text to encode.
4278
- * @returns {Array} The encoded tokens.
4279
- */
4280
- _encode_text(text) {
4281
- if (text === null) return null;
4282
-
4283
- // Check if text starts with language code:
4284
- const [matchInfo, ...remainder] = text.trim().split(this.languageRegex);
4285
-
4286
- if (remainder.length === 0) {
4287
- // No language code, encode normally
4288
- return super._encode_text(matchInfo);
4289
-
4290
- } else if (remainder.length === 2) {
4291
- // Text starts with language code, so we do not encode it with sentencepiece.
4292
- const [language, text] = remainder;
4293
-
4294
- if (!this.supported_language_codes.includes(language)) {
4295
- console.warn(`Unsupported language code "${language}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`)
4296
- }
4297
- return mergeArrays([language], super._encode_text(text));
4298
- }
4299
- }
4300
-
4301
- }
4302
-
4303
- export class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer { }
4304
-
4305
- export class BlenderbotTokenizer extends PreTrainedTokenizer { }
4306
- export class BlenderbotSmallTokenizer extends PreTrainedTokenizer { }
4307
-
4308
- export class SpeechT5Tokenizer extends PreTrainedTokenizer { }
4309
-
4310
- export class NougatTokenizer extends PreTrainedTokenizer { }
4311
-
4312
- export class VitsTokenizer extends PreTrainedTokenizer {
4313
-
4314
- constructor(tokenizerJSON, tokenizerConfig) {
4315
- super(tokenizerJSON, tokenizerConfig);
4316
-
4317
- // Custom decoder function
4318
- this.decoder = new VitsDecoder({});
4319
- }
4320
- }
4321
-
4322
- export class CohereTokenizer extends PreTrainedTokenizer { }
4323
-
4324
- export class MgpstrTokenizer extends PreTrainedTokenizer { }
4325
-
4326
- export class Ernie4_5_Tokenizer extends PreTrainedTokenizer { }
4327
-
4328
- /**
4329
- * Helper class which is used to instantiate pretrained tokenizers with the `from_pretrained` function.
4330
- * The chosen tokenizer class is determined by the type specified in the tokenizer config.
4331
- *
4332
- * @example
4333
- * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');
4334
- */
4335
- export class AutoTokenizer {
4336
- static TOKENIZER_CLASS_MAPPING = {
4337
- T5Tokenizer,
4338
- DistilBertTokenizer,
4339
- CamembertTokenizer,
4340
- DebertaTokenizer,
4341
- DebertaV2Tokenizer,
4342
- BertTokenizer,
4343
- HerbertTokenizer,
4344
- ConvBertTokenizer,
4345
- RoFormerTokenizer,
4346
- XLMTokenizer,
4347
- ElectraTokenizer,
4348
- MobileBertTokenizer,
4349
- SqueezeBertTokenizer,
4350
- AlbertTokenizer,
4351
- GPT2Tokenizer,
4352
- BartTokenizer,
4353
- MBartTokenizer,
4354
- MBart50Tokenizer,
4355
- RobertaTokenizer,
4356
- WhisperTokenizer,
4357
- CodeGenTokenizer,
4358
- CLIPTokenizer,
4359
- SiglipTokenizer,
4360
- MarianTokenizer,
4361
- BloomTokenizer,
4362
- NllbTokenizer,
4363
- M2M100Tokenizer,
4364
- LlamaTokenizer,
4365
- CodeLlamaTokenizer,
4366
- XLMRobertaTokenizer,
4367
- MPNetTokenizer,
4368
- FalconTokenizer,
4369
- GPTNeoXTokenizer,
4370
- EsmTokenizer,
4371
- Wav2Vec2CTCTokenizer,
4372
- BlenderbotTokenizer,
4373
- BlenderbotSmallTokenizer,
4374
- SpeechT5Tokenizer,
4375
- NougatTokenizer,
4376
- VitsTokenizer,
4377
- Qwen2Tokenizer,
4378
- GemmaTokenizer,
4379
- Grok1Tokenizer,
4380
- CohereTokenizer,
4381
- MgpstrTokenizer,
4382
- Ernie4_5_Tokenizer,
4383
-
4384
- // Base case:
4385
- PreTrainedTokenizer,
4386
- }
4387
-
4388
-
4389
- /**
4390
- * Instantiate one of the tokenizer classes of the library from a pretrained model.
4391
- *
4392
- * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object
4393
- * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
4394
- *
4395
- * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
4396
- * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co.
4397
- * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
4398
- * user or organization name, like `dbmdz/bert-base-german-cased`.
4399
- * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`.
4400
- * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
4401
- *
4402
- * @returns {Promise<PreTrainedTokenizer>} A new instance of the PreTrainedTokenizer class.
4403
- */
4404
- static async from_pretrained(pretrained_model_name_or_path, {
4405
- progress_callback = null,
4406
- config = null,
4407
- cache_dir = null,
4408
- local_files_only = false,
4409
- revision = 'main',
4410
- legacy = null,
4411
- } = {}) {
4412
-
4413
- const [tokenizerJSON, tokenizerConfig] = await loadTokenizer(pretrained_model_name_or_path, {
4414
- progress_callback,
4415
- config,
4416
- cache_dir,
4417
- local_files_only,
4418
- revision,
4419
- legacy,
4420
- })
4421
-
4422
- // Some tokenizers are saved with the "Fast" suffix, so we remove that if present.
4423
- const tokenizerName = tokenizerConfig.tokenizer_class?.replace(/Fast$/, '') ?? 'PreTrainedTokenizer';
4424
-
4425
- let cls = this.TOKENIZER_CLASS_MAPPING[tokenizerName];
4426
- if (!cls) {
4427
- console.warn(`Unknown tokenizer class "${tokenizerName}", attempting to construct from base class.`);
4428
- cls = PreTrainedTokenizer;
4429
- }
4430
- return new cls(tokenizerJSON, tokenizerConfig);
4431
- }
4432
- }