-
Notifications
You must be signed in to change notification settings - Fork 0
/
predict.go
482 lines (448 loc) · 11.8 KB
/
predict.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
package main
import (
"cmp"
"fmt"
"slices"
"sync"
)
type rule struct {
Locations []int
Produce string
}
func (r rule) String() string {
return fmt.Sprintf("l=%v p=%v", r.Locations, r.Produce)
}
type prediction struct {
rules map[int]map[string]*rule
context []string
counts map[string]int
countOrder map[string]int
}
func predict(entries map[string]*prediction, first string, count int) []string {
regenerated := []string{first}
for i := 0; i < count-1; i++ {
prediction := entries[regenerated[i]]
next := prediction.predict(regenerated)
regenerated = append(regenerated, next)
}
return regenerated
}
func fromFile(meta *file) map[string]*prediction {
entries := map[string]*prediction{}
for i, word := range meta.Words {
entries[word] = &prediction{
rules: map[int]map[string]*rule{
0: map[string]*rule{
"": &rule{
Locations: meta.Locations[word],
},
},
},
context: meta.Words,
counts: meta.Count,
countOrder: meta.CountLookup,
}
update("%05.2f building prediction structures\r", float32(i)/float32(len(meta.Words))*100)
}
// this was never added
entries[""].rules[0][""].Locations = []int{0}
fmt.Println("inflating rules")
wg := &sync.WaitGroup{}
work := make(chan struct {
p *prediction
i int
})
for i := 0; i < 32; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for w := range work {
p := float32(w.i) / float32(len(meta.Unique)) * 100
w.p.inflateRules(p, update)
}
}()
}
for i, word := range meta.Unique {
//fmt.Printf("working on '%v'\n", word)
work <- struct {
p *prediction
i int
}{
p: entries[word],
i: i,
}
}
close(work)
wg.Wait()
// cover the very first empty token. its not part of the Unique list
entries[""].inflateRules(100, update)
return entries
}
func (p *prediction) match(prev []string) (map[int]map[string]*rule, bool) {
found := map[int]map[string]*rule{}
loc := len(prev) - 1
depth := []int{}
for d := range p.rules {
depth = append(depth, d)
}
slices.Sort(depth)
for i := 0; i < len(depth); i++ {
//for i := len(depth) - 1; i >= 0; i-- {
d := depth[i]
if d > len(prev) {
continue
}
rules := p.rules[d]
for expected, aRule := range rules {
if loc-d < 0 {
continue
}
if prev[loc-d] == expected {
frules, ok := found[d]
if !ok {
frules = map[string]*rule{}
found[d] = frules
}
frules[expected] = aRule
} else {
// check for partial matches
}
}
}
return found, len(found) != 0
}
func (p *prediction) subMatch(prev []string) int {
max := -1
loc := len(prev) - 1
for d, rules := range p.rules {
for _, aRule := range rules {
for i := 0; i <= d; i++ {
//fmt.Println("subMatch", prev[loc-i], prev[aRule.Location-i])
for _, location := range aRule.Locations {
if prev[loc-i] == prev[location-i] {
if max < i {
max = i
}
}
}
}
}
}
return max + 1
}
func (p *prediction) addToken(prev []string, produce string) bool {
loc := len(prev) - 1
matchRules, didMatch := p.match(prev)
//fmt.Println("checking for matching rules", matchRules, didMatch, prev)
if !didMatch {
minDepth := p.subMatch(prev)
//fmt.Printf("no rules match, longest submatch is %v for %v %v\n", minDepth, prev, produce)
rules, ok := p.rules[minDepth]
if !ok {
rules = map[string]*rule{}
p.rules[minDepth] = rules
}
if rules[prev[loc-minDepth]] != nil {
//fmt.Println(rules[prev[loc-minDepth]], prev[loc-minDepth], loc-minDepth)
panic("we can't overwrite a rule")
}
rules[prev[loc-minDepth]] = &rule{
Locations: []int{loc},
Produce: produce,
}
return true
}
// look for exact match
for _, rules := range matchRules {
for _, rule := range rules {
if rule.Produce == produce {
rule.Locations = append(rule.Locations, loc)
//fmt.Println("! rule already exists")
return false
}
}
}
// we have matches, but nothing producing our token
// we need to adjust the matching rules backwards, then check again
for d, rules := range matchRules {
for expect, aRule := range rules {
//fmt.Println("match ", d, expect, aRule)
delete(p.rules[d], expect)
newDepth := d + 1
newRules, ok := p.rules[newDepth]
if !ok {
newRules = map[string]*rule{}
p.rules[newDepth] = newRules
}
reinsert := map[int][]*rule{
newDepth: []*rule{
aRule,
},
}
for len(reinsert) != 0 {
next := map[int][]*rule{}
for newDepth, rules := range reinsert {
for _, aRule := range rules {
for _, location := range aRule.Locations {
newExpect := prev[location-newDepth]
otherRule, ok := newRules[newExpect]
if !ok {
//fmt.Println("created new rule", location)
newRules[newExpect] = &rule{
Locations: []int{location},
Produce: aRule.Produce,
}
continue
}
if otherRule.Produce != aRule.Produce {
continue
delete(newRules, newExpect)
fmt.Println("adjusting rules", otherRule.Produce, aRule.Produce)
for _, location := range otherRule.Locations {
next[newDepth+1] = append(next[newDepth+1], &rule{
Locations: []int{location},
Produce: prev[location-newDepth-1],
})
}
aRule.Produce = prev[location-newDepth-1]
next[newDepth+1] = append(next[newDepth+1], otherRule, aRule)
continue
}
//fmt.Println("joined with another rule", location)
otherRule.Locations = append(otherRule.Locations, location)
//fmt.Println("update", newDepth, newExpect, aRule)
}
}
}
reinsert = next
}
}
}
// wow! recursion!
return p.addToken(prev, produce)
}
func (p *prediction) predict(prev []string) string {
matchRules, found := p.match(prev)
if !found {
fmt.Println(prev, p.rules)
panic("unable to predict next token")
}
// double check that we only have one?
//fmt.Println("found", prev, matchRules)
keys := []int{}
for key := range matchRules {
keys = append(keys, key)
}
slices.Sort(keys)
for i := 0; i < len(keys); i++ {
//for i := len(keys) - 1; i >= 0; i-- {
key := keys[i]
rules := matchRules[key]
for _, aRule := range rules {
return aRule.Produce
}
}
panic("we should have had a rule match somewhere...")
}
func (p *prediction) addLocation(loc int) {
rules, found := p.rules[0]
if !found {
rules = map[string]*rule{}
p.rules[0] = rules
}
aRule, found := rules[""]
if !found {
aRule = &rule{}
rules[""] = aRule
}
aRule.Locations = append(aRule.Locations, loc)
}
func (p *prediction) inflateRules(percent float32, update func(string, ...interface{})) {
//fmt.Println("working on", p.context[p.rules[0][""].Locations[0]])
// pull the rules out of the first level
byExpect := map[string][]int{}
/*
// the largest producer group should stay at the 0 level, better encoding
// 523,441 <-before:after-> 480,800
mapping := map[string]int{}
max := 0
maxKey := ""
for _, location := range p.rules[0][""].Locations {
key := p.context[location+1]
mapping[key]++
count := mapping[key]
if count > max {
max = count
maxKey = key
}
}
// now add into the level 0 mapping
locations := []int{}
orig := p.rules[0][""]
newRule := &rule{
Produce: maxKey,
}
p.rules[0] = map[string]*rule{
p.context[orig.Locations[0]]: newRule,
}
for _, location := range orig.Locations {
key := p.context[location+1]
if key != maxKey {
locations = append(locations, location)
continue
}
newRule.Locations = append(newRule.Locations, location)
}
for _, location := range locations {
key := p.context[location-1]
byExpect[key] = append(byExpect[key], location)
}
*/
for _, location := range p.rules[0][""].Locations {
key := p.context[location]
byExpect[key] = append(byExpect[key], location)
}
for depth := 0; true; depth++ {
if len(byExpect) == 0 {
break
}
// we are going to be adding rules at this depth
p.rules[depth] = map[string]*rule{}
// stay is all locations that will be staying at this level
stay := map[string][]int{}
// collision is all locations that don't have a unique match
collision := map[string][]int{}
// we need to process the locations that have been
// sorted into what they are expecting to find
// to be processed in the same order every time
// so we sort the keys
keys := []string{}
for k := range byExpect {
keys = append(keys, k)
}
slices.SortFunc(keys, func(a, b string) int {
// we want larger groups first
la := len(byExpect[a])
lb := len(byExpect[b])
if la == lb {
// sorter tokens might be better?
// also try to do this with more common tokens
return cmp.Compare(b, a)
}
// pick the option with more that go towards the same token
return cmp.Compare(la, lb)
})
// skey is keys that will be skipped
skey := []string{}
// pkey is keys that will be processed
pkey := []string{}
for _, k := range keys {
// lets just peg everything against the most common tokens O_o, or the first 128 tokens
if p.countOrder[k] < 128 || k == "" {
pkey = append(pkey, k)
} else {
skey = append(skey, k)
}
/*
// lets peg every rule to a unique token
if p.counts[k] == 1 {
pkey = append(pkey, k)
} else {
skey = append(skey, k)
}
*/
}
// if nothing was a common token, just let one in
if len(pkey) == 0 {
pkey = []string{skey[0]}
skey = skey[1:]
}
// move all skipped keys down a level
for _, k := range skey {
locations := byExpect[k]
// all rules that have collisions need to be shifted down deeper
for _, location := range locations {
if location == depth {
// we need to swap
t := stay[k]
stay[k] = []int{location}
//fmt.Println("swapping", location, t)
// work on the swapped values
for _, location := range t {
key := p.context[location-depth-1]
collision[key] = append(collision[key], location)
}
continue
}
key := p.context[location-depth-1]
//fmt.Println("passing", k, key)
collision[key] = append(collision[key], location)
}
}
for _, k := range pkey {
v := byExpect[k]
skip := []int{}
values, ok := stay[k]
// if we don't have one picked,
// just grab the first one
if !ok {
//fmt.Println("grabbing", k)
stay[k] = append(stay[k], v[0])
v = v[1:]
values = stay[k]
} else {
//fmt.Println("already there", k)
}
// maybe filter to largest group?
outer:
for _, l := range v {
// ensure that what is being produced matches
if p.context[values[0]+1] == p.context[l+1] {
stay[k] = append(stay[k], l)
} else {
// two possible rules produce different tokens
// but expect the same one
//fmt.Println("rule collision", k, l)
skip = append(skip, v...)
skip = append(skip, stay[k]...)
slices.Sort(skip)
slices.Compact(skip)
delete(stay, k)
break outer
}
}
// all rules that have collisions need to be shifted down deeper
for _, location := range skip {
if location == depth {
// we need to swap
t := stay[k]
stay[k] = []int{location}
//fmt.Println("swapping", location, t)
// work on the swapped values
for _, location := range t {
key := p.context[location-depth-1]
collision[key] = append(collision[key], location)
}
continue
}
//fmt.Println("dropping down", location)
key := p.context[location-depth-1]
collision[key] = append(collision[key], location)
}
}
// add in rules that are staying at this depth
for expected, locations := range stay {
_, ok := p.rules[depth][expected]
if ok {
panic("there should be no rules at this depth or key yet")
}
//fmt.Println("add rule", depth, expected, locations, p.context[locations[0]+1])
// all these rules should produce the same token.
p.rules[depth][expected] = &rule{
Produce: p.context[locations[0]+1],
Locations: locations,
}
}
byExpect = collision
}
}