-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathmaia.ts
More file actions
327 lines (273 loc) · 9.52 KB
/
maia.ts
File metadata and controls
327 lines (273 loc) · 9.52 KB
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
import { MaiaStatus } from 'src/types'
import { InferenceSession, Tensor } from 'onnxruntime-web'
import { mirrorMove, preprocess, allPossibleMovesReversed } from './tensor'
import { MaiaModelStorage } from './storage'
interface MaiaOptions {
model: string
modelVersion: string
setStatus: (status: MaiaStatus) => void
setProgress: (progress: number) => void
setError: (error: string) => void
}
class Maia {
private model!: InferenceSession
private modelUrl: string
private modelVersion: string
private options: MaiaOptions
private storage: MaiaModelStorage
constructor(options: MaiaOptions) {
this.modelUrl = options.model
this.modelVersion = options.modelVersion
this.options = options
this.storage = new MaiaModelStorage()
this.initialize()
}
private async initialize() {
// Request persistent storage for better reliability
await this.storage.requestPersistentStorage()
console.log('Attempting to get model from IndexedDB...')
const buffer = await this.storage.getModel(this.modelUrl, this.modelVersion)
if (buffer) {
console.log('Model found in IndexedDB, initializing...')
try {
await this.initializeModel(buffer)
console.log('Model initialized successfully')
} catch (e) {
console.error('Failed to initialize model:', e)
this.options.setStatus('error')
}
} else {
console.log('Model not found in cache, will show download modal')
const storageInfo = await this.storage.getStorageInfo()
console.log('Maia cache status:', {
modelUrl: this.modelUrl,
userAgent: navigator.userAgent,
indexedDBSupported: storageInfo.supported,
storageEstimate: storageInfo.quota
? { quota: storageInfo.quota, usage: storageInfo.usage }
: 'not supported',
modelSize: storageInfo.modelSize,
modelTimestamp: storageInfo.modelTimestamp,
})
this.options.setStatus('no-cache')
}
}
public async downloadModel() {
const response = await fetch(this.modelUrl)
if (!response.ok) throw new Error('Failed to fetch model')
const reader = response.body?.getReader()
const contentLength = +(response.headers.get('Content-Length') ?? 0)
if (!reader) throw new Error('No response body')
const chunks: Uint8Array[] = []
let receivedLength = 0
let lastReportedProgress = 0
while (true) {
const { done, value } = await reader.read()
if (done) break
chunks.push(value)
receivedLength += value.length
const currentProgress = Math.floor((receivedLength / contentLength) * 100)
if (currentProgress >= lastReportedProgress + 10) {
this.options.setProgress(currentProgress)
lastReportedProgress = currentProgress
}
}
const buffer = new Uint8Array(receivedLength)
let position = 0
for (const chunk of chunks) {
buffer.set(chunk, position)
position += chunk.length
}
await this.storage.storeModel(this.modelUrl, this.modelVersion, buffer.buffer)
await this.initializeModel(buffer.buffer)
this.options.setStatus('ready')
}
public async getStorageInfo() {
return await this.storage.getStorageInfo()
}
public async clearStorage() {
return await this.storage.clearAllStorage()
}
public async initializeModel(buffer: ArrayBuffer) {
this.model = await InferenceSession.create(buffer)
this.options.setStatus('ready')
}
/**
* Evaluates a given chess position using the Maia model.
*
* @param board - The FEN string representing the chess position.
* @param eloSelf - The ELO rating of the player making the move.
* @param eloOppo - The ELO rating of the opponent.
* @returns A promise that resolves to an object containing the policy and value predictions.
*/
async evaluate(board: string, eloSelf: number, eloOppo: number) {
if (!this.model) {
throw new Error('Maia model not initialized')
}
const { boardInput, legalMoves, eloSelfCategory, eloOppoCategory } =
preprocess(board, eloSelf, eloOppo)
// Load and run the model
const feeds: Record<string, Tensor> = {
boards: new Tensor('float32', boardInput, [1, 18, 8, 8]),
elo_self: new Tensor(
'int64',
BigInt64Array.from([BigInt(eloSelfCategory)]),
),
elo_oppo: new Tensor(
'int64',
BigInt64Array.from([BigInt(eloOppoCategory)]),
),
}
const { logits_maia, logits_value } = await this.model.run(feeds)
const { policy, value } = processOutputs(
board,
logits_maia,
logits_value,
legalMoves,
)
return {
policy,
value,
}
}
/**
* Evaluates a batch of chess positions using the Maia model.
*
* @param boards - An array of FEN strings representing the chess positions.
* @param eloSelfs - An array of ELO ratings for the player making the move.
* @param eloOppos - An array of ELO ratings for the opponent.
* @returns A promise that resolves to an array of objects containing the policy and value predictions.
*/
async batchEvaluate(
boards: string[],
eloSelfs: number[],
eloOppos: number[],
) {
if (!this.model) {
throw new Error('Maia model not initialized')
}
const batchSize = boards.length
const boardInputs = []
const eloSelfCategories = []
const eloOppoCategories = []
const legalMoves = []
for (let i = 0; i < boards.length; i++) {
const {
boardInput,
legalMoves: legalMoves_,
eloSelfCategory,
eloOppoCategory,
} = preprocess(boards[i], eloSelfs[i], eloOppos[i])
boardInputs.push(boardInput)
eloSelfCategories.push(eloSelfCategory)
eloOppoCategories.push(eloOppoCategory)
legalMoves.push(legalMoves_)
}
const combinedBoardInputs = new Float32Array(batchSize * 18 * 8 * 8)
for (let i = 0; i < batchSize; i++) {
combinedBoardInputs.set(boardInputs[i], i * 18 * 8 * 8)
}
const feeds: Record<string, Tensor> = {
boards: new Tensor('float32', combinedBoardInputs, [batchSize, 18, 8, 8]),
elo_self: new Tensor(
'int64',
BigInt64Array.from(eloSelfCategories.map(BigInt)),
[batchSize],
),
elo_oppo: new Tensor(
'int64',
BigInt64Array.from(eloOppoCategories.map(BigInt)),
[batchSize],
),
}
const start = performance.now()
const { logits_maia, logits_value } = await this.model.run(feeds)
const end = performance.now()
const results = []
for (let i = 0; i < batchSize; i++) {
const logitsPerItem = logits_maia.size / batchSize
const startIdx = i * logitsPerItem
const endIdx = startIdx + logitsPerItem
const policyLogitsArray = logits_maia.data.slice(
startIdx,
endIdx,
) as Float32Array
const policyTensor = new Tensor('float32', policyLogitsArray, [
logitsPerItem,
])
const valueLogit = logits_value.data[i] as number
const valueTensor = new Tensor('float32', [valueLogit], [1])
const { policy, value: winProb } = processOutputs(
boards[i],
policyTensor,
valueTensor,
legalMoves[i],
)
results.push({ policy, value: winProb })
}
return {
result: results,
time: end - start,
}
}
}
/**
* Processes the outputs of the ONNX model to compute the policy and value.
*
* @param {string} fen - The FEN string representing the current board state.
* @param {ort.Tensor} logits_maia - The logits tensor for the policy output from the model.
* @param {ort.Tensor} logits_value - The logits tensor for the value output from the model.
* @param {Float32Array} legalMoves - An array indicating the legal moves.
* @returns {{ policy: Record<string, number>, value: number }} An object containing the policy (move probabilities) and the value (win probability).
*/
function processOutputs(
fen: string,
logits_maia: Tensor,
logits_value: Tensor,
legalMoves: Float32Array,
) {
const logits = logits_maia.data as Float32Array
const value = logits_value.data as Float32Array
let winProb = Math.min(Math.max((value[0] as number) / 2 + 0.5, 0), 1)
let black_flag = false
if (fen.split(' ')[1] === 'b') {
black_flag = true
winProb = 1 - winProb
}
winProb = Math.round(winProb * 10000) / 10000
// Get indices of legal moves
const legalMoveIndices = legalMoves
.map((value, index) => (value > 0 ? index : -1))
.filter((index) => index !== -1)
const legalMovesMirrored = []
for (const moveIndex of legalMoveIndices) {
let move = allPossibleMovesReversed[moveIndex]
if (black_flag) {
move = mirrorMove(move)
}
legalMovesMirrored.push(move)
}
// Extract logits for legal moves
const legalLogits = legalMoveIndices.map((idx) => logits[idx])
// Compute softmax over the legal logits
const maxLogit = Math.max(...legalLogits)
const expLogits = legalLogits.map((logit) => Math.exp(logit - maxLogit))
const sumExp = expLogits.reduce((a, b) => a + b, 0)
const probs = expLogits.map((expLogit) => expLogit / sumExp)
// Map the probabilities back to their move indices
const moveProbs: Record<string, number> = {}
for (let i = 0; i < legalMoveIndices.length; i++) {
moveProbs[legalMovesMirrored[i]] = probs[i]
}
const sortedMoveProbs = Object.keys(moveProbs)
.sort((a, b) => moveProbs[b] - moveProbs[a])
.reduce(
(acc, key) => {
acc[key] = moveProbs[key]
return acc
},
{} as Record<string, number>,
)
return { policy: sortedMoveProbs, value: winProb }
}
export default Maia