-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathuseEngineAnalysis.ts
More file actions
288 lines (247 loc) · 8.41 KB
/
useEngineAnalysis.ts
File metadata and controls
288 lines (247 loc) · 8.41 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
import { Chess } from 'chess.ts'
import { fetchOpeningBookMoves } from 'src/api'
import { useEffect, useContext, useRef, useState } from 'react'
import { MAIA_MODELS, MAIA_RATINGS } from 'src/constants/common'
import {
STOCKFISH_DEBUG_RERUN_EVENT,
STOCKFISH_DEBUG_RERUN_KEY,
} from 'src/constants/analysis'
import { GameNode, MaiaEvaluation } from 'src/types'
import { MaiaEngineContext, StockfishEngineContext } from 'src/contexts'
export const useEngineAnalysis = (
currentNode: GameNode | null,
inProgressAnalyses: Set<string>,
currentMaiaModel: string,
setAnalysisState: React.Dispatch<React.SetStateAction<number>>,
targetDepth = 18,
enabled = true,
) => {
const maia = useContext(MaiaEngineContext)
const stockfish = useContext(StockfishEngineContext)
const [stockfishDebugRerunToken, setStockfishDebugRerunToken] = useState(0)
const lastConsumedStockfishRerunTokenRef = useRef(0)
const readRerunTokenFromStorage = () => {
if (typeof window === 'undefined') return 0
const raw = window.localStorage.getItem(STOCKFISH_DEBUG_RERUN_KEY)
const parsed = raw ? Number.parseInt(raw, 10) : 0
return Number.isFinite(parsed) ? parsed : 0
}
useEffect(() => {
if (typeof window === 'undefined') return
const onDebugRerun = () => {
const token = readRerunTokenFromStorage() || Date.now()
setStockfishDebugRerunToken(token)
}
setStockfishDebugRerunToken(readRerunTokenFromStorage())
window.addEventListener(STOCKFISH_DEBUG_RERUN_EVENT, onDebugRerun)
const intervalId = window.setInterval(() => {
const token = readRerunTokenFromStorage()
setStockfishDebugRerunToken((prev) => (token > prev ? token : prev))
}, 500)
return () => {
window.removeEventListener(STOCKFISH_DEBUG_RERUN_EVENT, onDebugRerun)
window.clearInterval(intervalId)
}
}, [])
async function inferenceMaiaModel(board: Chess): Promise<{
[key: string]: MaiaEvaluation
}> {
if (!maia.maia) {
throw new Error('Maia engine not initialized')
}
const { result } = await maia.maia.batchEvaluateMaia3(
Array(MAIA_RATINGS.length).fill(board.fen()),
MAIA_RATINGS,
MAIA_RATINGS,
)
const maiaEvaluations: { [key: string]: MaiaEvaluation } = {}
MAIA_MODELS.forEach((model, index) => {
maiaEvaluations[model] = result[index]
})
return maiaEvaluations
}
async function fetchOpeningBook(board: Chess) {
const bookMoves = await fetchOpeningBookMoves(board.fen())
return bookMoves
}
useEffect(() => {
if (!currentNode || !enabled) return
const board = new Chess(currentNode.fen)
const nodeFen = currentNode.fen
const attemptMaiaAnalysis = async () => {
const hasSelectedModelAnalysis =
!!currentNode?.analysis.maia?.[currentMaiaModel]
if (
!currentNode ||
hasSelectedModelAnalysis ||
inProgressAnalyses.has(nodeFen)
)
return
// Add retry logic for Maia initialization
let retries = 0
const maxRetries = 30 // 3 seconds with 100ms intervals
while (retries < maxRetries && maia.status !== 'ready') {
await new Promise((resolve) => setTimeout(resolve, 100))
retries++
}
if (maia.status !== 'ready') {
console.warn('Maia not ready after waiting, skipping analysis')
return
}
inProgressAnalyses.add(nodeFen)
try {
if (currentNode.moveNumber <= 5) {
const [openingBookMoves, maiaEvaluations] = await Promise.all([
fetchOpeningBook(board),
inferenceMaiaModel(board),
])
const analysis: { [key: string]: MaiaEvaluation } = {}
for (const model of MAIA_MODELS) {
const policySource = Object.keys(openingBookMoves[model] || {})
.length
? openingBookMoves[model]
: maiaEvaluations[model].policy
const sortedPolicy = Object.entries(policySource).sort(
([, a], [, b]) => (b as number) - (a as number),
)
analysis[model] = {
value: maiaEvaluations[model].value,
policy: Object.fromEntries(
sortedPolicy,
) as MaiaEvaluation['policy'],
}
}
currentNode.addMaiaAnalysis(analysis, currentMaiaModel)
setAnalysisState((state) => state + 1)
return
} else {
const maiaEvaluations = await inferenceMaiaModel(board)
currentNode.addMaiaAnalysis(maiaEvaluations, currentMaiaModel)
setAnalysisState((state) => state + 1)
}
} finally {
inProgressAnalyses.delete(nodeFen)
}
}
// Delay Maia analysis to prevent rapid fire when moving quickly
const timeoutId = setTimeout(() => {
attemptMaiaAnalysis()
}, 100)
return () => {
clearTimeout(timeoutId)
}
}, [
maia.status,
currentNode,
currentMaiaModel,
inProgressAnalyses,
maia,
setAnalysisState,
enabled,
])
useEffect(() => {
if (!currentNode || !enabled) return
const shouldForceStockfishRerun =
stockfishDebugRerunToken > lastConsumedStockfishRerunTokenRef.current
if (shouldForceStockfishRerun) {
lastConsumedStockfishRerunTokenRef.current = stockfishDebugRerunToken
}
if (
currentNode.analysis.stockfish &&
currentNode.analysis.stockfish?.depth >= targetDepth &&
!shouldForceStockfishRerun
)
return
let cancelled = false
// Add retry logic for Stockfish initialization
const attemptStockfishAnalysis = async () => {
// Wait longer for Stockfish to be ready on first load / slower devices.
let retries = 0
const maxRetries = 120 // 12 seconds with 100ms intervals
while (retries < maxRetries && !stockfish.isReady() && !cancelled) {
await new Promise((resolve) => setTimeout(resolve, 100))
retries++
}
if (cancelled || !stockfish.isReady()) {
if (!cancelled && stockfish.status === 'error') {
console.warn('Stockfish not ready after waiting, skipping analysis')
}
return
}
const chess = new Chess(currentNode.fen)
const legalMoves = new Set(
chess
.moves({ verbose: true })
.map((move) => `${move.from}${move.to}${move.promotion || ''}`),
)
const maiaPolicy = currentNode.analysis.maia?.[currentMaiaModel]?.policy
const maiaCandidateMoves: string[] = []
const playedMove = currentNode.mainChild?.move
const forcedCandidateMoves =
playedMove && legalMoves.has(playedMove) ? [playedMove] : []
if (maiaPolicy) {
let cumulative = 0
const sortedMaiaMoves = Object.entries(maiaPolicy)
.filter(([, prob]) => Number.isFinite(prob) && prob > 0)
.sort(([, a], [, b]) => b - a)
for (const [move, prob] of sortedMaiaMoves) {
if (!legalMoves.has(move)) continue
maiaCandidateMoves.push(move)
cumulative += prob
if (cumulative >= 0.95) {
break
}
}
}
const evaluationStream = stockfish.streamEvaluations(
chess.fen(),
chess.moves().length,
targetDepth,
{
maiaCandidateMoves,
forcedCandidateMoves,
maiaPolicy,
},
)
if (evaluationStream && !cancelled) {
const nodeForAnalysis = currentNode // Capture the node reference
try {
for await (const evaluation of evaluationStream) {
if (
cancelled ||
!nodeForAnalysis ||
nodeForAnalysis !== currentNode
) {
break
}
nodeForAnalysis.addStockfishAnalysis(evaluation, currentMaiaModel)
setAnalysisState((state) => state + 1)
}
} catch (error) {
if (!cancelled) {
console.error('Stockfish evaluation error:', error)
}
}
}
}
// Delay Stockfish analysis to prevent rapid fire when moving quickly
const timeoutId = setTimeout(() => {
if (cancelled) return
attemptStockfishAnalysis()
}, 100)
return () => {
cancelled = true
clearTimeout(timeoutId)
}
}, [
currentNode,
stockfish,
currentMaiaModel,
setAnalysisState,
targetDepth,
stockfishDebugRerunToken,
currentNode?.analysis.maia?.[currentMaiaModel]?.policy,
currentNode?.mainChild?.move,
enabled,
])
}