-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcuci.py
More file actions
1251 lines (1191 loc) · 69.3 KB
/
Copy pathcuci.py
File metadata and controls
1251 lines (1191 loc) · 69.3 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
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
cuci.py -- UCI wrapper for the C search core (cengine.py).
python3 cuci.py
Speaks standard UCI for external GUIs / match runners (cutechess-ob, Arena,
lichess-bot, ...). The engine is cengine.Engine (csearch.so under a Python
root driver); clock handling goes through the project's standard
time_manager.calculate_move_time, so `go wtime/btime/winc/binc` gets the
same budgets the internal harnesses use.
Options:
Threads (spin 1..512, default 1) -- Lazy-SMP helper threads in C
MultiPV (spin 1..20, default 1) -- k best lines per go (analysis;
>1 bypasses the opening book,
else book hits show no lines;
=1 is byte-identical to before,
match play never sets it)
OwnBook (check, default true) -- engine's own Polyglot book
BookFile (string, default empty) -- path to a custom Polyglot .bin
(empty = bundled Perfect2023.bin)
UseTB (check, default false) -- root Lichess-Syzygy probe
(difficulty-gated; needs network)
Ponder (check, default false) -- real go-ponder/ponderhit:
search the predicted position
on the opponent's clock, hold
bestmove until ponderhit (then
a timed release) or stop.
Mutually exclusive with Premove
by construction (held searches
skip PM-01 certification)
Move Overhead (spin 0..5000, default 40) -- per-move clock slack, ms
Hash (spin 2..6144 MB, default 192) -- C TT size (FI-10;
resize wipes the table; the
table is a power-of-two ENTRY
count, so a request rounds DOWN
and FB-46 says so in an
info string)
(+ the P-26 tuning spins; `bench [depth]` prints the OpenBench nodes
signature -- CONFIG-RELATIVE: it re-baselines after every tree-changing
ship, so compare only within one confirmed version; `go nodes N` is
honored via a C-side node budget)
`stop` aborts the search via engine.stop() -- the host-owned `_abort` flag
plus cs_stop(); the search thread then prints the bestmove found so far
(UCI-required). `go infinite` relies on that path. The flag (cleared only
here, at each `go`) is what makes a stop that races the search thread's
startup stick: cs_stop() alone was erased by cs_search_begin, leaving
`go infinite` running to the depth cap with the host hung in join().
"""
# lib/ holds the shared support modules (time_manager, wdl, interruptible,
# smp, shared_tt) since the 2026-07-24 reshuffle. They stay importable by
# their plain names, so nothing else in the tree had to change.
import os as _os, sys as _sys
_sys.path.insert(0, _os.path.join(_os.path.dirname(_os.path.abspath(__file__)), "lib"))
import os
import struct
import sys
import threading
import time
import traceback
import chess
import cengine
from time_manager import calculate_move_time
import math
# WDL model -- fitted by tuning/fit_wdl_model.py (coefficients from wdl_model.json). Converts pygin's own
# cp score + game phase into Stockfish-style win/draw/loss permille, so the extension's WDL readout
# works on pygin too. Local-only (pygin is not in the public fork). Refit via tuning/fit_wdl_model.py; do
# not hand-edit the coefficients.
#
# REFIT 2026-08-04 from 8,733,752 samples (hce) and 2,136,411 (nnue).
# Keep these in step with
# data/wdl_model.json -- they drifted apart once already, and the file said it
# took its numbers from there the whole time. match.py reads the json directly.
_WDL_AS = [-149.64916927492763, 455.96521022945683, -478.9409658684033, 276.49690384866153]
_WDL_BS = [83.9952667919631, 0.571979115933054, -95.9143821000079, 106.51542351556262]
# NNUE-family WDL model, fitted by fit_wdl_model.py alongside the hce one and
# kept in step by it. LIVE since v58: the runtime reports WDL on the eval it
# actually plays, so arming USE_NNUE has to move this too or every `wdl` line
# is calibrated to an eval the engine is no longer using.
_WDL_AS_NNUE = [-42.4794557137675, 283.9660641459952, -398.6448482585931, 257.6203371829198]
_WDL_BS_NNUE = [163.48997419569673, -126.20854083111506, -36.53128833766639, 94.56265702564619]
# Which family we report WDL on. Bound ONCE, by _bind_wdl_family() right after
# the engine is constructed -- deliberately not from cengine.Engine.USE_NNUE at
# import time. The class attribute is only the REQUEST: NNUE_REQUIRE_SIMD
# disarms the net during construction on a CPU with neither NEON nor AVX2, and
# such a host plays the HCE while the class still says True. Reading the class
# would report NNUE-calibrated win probabilities for hand-crafted scores on
# exactly the machines the guard exists to protect.
_WDL_A, _WDL_B = _WDL_AS, _WDL_BS
def _bind_wdl_family(engine):
"""Point the WDL polynomials at the eval the engine ACTUALLY armed."""
global _WDL_A, _WDL_B
_WDL_A, _WDL_B = ((_WDL_AS_NNUE, _WDL_BS_NNUE) if engine.USE_NNUE
else (_WDL_AS, _WDL_BS))
_WDL_PHASE_MAX = 24
_WDL_PHASE_CLAMP_MIN = 6
def _win_rate_model(cp, phase):
"""P(win) for a score of `cp` centipawns (side-to-move POV) at game `phase` (0..24)."""
cp = max(-1000, min(1000, cp)) # match the fit's cp clamp
m = min(max(phase, _WDL_PHASE_CLAMP_MIN), _WDL_PHASE_MAX) / _WDL_PHASE_MAX
a = ((_WDL_A[0] * m + _WDL_A[1]) * m + _WDL_A[2]) * m + _WDL_A[3]
b = ((_WDL_B[0] * m + _WDL_B[1]) * m + _WDL_B[2]) * m + _WDL_B[3]
z = max(-60.0, min(60.0, (a - cp) / b)) # guard math.exp overflow
return 1.0 / (1.0 + math.exp(z))
def _wdl_permille(cp, phase):
"""(win, draw, loss) permille ints summing to 1000 -- Stockfish's UCI `wdl` convention."""
w = _win_rate_model(cp, phase)
l = _win_rate_model(-cp, phase)
d = max(0.0, 1.0 - w - l)
vals = [round(w * 1000), round(d * 1000), round(l * 1000)]
vals[vals.index(max(vals))] += 1000 - sum(vals) # rounding can miss 1000 by +/-1
return vals[0], vals[1], vals[2]
def _nnue_banner(engine):
"""Stockfish-style `info string` naming the net actually in use.
Dimensions come from the file's own header (magic PYGINNUE, then version
and the int32 fields), so this cannot drift from what the C side loaded.
"""
if not getattr(engine, "USE_NNUE", False):
# A net that was ASKED for and then disarmed is a different story from
# one that was never asked for: the class attribute is the request,
# the instance is what survived construction. An engine whose class
# default is already False (a pre-v58 snapshot) never wanted a net.
wanted = getattr(type(engine), "USE_NNUE", False)
why = ("no SIMD on this CPU, and the scalar tail is ~3x slower than "
"the eval is worth" if wanted else "this build has USE_NNUE off")
return f"info string NNUE evaluation disabled ({why}) -- playing the HCE"
path = engine.NNUE_FILE
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(os.path.abspath(cengine.__file__)),
path)
try:
with open(path, "rb") as fh:
hdr = fh.read(64)
f = struct.unpack("<7I", hdr[12:40]) # feature_set, in, h, tdim, kb, d2, d3
arch = f"({f[1]}, {f[2]}, {f[3]}, {f[5]}, {f[6]}, 1)"
mib = max(1, round(os.path.getsize(path) / (1 << 20)))
extra = ""
try:
extra = f", {engine._lib.nnue_kernel_name().decode()}"
except Exception:
pass # pre-FI-104 csearch.so
return (f"info string NNUE evaluation using {os.path.basename(path)} "
f"({mib}MiB, {arch}{extra})")
except (OSError, struct.error) as ex:
# The net loaded (construction raises otherwise), so this is only the
# banner failing -- say so rather than claiming the eval is off.
return f"info string NNUE evaluation armed; could not read header ({ex})"
def _board_phase(board):
"""Mirror engine.py's tapered-eval phase: N/B weight 1, R weight 2, Q weight 4, capped at 24."""
return min(24, bin(board.knights).count("1") + bin(board.bishops).count("1")
+ bin(board.rooks).count("1") * 2 + bin(board.queens).count("1") * 4)
NAME = "Pygin C-core" # version-neutral: the old "Pygin C31" went stale
AUTHOR = "Nuke" # version-neutral pseudonym; snapshots carry the number
def out(line):
print(line, flush=True)
TT_ENTRY_BYTES = 24 # csearch.c TTEntry -- keep in sync with the C side
# Hash ceiling in MB. The table is indexed with `key & TT_MASK`, so the entry
# count must be a power of two; at 24 bytes/entry the reachable sizes near the
# top are 2^29 = 12,288 MB and 2^30 = 24,576 MB. NOTHING lands on 20,480.
#
# The ceiling is therefore 24,576, not the 20,480 first set here on 2026-07-30
# for a "20 GB" request: a 20,480 cap makes the 2^30 rung UNREACHABLE, so the
# largest table anyone could actually get was 12 GB while the option advertised
# 20. Cap on a reachable size, not on the number that was asked for.
HASH_MAX_MB = 24576
def apply_hash(engine, mb):
"""FI-10: Hash MB -> power-of-two TT bits, applied to the C table.
FB-46: the table can only be a power of two, so a request lands on the
largest size <= it (200 MB -> 192, 400 -> 384). Say so instead of
silently shrinking. Caller must guarantee the engine is idle -- a resize
is a realloc.
"""
mb = max(2, min(HASH_MAX_MB, int(mb)))
bits = (mb * 1024 * 1024 // TT_ENTRY_BYTES).bit_length() - 1
engine._lib.set_tt_bits(bits)
engine.TT_BITS = bits # FB-30: fingerprint honesty
actual = (1 << bits) * TT_ENTRY_BYTES // (1024 * 1024)
if actual != mb:
# Name the next rung UP too: "rounded down" alone leaves the user
# guessing which number would not have been rounded at all.
nxt = (1 << (bits + 1)) * TT_ENTRY_BYTES // (1024 * 1024)
hint = (f"; {nxt} MB is the next size up"
if nxt <= HASH_MAX_MB else "")
out(f"info string Hash {mb} MB rounded down to {actual} MB "
f"(the table is a power of two of {TT_ENTRY_BYTES}-byte "
f"entries{hint})")
def info_line(rec, white_to_move, engine, multipv=None, board=None):
"""Map a cengine record dict (White-POV, v30 mate convention) to UCI.
`multipv` (int) tags the line for MultiPV consumers; None = untagged
(identical to the pre-MultiPV output). `board` (when given) adds a `wdl`
token from the fitted model so the extension can show win/draw/loss."""
score = rec.get("score", 0)
stm = score if white_to_move else -score
if abs(stm) >= engine.MATE_THRESHOLD:
plies = engine.MATE_SCORE - abs(stm)
moves = (plies + 1) // 2
score_str = f"mate {moves if stm > 0 else -moves}"
else:
score_str = f"cp {stm}"
t = max(1, rec.get("time_ms", 0))
nodes = rec.get("nodes", 0)
# FI-13a: seldepth (deepest ply incl. extensions/qsearch) + hashfull
# (TT permille) -- standard GUI fields, sampled from the C side.
booky = bool(rec.get("book") or rec.get("tb")) # FB-25: no search ran;
parts = [f"info depth {rec.get('depth', 0)}", # the C counters still
f"seldepth {0 if booky else engine._lib.cs_seldepth()}", # hold
*([f"multipv {multipv}"] if multipv is not None else []),
f"score {score_str}", # the PREVIOUS search's
f"nodes {nodes}", f"nps {int(nodes * 1000 / t)}", # values
f"hashfull {0 if booky else engine._lib.cs_hashfull()}",
f"time {t}"]
# WDL (permille, side-to-move POV) for real cp scores only -- not mate/book/tb positions.
if (board is not None and not booky and getattr(engine, "show_wdl", True)
and abs(stm) < engine.MATE_THRESHOLD):
win, draw, loss = _wdl_permille(stm, _board_phase(board))
parts.append(f"wdl {win} {draw} {loss}")
pv = rec.get("pv", "")
if pv:
parts.append(f"pv {pv}")
return " ".join(parts)
# FI-13c: OpenBench-style `bench` -- fixed suite, fixed depth, cold TT per
# position; the node total is the reproducible signature.
# FB-39: 6 FENs. Adding/removing a FEN re-baselines the signature and
# invalidates every stored comparison; only do that at a tree-changing ship.
BENCH_FENS = [
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"r1bqkbnr/pppp1ppp/2n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 3 3",
"r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - - 0 10",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
"8/2k5/3p4/p2P1p2/P2P1P2/8/8/4K3 w - - 0 1",
"r2q1rk1/pP1p2pp/Q4n2/bbp1p3/Np6/1B3NBn/pPPP1PPP/R3K2R b KQ - 0 1",
]
def run_bench(engine, depth=11):
import time as _time
saved = (engine.use_book, engine.use_tb, engine.smp_workers,
engine.on_depth, engine.on_final, engine.contempt)
engine.use_book = engine.use_tb = False # FB-20: the signature must not
engine.smp_workers = 1 # depend on .bin files -- nor on
engine.on_depth = engine.on_final = None # Threads (FB-32): 1-thread only.
# FB-37: a prior go()'s closure
# must not spray info lines into
# the nodes/nps output (same
# leak class as FB-20/FB-32)
# FB-52: ...nor on CONTEMPT, which is the same leak one dimension further.
# draw_score is live and contempt-driven, so a host that sends
# `setoption name Contempt value 0` and then `bench` got a DIFFERENT
# signature from a fresh process -- and the signature's whole job is to
# prove the config has not drifted. Force the shipped defaults.
_py = engine._py
engine._lib.csearch_set_draw(_py.CONTEMPT, _py.DRAW_AVOID_MARGIN)
engine.contempt = _py.CONTEMPT
try:
total, t0 = 0, _time.perf_counter()
for fen in BENCH_FENS:
engine._lib.cs_tt_reset()
engine.get_best_move(chess.Board(fen), depth)
total += engine.nodes_searched
dt = max(1e-9, _time.perf_counter() - t0)
out(f"{total} nodes {int(total / dt)} nps")
finally:
(engine.use_book, engine.use_tb, engine.smp_workers,
engine.on_depth, engine.on_final, engine.contempt) = saved
engine._lib.csearch_set_draw(engine.contempt, # FB-52: restore the
_py.DRAW_AVOID_MARGIN) # host's value
def _search_multipv(engine, board, k, budget, max_depth, white_to_move,
stop_evt, fixed_depth=None):
"""Stockfish-style PROGRESSIVE MultiPV: at EVERY iterative-deepening
depth, search all k lines and emit all k, so a GUI shows k lines from
the first depth and watches them refine together.
Replaces the old emit-at-the-end design (2026-08-14), which ran the
main search to completion and only THEN re-searched k-1 extra lines,
printing everything in one burst at the very end. Two faults, both
measured on `setoption MultiPV 5` + `go movetime 3000`: nothing
appeared for 6.19s and then all five lines landed at once, and the
search overran its own budget by 2x because each extra line was given
a fresh time slice on top of the main search.
Lines 2..k are searched with the better lines' first moves EXCLUDED at
the C root (root_exclude_*, abi 10); the warm TT makes those cheap.
Returns line 1's move -- the caller's bestmove -- with the engine's
last_* snapshot left describing line 1, which is what PM-01's premove
certification and the GUI-facing state read.
MultiPV > 1 is an ANALYSIS feature and never active in match play, so
the extra node cost is deliberate: it buys the display GUIs expect.
"""
import time as _t
lib = engine._lib
t0 = _t.perf_counter()
deadline = (t0 + budget) if budget is not None else None
top = fixed_depth if fixed_depth is not None else max_depth
sv = (engine.use_book, engine.on_depth, engine.on_final)
engine.use_book = False # a book reply has no PV to show
engine.on_depth = engine.on_final = None # we emit; no per-depth spam
best_first, best_state, total_nodes = None, None, 0
try:
for d in range(1, max(1, top) + 1):
if stop_evt.is_set() or engine._abort:
break
# Do not START a depth that cannot finish: past ~45% of the
# budget the next depth reliably costs more than what is left,
# and overrunning `movetime` is a protocol violation.
if deadline is not None and _t.perf_counter() - t0 > 0.45 * budget:
break
lines, excl, depth_state = [], [], None
for i in range(k):
if stop_evt.is_set() or engine._abort:
break
if deadline is not None and _t.perf_counter() >= deadline:
break
lib.root_exclude_clear()
for m in excl: # 15-bit key: from|to<<6|promo<<12
lib.root_exclude_add(m.from_square | (m.to_square << 6)
| ((m.promotion or 0) << 12))
mv = engine.get_best_move(board, d)
# Two ways to run out of lines. None is the clean one; the
# other is the C root ignoring a fully-exhausted exclusion
# list and handing back an already-listed move, which used
# to print k copies of the same PV on a position with one
# legal reply. Either way we are done: k is capped by the
# legal move count, as in every other engine.
if mv is None or mv in excl:
break
total_nodes += engine.nodes_searched
lines.append((engine.last_score, engine.last_pv,
engine.last_depth or d))
excl.append(mv)
if i == 0:
best_first = mv
depth_state = (engine.last_score, engine.last_pv,
engine.last_depth, engine.nodes_searched)
lib.root_exclude_clear()
if not lines:
break
# A depth is emitted only when it COMPLETED: a partial set would
# make a GUI drop lines mid-search, which looks like a crash.
if len(lines) == min(k, len(lines)) and depth_state is not None:
best_state = depth_state
el = max(1, int((_t.perf_counter() - t0) * 1000))
for i, (score, pv, dd) in enumerate(lines, 1):
out(info_line({"depth": dd, "score": score, "pv": pv,
"nodes": total_nodes, "time_ms": el},
white_to_move, engine, multipv=i,
board=board))
finally:
lib.root_exclude_clear() # NEVER leak exclusions into play
engine.use_book, engine.on_depth, engine.on_final = sv
if best_state is not None: # leave line 1 as the visible state
(engine.last_score, engine.last_pv, engine.last_depth,
engine.nodes_searched) = best_state
return best_first
# --------------------------------------------------------------------------- #
# PM-01: certified instant reply (opt-in via `setoption name Premove value
# true`; inert by default, zero effect on match play).
#
# After `bestmove m1` the engine keeps working ON THE OPPONENT'S CLOCK for up
# to PREMOVE_CAP_S and FOLLOWS ITS OWN LINE, emitting an ordered CHAIN of
# certified pairs via spec-ignored info-string lines the bridge parses:
# info string pygin-reply <r> <m> -- "if the opponent plays r, answer m
# instantly" (the client walks the
# chain on exact matches only: zero
# misfire risk)
# info string pygin-end -- collection terminator (always)
# Chain caps (don't trade depth for speed): at most 2 pairs where the
# opponent had a CHOICE, and only while the searched line REMAINING after
# each pair is >= PREMOVE_MIN_LINE plies (a d13 search affords 1 pair, d14+
# the full 2, below d12 none) -- but UNCAPPED while the opponent's reply is
# FORCED (single legal move: mate funnels, forced recaptures -- nothing to
# search, no depth lost).
# Quality gate: the answer must be depth-stable (d6 and d9 agree) -- a missing
# reply costs one normal round-trip; a wrong one would cost a game. The
# certification searches warm the TT with exactly the position the next move
# will face (a free poor-man's ponder), and the loop bails on stop_evt between
# sub-searches -- a new go/stop/ucinewgame aborts the in-flight one (FB-32) and
# joins within one ms-scale step.
# --------------------------------------------------------------------------- #
# Certification gate raised 2026-08-01 (user call): agreement at d13 AND d14,
# and nothing is offered unless the real search reached d14. The old d6/d9 pair
# cost ~0.03s and proved little; d13/d14 costs ~0.7s per pair and is a genuine
# claim. MEASURED first, because the caps below had to move with it: d13 runs
# 0.24-0.35s and d14 0.38-0.48s, against the previous 0.25s per-search cap --
# left unchanged, cert_search would have missed its depth every time, returned
# None, and the feature would have silently never fired again.
PREMOVE_CHECK_DEPTH = 13
PREMOVE_TABLE_DEPTH = 14
PREMOVE_MIN_DEPTH = 14 # the REAL search must have reached this before any
# premove is offered at all
PREMOVE_FORCED_DEPTH = 10
PREMOVE_MIN_LINE = 10 # a choice-pair may only be played while the line
# REMAINING after it is >= this deep: each instant
# reply consumes 2 plies of the searched line, so a
# d13 search affords 1 pair (13-2=11 ok, 13-4=9 no),
# d14+ affords the max 2, below d12 none at all
PREMOVE_CAP_S = 1.5 # budget checkpoint: no NEW sub-search starts past it
PREMOVE_SEARCH_CAP_S = 0.8 # FB-45: and each sub-search carries its own
# deadline, so the true wall-clock bound on the whole
# certification is CAP_S + SEARCH_CAP_S = 0.35 s --
# spent on the OPPONENT's clock and abortable by
# go/stop (FB-32). Before this the cap was tested only
# BETWEEN searches, so one full d9/d10 ran past it
# unbounded and "bullet-safe" was not guaranteed.
# Sized ~5x a normal d9 (~35 ms at 4M nps): a search
# that actually hits it is pathological, and its pair
# is DISCARDED rather than certified from a shallower
# result -- never trade the depth-stability gate for
# the bound (a wrong premove costs a game).
def certify_premoves(engine, board, my_move, stop_evt):
"""Return an ordered CHAIN of certified (predicted_reply, answer) pairs,
following the engine's own PV. BOARD is the position MY_MOVE was played
from. Two caps, per the design rule "don't trade depth for speed":
* at most 2 pairs where the opponent had a CHOICE (each instant reply
skips a full search, so an uncapped chain would play shallow) --
* UNCAPPED while the opponent's reply is FORCED (single legal move --
mate funnels, forced recapture ladders: no depth is lost, there was
nothing to search)."""
import time as _t
t_end = _t.perf_counter() + PREMOVE_CAP_S
def cert_search(pos, depth):
"""FB-45: a bounded sub-search. The deadline makes PREMOVE_CAP_S a
real bound instead of a between-search checkpoint; a search that did
not REACH `depth` returns None so a truncated result can never be
certified while wearing the deeper search's name."""
# The soft-stop must NOT apply here. This search's contract is "reach
# `depth` or return None", and a timed search normally ends at
# soft_stop_frac (0.55) of its budget -- so it would stop at ~0.44s of
# a 0.8s cap, never reach d13/d14, and certify nothing. With the old
# d6/d9 gate that never bit, because those finish in milliseconds; the
# deeper gate exposed it. The cap still bounds the search: the deadline
# is enforced regardless of the fraction.
_sv = (engine.soft_stop_frac, engine.use_stability_time)
engine.soft_stop_frac, engine.use_stability_time = None, False
try:
mv = engine.get_best_move_timed(pos, PREMOVE_SEARCH_CAP_S, depth)
finally:
engine.soft_stop_frac, engine.use_stability_time = _sv
return None if engine.last_depth < depth else mv
pv = (engine.last_pv or "").split() # read BEFORE any cert search
d0 = engine.last_depth or 0 # the searched line's depth
if d0 < PREMOVE_MIN_DEPTH:
return [] # too shallow to certify anything
b = board.copy()
b.push(my_move)
chain = []
normal = 0 # pairs where opponent had choice
pvi = 1 # next PV token = opponent reply
pv_ok = True # PV still aligned with the chain
while not stop_evt.is_set() and _t.perf_counter() < t_end:
if b.is_game_over():
break
replies = list(b.legal_moves)
if len(replies) == 1: # FORCED: safe, uncapped
r = replies[0]
bb = b.copy(); bb.push(r)
if bb.is_game_over():
break
m = cert_search(bb, PREMOVE_FORCED_DEPTH)
if m is None:
break
chain.append((r, m))
# keep PV alignment only if the line predicted this exchange
if pv_ok and pvi + 1 < len(pv) and pv[pvi] == r.uci() \
and pv[pvi + 1] == m.uci():
pvi += 2
else:
pv_ok = False
b = bb; b.push(m)
continue
# CHOICE: follow the PV prediction -- capped at 2 such pairs AND
# only while the line remaining after this pair is >= d10 deep
# (PREMOVE_MIN_LINE): never trade real depth for instant speed.
if (normal >= 2 or d0 - 2 * (normal + 1) < PREMOVE_MIN_LINE
or not pv_ok or pvi >= len(pv)):
break
try:
r = chess.Move.from_uci(pv[pvi])
except ValueError:
break
if r not in b.legal_moves:
break
bb = b.copy(); bb.push(r)
if bb.is_game_over():
break
m6 = cert_search(bb, PREMOVE_CHECK_DEPTH)
s6 = engine.last_score
if m6 is None or stop_evt.is_set() or _t.perf_counter() > t_end:
break
m9 = cert_search(bb, PREMOVE_TABLE_DEPTH)
s9 = engine.last_score
if m9 is None or m6 != m9 or abs(s9 - s6) > 60:
break # not depth-stable: stop here
if pvi + 1 < len(pv) and m9.uci() != pv[pvi + 1]:
break # fresh checks must agree with
chain.append((r, m9)) # the line's own answer
normal += 1
pvi += 2
b = bb; b.push(m9)
return chain
def main():
engine = cengine.Engine()
_bind_wdl_family(engine) # AFTER construction: the SIMD guard may have
# disarmed the net, and WDL follows what plays
# The engine's OWN time-policy defaults, captured once. `go movetime`
# disables the soft-stop and clock mode restores it -- and "restore" used
# to mean the literal 0.55, which silently overwrote whatever cengine.py
# had set. Nothing broke because the two agreed, but it meant any future
# soft-stop tuning would work under match.py and be discarded under UCI:
# tuned in testing, ignored in every real game. Restore what the engine
# actually shipped with.
SOFT_BASE = engine.soft_stop_frac
STAB_BASE = engine.use_stability_time
# FB-42: _board_phase (wdl display) and time_manager._phase_24 hand-type
# the 1/1/2/4/24 taper weights. If PHASE_WEIGHTS is ever retuned, fail
# loudly here instead of letting the wdl field and the moves-to-go guess
# drift silently. Explicit raise, not assert: python -O must not strip it.
_pw = engine._py.PHASE_WEIGHTS
if ((_pw[chess.KNIGHT], _pw[chess.BISHOP], _pw[chess.ROOK],
_pw[chess.QUEEN], engine._py.PHASE_MAX) != (1, 1, 2, 4, 24)):
raise SystemExit(
"PHASE_WEIGHTS retuned: update cuci._board_phase, "
"cuci._WDL_PHASE_MAX and time_manager._phase_24 to match")
# OpenBench CLI mode: `pygin bench [depth]` prints the node signature
# and exits -- the OpenBench worker runs `./engine bench` (argv, not
# UCI) to verify every build. Same run_bench as the UCI `bench` command
# (FB-20/FB-32/FB-37 hygiene: book/tb/threads/closures all forced off).
if len(sys.argv) > 1 and sys.argv[1] == "bench":
run_bench(engine,
depth=int(sys.argv[2]) if len(sys.argv) > 2 else 11)
return
engine.pv_uci = True # UCI pv format
engine.move_overhead_ms = 40 # FI-13b: UCI Move Overhead
# P-26: shadow copies of the paired C-side tuning values (set_rfp and
# set_null_move each set two values; UCI options arrive one at a time).
# FB-06: PUSH them once so Python is authoritative -- if a C default ever
# drifts, the first setoption would otherwise pair a stale shadow with it.
engine.premove_on = False # PM-01 (opt-in)
# FB-56: read the shipped defaults from the C rather than re-typing them
# (P26_RFP_MARGIN / P26_RFP_DEPTH are indices 0 and 1 of the table).
engine._rfp_margin = engine._lib.cs_p26_default(0)
engine._rfp_depth = engine._lib.cs_p26_default(1)
engine._null_base = int(engine.NULL_BASE) # class attr = the
engine._null_div = int(engine.NULL_DIV) # armed/swept value
engine._lib.set_rfp(engine._rfp_margin, engine._rfp_depth)
engine._lib.set_null_move(engine._null_base, engine._null_div)
board = chess.Board()
search_thread = None
# FB-44: the ponderhit release watcher wakes up to `budget` seconds later
# and stops "the search" -- but engine._abort is PROCESS-wide, so if a new
# `go` started meanwhile it would truncate THAT search instead. The
# watcher therefore checks that the thread it was armed for is still the
# live one, and this lock makes the check-then-stop atomic against the go
# handler's swap (identity IS the generation counter: every go builds a
# fresh thread object).
swap_lock = threading.Lock()
pending_hash_mb = None # FB-25: Hash sent mid-search
engine.show_wdl = True # FI-45: UCI_ShowWDL default
dbg = {"on": False} # FI-45: `debug on` channels
hf_ring = [] # FI-45: hashfull trajectory
def searching():
return search_thread is not None and search_thread.is_alive()
def go(tokens):
# Host-clears rule (engine.py P-05, now mirrored by cengine): _abort
# is set by engine.stop() and only ever cleared HERE, before the next
# search starts -- so a stop that raced the previous search thread's
# startup can never leak into (or get erased by) this one.
engine._abort = False
engine._go_pending = True # FB-21: a stop arriving before
# the search thread starts is
# LIVE, not stale
params = {}
# FI-45: `searchmoves m1 m2 ...` -- collect the whitelist (tokens up
# to the next keyword), strip it, invert to the C exclusion list at
# search time (the MultiPV root_exclude_* infra, g_rx now 256-wide).
if "searchmoves" in tokens:
kw = {"wtime", "btime", "winc", "binc", "movestogo", "movetime",
"depth", "nodes", "mate", "infinite", "ponder"}
i = tokens.index("searchmoves")
j = i + 1
while j < len(tokens) and tokens[j] not in kw:
j += 1
params["searchmoves"] = tokens[i + 1:j]
tokens = tokens[:i] + tokens[j:]
it = iter(tokens)
for tok in it:
if tok in ("wtime", "btime", "winc", "binc", "movestogo",
"movetime", "depth", "nodes", "mate"):
# B-06: a malformed number must not swallow the whole go
# (no bestmove ever = host hang); skip the bad token.
try:
params[tok] = int(next(it, 0))
except (ValueError, TypeError):
pass
elif tok == "infinite":
params["infinite"] = True
elif tok == "ponder":
params["ponder"] = True # FI-13e: real go-ponder (2026-07-21)
max_depth = int(params.get("depth", 60))
if "mate" in params and "depth" not in params: # FB-25: `go mate N`
max_depth = min(60, 2 * max(1, params["mate"]))
# FB-09: honor `go nodes N` (deterministic testing / OpenBench);
# None = unlimited. Applied per-go, cleared after.
engine.node_limit = (max(1, params["nodes"])
if "nodes" in params else None) # FB-25: 0 -> 1
if engine.node_limit and engine.smp_workers > 1:
# FB-25: the C budget counts MAIN-thread nodes only -- helpers
# would make the reported total blow past the limit, and
# node-limited runs exist for determinism anyway.
engine._lib.set_threads(1)
if "movetime" in params:
# FB-09/B-22: movetime 0 (or negative) means "move now", not
# "search until the depth cap" -- clamp to a near-instant budget.
budget = max(1, params["movetime"]) / 1000.0
elif "wtime" in params or "btime" in params:
my = params.get("wtime" if board.turn else "btime", 0)
opp = params.get("btime" if board.turn else "wtime", 0)
inc = params.get("winc" if board.turn else "binc", 0)
budget = calculate_move_time(
board, my, opp, inc,
overhead_ms=engine.move_overhead_ms, # FI-13b
movestogo=params.get("movestogo")) / 1000.0
elif "nodes" in params:
budget = None # node-limited: C aborts at N
elif "infinite" in params or "depth" in params:
budget = None # until `stop` / depth cap
else:
budget = None # bare `go` == go infinite
# B-05: `go movetime X` means SPEND X -- the P-35 base soft-stop
# (soft_stop_frac 0.55) and the U-06 stability scaling are clock-game
# economies that would end an exact-time search at 40-80% of the
# budget. Disable BOTH for movetime; restore for clock mode.
if "movetime" in params:
engine.use_stability_time = False
engine.soft_stop_frac = None
else:
engine.use_stability_time = STAB_BASE
engine.soft_stop_frac = SOFT_BASE # what cengine.py shipped,
# not a hardcoded copy of it
# FI-13e ponder: search the predicted position open-ended on the
# OPPONENT'S clock, holding bestmove until ponderhit/stop -- the
# B-03 hold rail does the holding, the ponderhit handler does the
# timed release. The go's clocks are SAVED for that conversion; the
# ponder search itself runs the budget-None (depth-mode) path.
ponder_mode = bool(params.get("ponder"))
if ponder_mode:
budget = None
# B-03: UCI requires `go infinite` (and bare `go`) to hold bestmove
# until `stop`, even if the search finishes early (mate break,
# depth cap). Depth/time/clock/node-limited gos report on completion.
# Ponder holds by definition (release = ponderhit/stop). Holding
# also auto-skips PM-01 certification below -- the Ponder/Premove
# mutual exclusion falls out of the existing `not hold` gate.
hold = ponder_mode or ("infinite" in params) or not any(
k in params for k in ("movetime", "wtime", "btime", "depth",
"nodes", "mate")) # FB-25: mate reports
stop_evt = threading.Event()
holding = threading.Event() # FB-14: search DONE, only holding
white_to_move = board.turn == chess.WHITE
# FB-13d: snapshot the position NOW -- a `position` command racing
# the thread's startup must not change what gets searched. on_depth
# reads the SNAPSHOT too: it derives the WDL phase from the board, and
# main's live `board` can be reassigned by a `position` command while
# the search is still streaming info lines (same race FB-13d closed
# for the search itself).
search_board = board.copy()
prev_nodes = [0] # FI-45: per-go EBF tracking
# HOST-01: best-move stability, tracked here because the ponder search
# runs on the DEPTH-mode hold rail -- cengine's own soft-stop lives in
# get_best_move_timed and never sees this search.
stab = {"move": None, "iters": 0, "changed": False}
def on_depth(rec):
mv = rec.get("move")
if mv:
if mv == stab["move"]:
stab["iters"] += 1
stab["changed"] = False
else:
stab["move"], stab["iters"], stab["changed"] = mv, 0, True
if rec.get("book"):
out(f"info string book move {rec['move']}")
elif rec.get("tb"):
out(f"info string tablebase move {rec['move']} wdl {rec['wdl']}")
out(info_line(rec, white_to_move, engine, board=search_board))
if dbg["on"]: # FI-45: `debug on` observability
n = rec.get("nodes", 0)
if prev_nodes[0] > 0 and n > prev_nodes[0]:
out(f"info string ebf={n / prev_nodes[0]:.2f}"
f" depth={rec.get('depth', 0)}")
prev_nodes[0] = n
engine.on_depth = on_depth
engine.on_final = None # final info == last depth line
def run():
# FB-02: an unhandled exception here used to kill the thread
# silently -- no bestmove EVER = the host hangs the whole slot.
# Always emit a bestmove; 0000 on error (arbiter-visible, not
# a hang).
mv = None
sm_active = False
mpv_book = None
try:
# FI-45: searchmoves -> exclude every legal move NOT listed
# (root TT store + FI-06 recorder auto-suppressed while the
# exclusion list is non-empty, per the MultiPV design).
if params.get("searchmoves"):
want = set()
for u in params["searchmoves"]:
try:
m = chess.Move.from_uci(u)
if m in search_board.legal_moves:
want.add(m)
except ValueError:
pass
if want:
engine.search_moves = want # FB-53: the book and TB
# probes run before the
# C search and must obey
# the same whitelist
engine._lib.root_exclude_clear()
for m in search_board.legal_moves:
if m not in want:
engine._lib.root_exclude_add(
m.from_square | (m.to_square << 6)
| ((m.promotion or 0) << 12))
sm_active = True
# MultiPV > 1 = analysis: bypass the opening book for the
# MAIN search too -- a book hit returns a bare bestmove with
# no PV, so every book position would show ZERO lines in the
# GUI (the gate below needs a real search). =1 keeps the
# book path byte-identical (match play never sets MultiPV).
if getattr(engine, "multipv", 1) > 1 and engine.use_book:
mpv_book, engine.use_book = engine.use_book, False
# MultiPV > 1 (analysis, never match play) replaces the
# single search entirely: _search_multipv runs its own
# deepening loop so all k lines appear from depth 1 and
# refine together, Stockfish-style. =1 and searchmoves keep
# the original path byte-identical.
if getattr(engine, "multipv", 1) > 1 and not sm_active:
mv = _search_multipv(
engine, search_board, engine.multipv, budget,
max_depth, white_to_move, stop_evt,
fixed_depth=(max_depth if "depth" in params else None))
elif budget is None:
mv = engine.get_best_move(search_board, max_depth)
else:
mv = engine.get_best_move_timed(search_board, budget,
max_depth)
except Exception as ex:
print(f"cuci: search error: {ex!r}", file=sys.stderr)
finally:
if mpv_book is not None: # restore the book setting the
engine.use_book = mpv_book # MultiPV bypass overrode
if sm_active: # FI-45: NEVER leak exclusions
engine._lib.root_exclude_clear()
engine.search_moves = None # FB-53: nor the whitelist
engine.node_limit = None # FB-09: per-go, don't leak
holding.set() # FB-14/FI-27: set BEFORE the
# hold-wait AND as early as the
# search result exists -- a go
# arriving in the gap is handed
# off, not dropped. Release
if hold: # is instant -- no search running
stop_evt.wait() # B-03: hold until `stop`
bm_str = mv.uci() if mv is not None else "0000"
pv = (engine.last_pv or "").split()
if mv is not None and len(pv) >= 2 and pv[0] == bm_str:
out(f"bestmove {bm_str} ponder {pv[1]}") # FI-45 hint;
else: # go-ponder itself is real now
out(f"bestmove {bm_str}") # (FI-13e, 2026-07-21)
if ("mate" in params and mv is not None
and abs(engine.last_score) < engine.MATE_THRESHOLD):
out(f"info string no mate found in <={params['mate']}")
hf_ring.append(engine._lib.cs_hashfull()) # FI-45: per-move
del hf_ring[:-64] # trajectory, dumped on quit
# PM-01: certified premoves, computed on the OPPONENT'S clock
# (we are idle after bestmove). Not for held searches (a new
# position is coming) or after a stop.
if engine.premove_on and not hold:
try: # pygin-end ALWAYS follows (the
if mv is None or stop_evt.is_set(): # bridge's collector
raise StopIteration # needs a terminator either way)
_sv = (engine.last_score, engine.last_pv,
engine.last_depth, engine.nodes_searched,
engine.use_book, engine.smp_workers,
engine.on_depth, engine.on_final)
try:
engine.on_depth = engine.on_final = None
engine.use_book = False # cert needs real scores
engine.smp_workers = 1 # ms-scale probes: no SMP
pairs = certify_premoves(
engine, search_board, mv, stop_evt)
for r, m in pairs:
out(f"info string pygin-reply {r.uci()} {m.uci()}")
except Exception as ex:
print(f"cuci: premove cert error: {ex!r}",
file=sys.stderr)
finally:
(engine.last_score, engine.last_pv,
engine.last_depth, engine.nodes_searched,
engine.use_book, engine.smp_workers,
engine.on_depth, engine.on_final) = _sv
except StopIteration:
pass
finally:
out("info string pygin-end")
th = threading.Thread(target=run, daemon=True)
th.stop_evt = stop_evt
th.holding = holding
th.ponder = {"active": ponder_mode, "hit": False,
"params": params, "board": search_board}
th.stab = stab # HOST-01: read by the ponderhit
# watcher, written by on_depth
return th
for raw in sys.stdin:
# BUG-01: malformed input must never kill the process mid-game --
# that's an instant forfeit (uci.py's Z-02 rule). Log + continue.
try:
line = raw.strip()
if not line:
continue
tokens = line.split()
cmd = tokens[0]
if cmd == "uci":
out(f"id name {NAME}")
out(f"id author {AUTHOR}")
out("option name Threads type spin default 1 min 1 max 512")
out("option name MultiPV type spin default 1 min 1 max 20")
out("option name OwnBook type check default true")
out("option name BookFile type string default <empty>")
out("option name UseTB type check default false")
# P-26 tuning knobs are NOT advertised (2026-07-24): they are
# search internals with no user-facing meaning, and eleven
# extra spins in every GUI's option dialog is noise. The
# setoption handlers below still accept them, so
# chess-tuning-tools and any script that sets them by name
# keeps working -- they are hidden, not removed.
out("option name Premove type check default false")
out("option name UCI_ShowWDL type check default true")
out("option name Ponder type check default false")
out("option name Clear Hash type button")
out("option name Contempt type spin default 50 min -100 max 100")
out("option name Move Overhead type spin default 40 min 0 max 5000")
# P-35/U-06 time policy, exposed so the neighbourhood can be
# swept from a GUI or a match harness without editing source
# or rebuilding. Defaults ARE the shipped values, so an engine
# nobody configures is byte-identical to before.
out(f"option name SoftStop type spin default "
f"{0 if SOFT_BASE is None else int(round(SOFT_BASE * 100))}"
f" min 0 max 100")
out(f"option name SoftStopStable type spin default "
f"{int(round(engine.SOFT_STOP_STABLE_FRAC * 100))}"
f" min 0 max 100")
out(f"option name SoftStopUnstable type spin default "
f"{int(round(engine.SOFT_STOP_UNSTABLE_FRAC * 100))}"
f" min 0 max 100")
out(f"option name SoftStopStableIters type spin default "
f"{int(engine.SOFT_STOP_STABLE_ITERS)} min 1 max 20")
out(f"option name Hash type spin default 192 min 2 "
f"max {HASH_MAX_MB}")
# Stockfish-style eval banner, read from the net's own 64-byte
# header rather than from constants that could drift from the
# file. self.USE_NNUE (not the class attr) is what actually
# got armed, so a SIMD guard that disarmed the net says so
# here instead of leaving the GUI to guess from a silent line.
out(_nnue_banner(engine))
# FI-13d: self-identifying config line (A/B forensics: PGN
# headers grep this to know exactly what was playing).
out(f"info string abi={engine._lib.csearch_abi()}"
f" pv_exact={int(engine.PV_EXACT)}"
f" check_ext_budget={engine.CHECK_EXT_BUDGET}"
f" outpost={int(engine.USE_OUTPOST)}"
f" score_hygiene={int(engine.SCORE_HYGIENE)}"
f" simplify={int(engine.USE_SIMPLIFY)}"
f" ep_filter={int(engine.EP_FILTER)}"
f" cb2={int(engine.CB2)}"
f" cantwin={int(engine.CANTWIN)}"
f" null_verify={int(engine.NULL_VERIFY)}"
f" lmr_hist={engine.LMR_HIST}"
f" tt_eval_sharpen={int(engine.TT_EVAL_SHARPEN)}"
f" see_prune={int(engine.SEE_PRUNE)}"
f" root_order={int(engine.ROOT_ORDER)}"
f" qs_evict_max={engine.QS_EVICT_MAX}"
f" hist_prune={engine.HIST_PRUNE}"
f" qs_tt_sharpen={int(engine.QS_TT_SHARPEN)}"
f" qs_keep_move={int(engine.QS_KEEP_MOVE)}"
f" cycle={int(engine.CYCLE_DETECT)}"
f" qs_beta_narrow={int(engine.QS_BETA_NARROW)}"
f" qs_ttm_exempt={int(engine.QS_TTM_EXEMPT)}"
f" qs_chk_d1={int(engine.QS_CHK_D1)}"
f" tt_keep_exact={engine.TT_KEEP_EXACT}"
f" tt_fh_tight={int(engine.TT_FH_TIGHT)}"
f" tt_r50={int(engine.TT_R50)}"
f" term_store={int(engine.TERM_STORE)}"
f" tt_mate_cut={int(engine.TT_MATE_CUT)}"
f" root_lmr={int(engine.ROOT_LMR)}"
f" iir_weak={int(engine.IIR_WEAK)}"
f" lmr_badcap={int(engine.LMR_BADCAP)}"
f" null_nodouble={int(engine.NULL_NODOUBLE)}"
f" null_evalr={int(engine.NULL_EVALR)}"
f" qs_evasion_cap={engine.QS_EVASION_CAP}"
f" singular={int(engine.SINGULAR)}"
f" se={engine.SE_MIN_DEPTH}/{engine.SE_MARGIN}"
f" killer_inherit={int(engine.KILLER_INHERIT)}"
f" quiet_malus_all={int(engine.QUIET_MALUS_ALL)}"
f" use_nnue={int(engine.USE_NNUE)}"
f" king_shelter={int(engine.USE_KING_SHELTER)}"
f" tt_keep_warm={int(engine.TT_KEEP_WARM)}"
f" simplify_threshold={engine.SIMPLIFY_THRESHOLD}"
f" contempt={engine.contempt}"
f" hash_bits={engine.TT_BITS}"
f" threads={engine.smp_workers}")
out("uciok")
elif cmd == "isready":
out("readyok")
elif cmd == "setoption" and len(tokens) >= 3 and tokens[1] == "name":
# FB-13a: UCI option names may be MULTI-WORD ("Move Overhead")
# -- parse name as everything up to the `value` keyword and
# normalize by dropping spaces, so single-word names keep
# matching exactly as before.
if "value" in tokens:
vi = tokens.index("value")
name = "".join(tokens[2:vi]).lower()
value = " ".join(tokens[vi + 1:])
else:
name = "".join(tokens[2:]).lower()
value = ""
if name == "threads":
# 512 = csearch.c's CS_MAX_THREADS; keep the three
# clamps (here, cengine, battle_worker) in step with it.
engine.smp_workers = max(1, min(512, int(value)))
# Confirm it, Stockfish-style. Silence here cost a real
# measurement: `setoption name Threads 4` (no `value`
# keyword) parses as the option NAME "threads4", matches
# nothing, and was dropped without a word -- so a 112-
# thread benchmark ran single-threaded and read 1.8M nps.
out(f"info string Using {engine.smp_workers} threads")
elif name == "multipv":
engine.multipv = max(1, min(20, int(value)))
elif name == "ponder":
engine.ponder_ok = value.lower() == "true" # FI-13e:
# informational -- go-ponder is honored whenever it
# arrives; the option exists so GUIs enable pondering
elif name == "ownbook":
engine.use_book = value.lower() == "true"
elif name == "bookfile":
# Point at a custom Polyglot .bin; empty/<empty> restores
# the auto-discovered bundled book (Perfect2023.bin ...).
engine.book_path = None if value in ("", "<empty>") else value
elif name == "usetb":
engine.use_tb = value.lower() == "true" # online Lichess