-
Notifications
You must be signed in to change notification settings - Fork 13
/
gpt_bpe.go
1417 lines (1297 loc) · 38.3 KB
/
gpt_bpe.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"
"bytes"
"encoding/binary"
"encoding/json"
"github.com/pkg/errors"
"io"
"log"
"math"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"unicode"
lru "github.com/hashicorp/golang-lru"
"github.com/wbrown/gpt_bpe/resources"
"github.com/wbrown/gpt_bpe/types"
)
const BPE_LRU_SZ = 65536
const RUNEBUF_SZ = 16384
const WORDCHAN_SZ = 4096
const defaultPadTokenString = "[PAD]"
type Token = types.Token
type Tokens = types.Tokens
type GPTEncoder struct {
Encoder map[string]Token
Decoder map[Token][]byte
BpeRanks map[GPTPair]float64
TokenMerges map[TokenPair]Token
BytesEncoder *map[byte]Token
unitrim []int
pattern *regexp.Regexp
puncPat *regexp.Regexp
specialsPat *regexp.Regexp
byteToRune [256]rune
runeToByte map[rune]byte
Specials map[string]Tokens
SpecialsTree *RuneNode
Cache *lru.ARCCache
PuncRunes []rune
Normalizer *strings.Replacer
DecodeExtra *strings.Replacer
BosToken Token
EosToken Token
PadToken Token
ignoreMerges bool
encloseEosBos bool
encloseBos bool
encloseEos bool
prefixSpace bool
lowerCase bool
endOfWord string
replacements map[string]string
runeBufSz int
wordChanSz int
LruHits int
LruMisses int
LruEvictions int
LruSize int
SplitterThreads int
VocabId string
tokenizerClass string
}
type GPTPair struct {
Left string
Right string
}
type TokenPair struct {
Left Token
Right Token
}
type BGERank struct {
rank float64
bigram GPTPair
}
type BGERanks []BGERank
func (bs BGERanks) Len() int {
return len(bs)
}
func (bs BGERanks) Swap(i, j int) {
bs[i], bs[j] = bs[j], bs[i]
}
func (bs BGERanks) Less(i, j int) bool {
return bs[i].rank < bs[j].rank
}
const SPLIT_REGEX = "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L" +
"}+| ?\\p{N}+| ?[^\\s\\p{L" +
"}\\p{N}]+|\\s+(\\S){0}|\\s+"
const PUNC_REGEX = "\\p{L}[.!?;]\\p{L}"
const REGEX_ERROR = "gpt_bpe: Fatal error compiling regular expression: %v"
const VOCAB_ID_GPT2 = "gpt2-tokenizer"
const VOCAB_ID_PILE = "pile-tokenizer"
const VOCAB_ID_CLIP = "clip-tokenizer"
const VOCAB_ID_NERDSTASH_V1 = "nerdstash_v1-tokenizer"
const VOCAB_ID_NERDSTASH_V2 = "nerdstash_v2-tokenizer"
const VOCAB_ID_LLAMA = "llama-tokenizer"
const VOCAB_ID_LLAMA_3 = "llama3-tokenizer"
const VOCAB_ID_MISTRAL = "mistral-tokenizer"
func NewGPT2Encoder() GPTEncoder {
encoder, _ := NewEncoder(VOCAB_ID_GPT2)
return *encoder
}
func NewPileEncoder() GPTEncoder {
encoder, _ := NewEncoder(VOCAB_ID_PILE)
return *encoder
}
func NewCLIPEncoder() GPTEncoder {
encoder, _ := NewEncoder(VOCAB_ID_CLIP)
return *encoder
}
func NewNerdstashV1Encoder() GPTEncoder {
encoder, _ := NewEncoder(VOCAB_ID_NERDSTASH_V1)
return *encoder
}
func NewNerdstashV2Encoder() GPTEncoder {
encoder, _ := NewEncoder(VOCAB_ID_NERDSTASH_V2)
return *encoder
}
func NewLlama2Encoder() GPTEncoder {
encoder, _ := NewEncoder(VOCAB_ID_LLAMA)
return *encoder
}
func NewLlama3Encoder() GPTEncoder {
encoder, _ := NewEncoder(VOCAB_ID_LLAMA_3)
return *encoder
}
func NewMistralEncoder() GPTEncoder {
encoder, _ := NewEncoder(VOCAB_ID_MISTRAL)
return *encoder
}
// NewEncoder
// Returns a GPTEncoder with the tokenizer data loaded for that vocabulary
// id.
func NewEncoder(vocabId string) (*GPTEncoder, error) {
log.Printf("Loading encoder for vocab id: %s\n", vocabId)
hfConfig, resourcesPtr, vocabErr := resources.ResolveVocabId(vocabId, "")
if vocabErr != nil {
return nil, vocabErr
} else if hfConfig == nil {
// We should never get this error, but just in case, we return an
// error if we can't find the config.
return nil, errors.Errorf(
"Can't load encoder for vocab id: %s",
vocabId,
)
} else if resourcesPtr == nil {
return nil, errors.Errorf(
"Can't load resources for vocab id: %s",
vocabId,
)
}
rsrcs := *resourcesPtr
if hfConfig.ModelId != nil {
vocabId = *hfConfig.ModelId
}
specialConfig := resources.SpecialConfig{
PuncRunes: nil,
Normalizer: nil,
EncloseEosBos: false,
PrefixSpace: true,
LowerCase: false,
EndOfWord: "",
DecodeExtra: nil,
SplitRegex: nil,
}
if special, ok := (rsrcs)["special_config.json"]; ok {
if special.Data != nil {
if json.Unmarshal(*special.Data, &specialConfig) != nil {
log.Fatal("Error unmarshalling special_config.json")
}
}
}
// Sometimes we have a split regex that's provided by the model's
// tokenizer config.
if specialConfig.SplitRegex == nil {
splitRegexPtr := rsrcs.ResolveSplitRegex()
if splitRegexPtr != nil {
// Use our default split regex if we can't find one.
specialConfig.SplitRegex = splitRegexPtr
}
}
// These are the runes that are considered punctuation and have
// special handling.
puncRunes := make([]rune, 0)
if specialConfig.PuncRunes != nil {
for _, r := range specialConfig.PuncRunes {
puncRunes = append(puncRunes, rune((*r)[0]))
}
}
// Create a replacer for normalizing text.
normalizer := strings.NewReplacer()
if specialConfig.Normalizer != nil {
norms := make([]string, 0)
for k, v := range *specialConfig.Normalizer {
norms = append(norms, k, v)
}
normalizer = strings.NewReplacer(norms...)
}
// Create a replacer for extra decoding. This is used to decode
// special tokens that are not in the encoder.
decodeExtra := strings.NewReplacer()
if specialConfig.DecodeExtra != nil {
decode := make([]string, 0)
for k, v := range *specialConfig.DecodeExtra {
decode = append(decode, k, v)
}
decodeExtra = strings.NewReplacer(decode...)
}
// Build the bytes to unicode tables.
bytesUnicode, unicodeBytes := makeByteTranslationTables()
// Read encoder mappings.
vocab, err := rsrcs.GetVocab(hfConfig)
if err != nil {
return nil, err
}
encoderTokens := make(map[string]Token)
for k, v := range vocab {
encoderTokens[k] = Token(v)
}
// Build the unitrim array. This is used to trim token sequences
// to valid UTF-8 boundaries.
unitrimArr := makeUnitrimArr(encoderTokens)
// Go through the encoder mappings for possible byte runes
// and also generate reverse mappings.
bytesEncoder := make(map[byte]Token)
tokensEncoder := make(map[Token][]byte)
for text, token := range encoderTokens {
if strings.HasPrefix(text, "0x") && len(text) == 4 {
// Convert the hex string to a byte
byteValue, err := strconv.ParseUint(text[2:], 16, 8)
if err != nil {
panic(err)
}
tokensEncoder[token] = []byte{byte(byteValue)}
bytesEncoder[byte(byteValue)] = token
delete(encoderTokens, text)
} else {
tokensEncoder[token] = []byte(text)
}
}
bytesEncoderPtr := &bytesEncoder
if len(bytesEncoder) == 0 {
bytesEncoderPtr = nil
}
// Read merge table into BpeRanks
bpeRanks := make(map[GPTPair]float64)
rscBpeRanks, err := resources.GetMergesAsBpeRank(&rsrcs)
if err != nil {
return nil, err
}
// Convert rscBpeRanks to bpeRanks (map[GPTPair]float64)
for k, v := range rscBpeRanks {
bpeRanks[GPTPair{k.Left, k.Right}] = v
}
// Build our TokenMerges. These are used to merge tokens together
// based on the BPE merge table.
tokenMerges := make(map[TokenPair]Token)
for pair := range bpeRanks {
tokenMerges[TokenPair{
encoderTokens[pair.Left],
encoderTokens[pair.Right]}] =
encoderTokens[pair.Left+pair.Right]
}
// Handle special tokens. Special tokens are removed from input before
// tokenization, so we need to search for them before we tokenize.
specialsRegexTokens := make([]string, 0)
specials := make(map[string]Tokens)
specialsArr := make([]string, 0)
if specialsTxt, ok := rsrcs["specials.txt"]; ok {
specialsBuffer := bytes.NewBuffer(*specialsTxt.Data)
specialsScanner := bufio.NewScanner(specialsBuffer)
for specialsScanner.Scan() {
specialToken := specialsScanner.Text()
if specialToken == "" {
continue
}
specials[specialToken] = Tokens{encoderTokens[specialToken]}
specialsArr = append(specialsArr, specialToken)
quotedToken := regexp.QuoteMeta(specialToken)
specialsRegexTokens = append(specialsRegexTokens, quotedToken)
}
} else if specialsJson, ok := rsrcs["specials.json"]; ok {
specialsData := make(map[string]string)
seenSpecials := make(map[string]bool)
if specialErr := json.Unmarshal(
*specialsJson.Data,
&specialsData,
); specialErr != nil {
return nil, specialErr
}
for _, v := range specialsData {
if _, seen := seenSpecials[v]; !seen {
seenSpecials[v] = true
specials[v] = Tokens{encoderTokens[v]}
specialsArr = append(specialsArr, v)
quotedToken := regexp.QuoteMeta(v)
specialsRegexTokens = append(specialsRegexTokens, quotedToken)
}
}
}
specialsRegex := strings.Join(specialsRegexTokens, "|")
// Now compile our regexes.
specialsPat, err := regexp.Compile(specialsRegex)
if err != nil {
log.Fatalf(REGEX_ERROR, err)
}
var pat *regexp.Regexp
if specialConfig.SplitRegex != nil {
pat, err = regexp.Compile(*specialConfig.SplitRegex)
} else {
pat, err = regexp.Compile(SPLIT_REGEX)
}
if err != nil {
log.Fatalf(REGEX_ERROR, err)
}
puncPat, err := regexp.Compile(PUNC_REGEX)
if err != nil {
log.Fatalf(REGEX_ERROR, err)
}
cache, _ := lru.NewARC(BPE_LRU_SZ)
replacements := make(map[string]string)
if hfConfig.NewLineMode != nil && *hfConfig.NewLineMode == "s" {
replacements["\n"] = "</s>"
}
if specialConfig.EncloseEosBos {
bosBool := true
eosBool := true
hfConfig.AddBosToken = &bosBool
hfConfig.AddEosToken = &eosBool
}
// Add in default pad token if not already set
padTokenNotFound := hfConfig.PadTokenStr == nil ||
*hfConfig.PadTokenStr == ""
if padTokenNotFound {
// Attempt to resolve from specials
for k := range specials {
if strings.Contains(k, "pad") {
hfConfig.PadTokenStr = &k
padTokenNotFound = false
break
}
}
// Inject the pad token into the encoder to uintmax32,
// throw an error if vocab is larger than uintmax32
if len(encoderTokens) >= math.MaxUint32 {
log.Fatalf(
"Vocab size of %d is larger than uint32 max of %d. "+
"Please specify a pad token in the vocab file.",
len(encoderTokens), math.MaxUint32,
)
}
if padTokenNotFound {
padToken := defaultPadTokenString
if len(encoderTokens) >= math.MaxUint16 {
encoderTokens[padToken] = math.MaxUint32
} else {
encoderTokens[padToken] = math.MaxUint16
}
hfConfig.PadTokenStr = &padToken
}
}
// Create the encoder
encoder := &GPTEncoder{
Encoder: encoderTokens,
Decoder: tokensEncoder,
BpeRanks: bpeRanks,
TokenMerges: tokenMerges,
BytesEncoder: bytesEncoderPtr,
unitrim: unitrimArr,
pattern: pat,
puncPat: puncPat,
specialsPat: specialsPat,
byteToRune: bytesUnicode,
runeToByte: unicodeBytes,
Specials: specials,
SpecialsTree: nil,
Cache: cache,
PuncRunes: puncRunes,
Normalizer: normalizer,
DecodeExtra: decodeExtra,
BosToken: encoderTokens[*hfConfig.BosTokenStr],
EosToken: encoderTokens[*hfConfig.EosTokenStr],
PadToken: encoderTokens[*hfConfig.PadTokenStr],
ignoreMerges: *hfConfig.IgnoreMerges,
encloseEosBos: specialConfig.EncloseEosBos,
encloseBos: *hfConfig.AddBosToken,
encloseEos: *hfConfig.AddEosToken,
prefixSpace: specialConfig.PrefixSpace,
lowerCase: specialConfig.LowerCase,
endOfWord: specialConfig.EndOfWord,
replacements: replacements,
runeBufSz: RUNEBUF_SZ,
wordChanSz: WORDCHAN_SZ,
LruHits: 0,
LruMisses: 0,
LruEvictions: 0,
LruSize: BPE_LRU_SZ,
SplitterThreads: 4,
VocabId: vocabId,
tokenizerClass: *hfConfig.TokenizerClass,
}
encoder.UpdateSpecialsTree()
return encoder, nil
}
func (encoder *GPTEncoder) UpdateSpecialsTree() {
// Turn the keys of the specials map into a slice
idx := 0
specialsArr := make([]string, len(encoder.Specials))
for k := range encoder.Specials {
specialsArr[idx] = k
idx++
}
encoder.SpecialsTree = CreateRuneTree(specialsArr)
}
// makeByteTranslationTables creates lookup tables for interconverting
// between runes in decoded token strings and the UTF-8 byte sequences
// that they encode.
func makeByteTranslationTables() ([256]rune, map[rune]byte) {
// GPT2's BPE implementation reinterprets UTF-8-encoded bytes as
// Unicode codepoints, but remaps the 68 code points
// corresponding to control, format, and space-separator characters
// (i.e. Unicode character categories Cc, Cf, and Zs)
// in the range [0, 255] to sequential codepoints in [256, 323],
// which happens to contain no characters from those three categories.
// For example, the byte \x00 is mapped to codepoint 256, and the final
// affected byte \xAD is mapped to codepoint 323.
// The remapped bytes are sequential even though the original bytes
// are not. The original bytes' codepoint interpretations all fall
// in the following ranges:
// - [\x00, \x20] ('NUL' to 'SPACE'; up to right before '!'),
// - [\x7F, \xA0] ('DELETE' to 'NO-BREAK SPACE'; between '~' and '¡')
// - \xAD exactly ('SOFT HYPHEN')
// Refer to "src/encoder.py" in the openai/gpt-2 repository for
// more detail.
byteDecoderMap := make(map[rune]byte, 256)
var byteEncoderLUT [256]rune
for i, relocated := rune(0), rune(256); i < 256; i++ {
relocatedByte := i
if i < '!' || i > '~' && i < '¡' || i == '\xAD' {
relocatedByte = relocated
relocated++
}
byteEncoderLUT[i] = relocatedByte
byteDecoderMap[relocatedByte] = byte(i)
}
return byteEncoderLUT, byteDecoderMap
}
// makeUnitrimArr creates a lookup table for trimming token sequences
// to valid UTF-8 boundaries. It replaces unitrim.json files generated
// in advance.
func makeUnitrimArr(encoderMap map[string]Token) []int {
// In order to check how many UTF-8 continuation bytes are missing from
// each individual token, the decoded token strings need to be translated
// to UTF-8.
_, byteDecoderMap := makeByteTranslationTables()
// This function returns the following LUT, representing either
// how many continuation bytes are needed following a given token,
// or how many continuation bytes a given token fulfills.
// Positive entries require that many more continuation bytes to follow;
// negative entries fulfill that many continuation bytes.
debtLUT := make([]int, len(encoderMap))
// Continuation byte requirements are defined by the UTF-8 standard
// and can be determined from bit patterns of each byte. We make a
// LUT of bit patterns to make this calculation faster.
// Only the 5 most significant bits are relevant.
var byteDebtLUT [32]int8
for b := 0; b <= 0b11110; b++ {
// According to UTF-8 variable-length binary encoding:
if (b & 0b10000) == 0 {
// All 7-bit ASCII characters have the bit pattern 0xxxxxxx
// - They are self-contained, and require no continuation
// - They are the only characters encoded with a single byte
byteDebtLUT[b] = 0
} else if (b & 0b11100) == 0b11000 {
// All 2-byte characters start with a 110xxxxx byte
// - These add +1 continuation byte debt
byteDebtLUT[b] = 1
} else if (b & 0b11110) == 0b11100 {
// All 3-byte characters start with a 1110xxxx byte
// - These add +2 continuation byte debt
byteDebtLUT[b] = 2
} else if (b & 0b11110) == 0b11110 {
// All 4-byte characters start with a 11110xxx byte
// - These add +3 continuation byte debt
// - No valid Unicode starts with 11111xxx, so the last
// 0 should be redundant, but some tokenizers include
// such bytes in their vocabularies regardless.
byteDebtLUT[b] = 3
} else if (b & 0b11000) == 0b10000 {
// All continuation characters start with a 10xxxxxx byte
//- These satisfy (-) 1 continuation byte debt
byteDebtLUT[b] = -1
}
}
// Calculate the debtLUT entries for each token ID
for decodedToken, token := range encoderMap {
tokenDebt := 0
minTokenDebt := 0
// Decode each Unicode codepoint into a UTF-8 byte
codepoints := []rune(decodedToken)
utf8Bytes := make([]byte, len(codepoints))
for i, c := range codepoints {
utf8Bytes[i] = byteDecoderMap[c]
}
// Keep track of continuation byte requirements
// between each UTF-8 byte.
for _, b := range utf8Bytes {
b >>= 3 // trim to relevant bits
byteDebt := int(byteDebtLUT[b])
if byteDebt < 0 {
// Continuation bytes are tracked relative to the bytes
// preceding them
tokenDebt += byteDebt
} else {
// Starting bytes have no relation to bytes preceding them
tokenDebt = byteDebt
}
if tokenDebt < 0 {
minTokenDebt = tokenDebt
} else if tokenDebt == 0 {
// If the beginning of the string satisfies continuation
// byte debt, don't forget that just to track less-important
// information about self-contained byte sequences that follow.
// Do overwrite it if it ends with fresh debt.
// NB: if a token both satisfies continuation byte debt
// and then begins new debt, only the latter can be tracked.
// This is a limitation of the LUT entries being single
// integers rather than pairs of integers.
tokenDebt = minTokenDebt
}
}
debtLUT[token] = tokenDebt
}
return debtLUT
}
// insertAt inserts v into s at index i and returns the new slice.
func insertAt(data []BGERank, i int, v BGERank) []BGERank {
if i == len(data) {
// Insert at end is the easy case.
return append(data, v)
}
// Make space for the inserted element by shifting
// values at the insertion index up one index. The call
// to append does not allocate memory when cap(data) is
// greater than len(data).
data = append(data[:i+1], data[i:]...)
// Insert the new element.
data[i] = v
// Return the updated slice.
return data
}
// insertSortedNoDups inserts v, a BGERank, into data and returns the new slice.
// If v is already in data, it is not inserted again. It ensures that the slice
// is sorted and has no duplicates.
func insertSortedNoDups(data BGERanks, v BGERank) BGERanks {
i := sort.Search(
len(data), func(i int) bool {
return data[i].rank >= v.rank
},
)
if i < len(data) && data[i] == v {
return data
}
return insertAt(data, i, v)
}
func getPairs(word []string) []GPTPair {
pairsSet := make(map[GPTPair]bool, len(word))
pairs := make([]GPTPair, len(word))
begin := 1
prev := word[0]
ct := 0
for idx := begin; idx < len(word); idx++ {
present := word[idx]
pair := GPTPair{prev, present}
if _, ok := pairsSet[pair]; !ok {
pairs[len(pairsSet)] = pair
ct++
}
pairsSet[pair] = true
prev = present
}
return pairs[0:ct]
}
// getRankedPairs
// Accepts a slice of strings and returns a slice of BGERanks, sorted by
// their rank.
func (encoder *GPTEncoder) getRankedPairs(word []string) BGERanks {
rankedPairs := make(BGERanks, 0, len(word))
begin := 1
prev := word[0]
for idx := begin; idx < len(word); idx++ {
present := word[idx]
pair := GPTPair{prev, present}
bpe, ok := encoder.BpeRanks[pair]
if !ok {
bpe = math.Inf(1)
}
rankedPairs = insertSortedNoDups(
rankedPairs,
BGERank{bpe, pair},
)
prev = present
}
return rankedPairs
}
// rankPairs
// Accepts a slice of GPTPair and returns a slice of BGERanks, sorted by
// their rank.
func (encoder *GPTEncoder) rankPairs(pairs []GPTPair) BGERanks {
rankedPairs := make(BGERanks, 0)
for idx := range pairs {
bpe, ok := encoder.BpeRanks[pairs[idx]]
if !ok {
bpe = math.Inf(1)
}
rankedPairs = insertSortedNoDups(
rankedPairs,
BGERank{bpe, pairs[idx]},
)
}
sort.Sort(rankedPairs)
return rankedPairs
}
// minPair
// Accepts a slice of GPTPair and returns the pair with the lowest BPE rank.
func (encoder *GPTEncoder) minPair(pairs []GPTPair) (retPair GPTPair) {
rankedPairs := encoder.rankPairs(pairs)
if len(rankedPairs) > 0 {
retPair = rankedPairs[0].bigram
}
return retPair
}
// pos finds the index of the first occurrence of seek in word past index i.
func pos(word []string, seek string, i int) int {
for j, v := range word[i:] {
if seek == v {
return j + i
}
}
return -1
}
// findAllStringIndex returns a set of indexes of all occurrences of substr in
// string.
func findAllStringIndex(text string, substr string) [][]int {
var indexes [][]int
for i := 0; i < len(text); {
j := strings.Index(text[i:], substr)
if j < 0 {
break
}
indexes = append(indexes, []int{i + j, i + j + len(substr)})
i += j + len(substr)
}
return indexes
}
// findAllStringsIndexes returns a set of indexes of all occurrences of strings,
// which are substrings of text removing all overlaps.
func findAllStringsIndexes(text string, strings []string) [][]int {
var indexes [][]int
for _, substr := range strings {
indexes = append(indexes, findAllStringIndex(text, substr)...)
}
return indexes
}
// ToBPE
// Given pre-split text, perform bigram ranking and merges, and returns Tokens
func (encoder *GPTEncoder) ToBPE(text string) Tokens {
// If the text is in the cache, return it.
if lookup, ok := encoder.Cache.Get(text); ok {
encoder.LruHits++
return lookup.(Tokens)
} else {
encoder.LruMisses++
}
// Lookup text given before proceeding
if encoder.ignoreMerges {
if token, ok := encoder.Encoder[text]; ok {
encoder.Cache.Add(text, Tokens{token})
return Tokens{token}
}
}
// Split the text into words.
word := strings.Split(text, "")
word[len(word)-1] = word[len(word)-1] + encoder.endOfWord
rankedPairs := encoder.getRankedPairs(word)
if len(rankedPairs) == 0 {
// If the word is a single rune, we can just encode it directly.
var tokens Tokens
if token, ok := encoder.Encoder[word[0]]; ok {
tokens = Tokens{token}
} else if encoder.BytesEncoder != nil {
tokens = make(Tokens, 0)
runeBytes := []byte(word[0])
// Then encode each byte as a token.
for _, b := range runeBytes {
tokens = append(tokens, (*encoder.BytesEncoder)[b])
}
} else {
tokens = Tokens{encoder.Encoder[word[0]]}
}
encoder.Cache.Add(text, tokens)
return tokens
}
// Iterate over the ranked pairs and merge them.
for {
bigram := rankedPairs[0].bigram
if _, ok := encoder.BpeRanks[bigram]; !ok {
break
}
first := bigram.Left
second := bigram.Right
newWord := make([]string, 0, len(word))
for i := 0; i < len(word); {
j := pos(word, first, i)
if j == -1 {
newWord = append(newWord, word[i:]...)
break
}
newWord = append(newWord, word[i:j]...)
i = j
if word[i] == first && i < len(word)-1 && word[i+1] == second {
newWord = append(newWord, first+second)
i += 2
} else {
newWord = append(newWord, word[i])
i += 1
}
}
word = newWord
// If we've reduced the word to a single token, we're done.
if len(word) == 1 {
break
} else {
rankedPairs = encoder.getRankedPairs(word)
}
}
// Encode the word into tokens.
if len(word) > 0 {
idx := len(word) - 1
word[idx] = word[idx]
}
tokens := make(Tokens, 0)
// If we have a special token, we cap it off.
for _, token := range word {
if lookup, ok := encoder.Encoder[token]; ok {
tokens = append(tokens, lookup)
} else if encoder.BytesEncoder != nil {
// If we can't find the token in the encoder, we'll
// encode it in byte-level BPE. First convert the rune
// into 8-bit bytes.
runeBytes := []byte(token)
// Then encode each byte as a token.
for _, b := range runeBytes {
tokens = append(tokens, (*encoder.BytesEncoder)[b])
}
}
}
// Cache the tokens.
encoder.Cache.Add(text, tokens)
return tokens
}
func (encoder *GPTEncoder) getSpecials() map[int][][]rune {
lenMap := make(map[int][][]rune)
for k := range encoder.Specials {
keyLen := len(k)
keyRunes := []rune(k)
if entry, ok := lenMap[keyLen]; ok {
lenMap[keyLen] = append(entry, keyRunes)
} else {
lenMap[keyLen] = [][]rune{keyRunes}
}
}
return lenMap
}
func (encoder *GPTEncoder) splitWords(
text string,
specialToken bool, specialsNode *RuneNode,
) []*string {
// Some things such as KoboldAI have a 'replacement' rule, where
// they replace tokens such as `\n` with `</s>` for Fairseq
// handling.
for replaced, replacement := range encoder.replacements {
text = strings.ReplaceAll(text, replaced, replacement)
}
text = encoder.Normalizer.Replace(text)
idxes := encoder.pattern.FindAllStringIndex(text, -1)
words := make([]*string, 0, len(idxes)+1)
for idx := range idxes {
word := text[idxes[idx][0]:idxes[idx][1]]
if encoder.lowerCase {
word = strings.ToLower(word)
}
if !encoder.prefixSpace {
word = strings.TrimSpace(word)
}
if len(word) > 0 {
words = append(words, &word)
}
}
// Finally, if we have a special token, we cap it off.
if specialToken {
runeString := string(specialsNode.runes)
words = append(words, &runeString)
}
return words
}
type NextRuneFunc func() (rune, int, error)
type WordCallback func(*string)
func (encoder *GPTEncoder) splitOntoChan(
text string, ch chan *string,
specialToken bool, specialsNode *RuneNode, wg *sync.WaitGroup,
) {
defer close(ch)
words := encoder.splitWords(text, specialToken, specialsNode)
for _, word := range words {
ch <- word
}
wg.Done()
}
func (encoder *GPTEncoder) synchronousSplitterThread(
line string, specialToken bool, specialsNode *RuneNode,
wg *sync.WaitGroup,
) chan *string {
retCh := make(chan *string, 16)
go encoder.splitOntoChan(line, retCh, specialToken, specialsNode, wg)
return retCh
}
func (encoder *GPTEncoder) consumeSplitQueue(
queue chan chan *string,
cb WordCallback,
wg *sync.WaitGroup,
) {
for {
select {
case ch, ok := <-queue:
if !ok {
wg.Done()
return
}
for word := range ch {
cb(word)
}
}
}
}
func (encoder *GPTEncoder) makeWordSplitter(
nextRuneFunc NextRuneFunc,
wordCallback WordCallback,
completeCallback func(),
) func() {
workQueue := make(chan chan *string, encoder.SplitterThreads)
wg := sync.WaitGroup{}
wg.Add(1)
go encoder.consumeSplitQueue(workQueue, wordCallback, &wg)
return func() {
specialsRuneRoot := encoder.SpecialsTree
runeAccumulator := make([]rune, 0, encoder.runeBufSz)
specialToken := false
specialsCandidates := make(RuneNodes, 0, 16)
var candidateNode *RuneNode
checkAndReplaceNode := func() {
// We have a replacement, so we need to replace the
// runes that we've matched in the accumulator with
// the replacement.
matchLen := len(candidateNode.runes)
accTruncIdx := len(runeAccumulator) - matchLen
runeAccumulator = append(
runeAccumulator[:accTruncIdx],
*candidateNode.replacement...,
)
// Reset our states.
specialsCandidates = specialsCandidates[:0]
candidateNode = specialsRuneRoot
specialToken = false
}
for {
// Let's collect runes until we reach the end of our IO stream, or
// hit a newline.
for {
r, size, err := nextRuneFunc()
if size == 0 || err != nil {
break
}
runeAccumulator = append(runeAccumulator, r)
if r == '\n' {
break
}
// Evaluate our specialsCandidate in place, and if we have
// a node returned, then we have a terminal node.
candidateNode = specialsCandidates.evaluate(r)
if candidateNode != nil {
if candidateNode.replacement != nil {
checkAndReplaceNode()
} else if candidateNode.terminal {
specialToken = true
break
}
}
// Otherwise, we evaluate this rune against our root node, to
// see if we have another candidate to start and add to our
// list.
candidateNode = specialsRuneRoot.evaluate(r)
if candidateNode != nil {
specialsCandidates = append(
specialsCandidates,