-
Notifications
You must be signed in to change notification settings - Fork 31
/
GptEncoding.test.ts
257 lines (231 loc) · 7.73 KB
/
GptEncoding.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import fs from 'fs'
import path from 'path'
import { GptEncoding } from './GptEncoding.js'
import {
type ChatModelName,
type EncodingName,
chatModelParams,
encodingNames,
} from './mapping.js'
import { resolveEncoding } from './resolveEncoding.js'
const sharedResults = {
space: [220],
tab: [197],
'This is some text': [1_212, 318, 617, 2_420],
indivisible: [521, 452, 12_843],
'hello 👋 world 🌍': [31_373, 50_169, 233, 995, 12_520, 234, 235],
decodedHelloWorldTokens: ['hello', ' ', '👋', ' world', ' ', '🌍'],
'toString constructor hasOwnProperty valueOf': [
1_462, 10_100, 23_772, 468, 23_858, 21_746, 1_988, 5_189,
],
'hello, I am a text, and I have commas. a,b,c': [
31_373, 11, 314, 716, 257, 2_420, 11, 290, 314, 423, 725, 292, 13, 257, 11,
65, 11, 66,
],
}
const results = {
cl100k_base: {
space: [220],
tab: [197],
'This is some text': [2_028, 374, 1_063, 1_495],
indivisible: [485, 344, 23_936],
'hello 👋 world 🌍': [15_339, 62_904, 233, 1_917, 11_410, 234, 235],
decodedHelloWorldTokens: ['hello', ' ', '👋', ' world', ' ', '🌍'],
'toString constructor hasOwnProperty valueOf': [
6_712, 4_797, 706, 19_964, 907, 2_173,
],
'hello, I am a text, and I have commas. a,b,c': [
15_339, 11, 358, 1_097, 264, 1_495, 11, 323, 358, 617, 77_702, 13, 264,
8_568, 10_317,
],
},
p50k_base: sharedResults,
p50k_edit: sharedResults,
r50k_base: sharedResults,
} satisfies Record<EncodingName, unknown>
// eslint-disable-next-line @typescript-eslint/no-use-before-define
const testPlans = loadTestPlans()
describe.each(encodingNames)('%s', (encodingName: EncodingName) => {
const encoding = GptEncoding.getEncodingApi(encodingName, resolveEncoding)
const {
decode,
decodeGenerator,
decodeAsyncGenerator,
encode,
isWithinTokenLimit,
} = encoding
const result = results[encodingName]
describe('basic functionality', () => {
it('empty string', () => {
const str = ''
expect(encode(str)).toEqual([])
expect(decode(encode(str))).toEqual(str)
expect(isWithinTokenLimit(str, 0)).toBe(0)
expect(isWithinTokenLimit(str, 3)).toBe(0)
})
it('space', () => {
const str = ' '
expect(encode(str)).toEqual(result.space)
expect(decode(encode(str))).toEqual(str)
expect(isWithinTokenLimit(str, 3)).toBe(1)
expect(isWithinTokenLimit(str, 0)).toBe(false)
})
it('tab', () => {
const str = '\t'
expect(encode(str)).toEqual(result.tab)
expect(decode(encode(str))).toEqual(str)
})
it('simple text', () => {
const str = 'This is some text'
expect(encode(str)).toEqual(result[str])
expect(decode(encode(str))).toEqual(str)
expect(isWithinTokenLimit(str, 3)).toBe(false)
expect(isWithinTokenLimit(str, 5)).toBe(result[str].length)
})
it('multi-token word', () => {
const str = 'indivisible'
expect(encode(str)).toEqual(result.indivisible)
expect(decode(encode(str))).toEqual(str)
expect(isWithinTokenLimit(str, 3)).toBe(result.indivisible.length)
})
it('emojis', () => {
const str = 'hello 👋 world 🌍'
expect(encode(str)).toEqual(result[str])
expect(decode(encode(str))).toEqual(str)
expect(isWithinTokenLimit(str, 4)).toBe(false)
expect(isWithinTokenLimit(str, 400)).toBe(result[str].length)
})
it('decode token-by-token via generator', () => {
const str = 'hello 👋 world 🌍'
const generator = decodeGenerator(result[str])
result.decodedHelloWorldTokens.forEach((token) => {
expect(generator.next().value).toBe(token)
})
})
async function* getHelloWorldTokensAsync() {
const str = 'hello 👋 world 🌍'
for (const token of result[str]) {
// eslint-disable-next-line no-await-in-loop
yield await Promise.resolve(token)
}
}
it('decode token-by-token via async generator', async () => {
const generator = decodeAsyncGenerator(getHelloWorldTokensAsync())
const decoded = [...result.decodedHelloWorldTokens]
for await (const value of generator) {
expect(value).toEqual(decoded.shift())
}
})
it('properties of Object', () => {
const str = 'toString constructor hasOwnProperty valueOf'
expect(encode(str)).toEqual(result[str])
expect(decode(encode(str))).toEqual(str)
})
it('text with commas', () => {
const str = 'hello, I am a text, and I have commas. a,b,c'
expect(decode(encode(str))).toEqual(str)
expect(encode(str)).toStrictEqual(result[str])
expect(isWithinTokenLimit(str, result[str].length - 1)).toBe(false)
expect(isWithinTokenLimit(str, 300)).toBe(result[str].length)
})
})
describe('test plan', () => {
testPlans[encodingName].forEach(({ sample, encoded }) => {
it(`encodes ${sample}`, () => {
expect(encode(sample)).toEqual(encoded)
})
it(`decodes ${sample}`, () => {
expect(decode(encoded)).toEqual(sample)
})
})
})
})
const chatModelNames = Object.keys(chatModelParams) as readonly ChatModelName[]
const exampleMessages = [
{
role: 'system',
content:
'You are a helpful, pattern-following assistant that translates corporate jargon into plain English.',
},
{
role: 'system',
name: 'example_user',
content: 'New synergies will help drive top-line growth.',
},
{
role: 'system',
name: 'example_assistant',
content: 'Things working well together will increase revenue.',
},
{
role: 'system',
name: 'example_user',
content:
"Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage.",
},
{
role: 'system',
name: 'example_assistant',
content: "Let's talk later when we're less busy about how to do better.",
},
{
role: 'user',
content:
"This late pivot means we don't have time to boil the ocean for the client deliverable.",
},
] as const
describe.each(chatModelNames)('%s', (modelName) => {
const encoding = GptEncoding.getEncodingApiForModel(
modelName,
resolveEncoding,
)
const expectedEncodedLength = modelName.startsWith('gpt-3.5-turbo')
? 127
: 121
describe('chat functionality', () => {
it('encodes a chat correctly', () => {
const encoded = encoding.encodeChat(exampleMessages)
expect(encoded).toMatchSnapshot()
expect(encoded).toHaveLength(expectedEncodedLength)
const decoded = encoding.decode(encoded)
expect(decoded).toMatchSnapshot()
})
it('isWithinTokenLimit: false', () => {
const isWithinTokenLimit = encoding.isWithinTokenLimit(
exampleMessages,
50,
)
expect(isWithinTokenLimit).toBe(false)
})
it('isWithinTokenLimit: true (number)', () => {
const isWithinTokenLimit = encoding.isWithinTokenLimit(
exampleMessages,
150,
)
expect(isWithinTokenLimit).toBe(expectedEncodedLength)
})
})
})
function loadTestPlans() {
const testPlanPath = path.join(__dirname, '../data/TestPlans.txt')
const testPlanData = fs.readFileSync(testPlanPath, 'utf8')
const tests: Record<
EncodingName,
{ sample: string; encoded: readonly number[] }[]
> = {
cl100k_base: [],
p50k_base: [],
p50k_edit: [],
r50k_base: [],
}
testPlanData.split('\n\n').forEach((testPlan) => {
const [encodingNameLine, sampleLine, encodedLine] = testPlan.split('\n')
if (!encodingNameLine || !sampleLine || !encodedLine) return
const encodingName = encodingNameLine.split(': ')[1] as EncodingName
tests[encodingName].push({
sample: sampleLine.split(': ').slice(1).join(': ') ?? '',
encoded: JSON.parse(encodedLine.split(': ')[1] ?? '[]'),
})
})
return tests
}