Spaces:
Running on Zero

File size: 29,692 Bytes
88cc578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/*
 * NextBoard move generation in JavaScript: a port of the Space's Python path
 * (engine.py, samplers.confidence_sampler, chess_boards.py, illegal_moves.py).
 *
 * The model generates the whole next board. Chess rules are used only afterwards, to decide
 * whether that board is a legal move and so whether to sample again. Nothing here scores,
 * filters or picks moves.
 *
 * The model itself is passed in as `denoise(ids, t)`: Int32Array [context] and a number in,
 * Float32Array [64 * vocab] of log-probabilities out (what samplers.Denoiser returns).
 * Used by index.html (browser), and by the Node tests with onnxruntime-node.
 *
 * Boards are 64 tokens, index 0 = a8, 1 = b8, ..., 63 = h1, as in chess_boards.py.
 */
(function (root, factory) {
    if (typeof module === 'object' && module.exports) module.exports = factory();
    else root.NB = factory();
})(typeof self !== 'undefined' ? self : this, function () {
    'use strict';

    const N_SQ = 64;
    const START_TEMPERATURE = 0.1, MIN_TEMPERATURE = 0.1, MAX_TEMPERATURE = 1.5;
    const PLAN = new Array(64).fill(1);   // squares revealed per model call (engine.PLAN)
    const PIECE_RE = /^<([pnbrqk])([wb])>/;   // chess_boards._PIECE_PATTERN (re.match: anchored at the start)
    const PIECE_TOKENS = new Set(['<.>']);
    for (const p of 'pnbrqk') for (const c of 'wb') PIECE_TOKENS.add(`<${p}${c}>`);
    const FILES = 'abcdefgh';

    // ------------------------------------------------------------------------------------
    // tokenizer (tokenizer.json: WordLevel vocabulary, split on whitespace) and the prompt
    // ------------------------------------------------------------------------------------
    function makeTokenizer(json) {
        const model = json.model || {};
        const pre = json.pre_tokenizer && json.pre_tokenizer.type;
        if (model.type !== 'WordLevel' || pre !== 'WhitespaceSplit' || json.normalizer || json.post_processor) {
            throw new Error('Unsupported tokenizer.json (expected WordLevel with WhitespaceSplit)');
        }
        const vocab = new Map(Object.entries(model.vocab));
        const idToToken = [];
        for (const [token, id] of vocab) idToToken[id] = token;
        const unkId = vocab.get(model.unk_token);
        const need = name => {
            if (!vocab.has(name)) throw new Error(`tokenizer.json has no ${name} token`);
            return vocab.get(name);
        };
        return {
            vocab, idToToken, unkId,
            maskId: need('[MASK]'), padId: need('[PAD]'),
            vocabSize: idToToken.length,
            encode(text) {
                return text.split(/\s+/).filter(Boolean).map(w => (vocab.has(w) ? vocab.get(w) : unkId));
            },
        };
    }

    // engine.build_prompt_string: <ply> <result> <64 board tokens> per board, then <ply> <result>.
    function buildPromptString(history, outcome) {
        if (outcome) outcome = outcome.toLowerCase();
        const parts = [];
        history.forEach((board, i) => {
            parts.push(`<${i}>`, outcome);
            for (const t of board) parts.push(t);
        });
        parts.push(`<${history.length}>`, outcome);
        return parts.join(' ');
    }

    // engine.build_input_tensor: the last boards of the game, then 64 masked squares.
    function buildInputIds(tokenizer, contextSize, history, outcome) {
        let ids = tokenizer.encode(buildPromptString(history, outcome));
        for (let i = 0; i < N_SQ; i++) ids.push(tokenizer.maskId);
        ids = ids.slice(-contextSize);
        const out = new Int32Array(contextSize).fill(tokenizer.padId);
        out.set(ids, contextSize - ids.length);
        return out;
    }

    // ------------------------------------------------------------------------------------
    // sampler: samplers.confidence_sampler(order='maxprob', t_mode='sync') and sample_tokens
    // ------------------------------------------------------------------------------------
    // One token from softmax(logp / temp) (top_p = 1). temp <= 0: the most likely token.
    function sampleToken(logp, offset, vocabSize, maskId, temp, rng) {
        let best = -1, bestValue = -Infinity;
        for (let v = 0; v < vocabSize; v++) {
            if (v === maskId) continue;   // [MASK] is -inf by construction (SUBS)
            const value = logp[offset + v];
            if (value > bestValue) { bestValue = value; best = v; }
        }
        if (!(temp > 0)) return best;
        // exp((logp - max) / temp) is softmax(logp / temp) up to a constant factor.
        const weights = new Float64Array(vocabSize);
        let total = 0;
        for (let v = 0; v < vocabSize; v++) {
            if (v === maskId) continue;
            const w = Math.exp((logp[offset + v] - bestValue) / temp);
            weights[v] = w;
            total += w;
        }
        let u = rng() * total;
        for (let v = 0; v < vocabSize; v++) {
            u -= weights[v];
            if (u < 0 && weights[v] > 0) return v;
        }
        return best;   // rounding at the very end of the range
    }

    function tFromMasked(masked) { return Math.fround(Math.pow(masked / N_SQ, 1 / 3)); }

    /*
     * ids: Int32Array, the model input; its last 64 entries (all [MASK]) are filled in place.
     * Each step: one model call, then the `k` masked squares with the highest top probability
     * each get a token sampled from their own distribution.
     * onStep(step, t, boardIds) is called before each model call, like `trace` in Python.
     */
    async function confidenceSampler({ denoise, ids, maskId, vocabSize, temp, plan = PLAN, rng = Math.random, onStep }) {
        const start = ids.length - N_SQ;
        for (let step = 0; step < plan.length; step++) {
            const masked = [];
            for (let s = 0; s < N_SQ; s++) if (ids[start + s] === maskId) masked.push(s);
            if (!masked.length) break;
            const t = tFromMasked(masked.length);
            if (onStep) await onStep(step, t, ids.slice(start));
            const logp = await denoise(ids, t);
            if (logp.length !== N_SQ * vocabSize) throw new Error('Unexpected model output size');
            const scored = masked.map(s => {
                let top = -Infinity;
                const offset = s * vocabSize;
                for (let v = 0; v < vocabSize; v++) {
                    if (v !== maskId && logp[offset + v] > top) top = logp[offset + v];
                }
                return [top, s];
            });
            scored.sort((a, b) => (b[0] - a[0]) || (a[1] - b[1]));
            const k = Math.min(plan[step], masked.length);
            const chosen = scored.slice(0, k).map(x => x[1]);
            const tokens = chosen.map(s => sampleToken(logp, s * vocabSize, vocabSize, maskId, temp, rng));
            chosen.forEach((s, i) => { ids[start + s] = tokens[i]; });
        }
        return ids.slice(start);
    }

    // ------------------------------------------------------------------------------------
    // boards and legality with chess.js (chess_boards.py)
    // ------------------------------------------------------------------------------------
    // 64 tokens -> 64 piece letters (FEN style: upper case white) or null. Anything that is
    // not a piece token counts as an empty square, as in chess_boards.tokens_to_board.
    function tokensToPieces(tokens) {
        const out = new Array(N_SQ).fill(null);
        for (let i = 0; i < N_SQ && i < tokens.length; i++) {
            const m = PIECE_RE.exec(tokens[i] || '');
            if (m) out[i] = m[2] === 'w' ? m[1].toUpperCase() : m[1];
        }
        return out;
    }

    function piecesToPlacement(pieces) {
        const rows = [];
        for (let r = 0; r < 8; r++) {
            let row = '', empty = 0;
            for (let f = 0; f < 8; f++) {
                const p = pieces[r * 8 + f];
                if (!p) { empty++; continue; }
                if (empty) { row += empty; empty = 0; }
                row += p;
            }
            rows.push(row + (empty || ''));
        }
        return rows.join('/');
    }

    function placementOf(game) { return game.fen().split(' ')[0]; }

    function gameToTokens(game) {
        const tokens = [];
        for (const row of game.board()) for (const p of row) tokens.push(p ? `<${p.type}${p.color}>` : '<.>');
        return tokens;
    }

    // chess_boards.get_validated_move: the legal move after which the board equals the
    // generated one, as UCI text, or null. `game` is a chess.js game and is left unchanged.
    function getValidatedMove(game, tokens) {
        if (!game || !tokens) return null;
        const target = piecesToPlacement(tokensToPieces(tokens));
        for (const m of game.moves({ verbose: true })) {
            game.move({ from: m.from, to: m.to, promotion: m.promotion });
            const same = placementOf(game) === target;
            game.undo();
            if (same) return m.from + m.to + (m.promotion || '');
        }
        return null;
    }

    // chess_boards.board_from_last_position: best effort when the history cannot be replayed.
    function boardFromLastPosition(Chess, history) {
        const pieces = tokensToPieces(history[history.length - 1]);
        const turn = (history.length - 1) % 2 === 0 ? 'w' : 'b';
        let rights = '';
        if (pieces[60] === 'K' && pieces[63] === 'R') rights += 'K';
        if (pieces[60] === 'K' && pieces[56] === 'R') rights += 'Q';
        if (pieces[4] === 'k' && pieces[7] === 'r') rights += 'k';
        if (pieces[4] === 'k' && pieces[0] === 'r') rights += 'q';
        const game = new Chess();
        if (!game.load(`${piecesToPlacement(pieces)} ${turn} ${rights || '-'} - 0 1`)) return null;
        return game;
    }

    // chess_boards.board_from_history: replay from the standard starting position, which
    // recovers castling rights, the en-passant square and the side to move.
    function boardFromHistory(Chess, history) {
        if (!history || !history.length) return null;
        const game = new Chess();
        if (piecesToPlacement(tokensToPieces(history[0])) === placementOf(game)) {
            for (let ply = 1; ply < history.length; ply++) {
                const uci = getValidatedMove(game, history[ply]);
                if (uci === null) return boardFromLastPosition(Chess, history);
                game.move({ from: uci.slice(0, 2), to: uci.slice(2, 4), promotion: uci[4] });
            }
            return game;
        }
        return boardFromLastPosition(Chess, history);
    }

    // ------------------------------------------------------------------------------------
    // A small chess position with pseudo-legal moves, for the problem labels only.
    // chess.js offers legal moves only; illegal_moves.py also needs python-chess's
    // pseudo_legal_moves and boards with the turn changed by hand. The rules below follow
    // python-chess (pseudo-legal moves include castling, which is only generated when it is
    // fully allowed, and en passant when an en-passant square is set).
    // ------------------------------------------------------------------------------------
    const isWhite = p => p === p.toUpperCase();
    const colorOf = p => (isWhite(p) ? 'w' : 'b');
    const rowOf = s => s >> 3, colOf = s => s & 7;
    const KNIGHT = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]];
    const KING = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
    const DIAG = [[-1, -1], [-1, 1], [1, -1], [1, 1]];
    const ORTH = [[-1, 0], [1, 0], [0, -1], [0, 1]];

    class Pos {
        // sq: 64 piece letters or null; turn 'w'/'b'; castling: string of KQkq; ep: square index or -1
        constructor(sq, turn, castling, ep) {
            this.sq = sq; this.turn = turn; this.castling = castling || ''; this.ep = ep == null ? -1 : ep;
        }

        static fromFen(fen) {
            const [placement, turn, castling, ep] = fen.split(' ');
            const sq = new Array(N_SQ).fill(null);
            let i = 0;
            for (const ch of placement) {
                if (ch === '/') continue;
                if (ch >= '1' && ch <= '8') i += +ch; else sq[i++] = ch;
            }
            const epSq = ep && ep !== '-' ? (8 - +ep[1]) * 8 + FILES.indexOf(ep[0]) : -1;
            return new Pos(sq, turn, castling === '-' ? '' : castling, epSq);
        }

        copy() { return new Pos(this.sq.slice(), this.turn, this.castling, this.ep); }

        // Rights whose king and rook are still at home (python-chess clean_castling_rights).
        cleanCastling() {
            let out = '';
            const s = this.sq;
            if (this.castling.includes('K') && s[60] === 'K' && s[63] === 'R') out += 'K';
            if (this.castling.includes('Q') && s[60] === 'K' && s[56] === 'R') out += 'Q';
            if (this.castling.includes('k') && s[4] === 'k' && s[7] === 'r') out += 'k';
            if (this.castling.includes('q') && s[4] === 'k' && s[0] === 'r') out += 'q';
            return out;
        }

        // Is `square` attacked by a piece of colour `by`? `sq` may be an edited copy of the board.
        attacked(square, by, sq = this.sq) {
            const r = rowOf(square), c = colOf(square);
            const own = p => p && colorOf(p) === by;
            // pawns: a white pawn attacks one row up (towards row 0)
            const pr = by === 'w' ? r + 1 : r - 1;
            if (pr >= 0 && pr < 8) {
                for (const pc of [c - 1, c + 1]) {
                    if (pc >= 0 && pc < 8) {
                        const p = sq[pr * 8 + pc];
                        if (p && own(p) && p.toLowerCase() === 'p') return true;
                    }
                }
            }
            for (const [dr, dc] of KNIGHT) {
                const rr = r + dr, cc = c + dc;
                if (rr >= 0 && rr < 8 && cc >= 0 && cc < 8) {
                    const p = sq[rr * 8 + cc];
                    if (p && own(p) && p.toLowerCase() === 'n') return true;
                }
            }
            for (const [dr, dc] of KING) {
                const rr = r + dr, cc = c + dc;
                if (rr >= 0 && rr < 8 && cc >= 0 && cc < 8) {
                    const p = sq[rr * 8 + cc];
                    if (p && own(p) && p.toLowerCase() === 'k') return true;
                }
            }
            for (const [dirs, kinds] of [[DIAG, 'bq'], [ORTH, 'rq']]) {
                for (const [dr, dc] of dirs) {
                    let rr = r + dr, cc = c + dc;
                    while (rr >= 0 && rr < 8 && cc >= 0 && cc < 8) {
                        const p = sq[rr * 8 + cc];
                        if (p) {
                            if (own(p) && kinds.includes(p.toLowerCase())) return true;
                            break;
                        }
                        rr += dr; cc += dc;
                    }
                }
            }
            return false;
        }

        kingSquare(color) { return this.sq.indexOf(color === 'w' ? 'K' : 'k'); }

        isCheck() {
            const k = this.kingSquare(this.turn);
            return k >= 0 && this.attacked(k, this.turn === 'w' ? 'b' : 'w');
        }

        // python-chess generate_pseudo_legal_moves: moves as {from, to, promotion?, castle?}
        pseudoLegalMoves() {
            const moves = [], sq = this.sq, me = this.turn, them = me === 'w' ? 'b' : 'w';
            for (let from = 0; from < N_SQ; from++) {
                const p = sq[from];
                if (!p || colorOf(p) !== me) continue;
                const kind = p.toLowerCase(), r = rowOf(from), c = colOf(from);
                const add = (rr, cc) => {
                    if (rr < 0 || rr > 7 || cc < 0 || cc > 7) return false;
                    const q = sq[rr * 8 + cc];
                    if (q && colorOf(q) === me) return false;
                    moves.push({ from, to: rr * 8 + cc });
                    return !q;   // a slider goes on only over empty squares
                };
                if (kind === 'n') for (const [dr, dc] of KNIGHT) add(r + dr, c + dc);
                else if (kind === 'k') for (const [dr, dc] of KING) add(r + dr, c + dc);
                else if (kind === 'p') {
                    const dir = me === 'w' ? -1 : 1, homeRow = me === 'w' ? 6 : 1, lastRow = me === 'w' ? 0 : 7;
                    const push = (to) => {
                        if (rowOf(to) === lastRow) for (const promo of 'qrbn') moves.push({ from, to, promotion: promo });
                        else moves.push({ from, to });
                    };
                    const r1 = r + dir;
                    if (r1 >= 0 && r1 <= 7) {
                        for (const cc of [c - 1, c + 1]) {
                            if (cc < 0 || cc > 7) continue;
                            const q = sq[r1 * 8 + cc];
                            if (q && colorOf(q) === them) push(r1 * 8 + cc);
                        }
                        if (!sq[r1 * 8 + c]) {
                            push(r1 * 8 + c);
                            if (r === homeRow && !sq[(r + 2 * dir) * 8 + c]) moves.push({ from, to: (r + 2 * dir) * 8 + c });
                        }
                    }
                } else {
                    const dirs = kind === 'b' ? DIAG : kind === 'r' ? ORTH : DIAG.concat(ORTH);
                    for (const [dr, dc] of dirs) {
                        let rr = r + dr, cc = c + dc;
                        while (add(rr, cc)) { rr += dr; cc += dc; }
                    }
                }
            }
            // castling: rights, empty squares between, king not attacked now, on the way or at the end
            const home = me === 'w' ? 56 : 0, rights = this.cleanCastling();
            const king = home + 4;
            for (const [flag, rookFrom, kingTo, rookTo, between] of [
                [me === 'w' ? 'K' : 'k', home + 7, home + 6, home + 5, [home + 5, home + 6]],
                [me === 'w' ? 'Q' : 'q', home, home + 2, home + 3, [home + 1, home + 2, home + 3]]]) {
                if (!rights.includes(flag) || between.some(s => sq[s])) continue;
                const without = sq.slice();
                without[king] = null;
                const path = [king, rookTo, kingTo];   // the king's square, the one it crosses, where it lands
                if (path.some(s => this.attacked(s, them, without))) continue;
                moves.push({ from: king, to: kingTo, castle: [rookFrom, rookTo] });
            }
            // en passant
            if (this.ep >= 0 && !sq[this.ep]) {
                const er = rowOf(this.ep), ec = colOf(this.ep);
                const fromRow = me === 'w' ? 3 : 4;   // rank 5 for white, rank 4 for black
                if (er === (me === 'w' ? 2 : 5)) {
                    for (const cc of [ec - 1, ec + 1]) {
                        if (cc < 0 || cc > 7) continue;
                        const from = fromRow * 8 + cc;
                        if (sq[from] === (me === 'w' ? 'P' : 'p')) moves.push({ from, to: this.ep });
                    }
                }
            }
            return moves;
        }

        // python-chess push(): plays a move from pseudoLegalMoves() in place.
        push(move) {
            this.castling = this.cleanCastling();
            const sq = this.sq, me = this.turn, piece = sq[move.from], kind = piece.toLowerCase();
            const ep = this.ep;
            this.ep = -1;
            const strip = chars => { this.castling = this.castling.split('').filter(ch => !chars.includes(ch)).join(''); };
            for (const s of [move.from, move.to]) {
                if (s === 63) strip('K'); else if (s === 56) strip('Q'); else if (s === 7) strip('k'); else if (s === 0) strip('q');
            }
            if (kind === 'k') strip(me === 'w' ? 'KQ' : 'kq');
            sq[move.from] = null;
            if (kind === 'p') {
                const diff = move.to - move.from;
                if (Math.abs(diff) === 16) this.ep = move.from + diff / 2;
                else if (move.to === ep && (Math.abs(diff) === 7 || Math.abs(diff) === 9) && !sq[move.to]) {
                    sq[move.to + (me === 'w' ? 8 : -8)] = null;   // the pawn taken en passant
                }
            }
            if (move.castle) {
                sq[move.castle[1]] = sq[move.castle[0]];
                sq[move.castle[0]] = null;
            }
            sq[move.to] = move.promotion ? (me === 'w' ? move.promotion.toUpperCase() : move.promotion) : piece;
            this.turn = me === 'w' ? 'b' : 'w';
        }

        after(move) { const p = this.copy(); p.push(move); return p; }

        // Legal moves: pseudo-legal moves that do not leave the mover's king attacked.
        legalMoves() {
            const me = this.turn, them = me === 'w' ? 'b' : 'w';
            return this.pseudoLegalMoves().filter(m => {
                const next = this.after(m);
                const k = next.kingSquare(me);
                return k < 0 || !next.attacked(k, them);
            });
        }
    }

    const sameBoard = (a, b) => { for (let i = 0; i < N_SQ; i++) if (a[i] !== b[i]) return false; return true; };
    const moveUci = m => FILES[colOf(m.from)] + (8 - rowOf(m.from)) + FILES[colOf(m.to)] + (8 - rowOf(m.to)) + (m.promotion || '');

    // illegal_moves._castled_boards: boards after castling as if king and rook had the right to.
    function castledBoards(before) {
        const me = before.turn, home = me === 'w' ? 56 : 0;
        const K = me === 'w' ? 'K' : 'k', R = me === 'w' ? 'R' : 'r';
        const out = [];
        for (const [rookSq, kingTo, rookTo] of [[home + 7, home + 6, home + 5], [home, home + 2, home + 3]]) {
            if (before.sq[home + 4] === K && before.sq[rookSq] === R) {
                const b = before.sq.slice();
                b[home + 4] = null; b[rookSq] = null;
                b[kingTo] = K; b[rookTo] = R;
                out.push(b);
            }
        }
        return out;
    }

    // illegal_moves._two_moves: is the target two moves away (both by the side to move, or move + reply)?
    function twoMoves(before, target, sameSide) {
        for (const first of before.legalMoves()) {
            const b = before.after(first);
            if (sameSide) { b.turn = before.turn; b.ep = -1; }
            if (b.pseudoLegalMoves().some(second => sameBoard(b.after(second).sq, target))) return true;
        }
        return false;
    }

    /*
     * illegal_moves.classify_board: 'legal', or a short label for the mistake.
     * before: a Pos (the position the model had to move in); tokens: the generated board.
     * Measurement only: nothing here picks, filters or corrects a move.
     */
    function classifyBoard(before, tokens) {
        if (tokens.some(t => !PIECE_TOKENS.has(t))) return 'a square holds a non-piece token';
        const target = tokensToPieces(tokens), prev = before.sq, me = before.turn;
        const legal = before.legalMoves();
        if (legal.some(m => sameBoard(before.after(m).sq, target))) return 'legal';
        if (sameBoard(target, prev)) return 'nothing moved';

        // Right kind of move, but the king is left attacked.
        for (const move of before.pseudoLegalMoves()) {
            if (sameBoard(before.after(move).sq, target)) {
                if (before.isCheck()) return 'did not answer a check';
                if (prev[move.from].toLowerCase() === 'k') return 'king moved into check';
                return 'pinned piece moved';
            }
        }
        if (castledBoards(before).some(b => sameBoard(b, target))) return 'castling not allowed';

        // The other side's move.
        const other = before.copy();
        other.turn = me === 'w' ? 'b' : 'w';
        other.ep = -1;
        if (other.pseudoLegalMoves().some(m => sameBoard(other.after(m).sq, target))) return "moved the opponent's piece";

        const mine = p => p && colorOf(p) === me, theirs = p => p && colorOf(p) !== me;
        const changed = [];
        for (let s = 0; s < N_SQ; s++) if (prev[s] !== target[s]) changed.push(s);
        const gone = changed.filter(s => mine(prev[s]));       // own piece left / was replaced
        const came = changed.filter(s => mine(target[s]));     // own piece arrived
        const oppChanged = changed.filter(s => (theirs(prev[s]) && !came.includes(s)) || theirs(target[s]));
        if (oppChanged.length) {
            if (twoMoves(before, target, false)) return "own move plus the opponent's reply";
            const ep = oppChanged.filter(s => prev[s] && !target[s] && prev[s].toLowerCase() === 'p');
            if (gone.length === 1 && came.length === 1 && ep.length === 1 && oppChanged.length === 1
                    && prev[gone[0]].toLowerCase() === 'p'
                    && rowOf(ep[0]) === rowOf(gone[0]) && colOf(ep[0]) === colOf(came[0])) {
                return 'en passant not allowed';
            }
            return "opponent's pieces changed";
        }

        const left = gone.filter(s => !came.includes(s));
        if (left.length === 1 && came.length === 1) {
            const src = left[0], dst = came[0];
            const moved = prev[src], arrived = target[dst];
            if (moved === arrived) {
                if (mine(prev[dst])) return 'captured its own piece';
                const alone = new Pos(new Array(N_SQ).fill(null), me, '', -1);
                alone.sq[src] = moved;
                if (prev[dst]) alone.sq[dst] = prev[dst];
                if (alone.pseudoLegalMoves().some(m => m.from === src && m.to === dst)) return 'jumped over a piece';
                return 'piece moved in a way it cannot';
            }
            const blend = legal.some(m => m.from === src) && legal.some(m => m.to === dst && prev[m.from] === arrived);
            return blend ? 'blend of two moves (one piece leaves, another arrives)' : 'piece changed type';
        }
        if (!left.length && came.length) return came.length === 1 ? 'piece duplicated (arrived without leaving)' : 'several pieces duplicated';
        if (left.length && !came.length) return left.length === 1 ? 'piece vanished' : 'several pieces vanished';
        if (twoMoves(before, target, true)) return 'two moves at once';
        return 'several own pieces wrong';
    }

    // ------------------------------------------------------------------------------------
    // the attempt loop: engine.board_attempts
    // ------------------------------------------------------------------------------------
    // Temperature of attempt `attempt` (0-based): `start` first, rising to 1.0; constant from 1.0 up.
    function attemptTemperature(attempt, maxAttempts, start = START_TEMPERATURE) {
        return start + (attempt / Math.max(maxAttempts, 1)) * Math.max(0, 1 - start);
    }

    const round3 = x => Math.round(x * 1000) / 1000;

    /*
     * Yields one object per generated board until one is a legal move, with the same fields
     * as the server's messages. onStep(attemptNumber, temperature, step) is called before
     * each model call, so the page can draw the board while it is being generated.
     * argmax is for tests only (compare with Python without random numbers).
     */
    async function* boardAttempts({ Chess, tokenizer, contextSize, denoise, history, outcome, maxAttempts,
                                    temperature = START_TEMPERATURE, argmax = false, plan = PLAN,
                                    firstAttempt = 0, rng = Math.random, onStep }) {
        const game = boardFromHistory(Chess, history);
        if (!game) throw new Error('Failed to parse original board state');
        const before = Pos.fromFen(game.fen());
        const x = buildInputIds(tokenizer, contextSize, history, outcome);
        const name = id => tokenizer.idToToken[id];
        for (let attempt = firstAttempt; attempt < maxAttempts; attempt++) {
            const temp = argmax ? 0 : attemptTemperature(attempt, maxAttempts, temperature);
            const steps = [];
            const final = await confidenceSampler({
                denoise, ids: x.slice(), maskId: tokenizer.maskId, vocabSize: tokenizer.vocabSize, temp, plan, rng,
                onStep: async (step, t, board) => {
                    let masks = 0;
                    for (const id of board) if (id === tokenizer.maskId) masks++;
                    const entry = { step, t: round3(t), board_tokens: Array.from(board, name), masks_remaining: masks };
                    steps.push(entry);
                    if (onStep) await onStep(attempt + 1, round3(temp), entry);
                },
            });
            const finalTokens = Array.from(final, name);
            const move = getValidatedMove(game, finalTokens);
            const problem = move ? null : classifyBoard(before, finalTokens);
            yield {
                type: 'attempt', attempt: attempt + 1, temperature: round3(temp), steps,
                final_tokens: finalTokens,
                final_fen: piecesToPlacement(tokensToPieces(finalTokens)) + ' w - - 0 1',
                valid: move !== null, move, problem,
            };
            if (move !== null) break;
        }
    }

    return {
        N_SQ, PLAN, START_TEMPERATURE, MIN_TEMPERATURE, MAX_TEMPERATURE, PIECE_TOKENS,
        makeTokenizer, buildPromptString, buildInputIds,
        sampleToken, tFromMasked, confidenceSampler,
        tokensToPieces, piecesToPlacement, gameToTokens, getValidatedMove, boardFromHistory, boardFromLastPosition,
        Pos, moveUci, classifyBoard,
        attemptTemperature, boardAttempts,
    };
});