-
Notifications
You must be signed in to change notification settings - Fork 9
/
transposition_table.go
252 lines (213 loc) · 6 KB
/
transposition_table.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
package negamax
import (
"fmt"
"math"
"os"
"runtime"
"runtime/debug"
"sync"
"sync/atomic"
"github.com/domino14/macondo/tinymove"
"github.com/domino14/macondo/zobrist"
"github.com/pbnjay/memory"
"github.com/rs/zerolog/log"
)
const (
TTExact = 0x01
TTLower = 0x02
TTUpper = 0x03
)
const entrySize = 16
const bottom3ByteMask = (1 << 24) - 1
const depthMask = (1 << 6) - 1
const (
mutexStripeSize = 1024
mutexStripeMask = mutexStripeSize - 1
)
// 16 bytes (entrySize)
type TableEntry struct {
// Don't store the full hash, but the top 5 bytes. The bottom 3 bytes
// can be determined from the bucket in the array.
top4bytes uint32
score int16
fifthbyte uint8
flagAndDepth uint8
play tinymove.TinyMove
}
// fullHash calculates the full 64-bit hash for this table entry, given the bottom
// bytes in zval.
func (t TableEntry) fullHash(idx uint64) uint64 {
return uint64(t.top4bytes)<<32 + uint64(t.fifthbyte)<<24 + (idx & bottom3ByteMask)
}
func (t TableEntry) flag() uint8 {
return t.flagAndDepth >> 6
}
func (t TableEntry) depth() uint8 {
return t.flagAndDepth & depthMask
}
func (t TableEntry) valid() bool {
// a table flag is 1, 2, or 3.
return t.flag() != 0
}
func (t TableEntry) move() tinymove.TinyMove {
return t.play
}
type TableLock interface {
Lock()
Unlock()
RLock()
RUnlock()
}
type FakeLock struct{}
func (f FakeLock) Lock() {}
func (f FakeLock) Unlock() {}
func (f FakeLock) RLock() {}
func (f FakeLock) RUnlock() {}
type TranspositionTable struct {
locks [mutexStripeSize]TableLock
table []TableEntry
created atomic.Uint64
lookups atomic.Uint64
hits atomic.Uint64
sizePowerOf2 int
sizeMask uint64
// "type 2" collisions. A type 2 collision happens when two positions share
// the same lower bytes. A type 1 collision happens when two positions share the
// same overall hash. We don't have a super easy way to detect the latter,
// but it should be much less common.
t2collisions atomic.Uint64
zobrist *zobrist.Zobrist
}
// GlobalTranspositionTable is a singleton instance. Since transposition tables
// take up a large enough amount of memory, and they're meant to be shared,
// we only really want to keep one in memory to avoid re-allocation costs.
var GlobalTranspositionTable = &TranspositionTable{}
func (t *TranspositionTable) SetSingleThreadedMode() {
for i := range mutexStripeSize {
t.locks[i] = &FakeLock{}
}
}
func (t *TranspositionTable) SetMultiThreadedMode() {
for i := range mutexStripeSize {
t.locks[i] = new(sync.RWMutex)
// t.locks[i] = &FakeLock{}
}
}
func (t *TranspositionTable) lookup(zval uint64) TableEntry {
t.lookups.Add(1)
idx := zval & t.sizeMask
t.locks[zval&mutexStripeMask].RLock()
defer t.locks[zval&mutexStripeMask].RUnlock()
fullHash := t.table[idx].fullHash(idx)
if fullHash != zval {
if t.table[idx].valid() {
// There is another unrelated node at this position.
t.t2collisions.Add(1)
}
return TableEntry{}
}
t.hits.Add(1)
// otherwise, assume the same zobrist hash is the same position. this fails
// very, very rarely. but it could happen.
return t.table[idx]
}
func (t *TranspositionTable) store(zval uint64, tentry TableEntry) {
idx := zval & t.sizeMask
tentry.top4bytes = uint32(zval >> 32)
tentry.fifthbyte = uint8(zval >> 24)
t.created.Add(1)
t.locks[zval&mutexStripeMask].Lock()
defer t.locks[zval&mutexStripeMask].Unlock()
// just overwrite whatever is there for now.
t.table[idx] = tentry
}
func (t *TranspositionTable) Reset(fractionOfMemory float64, boardDim int) {
// Get memory limit, if set.
memLimit := debug.SetMemoryLimit(-1)
totalMem := memory.TotalMemory()
if memLimit != math.MaxInt64 {
// Let's obey the set value as the memory limit.
totalMem = uint64(memLimit)
}
desiredNElems := fractionOfMemory * (float64(totalMem) / float64(entrySize))
// find biggest power of 2 lower than desired.
t.sizePowerOf2 = int(math.Log2(desiredNElems))
// Guarantee at least 2^24 elements in the table. Anything less and our
// 5-byte full hash proxy won't work.
if t.sizePowerOf2 < 24 {
t.sizePowerOf2 = 24
}
numElems := 1 << t.sizePowerOf2
t.sizeMask = uint64(numElems - 1)
reset := false
if t.table != nil && len(t.table) == numElems {
reset = true
clear(t.table)
} else {
t.table = make([]TableEntry, numElems)
}
if t.zobrist == nil || t.zobrist.BoardDim() != boardDim {
log.Info().Msg("creating zobrist hash")
t.zobrist = &zobrist.Zobrist{}
t.zobrist.Initialize(boardDim)
zd, err := os.Create("/tmp/macondo-zobrist-dump")
if err != nil {
log.Err(err).Msg("could not dump zobrist hashes to file")
} else {
t.zobrist.Dump(zd)
zd.Close()
}
}
log.Info().Int("num-elems", numElems).
Float64("desired-num-elems", desiredNElems).
Int("estimated-total-memory-bytes", numElems*entrySize).
Uint64("mem-limit", totalMem).
Bool("reset", reset).
Msg("transposition-table-size")
t.created.Store(0)
t.lookups.Store(0)
t.hits.Store(0)
t.t2collisions.Store(0)
}
func (t *TranspositionTable) Zobrist() *zobrist.Zobrist {
return t.zobrist
}
func (t *TranspositionTable) SetZobrist(z *zobrist.Zobrist) {
t.zobrist = z
}
func (t *TranspositionTable) Stats() string {
return fmt.Sprintf("created: %d lookups: %d hits: %d t2collisions: %d",
t.created.Load(), t.lookups.Load(), t.hits.Load(), t.t2collisions.Load())
}
// a debug tt
type DebugTableEntry struct {
score float32
flag uint8
depth uint8
}
type DebugTranspositionTable struct {
table map[string]*DebugTableEntry
created uint64
lookups uint64
hits uint64
}
func (t *DebugTranspositionTable) lookup(cgp string) *DebugTableEntry {
t.lookups++
entry := t.table[cgp]
if entry != nil {
t.hits++
}
return entry
}
func (t *DebugTranspositionTable) store(cgp string, tentry DebugTableEntry) {
// just overwrite whatever is there for now.
t.table[cgp] = &tentry
t.created++
}
func (t *DebugTranspositionTable) reset() {
t.table = nil
runtime.GC() // ?
t.table = make(map[string]*DebugTableEntry)
t.created = 0
log.Info().Msg("allocated-debug-transposition-table")
}