-
Notifications
You must be signed in to change notification settings - Fork 20
/
tokenmonster.go
4027 lines (3762 loc) · 148 KB
/
tokenmonster.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 tokenmonster
import (
"os"
"io"
"bytes"
"unsafe"
"errors"
"strings"
"strconv"
"unicode"
"unicode/utf8"
"unicode/utf16"
"encoding/hex"
"encoding/binary"
"gopkg.in/yaml.v3"
"github.com/AlasdairF/Custom"
"github.com/AlasdairF/Conv"
"github.com/AlasdairF/Sort/Uint32Float32"
"github.com/alasdairforsythe/norm"
"github.com/alasdairforsythe/pansearch"
"github.com/alasdairforsythe/branchless"
"github.com/alasdairforsythe/capcode/go"
)
const (
minHighSurrogate = 0xD800 // Start of high surrogate range
maxHighSurrogate = 0xDBFF // End of high surrogate range
minLowSurrogate = 0xDC00 // Start of low surrogate range
maxLowSurrogate = 0xDFFF // End of low surrogate range
runeError = '\uFFFD'
DOES_NOT_EXIST = 16777215
)
var isLittleEndian = *(*byte)(unsafe.Pointer(&[]uint16{256}[0])) == 0
// The main struct for the vocabulary
type Vocab struct {
dictionary *pansearch.Fast
info []tokenInfo
reverse [][]byte
deleted []deletedStruct // deleted tokens are stored here and can later be restored
beginByte [256]byte
vocabSize int
maxTokenLength int
deleteToken uint32 // ID of the delete token, or DOES_NOT_EXIST
unkToken uint32 // ID of the UNK token, or DOES_NOT_EXIST
usingCapcode uint8
charset uint8
level uint8
reserve uint8
normalizer norm.Normalizer // uint8
}
// A decoder object for sequential decoding.
// Use the NewDecoder function of the Vocab struct.
type Decoder struct {
vocab Vocab
remainder []byte
capcodeDecoder *capcode.Decoder
}
type tokenInfo struct {
alt tokenOuter
token []byte
score float32
}
type tokenOuter struct {
data tokenInner
length int // length of alternative1
length2 int // length of alternative2
index uint32 // index of alternative 1
index2 uint32 // index of alternative 2
id uint32 // my ID
id1 uint32 // ID of alternative1
id2 uint32 // ID of alternative2
}
type tokenInner struct {
flag uint8
nWords uint8
}
type deletedStruct struct {
token []byte
id uint32
score float32
}
/*
'flag' bits:
1 ends with a letter
2 begins with a letter
4 begins with a space OR characterToken OR wordToken
8 ends on capcode
16 begins on capcode
32 a single straight word, beginning space, no punctuation
64 is a special token
128 is either all letters or no letters
beginByte
1 = letter
10 = anything else
12 = space >>2 & 1 == 1
>>3 means not a letter
*/
// --------- HELPER FUNCTIONS ---------
/*
func norm_UTF16_NFD(input []byte) ([]byte, error) {
// Assume LittleEndian by default
endian := uni.LittleEndian
bomPolicy := uni.IgnoreBOM
if len(input) >= 2 {
if input[0] == 0xFE && input[1] == 0xFF {
endian = uni.BigEndian
bomPolicy = uni.ExpectBOM
} else if input[0] == 0xFF && input[1] == 0xFE {
endian = uni.LittleEndian
bomPolicy = uni.ExpectBOM
}
}
// Attempt to decode the input with decided endian
utf16Decoder := uni.UTF16(endian, bomPolicy)
// Create a transformer to decode to UTF-16 and normalize the text to NFD
transformer := transform.Chain(utf16Decoder.NewDecoder(), norm.NFD)
// Create a reader with the transformer
reader := transform.NewReader(bytes.NewReader(input), transformer)
// Read normalized NFD UTF-16 bytes
nfdBytes, err := ioutil.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("Error normalizing content: %w", err)
}
// Encode normalized NFD back to UTF-16LE
utf16LEEncoder := uni.UTF16(uni.LittleEndian, uni.UseBOM).NewEncoder()
reader = transform.NewReader(bytes.NewReader(nfdBytes), utf16LEEncoder)
// Read UTF-16LE bytes
utf16LEBytes, err := ioutil.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("Error converting content to []byte: %w", err)
}
return utf16LEBytes, nil
}
*/
// Returns the number of bytes at the end of the slice of bytes that are part of an incomplete UTF-8 sequence.
func incompleteUTF8Bytes(bytes []byte) int {
bytesLen := len(bytes)
// Single byte or empty string
if bytesLen == 0 {
return 0
}
if bytes[bytesLen-1]&0b10000000 == 0 {
return 0
}
// Find the start of the last character sequence
seqStart := bytesLen - 1
for seqStart >= 0 && (bytes[seqStart]&0b11000000) == 0b10000000 {
seqStart--
}
// If no sequence start found, all bytes are continuation bytes and thus are all incomplete
if seqStart == -1 {
return bytesLen
}
// Determine expected sequence length from leading byte
firstByte := bytes[seqStart]
var seqLen int
if (firstByte & 0b10000000) == 0 {
seqLen = 1
} else if (firstByte & 0b11100000) == 0b11000000 {
seqLen = 2
} else if (firstByte & 0b11110000) == 0b11100000 {
seqLen = 3
} else if (firstByte & 0b11111000) == 0b11110000 {
seqLen = 4
} else {
// This is not a valid UTF-8 starting byte
return bytesLen - seqStart
}
// If sequence length is larger than the remaining bytes, it's incomplete
if bytesLen-seqStart < seqLen {
return seqLen - (bytesLen - seqStart)
}
// If the sequence start byte was not the start of a multi-byte sequence, then the array is incomplete.
if seqLen == 1 && (bytes[seqStart] & 0b11000000) != 0 {
return bytesLen
}
return 0
}
func incompleteUTF16Bytes(bytes []byte) int {
bytesLen := len(bytes)
if bytesLen == 0 {
return 0
}
if bytesLen % 2 != 0 {
var lastThreeBytes uint16
if bytesLen >= 3 {
lastThreeBytes = binary.LittleEndian.Uint16(bytes[bytesLen-3 : bytesLen-1])
if lastThreeBytes >= 0xD800 && lastThreeBytes <= 0xDBFF {
return 3 // High surrogate followed by a stray byte
}
}
return 1 // Single stray byte
}
// Check if last 16-bit unit is a high surrogate
lastTwoBytes := binary.LittleEndian.Uint16(bytes[bytesLen-2 : bytesLen])
if lastTwoBytes >= 0xD800 && lastTwoBytes <= 0xDBFF {
return 2 // High surrogate without a following low surrogate
}
// Check if first 16-bit unit is a low surrogate
firstTwoBytes := binary.LittleEndian.Uint16(bytes[:2])
if firstTwoBytes >= 0xDC00 && firstTwoBytes <= 0xDFFF {
return 2 // Low surrogate without a preceding high surrogate
}
return 0
}
func convertStringToUTF16(s string) []byte {
return []byte(s)
/*
b := []byte(s)
buf := &bytes.Buffer{}
w := transform.NewWriter(buf, uni.UTF16(uni.LittleEndian, uni.IgnoreBOM).NewEncoder())
w.Write(b)
w.Close()
return buf.Bytes()
*/
}
func applyCapcode(data []byte, usingCapcode uint8) []byte {
if usingCapcode == 2 {
return capcode.Encode(data)
} else if usingCapcode == 1 {
return capcode.NoCapcodeEncode(data)
}
return data
}
func normalize(data []byte, usingCapcode uint8, normalizer norm.Normalizer) ([]byte, error) {
processed, err := normalizer.Normalize(data)
if err == nil {
return applyCapcode(processed, usingCapcode), nil
} else { // if failed try it the other way around
if !normalizer.SpecifiedLowercase() {
processed = applyCapcode(data, usingCapcode)
processed, err = normalizer.Normalize(processed)
}
}
return processed, err
}
// normalizes but avoids double encoding with capcode
func normalizeSafe(b []byte, usingCapcode uint8, normalizer norm.Normalizer) ([]byte, error) {
var err error
var okay bool = true
if usingCapcode == 2 {
for _, v := range b {
if v == capcode.DeleteToken || v == capcode.CharacterToken || v == capcode.WordToken {
okay = false
break
}
}
if okay {
b, err = normalizer.Normalize(b)
b = capcode.Encode(b)
}
return b, err
} else if usingCapcode == 1 {
for _, v := range b {
if v == capcode.NoCapcodeDeleteToken {
okay = false
break
}
}
if okay {
b, err = normalizer.Normalize(b)
b = capcode.NoCapcodeEncode(b)
}
return b, err
}
return normalizer.Normalize(b)
}
func hasSuffixPos(ungreedySuffixesB [][]byte, key []byte, charset uint8, usingCapcode uint8) int {
for _, suffix := range ungreedySuffixesB {
if bytes.HasSuffix(key, suffix) {
if len(suffix) < len(key) {
r := decodeLastRune(key[:len(key)-len(suffix)], charset)
if isLetter(r, usingCapcode) {
return len(key) - len(suffix)
}
}
}
}
return -1
}
func genUTF8bytes(list []bool, usingCapcode uint8) {
genASCIIbytes(list, usingCapcode)
// Continuation bytes in multi-byte characters
for i := 0x80; i <= 0xBF; i++ {
list[i] = true
}
// Starting bytes of multi-byte characters excluding overlongs
for i := 0xC2; i <= 0xF4; i++ {
list[i] = true
}
}
func genASCIIbytes(list []bool, usingCapcode uint8) {
for i:=32; i<127; i++ {
if usingCapcode != 2 || (!(i >= 'A' && i <= 'Z' && i != 'C' && i != 'W' && i != 'D')) {
list[i] = true
}
}
list[9] = true
list[10] = true
list[13] = true
if usingCapcode == 1 {
list[127] = true
}
}
func genExtendedbytes(list []bool, usingCapcode uint8, normalizer norm.Normalizer) {
s := `£€©®™°%¢¥—–•‘’“”áéíóúýàèìòùâêîôûäëïöüñãõçåæœ`
if usingCapcode != 2 && !normalizer.SpecifiedLowercase() {
s += `ÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÑÃÕÇÅÆŒ`
}
s2, _ := normalizer.Normalize([]byte(s))
for _, b := range s2 {
list[b] = true
}
genASCIIbytes(list, usingCapcode)
}
func gen128bytes(list []bool, usingCapcode uint8) {
var b byte
for i:=0; i<128; i++ {
b = byte(i)
if usingCapcode != 2 || (!(b >= 'A' && b <= 'Z' && b != 'C' && b != 'W' && b != 'D')) {
list[i] = true
}
}
}
func gen256bytes(list []bool, usingCapcode uint8) {
var b byte
for i:=0; i<256; i++ {
b = byte(i)
if usingCapcode != 2 || (!(b >= 'A' && b <= 'Z' && b != 'C' && b != 'W' && b != 'D')) {
list[i] = true
}
}
}
func isLetter(r rune, usingCapcode uint8) bool {
return (unicode.IsLetter(r) && (usingCapcode!=2 || (r != 'W' && r != 'C' && r != 'D'))) || unicode.Is(unicode.Mn, r) || unicode.Is(unicode.Mc, r) || unicode.Is(unicode.Me, r)
}
func isAlphaNum(r rune, usingCapcode uint8) bool {
return (unicode.IsLetter(r) && (usingCapcode!=2 || (r != 'W' && r != 'C' && r != 'D'))) || unicode.IsNumber(r) || unicode.Is(unicode.Mn, r) || unicode.Is(unicode.Mc, r) || unicode.Is(unicode.Me, r)
}
func isCapcode(r rune, usingCapcode uint8) bool {
return (usingCapcode == 1 && r == '\x7F') || (usingCapcode==2 && (r == 'C' || r == 'W' || r == 'D'))
}
func decodeRune(b []byte, charsetFlag uint8) (rune, int) {
switch charsetFlag {
case 0, 1: // UTF-8
return utf8.DecodeRune(b)
case 2: // UTF-16
if len(b) < 2 {
return runeError, 0
}
u := binary.LittleEndian.Uint16(b)
if u >= minHighSurrogate && u <= maxHighSurrogate {
// This is a surrogate pair. We need another two bytes.
if len(b) < 4 {
return runeError, 0
}
u2 := binary.LittleEndian.Uint16(b[2:])
if u2 < minLowSurrogate || u2 > maxLowSurrogate {
return runeError, 0
}
r := utf16.Decode([]uint16{u, u2})
if len(r) == 0 {
return runeError, 0
}
return r[0], 4 // surrogate pair is 4 bytes in UTF-16
}
return rune(u), 2 // normal character is 2 bytes in UTF-16
default:
return -1, 0
}
}
func decodeLastRune(b []byte, charsetFlag uint8) rune {
switch charsetFlag {
case 0, 1: // UTF-8
r, _ := utf8.DecodeLastRune(b)
return r
case 2: // UTF-16
if len(b) < 2 {
return runeError
}
u := binary.LittleEndian.Uint16(b[len(b)-2:])
if u >= minLowSurrogate && u <= maxLowSurrogate {
// This is a surrogate pair. We need another two bytes.
if len(b) < 4 {
return runeError
}
u2 := binary.LittleEndian.Uint16(b[len(b)-4:])
if u2 < minHighSurrogate || u2 > maxHighSurrogate {
return runeError
}
r := utf16.Decode([]uint16{u2, u})
if len(r) == 0 {
return runeError
}
return r[0]
}
return rune(u)
default:
return -1
}
}
func unleak(b []byte) []byte {
new := make([]byte, len(b))
copy(new, b)
return new
}
func canHaveUnkToken(i int, usingCapcode uint8) bool {
if (i < 256 && usingCapcode != 2) || i < 233 {
return true
}
return false
}
// --------- DECODER ---------
// Creates a new Decoder instance.
// This is for decoding tokens in a sequence when they are to be decoded individually or in batches.
// If you are decoding all in one go, you can use the Vocab's Decode method.
func (vocab *Vocab) NewDecoder() *Decoder {
return &Decoder{vocab:*vocab, capcodeDecoder: new(capcode.Decoder)}
}
// Flushes the remainder from the Decoder instance
// These will any trailing incomplete UTF-8 sequences or capcode encoding marks
func (d *Decoder) Flush() []byte {
data := d.remainder
d.remainder = nil
return data
}
// Decodes tokens from a serialized bytes slice.
// `encodingLength` must be one of: 0, 2, 3, 4.
// If you enter `encodingLength` 0 then it will determine the encoding length from the vocabulary size.
// `buffer` is optional, you can send it `nil` and it will allocate a new slice.
func (d *Decoder) DecodeSerialized(b []byte, encodingLength uint8, buffer []byte) []byte {
if encodingLength <= 1 {
if len(d.vocab.reverse) <= 65536 {
encodingLength = 2
} else {
encodingLength = 3
}
}
if encodingLength == 2 {
var tokens []uint16
var l uint64 = uint64(len(b)) >> 1
if isLittleEndian {
tokens = (*(*[]uint16)(unsafe.Pointer(&b)))[:l:l]
} else {
tokens = make([]uint16, l)
var to uint64 = uint64(len(b))
var i uint64
for ; i<to; i+=2 {
tokens[i >> 1] = uint16(b[i]) | (uint16(b[i+1]) << 8)
}
}
reverse := d.vocab.reverse
if len(reverse) == 0 {
return []byte{}
}
nTokens := uint16(len(reverse) - 1)
var i int
if d.vocab.charset == 0 {
for _, v := range tokens {
if v <= nTokens {
i += len(reverse[v])
}
}
// Make the exact size array
if i > len(buffer) {
buffer = make([]byte, i)
} else {
buffer = buffer[0:i]
}
// Copy the keys into it
i = 0
for _, v := range tokens {
if v <= nTokens {
copy(buffer[i:], reverse[v])
i += len(reverse[v])
}
}
return buffer
}
// Get the size
i = len(d.remainder)
for _, v := range tokens {
if v <= nTokens {
i += len(reverse[v])
}
}
// Make the exact size array
if i > len(buffer) {
buffer = make([]byte, i)
} else {
buffer = buffer[0:i]
}
// Copy the keys into it
copy(buffer, d.remainder)
i = len(d.remainder)
for _, v := range tokens {
if v <= nTokens {
copy(buffer[i:], reverse[v])
i += len(reverse[v])
}
}
if d.vocab.charset == 1 { // UTF-8
remaining := len(buffer) - incompleteUTF8Bytes(buffer)
d.remainder = buffer[remaining:]
buffer = buffer[:remaining]
} else { // UTF-16
remaining := len(buffer) - incompleteUTF16Bytes(buffer)
d.remainder = buffer[remaining:]
buffer = buffer[:remaining]
}
if d.vocab.usingCapcode == 2 {
buffer = d.capcodeDecoder.Decode(buffer)
} else if d.vocab.usingCapcode == 1 {
buffer = d.capcodeDecoder.NoCapcodeDecode(buffer)
}
return buffer
} else if encodingLength == 3 {
var on uint64
var to uint64 = uint64(len(b))
var v uint32
reverse := d.vocab.reverse
nTokens := uint32(len(reverse))
var i int
if d.vocab.charset == 0 {
for on=0; on<to; on+=3 {
v = uint32(b[on]) | (uint32(b[on+1]) << 8) | (uint32(b[on+2]) << 16)
if v < nTokens {
i += len(reverse[v])
}
}
// Make the exact size array
if i > len(buffer) {
buffer = make([]byte, i)
} else {
buffer = buffer[0:i]
}
// Copy the keys into it
for on=0; on<to; on+=3 {
v = uint32(b[on]) | (uint32(b[on+1]) << 8) | (uint32(b[on+2]) << 16)
if v < nTokens {
copy(buffer[i:], reverse[v])
i += len(reverse[v])
}
}
return buffer
}
// Get the size
i = len(d.remainder)
for on=0; on<to; on+=3 {
v = uint32(b[on]) | (uint32(b[on+1]) << 8) | (uint32(b[on+2]) << 16)
if v < nTokens {
i += len(reverse[v])
}
}
// Make the exact size array
if i > len(buffer) {
buffer = make([]byte, i)
} else {
buffer = buffer[0:i]
}
// Copy the keys into it
copy(buffer, d.remainder)
i = len(d.remainder)
for on=0; on<to; on+=3 {
v = uint32(b[on]) | (uint32(b[on+1]) << 8) | (uint32(b[on+2]) << 16)
if v < nTokens {
copy(buffer[i:], reverse[v])
i += len(reverse[v])
}
}
if d.vocab.charset == 1 { // UTF-8
remaining := len(buffer) - incompleteUTF8Bytes(buffer)
d.remainder = buffer[remaining:]
buffer = buffer[:remaining]
} else { // UTF-16
remaining := len(buffer) - incompleteUTF16Bytes(buffer)
d.remainder = buffer[remaining:]
buffer = buffer[:remaining]
}
if d.vocab.usingCapcode == 2 {
buffer = d.capcodeDecoder.Decode(buffer)
} else if d.vocab.usingCapcode == 1 {
buffer = d.capcodeDecoder.NoCapcodeDecode(buffer)
}
return buffer
} else if encodingLength == 4 {
var tokens []uint32
var l uint64 = uint64(len(b)) >> 2
if isLittleEndian {
tokens = (*(*[]uint32)(unsafe.Pointer(&b)))[:l:l]
} else {
tokens = make([]uint32, l)
var to uint64 = uint64(len(b))
var i uint64
for ; i<to; i+=4 {
tokens[i >> 2] = uint32(b[i]) | (uint32(b[i+1]) << 8) | (uint32(b[i+2]) << 16) | (uint32(b[i+3]) << 24)
}
}
reverse := d.vocab.reverse
nTokens := uint32(len(reverse))
var i int
if d.vocab.charset == 0 {
for _, v := range tokens {
if v < nTokens {
i += len(reverse[v])
}
}
// Make the exact size array
if i > len(buffer) {
buffer = make([]byte, i)
} else {
buffer = buffer[0:i]
}
// Copy the keys into it
i = 0
for _, v := range tokens {
if v < nTokens {
copy(buffer[i:], reverse[v])
i += len(reverse[v])
}
}
return buffer
}
// Get the size
i = len(d.remainder)
for _, v := range tokens {
if v < nTokens {
i += len(reverse[v])
}
}
// Make the exact size array
if i > len(buffer) {
buffer = make([]byte, i)
} else {
buffer = buffer[0:i]
}
// Copy the keys into it
copy(buffer, d.remainder)
i = len(d.remainder)
for _, v := range tokens {
if v < nTokens {
copy(buffer[i:], reverse[v])
i += len(reverse[v])
}
}
if d.vocab.charset == 1 { // UTF-8
remaining := len(buffer) - incompleteUTF8Bytes(buffer)
d.remainder = buffer[remaining:]
buffer = buffer[:remaining]
} else { // UTF-16
remaining := len(buffer) - incompleteUTF16Bytes(buffer)
d.remainder = buffer[remaining:]
buffer = buffer[:remaining]
}
if d.vocab.usingCapcode == 2 {
buffer = d.capcodeDecoder.Decode(buffer)
} else if d.vocab.usingCapcode == 1 {
buffer = d.capcodeDecoder.NoCapcodeDecode(buffer)
}
return buffer
}
return nil
}
// Decodes tokens IDs back into bytes.
func (d *Decoder) Decode(tokens []uint32) []byte {
if d.vocab.charset == 0 {
return d.vocab.decode(tokens)
}
// Get the size
reverse := d.vocab.reverse
nTokens := uint32(len(reverse))
var i int = len(d.remainder)
for _, v := range tokens {
if v < nTokens {
i += len(reverse[v])
}
}
// Make the exact size array
data := make([]byte, i)
// Copy the keys into it
copy(data, d.remainder)
i = len(d.remainder)
for _, v := range tokens {
if v < nTokens {
copy(data[i:], reverse[v])
i += len(reverse[v])
}
}
if d.vocab.charset == 1 { // UTF-8
remaining := len(data) - incompleteUTF8Bytes(data)
d.remainder = data[remaining:]
data = data[:remaining]
} else { // UTF-16
remaining := len(data) - incompleteUTF16Bytes(data)
d.remainder = data[remaining:]
data = data[:remaining]
}
if d.vocab.usingCapcode == 2 {
data = d.capcodeDecoder.Decode(data)
} else if d.vocab.usingCapcode == 1 {
data = d.capcodeDecoder.NoCapcodeDecode(data)
}
return data
}
// Deserializes tokens encoded in a bytes stream into a slice of uint32 token IDs.
// `encodingLength` must be one of: 0, 2, 3, 4.
// If you enter `encodingLength` 0 then it will determine the encoding length from the vocabulary size.
func (d *Decoder) Deserialize(data []byte, encodingLength uint8) []uint32 {
return d.vocab.Deserialize(data, encodingLength)
}
func (vocab *Vocab) Deserialize(data []byte, encodingLength uint8) (tokens []uint32) {
if encodingLength == 0 {
if len(vocab.reverse) <= 65536 {
encodingLength = 2
} else {
encodingLength = 3
}
}
if encodingLength == 2 {
tokens = make([]uint32, len(data) / 2)
var l uint64 = uint64(len(data))
var i uint64
for ; i<l; i+=2 {
tokens[i >> 1] = uint32(data[i]) | (uint32(data[i+1]) << 8)
}
return
} else if encodingLength == 3 {
tokens = make([]uint32, len(data) / 3)
var l uint64 = uint64(len(data))
var i, on uint64
for ; i<l; i+=3 {
tokens[on] = uint32(data[i]) | (uint32(data[i+1]) << 8) | (uint32(data[i+2]) << 16)
on++
}
return
} else if encodingLength == 4 {
tokens = make([]uint32, len(data) / 4)
var l uint64 = uint64(len(data))
var i uint64
for ; i<l; i+=4 {
tokens[i >> 2] = uint32(data[i]) | (uint32(data[i+1]) << 8) | (uint32(data[i+2]) << 16) | (uint32(data[i+3]) << 24)
}
return
}
return
}
// Decodes tokens backs into bytes.
// If you are decoding a stream of tokens individually or in batches, instead of all at once, you should use the Decode method for the Decoder struct instead.
func (vocab *Vocab) Decode(tokens []uint32) []byte {
data := vocab.decode(tokens)
if vocab.usingCapcode == 2 {
return capcode.Decode(data)
} else if vocab.usingCapcode == 1 {
return capcode.NoCapcodeDecode(data)
}
return data
}
// Decodes tokens from a serialized bytes slice.
// `encodingLength` must be one of: 0, 2, 3, 4.
// If you enter `encodingLength` 0 then it will determine the encoding length from the vocabulary size.
// `buffer` is optional, you can send it `nil` and it will allocate a new slice.
// If you are decoding a stream of tokens individually or in batches, instead of all at once, you should use the Decode method for the Decoder struct instead.
func (vocab *Vocab) DecodeSerialized(b []byte, encodingLength uint8, buffer []byte) []byte {
data := vocab.decodeSerialized(b, encodingLength, buffer)
if vocab.usingCapcode == 2 {
return capcode.Decode(data)
} else if vocab.usingCapcode == 1 {
return capcode.NoCapcodeDecode(data)
}
return data
}
func (vocab *Vocab) decode(tokens []uint32) []byte {
// Get the size
reverse := vocab.reverse
nTokens := uint32(len(reverse))
var i int
for _, v := range tokens {
if v < nTokens {
i += len(reverse[v])
}
}
// Make the exact size array
data := make([]byte, i)
// Copy the keys into it
i = 0
for _, v := range tokens {
if v < nTokens {
copy(data[i:], reverse[v])
i += len(reverse[v])
}
}
return data
}
func (vocab *Vocab) decodeSerialized(b []byte, encodingLength uint8, buffer []byte) []byte {
reverse := vocab.reverse
if encodingLength <= 1 {
if len(reverse) <= 65536 {
encodingLength = 2
} else {
encodingLength = 3
}
}
if encodingLength == 2 {
var tokens []uint16
var l uint64 = uint64(len(b)) >> 1
if isLittleEndian {
tokens = (*(*[]uint16)(unsafe.Pointer(&b)))[:l:l] // interpret the serialized bytes as a slice of uint16
} else {
tokens = make([]uint16, l)
var to uint64 = uint64(len(b))
var i uint64
for ; i<to; i+=2 {
tokens[i >> 1] = uint16(b[i]) | (uint16(b[i+1]) << 8)
}
}
if len(reverse) == 0 {
return []byte{}
}
nTokens := uint16(len(reverse) - 1)
var i int
for _, v := range tokens {
if v <= nTokens {
i += len(reverse[v])
}
}
// Make the exact size array
if i > len(buffer) {
buffer = make([]byte, i)
} else {
buffer = buffer[0:i]
}
// Copy the keys into it
i = 0
for _, v := range tokens {
if v <= nTokens {
copy(buffer[i:], reverse[v])
i += len(reverse[v])
}
}
return buffer
} else if encodingLength == 3 {
var on uint64
var to uint64 = uint64(len(b))
var v uint32
nTokens := uint32(len(reverse))
var i int
for on=0; on<to; on+=3 {
v = uint32(b[on]) | (uint32(b[on+1]) << 8) | (uint32(b[on+2]) << 16)
if v < nTokens {
i += len(reverse[v])
}
}
// Make the exact size array
if i > len(buffer) {
buffer = make([]byte, i)
} else {
buffer = buffer[0:i]
}
// Copy the keys into it
i = 0
for on=0; on<to; on+=3 {
v = uint32(b[on]) | (uint32(b[on+1]) << 8) | (uint32(b[on+2]) << 16)
if v < nTokens {
copy(buffer[i:], reverse[v])
i += len(reverse[v])
}
}
return buffer
} else if encodingLength == 4 {
var tokens []uint32
var l uint64 = uint64(len(b)) >> 2
if isLittleEndian {
tokens = (*(*[]uint32)(unsafe.Pointer(&b)))[:l:l]
} else {
tokens = make([]uint32, l)
var to uint64 = uint64(len(b))
var i uint64
for ; i<to; i+=4 {
tokens[i >> 2] = uint32(b[i]) | (uint32(b[i+1]) << 8) | (uint32(b[i+2]) << 16) | (uint32(b[i+3]) << 24)
}
}
nTokens := uint32(len(reverse))
var i int
for _, v := range tokens {
if v < nTokens {
i += len(reverse[v])
}
}
// Make the exact size array
if i > len(buffer) {
buffer = make([]byte, i)
} else {
buffer = buffer[0:i]
}
// Copy the keys into it
i = 0
for _, v := range tokens {
if v < nTokens {
copy(buffer[i:], reverse[v])
i += len(reverse[v])
}
}
return buffer
}
return nil
}
// --------- TOKENIZE ---------
// Applies all normalizations to the bytes, including capcode and NFD.
func (vocab *Vocab) Normalize(data []byte) ([]byte, error) {
return normalize(data, vocab.usingCapcode, vocab.normalizer)
}
// Tokenizes text from bytes slice to token IDs.
// The 2nd returned value (int) is the number of characters for which there were no tokens and were replaced with Unk token.
func (vocab *Vocab) Tokenize(data []byte) ([]uint32, int, error) {
if vocab.maxTokenLength == 0 {
return []uint32{}, 0, nil
}
normalized, err := normalize(data, vocab.usingCapcode, vocab.normalizer)
if err != nil {
return nil, 0, err
}
return vocab.tokenize(normalized)
}
// Tokenizes but returns the number of tokens instead of the tokens.
func (vocab *Vocab) Count(data []byte) (int, int, error) {
if vocab.maxTokenLength == 0 {
return 0, 0, nil
}
normalized, err := normalize(data, vocab.usingCapcode, vocab.normalizer)
if err != nil {
return 0, 0, err
}
return vocab.tokenizeCount(normalized)
}
// Tokenizes directly into serialized bytes with either 16-bit, 24-bit or 32-bit encoded unsigned integers depending on the vocabulary size.
// Set encodingLength to 0 for it to be chosen automatically, or set `encodingLength` to 2, 3 or 4.
// The 2rd return value is the encodingLength that was used, and the 3rd is the number of characters for which there were no tokens.
// `buffer` is an optional reusable buffer, you can send nil.
func (vocab *Vocab) TokenizeToSerialized(data []byte, encodingLength uint8, buffer []byte) ([]byte, uint8, int, error) {
if vocab.maxTokenLength == 0 {
return []byte{}, 2, 0, nil
}
if encodingLength <= 1 {
if len(vocab.reverse) <= 65536 {
encodingLength = 2
} else {
encodingLength = 3
}
}
normalized, err := normalize(data, vocab.usingCapcode, vocab.normalizer)
if err != nil {
return nil, 0, 0, err
}