-
Notifications
You must be signed in to change notification settings - Fork 20
/
trainvocab.go
2274 lines (2160 loc) · 74.4 KB
/
trainvocab.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 main
import (
"os"
"log"
"fmt"
"time"
"flag"
"bytes"
"errors"
"regexp"
"unicode"
"reflect"
"strings"
"math/rand"
"io/ioutil"
"sync/atomic"
"unicode/utf8"
"unicode/utf16"
"path/filepath"
"encoding/json"
"encoding/binary"
"github.com/AlasdairF/Conv"
"github.com/AlasdairF/Custom"
"github.com/AlasdairF/Sort/Uint32Uint32"
"github.com/alasdairforsythe/norm"
"github.com/alasdairforsythe/branchless"
"github.com/alasdairforsythe/pansearch"
"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'
apostrophe = '\''
apostrophe2 = '’'
DOES_NOT_EXIST = 16777215
MAXINT = 9223372036854775807
)
var (
vocabSize int // common: 30000, 30522, 32000, 50265, 65535
workers int = 8
strips int = 100
percentage int = 15
midwayTarget int = 0
datasetFilename string
dictionaryFilename string
resultsDir string
keepTrying int = 1000
include256bytes bool
includeUTF8bytes bool
include128bytes bool
includeASCIIbytes bool
includeExtendedbytes bool
excludeOtherBytes bool
reserve uint8
usingCapcode uint8
charsetFlag uint8
level uint8
fast bool
specialTokensFilename string
dictionary2 string
hasSpecial bool
includeMissingBytes bool
normalizer norm.Normalizer
ungreedySuffixes = []string{"'s", "’s"}
ungreedySuffixesB [][]byte
specialMap map[string]bool
remainingTokens_atomic int64
)
type resultStruct struct {
testVocab *pansearch.Light
tokensInText int
tokensToRemove [][]byte
missing []byte
scores []uint32
usingFullDataset bool
workType uint8
}
type workStruct struct {
testVocab *pansearch.Light
workType uint8
fast bool
}
type bestStruct struct {
tokens int
filename string
}
type tokenInfo struct {
alt tokenOuter
}
type tokenOuter struct {
index uint32 // the index of the alternative token
index2 uint32 // the index of the 2nd alternative token
id uint32 // my ID
id1 uint32 // alternative ID
id2 uint32 // alternative 2 ID
length int // that token is this many bytes long
length2 int
data tokenInner
}
type tokenInner struct {
flag uint8
nWords uint8 // the number of word beginnings
}
// Channels that holds the various random dictionaries
var channelWork = make(chan workStruct, 2)
var channelResult = make(chan resultStruct, workers * 4)
var regx = regexp.MustCompile("^[0-9]+_[0-9]+\\.[a-zA-Z0-9]+$")
func flagRequired(name string, value interface{}) {
switch v := reflect.ValueOf(value); v.Kind() {
case reflect.String:
if v.String() == "" {
fmt.Fprintf(os.Stderr, "%s is required\n", name)
flag.Usage()
os.Exit(1)
}
case reflect.Int:
if v.Int() == 0 {
fmt.Fprintf(os.Stderr, "%s is required\n", name)
flag.Usage()
os.Exit(1)
}
}
}
func flagIsSet(flagName string) bool {
var set bool
flag.Visit(func(f *flag.Flag) {
if f.Name == flagName {
set = true
}
})
return set
}
func formatInt(v int) string {
return string(conv.FormatThousands(conv.Bytes(v), ','))
}
func hasSuffixPos(key []byte) int {
for _, suffix := range ungreedySuffixesB {
if bytes.HasSuffix(key, suffix) {
if len(suffix) < len(key) {
r := decodeLastRune(key[:len(key)-len(suffix)])
if isLetter(r) {
return len(key) - len(suffix)
}
}
}
}
return -1
}
func genUTF8bytes(list []bool) {
genASCIIbytes(list)
// 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) {
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) {
s := `£€©®™°%¢¥—–•‘’“”áéíóúýàèìòùâêîôûäëïöüñãõçåæœ`
if usingCapcode != 2 && !normalizer.SpecifiedLowercase() {
s += `ÁÉÍÓÚÝÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÑÃÕÇÅÆŒ`
}
s2, _ := normalizer.Normalize([]byte(s))
for _, b := range s2 {
list[b] = true
}
genASCIIbytes(list)
}
func gen128bytes(list []bool) {
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) {
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 mergeBytes(list [][]byte, new []byte) ([][]byte, int) {
var num int
for _, b1 := range new {
exists := false
for _, b2 := range list {
if b1 == b2[0] {
exists = true
break
}
}
if !exists {
list = append(list, []byte{byte(b1)})
num++
}
}
return list, num
}
func isLetter(r rune) 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) 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) bool {
return (usingCapcode == 1 && r == '\x7F') || (usingCapcode==2 && (r == 'C' || r == 'W' || r == 'D'))
}
func decodeRune(b []byte) (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) 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 runeError
}
}
func applyCapcode(data []byte) []byte {
if usingCapcode == 2 {
return capcode.Encode(data)
} else if usingCapcode == 1 {
return capcode.NoCapcodeEncode(data)
}
return data
}
func normalize(data []byte) []byte {
processed, err := normalizer.Normalize(data)
if err == nil {
return applyCapcode(processed)
} else { // if failed try it the other way around
if !normalizer.SpecifiedLowercase() {
processed = applyCapcode(data)
processed, err = normalizer.Normalize(processed)
if err != nil {
panic(err)
}
} else {
panic(err)
}
}
return processed
}
/*
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
}
func convertStringToUTF16WithNFDNormalization(s string) []byte {
s = norm.NFD.String(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 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 saveTokensToFile(filename string, data [][]byte, data2 [][]byte, data3 [][]byte, scores []uint32, datasize int, special [][]byte) error {
fi, err := os.Create(filename)
if err != nil {
return err
}
defer fi.Close()
w := custom.NewZlibWriter(fi)
defer w.Close()
w.WriteByte(usingCapcode)
w.WriteByte(charsetFlag)
w.WriteByte(normalizer.Flag)
w.WriteByte(level)
w.WriteByte(reserve)
w.WriteByte(0) // reserved
w.WriteByte(0) // reserved
w.WriteByte(0) // reserved
w.WriteUint64(uint64(len(data) + len(data2) + len(data3)))
for _, b := range data {
w.WriteBytes8(b)
}
for _, b := range data2 {
w.WriteBytes8(b)
}
for _, b := range data3 {
w.WriteBytes8(b)
}
if len(scores) > 0 {
var divider float64 = float64(datasize)
for _, v := range scores {
w.WriteFloat32(float32(float64(v) / divider))
}
if len(special) > 0 {
w.WriteUint32(uint32(len(special)))
for _, b := range special {
w.WriteBytes8(b)
}
}
}
return nil
}
func loadTokensFromFile(filename string) (uint8, uint8, uint8, uint8, uint8, [][]byte, error) {
fi, err := os.Open(filename)
if err != nil {
return 0, 0, 0, 0, 0, nil, err
}
defer fi.Close()
r := custom.NewZlibReader(fi)
_usingCapcode := r.ReadByte()
_charsetFlag := r.ReadByte()
_norm := r.ReadByte()
_level := r.ReadByte()
_reserve := r.ReadByte()
r.ReadByte()
r.ReadByte()
r.ReadByte()
l := int(r.ReadUint64())
data := make([][]byte, l)
for i:=0; i<l; i++ {
data[i] = r.ReadBytes8()
}
// Make sure we're at the end
if r.EOF() != nil { // it can be longer if it includes scores, so just do a quick sanity check
if _charsetFlag > 2 || _level > 5 || len(data[0]) > 40 || len(data[1]) > 40 || len(data[len(data)-1]) > 40 {
return 0, 0, 0, 0, 0, nil, errors.New(filename + ` not valid.`)
}
}
return _usingCapcode, _charsetFlag, _norm, _level, _reserve, data, nil
}
/*
Bitwise stuff:
Things that I need:
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
64 is special
128 is either all letters or no letters
beginByte
1 = letter
10 = anything else
12 = space >>2 & 1 == 1
>>3 means not a letter
*/
func worker(id int, datastrips [][]byte, filedata []byte) {
var i, i1, i2, i3, length, length1, length2, length3, length1b, length2b, length3b int
var score1, score2, score3, score1b, score2b, score3b, nWords, branchLength int
var index, index1, index2, index3, index1b, index2b, index3b, deleteToken uint32
var divider, remainingTokens, tokensInText, maxlen, lenData, maxlenWithSpace int
var run int = 1
var reachedMidway, hasDeleteToken bool
var found, found1, found2, found3, usingFullDataset bool
var firstRun bool = true
var data []byte
var dataList [][]byte
var tokenData, original tokenInfo
var first, second tokenInner
var forwardDelete, maxScore int
var nextByte uint8
keys := make([][]byte, vocabSize)
scores := make([]sortUint32Uint32.KeyVal, vocabSize)
lilbuf := make([]byte, 40)
lilbuf[0] = 32
lilbufOffset := 1
if charsetFlag == 2 {
lilbufOffset = 2
}
lilbufStart := lilbuf[lilbufOffset:]
for asset := range channelWork {
if firstRun {
log.Println(`Worker`, id, `starting run`, run)
firstRun = false
}
// Reset vars this round's total and scores
tokensInText = 0
missingList := []byte{}
for i, _ = range scores {
scores[i] = sortUint32Uint32.KeyVal{uint32(i), 0}
}
// Sanity check, this should never happen
if asset.testVocab.Len() != vocabSize {
panic(errors.New(`testVocab contains ` + conv.String(asset.testVocab.Len()) + ` not the target ` + conv.String(vocabSize)))
}
// We can add extra tokens beginning "D " for any token beginning with a letter or number
// Let's first assigned ID numbers
index = 0
idsmap := make(map[string]uint32)
var testVocab pansearch.Fast
if asset.testVocab.Reset() {
var token []byte
var r rune
var s, last string
add := string(capcode.DeleteToken) + " "
if usingCapcode == 1 {
add = string(capcode.NoCapcodeDeleteToken) + " "
}
for eof := false; !eof; {
token, eof = asset.testVocab.Next()
keys[index] = token
testVocab.Add(token)
s = string(token)
if s == last {
panic(errors.New(`Duplicate token detected in vocabulary: ` + s))
}
last = s
idsmap[s] = index
r, _ = decodeRune(token)
if usingCapcode != 0 && isAlphaNum(r) {
if hasSpecial {
if _, found = specialMap[s]; found {
specialMap[add + s] = true
}
}
s = add + s
if len(s) <= 40 {
testVocab.Add([]byte(s))
idsmap[s] = index
}
}
index++
}
}
testVocab.Build()
// Finish building the testVocab
maxlen = testVocab.LongestLength() // the longest token length in this testVocab
maxlenWithSpace = maxlen - lilbufOffset
// Loop through all tokens in the testVocab and try to find other tokens that have the same beginning, these are potential ungreedy alternatives
var charTable [256][4]uint32
vocabList := make([]tokenInfo, testVocab.Len())
if testVocab.Reset() {
var token, subword []byte
var on, hasSuffix, minAltSize int
var r, r2 rune
var n, n2 int
var s string
var priority1, priority2, nWords uint8
var onlyLetterSpace, onlyPunc, onlyNumberSpace bool
for eof := false; !eof; {
token, eof = testVocab.Next()
s = string(token)
index = idsmap[s]
tokenData = tokenInfo{alt:tokenOuter{index:DOES_NOT_EXIST, index2:DOES_NOT_EXIST, id:index}}
// Check for special tokens
if hasSpecial {
if _, found = specialMap[s]; found {
tokenData.alt.data.flag = 64
vocabList[on] = tokenData
on++
// special tokens aren't allowed to have tokenDatas
continue
}
}
priority1 = 0
priority2 = 0
nWords = 0
minAltSize = 1
onlyLetterSpace = false
onlyNumberSpace = false
onlyPunc = false
r, n = decodeRune(token)
r2, n2 = decodeRune(token[n:])
// Check beginning of token
if r == ' ' {
tokenData.alt.data.flag = 4
charTable[token[0]][0]++
if isAlphaNum(r2) {
nWords++
minAltSize = 2
}
} else if isLetter(r) {
tokenData.alt.data.flag = 2
charTable[token[0]][1]++
} else if isCapcode(r) {
if r == capcode.CharacterToken || r == capcode.WordToken {
tokenData.alt.data.flag = 4 // count as a space
}
tokenData.alt.data.flag |= 16 // begins on capcode
charTable[token[0]][3]++
} else if unicode.IsNumber(r) {
charTable[token[0]][2]++
} else {
charTable[token[0]][3]++
}
// Count words in token
if len(token) == 1 {
onlyPunc = true
} else {
if (r == ' ' || isLetter(r)) && isLetter(r2) {
onlyLetterSpace = true
} else if (r == ' ' || unicode.IsNumber(r)) && unicode.IsNumber(r2) {
onlyNumberSpace = true
} else if !isAlphaNum(r) && !isAlphaNum(r2) {
onlyPunc = true
}
for i = n + n2; i < len(token); i += n2 {
r = r2
n = n2
r2, n2 = decodeRune(token[i:])
if r == ' ' && isAlphaNum(r2) {
nWords++
}
if isLetter(r2) {
onlyPunc = false
onlyNumberSpace = false
} else if unicode.IsNumber(r2) {
onlyPunc = false
onlyLetterSpace = false
} else if r2 != ' ' {
onlyLetterSpace = false
onlyNumberSpace = false
}
}
}
tokenData.alt.data.nWords = nWords
// Now do some precalculations concerning the token
r = decodeLastRune(token)
if minAltSize == 2 && isLetter(r) && onlyLetterSpace { // only letters and full words
if nWords == 1 {
tokenData.alt.data.flag |= 32 // 1 word beginning space with only letters
}
}
if minAltSize == 2 && nWords <= 1 { // begins _A and more than 1 word
minAltSize = 1
}
if isCapcode(r) {
tokenData.alt.data.flag |= 8
}
// Check end of token
if isLetter(r) { // token ends with a letter
tokenData.alt.data.flag |= 1
}
if onlyLetterSpace || onlyPunc || onlyNumberSpace {
tokenData.alt.data.flag |= 128
}
hasSuffix = hasSuffixPos(token)
for length=len(token)-1; length>=minAltSize; length-- { // loop through all possible subwords that would also fit beneath this one
subword = token[:length] // the subword
if index, found = testVocab.Find(subword); found { // is this subword in the testVocab? (and not the same ID)
// anything | space_letter or space_number
if length <= len(token) - 2 {
if token[length] == ' ' {
r, _ = decodeRune(token[length+1:])
if isLetter(r) || unicode.IsNumber(r) { // space then letter or number
if priority1 < priority2 || (priority1 == priority2 && tokenData.alt.length <= tokenData.alt.length2) {
if priority1 < 10 {
tokenData.alt.index = index
tokenData.alt.length = length
priority1 = 10
}
} else {
if priority2 < 10 {
tokenData.alt.index2 = index
tokenData.alt.length2 = length
priority2 = 10
}
}
continue
}
}
}
r = decodeLastRune(subword) // last char in subtoken
r2, _ = decodeRune(token[length:]) // the next char
if usingCapcode == 0 {
switch {
case (!isLetter(r) && r != '_') && (isLetter(r2) || r2 == '_'):
fallthrough
case !unicode.IsNumber(r) && unicode.IsNumber(r2):
if priority1 < priority2 || (priority1 == priority2 && tokenData.alt.length <= tokenData.alt.length2) {
if priority1 < 9 {
tokenData.alt.index = index
tokenData.alt.length = length
priority1 = 9
}
} else {
if priority2 < 9 {
tokenData.alt.index2 = index
tokenData.alt.length2 = length
priority2 = 9
}
}
continue
}
}
switch {
// letter | non-letter
case (isLetter(r) || r == '_') && (!isLetter(r2) && r2 != '_'):
fallthrough
// number | non-number
case unicode.IsNumber(r) && !unicode.IsNumber(r2):
if priority1 < priority2 || (priority1 == priority2 && tokenData.alt.length <= tokenData.alt.length2) {
if priority1 < 9 {
tokenData.alt.index = index
tokenData.alt.length = length
priority1 = 9
}
} else {
if priority2 < 9 {
tokenData.alt.index2 = index
tokenData.alt.length2 = length
priority2 = 9
}
}
continue
// space | non-space
case unicode.IsSpace(r) && !unicode.IsSpace(r2):
if priority1 < priority2 || (priority1 == priority2 && tokenData.alt.length <= tokenData.alt.length2) {
if priority1 < 7 {
tokenData.alt.index = index
tokenData.alt.length = length
priority1 = 7
}
} else {
if priority2 < 7 {
tokenData.alt.index2 = index
tokenData.alt.length2 = length
priority2 = 7
}
}
continue
// non-space | space
case !unicode.IsSpace(r) && unicode.IsSpace(r2):
if priority1 < priority2 || (priority1 == priority2 && tokenData.alt.length <= tokenData.alt.length2) {
if priority1 < 8 {
tokenData.alt.index = index
tokenData.alt.length = length
priority1 = 8
}
} else {
if priority2 < 8 {
tokenData.alt.index2 = index
tokenData.alt.length2 = length
priority2 = 8
}
}
continue
// everything | capcode
case isCapcode(r2):
if priority1 < priority2 || (priority1 == priority2 && tokenData.alt.length <= tokenData.alt.length2) {
if priority1 < 9 {
tokenData.alt.index = index
tokenData.alt.length = length
priority1 = 9
}
} else {
if priority2 < 9 {
tokenData.alt.index2 = index
tokenData.alt.length2 = length
priority2 = 9
}
}
continue
}
// Suffix
if length == hasSuffix {
if priority1 < priority2 || (priority1 == priority2 && tokenData.alt.length <= tokenData.alt.length2) {
if priority1 < 8 {
tokenData.alt.index = index
tokenData.alt.length = length
priority1 = 8
}
} else {
if priority2 < 8 {
tokenData.alt.index2 = index
tokenData.alt.length2 = length
priority2 = 8
}
}
break
}
// Everything else
if priority1 < priority2 || (priority1 == priority2 && tokenData.alt.length <= tokenData.alt.length2) {
if priority1 < 1 {
tokenData.alt.index = index
tokenData.alt.length = length
priority1 = 1
}
} else {
if priority2 < 1 {
tokenData.alt.index2 = index
tokenData.alt.length2 = length
priority2 = 1
}
}
}
}
// tokenData now contains the index & length of the longest preferred subtoken of this token in the vocabulary
if tokenData.alt.length == 0 && tokenData.alt.length2 > 0 {
panic(errors.New(`Sanity check failed`))
}
// Make sure the first alternative is the better one
if tokenData.alt.length2 > 0 && (priority2 > priority1 || (priority2 == priority1 && tokenData.alt.length2 > tokenData.alt.length)) {
tokenData.alt.index, tokenData.alt.index2 = tokenData.alt.index2, tokenData.alt.index
tokenData.alt.length, tokenData.alt.length2 = tokenData.alt.length2, tokenData.alt.length
}
if tokenData.alt.length > 0 {
tokenData.alt.id1 = vocabList[tokenData.alt.index].alt.id
if tokenData.alt.length2 > 0 {
tokenData.alt.id2 = vocabList[tokenData.alt.index2].alt.id
}
}
vocabList[on] = tokenData
on++
}
}
// Build chartable
var beginByte [256]uint8
for i=0; i<256; i++ {
if charTable[i][1] > charTable[i][0] && charTable[i][1] > charTable[i][2] && charTable[i][1] > charTable[i][3] && charTable[i][1] > 2 {
beginByte[i] = 1 // it's a letter
} else if charTable[i][0] > charTable[i][1] && charTable[i][0] > charTable[i][2] && charTable[i][0] > charTable[i][3] && charTable[i][0] > 2 {
beginByte[i] = 4 + 8 // it's a space
} else if charTable[i][3] > charTable[i][0] && charTable[i][3] > charTable[i][1] && charTable[i][3] > charTable[i][2] && charTable[i][3] > 2 {
beginByte[i] = 2 + 8 // it's punctuation or capcode
}
}
// Find the deleteToken
hasDeleteToken = false
if usingCapcode == 2 {
if index, found = testVocab.Find([]byte{capcode.DeleteToken}); found {
deleteToken = index
hasDeleteToken = true
}
} else if usingCapcode == 1 {
if index, found = testVocab.Find([]byte{capcode.NoCapcodeDeleteToken}); found {
deleteToken = index
hasDeleteToken = true
}
}
// If midwayTarget has been reached, check the full dataset
if !reachedMidway {
remainingTokens = int(atomic.LoadInt64(&remainingTokens_atomic))
if remainingTokens <= midwayTarget {
reachedMidway = true
}
}
if !asset.fast && reachedMidway && asset.workType == 0 {
dataList = [][]byte{filedata}
usingFullDataset = true
} else {
dataList = datastrips
usingFullDataset = false
}
// Main tokenization loop
for _, data = range dataList {
// We increase the data length by 1 because we're always checking the next byte
lenData = len(data) // remember the true length
if cap(data) > len(data) { // this should be true because capcode copies it originally
data = data[0:len(data)+1]
} else {
data2 := make([]byte, len(data) + 1)
copy(data2, data)
data = data2
}
i = 0
for i < lenData {
if index, length, found = testVocab.LongestSubstring(data[ i : i + branchless.Min(lenData - i, maxlen) ]); found {
checkpoint:
original = vocabList[index]
i1 = i + length
// Skip checking alternatives if the longest first match is a single whole word of only letters: begins _A + ends A + next_is_space + 1word
if (i1 < lenData && (original.alt.data.flag & 32 == 0 || beginByte[data[i1]] != 12)) {
score1 = -1000000
score2 = -1000000
score3 = -1000000
score1b = -1000000
score2b = -1000000
score3b = -1000000
maxScore = -1000000
// First lookahead to the next token after me
index1, length1, found1 = testVocab.LongestSubstring(data[ i1 : i1 + branchless.Min(lenData - i1, maxlen) ])
if found1 {
nWords = int(original.alt.data.nWords) - forwardDelete
second = vocabList[index1].alt.data
nextByte = beginByte[data[i1 + length1]]
score1 = (( length + length1 + // the total length of the branch
int((original.alt.data.flag >> 7) + (second.flag >> 7)) + // 1 point for each token being either all letters or all punctuation
branchless.MaxZeroAnd(nWords - 1) + // 1 less than the number of word beginnings in the 1st token, min 0
branchless.MaxZeroAnd(int(second.nWords) - 1) + // 1 less than the number of word beginnings in the second token, min 0
int((second.flag >> 2) & 1) + // 1 if the second token begins with a space
int((nextByte >> 2) & 1) + // 1 if the next character after the 2nd token is a space
((nWords + int(second.nWords + (nextByte >> 3))) * 100)) - // 100x the number of whole words covered by this and next token
( (int(original.alt.data.flag & 1 & (second.flag >> 1)) * 103) + // Deduct 103 if the first and second token split a word
(int((original.alt.data.flag >> 3) & 1 & (second.flag >> 4)) * 100) + // Deduct 100 if it splits a capcode token
((int(second.flag & 1 & nextByte) * 3)) )) // Deduct 3 if the second token ends inside a word
maxScore = score1
// Check if we're in the middle of a word
if hasDeleteToken && second.flag & 2 != 0 && nextByte == 1 && second.nWords == 0 {
length1b = branchless.Min(lenData - i1, maxlenWithSpace)
copy(lilbufStart, data[ i1 : i1 + length1b ])
index1b, length1b, _ = testVocab.LongestSubstring(lilbuf[:length1b + lilbufOffset])
if length1b > length1 + 1 {
length1b -= lilbufOffset
second = vocabList[index1b].alt.data
nextByte = beginByte[data[i1 + length1b]]
score1b = (( length + length1b + // the total length of the branch
int((original.alt.data.flag >> 7) + (second.flag >> 7)) + // 1 point for each token being either all letters or all punctuation
branchless.MaxZeroAnd(nWords - 1) + // 1 less than the number of word beginnings in the 1st token, min 0
branchless.MaxZeroAnd(int(second.nWords) - 1) + // 1 less than the number of word beginnings in the second token, min 0
int((nextByte >> 2) & 1) + // 1 if the next character after the 2nd token is a space
((nWords + int(second.nWords + (nextByte >> 3))) * 100)) - // 100x the number of whole words covered by this and next token
( (int(original.alt.data.flag & 1) * 103) + // Deduct 103 if the first and second token split a word
(int((original.alt.data.flag >> 3) & 1 & (second.flag >> 4)) * 100) + // Deduct 100 if it splits a capcode token
((int(second.flag & 1 & nextByte) * 3)) + // Deduct 3 if the second token ends inside a word
1 )) // Deduct 1 for using an extra token
maxScore = branchless.Max(maxScore, score1b)
}
}
}
if original.alt.index != DOES_NOT_EXIST {
i2 = i + original.alt.length - forwardDelete
index2, length2, found2 = testVocab.LongestSubstring(data[ i2 : i2 + branchless.Min(lenData - i2, maxlen) ])
if found2 {
first = vocabList[original.alt.index].alt.data
nWords = int(first.nWords) - forwardDelete
second = vocabList[index2].alt.data
nextByte = beginByte[data[i2 + length2]]