gpt-tokenizer 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/encoder.ts ADDED
@@ -0,0 +1,252 @@
1
+ /* eslint-disable unicorn/prefer-spread */
2
+ /* eslint-disable unicorn/prefer-code-point */
3
+
4
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error
5
+ // @ts-ignore
6
+ import bpeRanksData from '../data/bpeRanks.json'
7
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error
8
+ // @ts-ignore
9
+ import encoderData from '../data/encoder.json'
10
+ import {
11
+ dictZip,
12
+ getCharCode,
13
+ getCharFromCode,
14
+ getPairs,
15
+ range,
16
+ splitToken,
17
+ } from './utils'
18
+
19
+ const encoder: Record<string, number> = encoderData
20
+ const bpeRanks: Record<string, number> = bpeRanksData
21
+
22
+ const decoder: Record<number, string> = dictZip(
23
+ Object.values(encoder),
24
+ Object.keys(encoder),
25
+ )
26
+
27
+ const textEncoder = new TextEncoder()
28
+ const textDecoder = new TextDecoder()
29
+
30
+ // eslint-disable-next-line no-magic-numbers
31
+ const UPPER_BYTE_VALUE = 2 ** 8
32
+
33
+ function createByteToUnicodeMap(): Map<number, string> {
34
+ const asciiRange = range(getCharCode('!'), getCharCode('~') + 1)
35
+ const latin1Range1 = range(getCharCode('¡'), getCharCode('¬') + 1)
36
+ const latin1Range2 = range(getCharCode('®'), getCharCode('ÿ') + 1)
37
+
38
+ const initialCodePoints = [...asciiRange, ...latin1Range1, ...latin1Range2]
39
+ const mappedCodePoints = [...initialCodePoints]
40
+
41
+ let newCodePointOffset = 0
42
+ for (let byteValue = 0; byteValue < UPPER_BYTE_VALUE; byteValue++) {
43
+ if (!initialCodePoints.includes(byteValue)) {
44
+ initialCodePoints.push(byteValue)
45
+ mappedCodePoints.push(UPPER_BYTE_VALUE + newCodePointOffset)
46
+ newCodePointOffset += 1
47
+ }
48
+ }
49
+
50
+ const unicodeChars = mappedCodePoints.map(getCharFromCode)
51
+ return new Map(initialCodePoints.map((x, i) => [x, unicodeChars[i]!]))
52
+ }
53
+
54
+ const pat =
55
+ /'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu
56
+
57
+ const byteEncoder = createByteToUnicodeMap()
58
+ const byteDecoder: Map<string, number> = new Map(
59
+ [...byteEncoder].map(([k, v]) => [v, k]),
60
+ )
61
+
62
+ function bpe(token: string, cache: Map<string, string> = new Map()): string {
63
+ if (cache.has(token)) {
64
+ return cache.get(token)!
65
+ }
66
+
67
+ let word = splitToken(token)
68
+ let pairs = getPairs(word)
69
+
70
+ if (pairs.length === 0) {
71
+ return token
72
+ }
73
+
74
+ // eslint-disable-next-line no-constant-condition
75
+ while (true) {
76
+ const minPairs: Map<number, [string, string]> = new Map()
77
+ pairs.forEach((pair) => {
78
+ const rank = bpeRanks[pair.join(',')]
79
+ minPairs.set(
80
+ // eslint-disable-next-line no-magic-numbers
81
+ typeof rank === 'undefined' || Number.isNaN(rank) ? 10e10 : rank,
82
+ pair,
83
+ )
84
+ })
85
+ const keys = [...minPairs.keys()]
86
+
87
+ const bigram = minPairs.get(Math.min(...keys))
88
+
89
+ if (!bigram || !(bigram.join(',') in bpeRanks)) {
90
+ break
91
+ }
92
+
93
+ const [first, second] = bigram
94
+ let newWord: string[] = []
95
+ let i = 0
96
+
97
+ while (i < word.length) {
98
+ const j = word.indexOf(first, i)
99
+ if (j === -1) {
100
+ newWord = newWord.concat(word.slice(i))
101
+ break
102
+ }
103
+ newWord = newWord.concat(word.slice(i, j))
104
+ i = j
105
+
106
+ if (word[i] === first && i < word.length - 1 && word[i + 1] === second) {
107
+ newWord.push(first + second)
108
+ i += 2
109
+ } else {
110
+ newWord.push(word[i]!)
111
+ i += 1
112
+ }
113
+ }
114
+
115
+ word = newWord
116
+ if (word.length === 1) {
117
+ break
118
+ } else {
119
+ pairs = getPairs(word)
120
+ }
121
+ }
122
+
123
+ const result = word.join(' ')
124
+ cache.set(token, result)
125
+
126
+ return result
127
+ }
128
+
129
+ function* encodeGenerator(
130
+ text: string,
131
+ cache: Map<string, string> = new Map(),
132
+ ): Generator<number[], void, undefined> {
133
+ for (let [token] of text.matchAll(pat)) {
134
+ token = [...textEncoder.encode(token)]
135
+ .map((x) => byteEncoder.get(x) ?? '')
136
+ .join('')
137
+
138
+ const newTokens = bpe(token, cache)
139
+ .split(' ')
140
+ .map((x) => encoder[x]!)
141
+
142
+ yield newTokens
143
+ }
144
+ }
145
+
146
+ /**
147
+ * @returns {false | number} false if token limit is exceeded, otherwise the number of tokens
148
+ */
149
+ export function isWithinTokenLimit(
150
+ text: string,
151
+ tokenLimit: number,
152
+ cache: Map<string, string> = new Map(),
153
+ ): false | number {
154
+ const tokenGenerator = encodeGenerator(text, cache)
155
+ let count = 0
156
+ for (const tokens of tokenGenerator) {
157
+ count += tokens.length
158
+ if (count > tokenLimit) {
159
+ return false
160
+ }
161
+ }
162
+ return count
163
+ }
164
+
165
+ export function encode(
166
+ text: string,
167
+ cache: Map<string, string> = new Map(),
168
+ ): number[] {
169
+ return [...encodeGenerator(text, cache)].flat(1)
170
+ }
171
+
172
+ export function decodeToken(token: number): string {
173
+ const decodedToken = decoder[token]
174
+ if (typeof decodedToken === 'undefined') {
175
+ return ''
176
+ }
177
+ const decodedBytes = splitToken(decodedToken).map((x) => byteDecoder.get(x)!)
178
+ return textDecoder.decode(new Uint8Array(decodedBytes), {
179
+ stream: true,
180
+ })
181
+ }
182
+
183
+ const HIGH_SURROGATE_START = 55_296
184
+ const HIGH_SURROGATE_END = 56_319
185
+ export function endsWithIncompleteUtfPairSurrogate(string: string): boolean {
186
+ if (string.length === 0) return false
187
+ // Check if the last character is a high surrogate
188
+ const lastCharCode = string.charCodeAt(string.length - 1)
189
+ return (
190
+ lastCharCode >= HIGH_SURROGATE_START && lastCharCode <= HIGH_SURROGATE_END
191
+ )
192
+ }
193
+
194
+ export function* decodeGenerator(
195
+ tokens: Iterable<number>,
196
+ ): Generator<string, void, undefined> {
197
+ let buffer = ''
198
+
199
+ for (const token of tokens) {
200
+ buffer += decodeToken(token)
201
+
202
+ if (buffer.length === 0 || endsWithIncompleteUtfPairSurrogate(buffer)) {
203
+ // Keep the high surrogate in the buffer and continue with the next token
204
+ // eslint-disable-next-line no-continue
205
+ continue
206
+ } else {
207
+ yield buffer
208
+ // reset buffer
209
+ buffer = ''
210
+ }
211
+ }
212
+
213
+ // Yield any remaining characters in the buffer
214
+ if (buffer.length > 0) {
215
+ yield buffer
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Decode tokens asynchronously and yield the decoded strings, one by one.
221
+ * Will not yield for tokens that include a high surrogate, but wait for the next token.
222
+ * @param {AsyncIterable<number>} tokens
223
+ * @returns {AsyncGenerator<string, void, undefined>}
224
+ */
225
+ export async function* decodeAsyncGenerator(
226
+ tokens: AsyncIterable<number>,
227
+ ): AsyncGenerator<string, void, undefined> {
228
+ let buffer = ''
229
+
230
+ for await (const token of tokens) {
231
+ buffer += decodeToken(token)
232
+
233
+ if (buffer.length === 0 || endsWithIncompleteUtfPairSurrogate(buffer)) {
234
+ // Keep the high surrogate in the buffer and continue with the next token
235
+ // eslint-disable-next-line no-continue
236
+ continue
237
+ } else {
238
+ yield buffer
239
+ // reset buffer
240
+ buffer = ''
241
+ }
242
+ }
243
+
244
+ // Yield any remaining characters in the buffer
245
+ if (buffer.length > 0) {
246
+ yield buffer
247
+ }
248
+ }
249
+
250
+ export function decode(tokens: number[]): string {
251
+ return [...decodeGenerator(tokens)].join('')
252
+ }
package/src/getBpe.ts ADDED
@@ -0,0 +1,23 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+ import { dictZip, range } from './utils'
4
+
5
+ const bpeFile = fs.readFileSync(
6
+ path.join(__dirname, '../data/vocab.bpe'),
7
+ 'utf8',
8
+ )
9
+ const lines = bpeFile.split('\n')
10
+
11
+ const bpeMerges = lines.slice(1, -1).map((x) =>
12
+ x
13
+ .split(/(\s+)/)
14
+ .filter((e) => e.trim().length > 0)
15
+ .join(','),
16
+ )
17
+
18
+ const bpeRanks = dictZip(bpeMerges, range(0, bpeMerges.length))
19
+
20
+ fs.writeFileSync(
21
+ path.join(__dirname, '../data/bpeRanks.json'),
22
+ JSON.stringify(bpeRanks),
23
+ )
package/src/main.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './encoder'
package/src/utils.ts ADDED
@@ -0,0 +1,36 @@
1
+ /* eslint-disable unicorn/prefer-spread */
2
+ /* eslint-disable unicorn/prefer-code-point */
3
+
4
+ export function dictZip<T extends PropertyKey, U>(
5
+ x: T[],
6
+ y: U[],
7
+ ): Record<T, U> {
8
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
9
+ const result = {} as Record<T, U>
10
+ x.forEach((k, i) => {
11
+ result[k] = y[i]!
12
+ })
13
+ return result
14
+ }
15
+
16
+ export function range(x: number, y: number): number[] {
17
+ return Array.from({ length: y - x }, (_, i) => x + i)
18
+ }
19
+
20
+ export const getCharCode = (x: string): number => x.charCodeAt(0)
21
+
22
+ export const getCharFromCode = (x: number): string => String.fromCharCode(x)
23
+
24
+ export function getPairs(word: string[]): [string, string][] {
25
+ /** @type {[string, string][]} */
26
+ const pairs: [string, string][] = []
27
+ let prevChar = word[0]
28
+ for (let i = 1; i < word.length; i++) {
29
+ const char = word[i]
30
+ pairs.push([prevChar!, char!])
31
+ prevChar = char
32
+ }
33
+ return pairs
34
+ }
35
+
36
+ export const splitToken = (token: string): string[] => token.split('')