-
Notifications
You must be signed in to change notification settings - Fork 13
/
gpt_bpe_test.go
1622 lines (1478 loc) · 50.9 KB
/
gpt_bpe_test.go
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gpt_bpe
import (
"bufio"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
"testing"
"time"
"github.com/wbrown/gpt_bpe/types"
"github.com/stretchr/testify/assert"
"github.com/ulikunitz/xz"
"github.com/wbrown/gpt_bpe/resources"
)
var clipEncoder GPTEncoder
var gpt2Encoder GPTEncoder
var pileEncoder GPTEncoder
var nerdstashV2Encoder GPTEncoder
var llama2Encoder GPTEncoder
var llama3Encoder GPTEncoder
var mistralEncoder GPTEncoder
var corpus string
var clipCorpus string
// var corpus2 string
var gpt2Encoded *Tokens
var pileEncoded *Tokens
var clipEncoded *Tokens
var nerdstashEncoded *Tokens
var llama2Encoded *Tokens
var llama3Encoded *Tokens
var mistralEncoded *Tokens
var unicodeTrimTests []*Tokens
const largeCorpusPath = "resources/wiki.train.raw.xz"
func handleRead(path string) []byte {
if textBytes, err := os.ReadFile(path); err != nil {
log.Fatalf("Error opening `%s`: %v", path, err)
} else {
return textBytes
}
return nil
}
func loadUnicodeTrimTests(path string) []*Tokens {
tests := make([]*Tokens, 0)
fileBlob := string(handleRead(path))
fileLines := strings.Split(fileBlob, "\n")
for idx := range fileLines {
line := fileLines[idx]
if len(line) == 0 {
continue
}
unicodeTrimTest := make(Tokens, 0)
if err := json.Unmarshal(
[]byte(line),
&unicodeTrimTest,
); err != nil {
log.Fatalf("Error unmarshaling `%s`: %v", path, err)
}
tests = append(tests, &unicodeTrimTest)
}
return tests
}
func Chunks(s string, chunkSize int) []string {
if len(s) == 0 {
return nil
}
if chunkSize >= len(s) {
return []string{s}
}
var chunks []string = make([]string, 0, (len(s)-1)/chunkSize+1)
currentLen := 0
currentStart := 0
for i := range s {
if currentLen == chunkSize {
chunks = append(chunks, s[currentStart:i])
currentLen = 0
currentStart = i
}
currentLen++
}
chunks = append(chunks, s[currentStart:])
return chunks
}
func getStringBounds(
i int,
output string,
decoded string,
) (
left int,
right int,
) {
if i < 20 {
left = 0
} else {
left = i - 20
}
if len(output) < len(decoded) {
right = len(output)
} else {
right = len(decoded)
}
if i+20 < right {
right = i + 20
}
return left, right
}
func init() {
gpt2Encoder = NewGPT2Encoder()
pileEncoder = NewPileEncoder()
clipEncoder = NewCLIPEncoder()
nerdstashV2Encoder = NewNerdstashV2Encoder()
llama2Encoder = NewLlama2Encoder()
llama3Encoder = NewLlama3Encoder()
mistralEncoder = NewMistralEncoder()
textBytes := handleRead("resources/frankenstein.txt")
clipBytes := handleRead("resources/frankenstein_clip.txt")
corpus = string(textBytes)
clipCorpus = string(clipBytes)
unicodeTrimTests = loadUnicodeTrimTests("resources/trim_tests.jsonl")
}
func TestMain(m *testing.M) {
m.Run()
}
type TrimTest struct {
Input string
Direction TrimDirection
Limit uint
Expected string
}
const sent1 = "This is test sentence 1. This is test sentence 2. This is test sentence 3."
const sent2 = "\nThis is test sentence 4.\nThis is test sentence 5.\nThis is test sentence 6.\n"
const hindiSentence = "व्याकरण शास्त्रीय परिभाषाएँ : डॉ. पर्णदत्त सिंह द्वारा हिंदी पीडीऍफ़ पुस्तक"
const jpSentence = "「そんな心構えで、本当に俺の『未練』を果たせるのか? 知ってのとおり、俺の『未練』は『<|rubycover|>相川渦波<|rubystart|>おまえ<|rubyend|>の成長を最後まで見届けること』だ。……言っとくが、俺は年季が入ってる上に、拗らせに拗らせた元神学者。俺の『大いなる<|rubycover|>救世主<|rubystart|>マグナ・メサイア<|rubyend|>』の『理想』は高いぞ? 少なくとも、この『血陸』を止められないようじゃ、任せ切れないな」\n<|mtsentence|><|mtsenglish|>Please check if the meat is being roasted at the right heat.<|mtsjapanese|>焼き肉の火加減を見なさい。<|mtsentenceend|>\n<|mtvocab|><|mtvjapanese|>[ぶんけんがく] 文献学<|mtvenglish|>(n) philology<|mtvocabend|>"
var TrimSentencesTests = []TrimTest{
{sent1, TrimTop, 10,
" This is test sentence 3."},
{sent1, TrimTop, 20,
" This is test sentence 2. This is test sentence 3."},
{sent1, TrimTop, 30,
sent1},
{sent2, TrimTop, 10,
"\nThis is test sentence 6.\n"},
{sent2, TrimTop, 18,
"\nThis is test sentence 5.\nThis is test sentence 6.\n"},
{sent2, TrimTop, 30,
sent2},
{sent1, TrimBottom, 10,
"This is test sentence 1."},
{sent1, TrimBottom, 20,
"This is test sentence 1. This is test sentence 2."},
{sent1, TrimBottom, 30,
sent1},
{sent2, TrimBottom, 10,
"\nThis is test sentence 4.\n"},
{sent2, TrimBottom, 18,
"\nThis is test sentence 4.\nThis is test sentence 5.\n"},
{sent2, TrimBottom, 30,
sent2},
}
func TestHFResolution(t *testing.T) {
_, err := NewEncoder("EleutherAI/gpt-j-6B")
if err != nil {
t.Error(err)
}
_, err = NewEncoder("nonexist/nonexist")
if err == nil {
t.Error(errors.New("failed to return error on non-existent model"))
}
}
func TestHFTokenzier(t *testing.T) {
enc, err := NewEncoder("EleutherAI/gpt-j-6B")
if err != nil {
t.Error(err)
}
sent := "The fox jumped over the hare."
hfTokens := enc.Encode(&sent)
gptTokens := gpt2Encoder.Encode(&sent)
assert.Equal(t, hfTokens, gptTokens)
}
func TestFairSeqTokenizer(t *testing.T) {
enc, err := NewEncoder("KoboldAI/fairseq-dense-2.7B")
if err != nil {
t.Error(err)
return
}
sent := "The fox jumped over the hare.\nThe turtle is faster than the hare."
tokens := Tokens{464, 21831, 11687, 625, 262, 387, 260, 25970, 82, 29,
464, 28699, 318, 5443, 621, 262, 387, 260, 13}
fsTokens := enc.Encode(&sent)
assert.Equal(t, *fsTokens, tokens)
}
var TrimNewLinesTests = append(
TrimSentencesTests[3:5], TrimSentencesTests[9:11]...,
)
func TestGPTEncoder_TrimIncompleteSentence(t *testing.T) {
testStr := "This is a test. He says, \"This is an unterminated quote. She says, this is actually terminated.\" This is awesome! This is incomplete "
expected := "This is a test. He says, \"This is an unterminated quote. She says, this is actually terminated.\" This is awesome!"
trimmed, _ := gpt2Encoder.TrimIncompleteSentence(gpt2Encoder.Encode(&testStr))
output := gpt2Encoder.Decode(trimmed)
if expected != output {
t.Error("output != expected; output := ", expected)
}
}
func TestGPTEncoder_TrimTokens(t *testing.T) {
for testIdx := range unicodeTrimTests {
assert.NotEqual(
t, len(
*gpt2Encoder.TrimTokens(
unicodeTrimTests[testIdx],
),
),
len(*unicodeTrimTests[testIdx]),
)
}
}
func TestGPTEncoder_TrimNewlines(t *testing.T) {
for testIdx := range TrimNewLinesTests {
test := TrimNewLinesTests[testIdx]
res, err := gpt2Encoder.TrimNewlines(
gpt2Encoder.Encode(&test.Input),
test.Direction, test.Limit,
)
if err != nil {
t.Error("TrimNewlines: error:", err)
}
decodeRes := gpt2Encoder.Decode(res)
if decodeRes != test.Expected {
t.Error(
"TrimNewlines: expected '" + test.Expected + "' got '" +
decodeRes + "'",
)
}
}
}
func TestGPTEncoder_TrimSentences(t *testing.T) {
for testIdx := range TrimSentencesTests {
test := TrimSentencesTests[testIdx]
res, err := gpt2Encoder.TrimSentences(
gpt2Encoder.Encode(&test.Input),
test.Direction, test.Limit,
)
if err != nil {
t.Error("TrimSentences: error:", err)
}
decodeRes := gpt2Encoder.Decode(res)
if decodeRes != test.Expected {
t.Error(
"TrimSentences: expected '" + test.Expected + "' got '" +
decodeRes + "'",
)
}
}
}
type SplitTest struct {
Input string
Expected []string
}
var SplitTests = []SplitTest{
{"we'll go jump in a lake.",
[]string{"we", "'ll", " go", " jump", " in", " a", " lake",
"."}},
{"multiple encoded spaces.",
[]string{"multiple", " ", "encoded", " spaces", "."}},
{"Capitalized Words Are Cool",
[]string{"Capitalized", " Words", " Are", " Cool"}},
{"we'LL test irregular cApitalizatioN.",
[]string{"we", "'", "LL", " test", " irregular",
" cApitalizatioN", "."}},
{"multilines\nare awesome",
[]string{"multilines", "\n", "are", " awesome"}},
{"\nstarting with multilines\nis awesome",
[]string{"\n", "starting", " with", " multilines",
"\n", "is", " awesome"}},
{"we'll go jump<|endoftext|> in a lake.",
[]string{"we", "'ll", " go", " jump", "<|endoftext|>",
" in", " a", " lake", "."}},
{"we'll go jump<|end\noftext|> in a lake.",
[]string{"we", "'ll", " go", " jump", "<|", "end", "\n",
"oftext", "|>", " in", " a", " lake", "."}},
}
func TestGPTEncoder_Split(t *testing.T) {
for testIdx := range SplitTests {
test := SplitTests[testIdx]
assert.Equal(t, test.Expected, *(gpt2Encoder.SplitWords(&test.Input)))
}
}
func OpenXZStream(path string) (*xz.Reader, *os.File, error) {
corpusHandle, err := os.Open(path)
if err != nil {
return nil, nil, err
}
decompressorHandle, err := xz.NewReader(corpusHandle)
if err != nil {
return nil, nil, err
}
return decompressorHandle, corpusHandle, nil
}
func BenchmarkGPTEncoder_WordSplitterChan(b *testing.B) {
b.StopTimer()
corpusHandle, fileHandle, err := OpenXZStream(largeCorpusPath)
if err != nil {
b.Error(err)
}
defer fileHandle.Close()
gpt2Encoder.SplitterThreads = 8
nextWord := gpt2Encoder.WordSplitter(
bufio.NewReaderSize(
corpusHandle,
8*1024*1024,
),
)
start := time.Now()
b.StartTimer()
wordCount := 0
for {
word := nextWord()
if word == nil {
break
}
wordCount++
}
b.StopTimer()
elapsed := time.Since(start)
numBytes, _ := fileHandle.Seek(0, io.SeekCurrent)
b.ReportMetric(float64(wordCount)/elapsed.Seconds(), "words/sec")
b.ReportMetric(float64(wordCount), "words")
b.ReportMetric(
float64(numBytes)/elapsed.Seconds(), "compbytes/sec",
)
b.ReportMetric(float64(numBytes), "bytes")
}
func BenchmarkGPTEncoder_WordSplitter(b *testing.B) {
b.StopTimer()
corpusHandle, fileHandle, err := OpenXZStream(largeCorpusPath)
if err != nil {
b.Error(err)
}
defer fileHandle.Close()
gpt2Encoder.SplitterThreads = 8
//defer corpusHandle.Close()
if err != nil {
b.Error(err)
}
wordCount := 0
runeReader := bufio.NewReaderSize(corpusHandle, 8*1024*1024)
wordSplitter := gpt2Encoder.makeWordSplitter(
runeReader.ReadRune,
func(*string) {
wordCount++
},
func() {},
)
start := time.Now()
b.StartTimer()
wordSplitter()
b.StopTimer()
elapsed := time.Since(start)
//numBytes := int64(len(corpusText))
numBytes, _ := fileHandle.Seek(0, io.SeekCurrent)
b.ReportMetric(float64(wordCount)/elapsed.Seconds(), "words/sec")
b.ReportMetric(float64(wordCount), "words")
b.ReportMetric(
float64(numBytes)/elapsed.Seconds(), "compbytes/sec",
)
b.ReportMetric(float64(numBytes), "bytes")
}
func BenchmarkGPTEncoder_WordSplitterTokens(b *testing.B) {
b.StopTimer()
corpusHandle, fileHandle, err := OpenXZStream(largeCorpusPath)
if err != nil {
b.Error(err)
}
defer fileHandle.Close()
nerdstashV2Encoder.SplitterThreads = 1
//defer corpusHandle.Close()
if err != nil {
b.Error(err)
}
wordCount := 0
tokensCount := 0
runeReader := bufio.NewReaderSize(corpusHandle, 8*1024*1024)
wordSplitter := nerdstashV2Encoder.makeWordSplitter(
runeReader.ReadRune,
func(word *string) {
if word != nil {
tokensCount += len(gpt2Encoder.ToBPE(*word))
}
wordCount++
},
func() {},
)
start := time.Now()
b.StartTimer()
wordSplitter()
b.StopTimer()
elapsed := time.Since(start)
//numBytes := int64(len(corpusText))
numBytes, _ := fileHandle.Seek(0, io.SeekCurrent)
b.ReportMetric(float64(wordCount)/elapsed.Seconds(), "words/sec")
b.ReportMetric(float64(wordCount), "words")
b.ReportMetric(
float64(numBytes)/elapsed.Seconds(), "compbytes/sec",
)
b.ReportMetric(float64(numBytes), "bytes")
b.ReportMetric(float64(tokensCount)/elapsed.Seconds(), "tokens/sec")
b.ReportMetric(float64(tokensCount), "tokens")
}
//func BenchmarkGPTEncoder_WordSplitterTokensChan(b *testing.B) {
// b.StopTimer()
// corpusHandle, err := os.Open(largeCorpusPath)
// //corpusText, err := ioutil.ReadFile(largeCorpusPath)
// nerdstashEncoder.SplitterThreads = 1
// //defer corpusHandle.Close()
// if err != nil {
// b.Error(err)
// }
// wordCount := 0
// tokensCount := 0
// runeReader := bufio.NewReaderSize(corpusHandle, 8*1024*1024)
// wordsChan := make(chan *string, 1000)
// go nerdstashEncoder.splitWordsOntoChan(runeReader.ReadRune,
// wordsChan)
// start := time.Now()
// b.StartTimer()
// for {
// word := <-wordsChan
// if word == nil {
// break
// }
// tokensCount += len(gpt2Encoder.ToBPE(*word))
// wordCount++
// }
// b.StopTimer()
// elapsed := time.Since(start)
// //numBytes := int64(len(corpusText))
// numBytes, _ := corpusHandle.Seek(0, io.SeekCurrent)
// b.ReportMetric(float64(wordCount)/elapsed.Seconds(), "words/sec")
// b.ReportMetric(float64(wordCount), "words")
// b.ReportMetric(float64(numBytes)/elapsed.Seconds(), "bytes/sec")
// b.ReportMetric(float64(numBytes), "bytes")
// b.ReportMetric(float64(tokensCount)/elapsed.Seconds(), "tokens/sec")
// b.ReportMetric(float64(tokensCount), "tokens")
//}
func BenchmarkGPTEncoder_Decode(b *testing.B) {
if gpt2Encoded == nil {
corpEncoded := gpt2Encoder.Encode(&corpus)
gpt2Encoded = corpEncoded
}
start := time.Now()
tokenNumBytes := len(gpt2Encoder.Decode(gpt2Encoded))
duration := time.Since(start)
b.Logf(
"%v tokens into %v bytes over %v",
len(*gpt2Encoded), tokenNumBytes, duration,
)
}
type EncoderTest struct {
Input string
GPT2Expected Tokens
PileExpected Tokens
CLIPExpected Tokens
NerdstashExpected Tokens
}
var GPTEncoderTests = []EncoderTest{
{"… …",
Tokens{1399, 3926},
Tokens{2866, 8139},
Tokens{49406, 959, 959, 49407},
Tokens{49289, 5512}},
{"<|endoftext|>",
Tokens{50256},
Tokens{0},
Tokens{49406, 49407, 49407},
Tokens{3}},
{" <|endoftext|>\n<|endoftext|>foo",
Tokens{220, 50256, 198, 50256, 21943},
Tokens{209, 0, 187, 0, 12110},
Tokens{49406, 49407, 49407, 23435, 49407},
Tokens{49209, 3, 85, 3, 49225, 3292}},
{" <|padding|>test",
Tokens{220, 50257, 9288},
Tokens{209, 1, 2566},
Tokens{49406, 27, 347, 3798, 796, 91, 285, 1628, 49407},
Tokens{3252, 49376, 42545, 49376, 49405, 10180},
},
}
func BenchmarkGPTEncoder_Encode(b *testing.B) {
start := time.Now()
tokenCt := len(*gpt2Encoder.Encode(&corpus))
duration := time.Since(start)
b.Logf(
"%v bytes into %v tokens over %v",
len(corpus), tokenCt, duration,
)
}
func BenchmarkGPTEncoder_EncodeBuffer(b *testing.B) {
corpusBytes := []byte(corpus)
start := time.Now()
_, tokenCt := gpt2Encoder.EncodeBuffer(&corpusBytes)
duration := time.Since(start)
b.Logf(
"%v bytes into %v tokens over %v",
len(corpus), tokenCt, duration,
)
}
func TestGPTEncoder_Encode(t *testing.T) {
// This test is to check if the GPTEncoder is able to encode the tokens correctly
start := time.Now()
tokenCt := len(*gpt2Encoder.Encode(&corpus))
duration := time.Since(start)
t.Logf(
"%v bytes into %v tokens over %v",
len(corpus), tokenCt, duration,
)
for testIdx := range GPTEncoderTests {
tokensPtr := *gpt2Encoder.Encode(
&(GPTEncoderTests[testIdx].Input),
)
assert.Equal(t, tokensPtr, GPTEncoderTests[testIdx].GPT2Expected)
}
}
func TestGPTEncode(t *testing.T) {
// This test is to check if the GPTEncoder is able to encode the tokens correctly
strin := "The quick brown fox jumps over the lazy dog."
expected := Tokens{464, 21831, 11687, 625, 262, 387, 260, 25970, 82, 29, 464, 28699, 318, 5443, 621, 262, 387, 260, 13}
encoded := gpt2Encoder.Encode(&strin)
fmt.Printf("Encoded: with commas:")
for _, token := range *encoded {
fmt.Printf("%v, ", token)
}
assert.Equal(t, *encoded, expected)
}
func TestGPTEncoder_StreamingEncode(t *testing.T) {
// This test is to check if the GPTEncoder is able to encode the tokens correctly
start := time.Now()
corpusRunes := strings.NewReader(corpus)
nextTokens := gpt2Encoder.StreamingEncode(corpusRunes)
tokenCt := 0
for {
tokens := nextTokens(16384)
if tokens == nil {
break
}
tokenCt += len(*tokens)
}
duration := time.Since(start)
t.Logf(
"%v bytes into %v tokens over %v",
len(corpus), tokenCt, duration,
)
}
func TestCLIPEncoder_Encode(t *testing.T) {
// This test is to check if the CLIPEncoder is able to encode the tokens correctly
start := time.Now()
tokenCt := len(*clipEncoder.Encode(&corpus))
duration := time.Since(start)
t.Logf(
"%v bytes into %v tokens over %v",
len(corpus), tokenCt, duration,
)
for testIdx := range GPTEncoderTests {
testStr := GPTEncoderTests[testIdx].Input
tokensPtr := *clipEncoder.Encode(&testStr)
assert.Equal(t, GPTEncoderTests[testIdx].CLIPExpected, tokensPtr)
}
}
func TestPileEncoder_Encode(t *testing.T) {
// This test is to check if the PileEncoder is able to encode the tokens correctly
start := time.Now()
tokenCt := len(*pileEncoder.Encode(&corpus))
duration := time.Since(start)
t.Logf(
"%v bytes into %v tokens over %v",
len(corpus), tokenCt, duration,
)
for testIdx := range GPTEncoderTests {
tokensPtr := *pileEncoder.Encode(
&(GPTEncoderTests[testIdx].Input),
)
assert.Equal(t, GPTEncoderTests[testIdx].PileExpected, tokensPtr)
}
}
func TestNerdstashEncoder_Encode(t *testing.T) {
// This test is to check if the NerdstashEncoder is able to encode the tokens correctly
start := time.Now()
tokenCt := len(*nerdstashV2Encoder.Encode(&corpus))
duration := time.Since(start)
t.Logf(
"%v bytes into %v tokens over %v",
len(corpus), tokenCt, duration,
)
for testIdx := range GPTEncoderTests {
tokensPtr := *nerdstashV2Encoder.Encode(
&(GPTEncoderTests[testIdx].Input),
)
assert.Equal(t, GPTEncoderTests[testIdx].NerdstashExpected, tokensPtr)
}
}
func TestNerdstashEncoder_EncodeSpaces(t *testing.T) {
// This test is to check if the NerdstashEncoder is able to encode spaces correctly
testString := " 12 => '',\n"
expected := Tokens{16, 124, 125, 10631, 1695, 49231, 85}
encoded := nerdstashV2Encoder.Encode(&testString)
assert.Equal(t, expected, *encoded)
}
func TestNerdstashEncoder_Encode2(t *testing.T) {
// read the jsonl test file in
testFile, err := os.Open("resources/subset.jsonl")
if err != nil {
t.Error(err)
}
defer testFile.Close()
scanner := bufio.NewScanner(testFile)
scanner.Split(bufio.ScanLines)
type testLineStruct struct {
Text *string `json:"text"`
Hex *string `json:"hex"`
Encoded Tokens `json:"encoded"`
}
passCt := 0
failCt := 0
for scanner.Scan() {
jsonLine := scanner.Text()
testLine := testLineStruct{}
err := json.Unmarshal([]byte(jsonLine), &testLine)
if err != nil {
t.Error(err)
}
expected := testLine.Encoded
var inputStr string
if testLine.Hex != nil {
inputBytes, hexErr := hex.DecodeString(*testLine.Hex)
if hexErr != nil {
t.Error(hexErr)
}
inputStr = string(inputBytes)
} else {
inputStr = *testLine.Text
}
// encode the string
encoded := nerdstashV2Encoder.Encode(&inputStr)
// check that the encoded string is the same as the expected
if !assert.Equal(t, expected, *encoded) {
t.Logf("failure on input: `%v`", inputStr)
expectedRepr := []string{}
for _, token := range expected {
expectedRepr = append(
expectedRepr,
string(nerdstashV2Encoder.Decoder[token]),
)
}
actualRepr := []string{}
for _, token := range *encoded {
actualRepr = append(
actualRepr,
string(nerdstashV2Encoder.Decoder[token]),
)
}
t.Logf("expected: |%s", strings.Join(expectedRepr, "|"))
t.Logf("actual: |%s", strings.Join(actualRepr, "|"))
failCt += 1
} else {
passCt += 1
}
}
t.Logf("pass: %v, fail: %v", passCt, failCt)
}
func TestNerdstashEncoder_Decode(t *testing.T) {
// This test is to check if the NerdstashEncoder is able to decode the tokens correctly
for testIdx := range GPTEncoderTests {
decodedStr := nerdstashV2Encoder.Decode(
&(GPTEncoderTests[testIdx].NerdstashExpected),
)
assert.Equal(t, GPTEncoderTests[testIdx].Input, decodedStr)
}
}
func TestGPTEncoder_Decode2(t *testing.T) {
// This test is to check if the GPTEncoder is able to decode the tokens correctly from a base64 encoded string
gpt2EncodedCorpus := "NrGIEOQBRzFfAQEBCAE5GeADPCFGAQhdBgFhBkcHXwEBATM5HgGilUYBpAdDEaUheR8iAQEBmgSnbyQpRgHIjaYBiSQYLfoHYwHogg0A0AHsGFUmpgEGAcd0qApjAzwa7hscAeHAYwEGAbYRB3UiAax0PQPjAgoXpgEGAZgE6G2gAWMExy5GAb5szQdGAXUBAR2gAVQBRgG8CdYBYbCgAe4QAxg/NA0AdyoiAZMGOXL8AWlmAQGgFXknNlIGAdADLiciAT4B6lk="
decodedCorpus := "frying whatever they touched with a sizzled smell that fills the air along with a shower of sparks that land harmlessly elsewhere and a few stray drops that drip from fingers burned black as charcoal.The shock waves from the blasts cause many nearby trees to topple as the earth shakes and trembles underfoot from the power unleashed by each blast that destroys anything that was struck by it that wasn't shielded by heavy metal plates."
if binTokens, err := base64.StdEncoding.DecodeString(gpt2EncodedCorpus); err != nil {
log.Println("ERROR:", err)
} else {
tokens := types.TokensFromBin(&binTokens)
tokens, err = gpt2Encoder.TrimIncompleteSentence(tokens)
if err != nil {
t.Error(err)
}
assert.Equal(t, gpt2Encoder.Decode(tokens), decodedCorpus)
}
}
func TestGPTEncoder_Decode(t *testing.T) {
// This test is to check if the GPTEncoder is able to decode the tokens correctly
if gpt2Encoded == nil {
corpEncoded := gpt2Encoder.Encode(&corpus)
gpt2Encoded = corpEncoded
}
start := time.Now()
decoded := gpt2Encoder.Decode(gpt2Encoded)
duration := time.Since(start)
tokenNumBytes := len(decoded)
t.Logf(
"%v tokens into %v bytes over %v\n",
len(*gpt2Encoded), tokenNumBytes, duration,
)
assert.Equal(t, corpus, decoded)
}
// BUG: CLIP TOKENIZER has a bug that causes 'the to be split into
// "'t<w>he<w>" instead of "'<w>the<w>". This causes the
// clipCorpus to be different from the corpus. This is a bug in
// the CLIP tokenizer from huggingface that was used to generate
// the clipCorpus. The decoded corpus is correct in this test.
// We stop the test right before the bug.
func TestCLIPEncoder_Decode(t *testing.T) {
if clipEncoded == nil {
corpEncoded := clipEncoder.Encode(&corpus)
clipEncoded = corpEncoded
}
start := time.Now()
decoded := clipEncoder.Decode(clipEncoded)
duration := time.Since(start)
tokenNumBytes := len(decoded)
idxToStop := 229550
t.Logf(
"%v tokens into %v bytes over %v\n", len(*clipEncoded), tokenNumBytes,
duration,
)
for idx := range clipCorpus {
if idx > idxToStop {
break
}
if clipCorpus[idx] != decoded[idx] {
t.Errorf(
"idx: %d, clipCorpus: %v, decoded: %v\n", idx,
clipCorpus[idx], decoded[idx],
)
break
}
}
// assert.Equal(t, clipCorpus, decoded)
}
func TestPileEncoder_Decode(t *testing.T) {
// This test is to check if the PileEncoder is able to decode the tokens correctly
if pileEncoded == nil {
corpEncoded := pileEncoder.Encode(&corpus)
pileEncoded = corpEncoded
}
start := time.Now()
decoded := pileEncoder.Decode(pileEncoded)
duration := time.Since(start)
tokenNumBytes := len(decoded)
t.Logf(
"%v tokens into %v bytes over %v\n",
len(*pileEncoded), tokenNumBytes, duration,
)
range_data := corpus
if len(corpus) > len(decoded) {
range_data = decoded
}
if len(corpus) != len(decoded) {
t.Errorf(fmt.Sprintf("%v != %v", len(corpus), len(decoded)))
}
for idx := range range_data {
if corpus[idx] != decoded[idx] {
t.Errorf(
"%v != %v", clipCorpus[idx-20:idx+20],
decoded[idx-20:idx+20],
)
return
}
}
}
func TestGPTEncoder_TokensReady(t *testing.T) {
// This test is to check if the TokensReady function is able to determine if the tokens are ready for context
multiTokenAsterism := "⁂"
tokens := gpt2Encoder.Encode(&multiTokenAsterism)
fmt.Printf("Tokens: %v, len: %v\n", tokens, len(*tokens))
var idx int
for idx = range *tokens {
tokenSlice := (*tokens)[0 : idx+1]
fmt.Printf("TokenSlice: %v, len: %v\n", tokenSlice, len(tokenSlice))
if gpt2Encoder.TokensReady(&tokenSlice) {
break
}
}
if idx < len(*tokens)-1 {
t.Errorf(
"Expected TokensReady on idx: %d for `%s`", idx,
multiTokenAsterism,
)
}
}
func TestGPTEncoder_TokensReadyContext(t *testing.T) {
// This test is to check if the TokensReady function is able to determine if the tokens are ready for context
var tokens Tokens
badContext, err := os.ReadFile("resources/badcontext.json")
if err != nil {
t.Errorf("Could not read badcontext.json: %v", err)
}
unmarshalErr := json.Unmarshal(badContext, &tokens)
if unmarshalErr != nil {
t.Errorf("Could not unmarshal badcontext.json: %v", unmarshalErr)
}
if !pileEncoder.TokensReady(&tokens) {
t.Errorf("Expected TokensReady to be true for badcontext.json")
}
}
func TestUnitrimFunctionality(t *testing.T) {
// This test is to check if the makeUnitrimArr function is able to generate the unitrim array correctly
for _, tokenizer := range []string{"clip-tokenizer", "gpt2-tokenizer", "pile-tokenizer"} {
encoderFile := fmt.Sprintf(
"resources/data/%s/encoder.json", tokenizer,
)
unitrimFile := fmt.Sprintf(
"resources/data/%s/unitrim.json", tokenizer,
)
// make sure the files exist
if _, err := os.Stat(encoderFile); os.IsNotExist(err) {
t.Errorf("Could not find file %s\n", encoderFile)
}
if _, err := os.Stat(unitrimFile); os.IsNotExist(err) {
t.Errorf("Could not find file %s\n", unitrimFile)
}
// read in the Encoder and unitrim files
encoderBytes, err := os.ReadFile(encoderFile)
if err != nil {
t.Errorf("Could not read Encoder file: %v\n", err)
}
// unmarshal the Encoder file
var encoder map[string]Token
err = json.Unmarshal(encoderBytes, &encoder)
if err != nil {
t.Errorf("Could not unmarshal Encoder file: %v\n", err)
}
// read in the unitrim file
unitrimBytes, err := os.ReadFile(unitrimFile)
if err != nil {
t.Errorf("Could not read unitrim file: %v\n", err)
}
// unmarshal the unitrim file
var unitrim []int
err = json.Unmarshal(unitrimBytes, &unitrim)
if err != nil {
t.Errorf("Could not unmarshal unitrim file: %v\n", err)
}
// get generated array for unitrim with the makeUnitrimArr function
generatedArray := makeUnitrimArr(encoder)
// check that the generated array is the same as the unitrim array
fmt.Printf(
"Generated array length: %d, unitrim array length: %d\n",
len(generatedArray), len(unitrim),
)
if len(generatedArray) != len(unitrim) {
t.Errorf("Generated array and unitrim array are not the same length\n")
}
for i := range generatedArray {
if generatedArray[i] != unitrim[i] {
fmt.Printf(
"Generated array: %v and unitrim array: %v at index %d are not the same\n",
generatedArray[i], unitrim[i], i,
)
fmt.Printf(
"mismatched unicode is: %c\n", rune(generatedArray[i]),
)
t.Errorf("Generated array and unitrim array are not the same\n")
}
}
fmt.Printf("Length and contents of generated array and unitrim array are the same\n")
}
}
func TestLlamaEncoder_Encode(t *testing.T) {
// This test is to check if the encoder is able to encode a basic string
start := time.Now()
tokenCt := len(*gpt2Encoder.Encode(&corpus))
duration := time.Since(start)
t.Logf(
"%v bytes into %v tokens over %v",
len(corpus), tokenCt, duration,
)
for testIdx := range GPTEncoderTests {
tokensPtr := *gpt2Encoder.Encode(
&(GPTEncoderTests[testIdx].Input),
)
assert.Equal(t, tokensPtr, GPTEncoderTests[testIdx].GPT2Expected)
}
}
func TestLlamaTwoEncoder_Encode(t *testing.T) {
// This test is to check if the encoder is able to encode a basic string
testString := "The fox jumped over the hare.\nThe turtle is faster than the hare."
llamaTokens := llama2Encoder.Encode(&testString)
assert.Equal(
t, llamaTokens,
&Tokens{1576, 1701, 29916, 12500, 287, 975, 278, 447, 276, 29889, 13, 1576, 260, 4227, 280, 338, 8473, 1135, 278, 447, 276, 29889},
)
}
func TestLlamaTwoTokenizerDecode(t *testing.T) {
// This test is to check if the decoder is able to decode the tokens correctly
outputString := "<s>The fox jumped over the hare.\nThe turtle is faster than the hare."
llamaTokens := Tokens{1, 1576, 1701, 29916, 12500, 287, 975, 278, 447, 276, 29889, 13, 1576, 260, 4227, 280, 338, 8473, 1135, 278, 447, 276, 29889}
output := llama2Encoder.Decode(&llamaTokens)
assert.Equal(t, outputString, output)
}
func TestLlamaTwoEncodeDecode(t *testing.T) {
// This test is to check if the encoder is able to encode and decode a basic string
testString := "The fox jumped over the hare.\nThe turtle is faster than the hare."
outputString := "The fox jumped over the hare.\nThe turtle is faster than the hare."
llamaTokens := llama2Encoder.Encode(&testString)
output := llama2Encoder.Decode(llamaTokens)
assert.Equal(t, outputString, output)
}
// This is Mistral tokenizer V1, associated with 7b instruct https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2
func TestMistralEncoder_Encode(t *testing.T) {
// This test is to check if the encoder is able to encode a basic string
testString := "The fox jumped over the hare.\nThe turtle is faster than the hare."
mistralTokens := mistralEncoder.Encode(&testString)
assert.Equal(
t, mistralTokens,
&Tokens{1, 415, 285, 1142, 14949, 754, 272, 295, 492, 28723, 13, 1014, 261, 3525, 291, 349, 9556, 821, 272, 295, 492, 28723},
)
}
func TestMistralTokenizerDecode(t *testing.T) {
// This test is to check if the decoder is able to decode the tokens correctly
outputString := "<s> The fox jumped over the hare.\nThe turtle is faster than the hare."
mistralTokens := Tokens{1, 415, 285, 1142, 14949, 754, 272, 295, 492, 28723, 13, 1014, 261, 3525, 291, 349, 9556, 821, 272, 295, 492, 28723}
output := mistralEncoder.Decode(&mistralTokens)