355 Commits
Author SHA1 Message Date
rektdie edfa6ead28 storing score into tt correctly on mate | bench 1632393 2026-10-03 17:16:16 +02:00
rektdie 134af1abde Merge pull request #193 from rektdie/lazy-acc-with-finny
lazy accumulator updates with finny tables bench 1632393
2026-10-03 16:38:26 +02:00
rektdie 1e41671002 lazy accumulator updates with finny tables 1632393 2026-10-03 16:13:52 +02:00
rektdie dd831d14bf Merge pull request #192 from rektdie/fix-qs-tt-write
check for stop before writing into qs tt (cutnode) | bench 1402552
2026-10-03 15:58:20 +02:00
rektdie ae3a39cf04 check for stop before writing into qs tt (cutnode) | bench 1402552 2026-10-03 15:57:50 +02:00
rektdie aa120b14f9 Merge pull request #191 from rektdie/pvs-see-notmated
pvs see not mated guard | bench 1632393
2026-10-03 09:27:30 +02:00
rektdie 4c67267c8c pvs see not mated guard | bench 1632393 2026-10-03 09:21:09 +02:00
rektdie 2c4292c485 Merge pull request #190 from rektdie/excluded-terminal-decision
when moveseen = 0, returning alpha in case of excluded move | bench 1293332
2026-10-03 09:19:53 +02:00
rektdie f77c4c1fbd when moveseen = 0, returning alpha in case of excluded move | bench 1293332 2026-10-01 22:47:27 +02:00
rektdie e64c6c60b9 Merge pull request #189 from rektdie/fix-se-ss-overwrite
moving ss storing under se to prevent overwriting | bench 1342782
2026-10-01 18:30:02 +02:00
rektdie de1d0e22ff moving ss storing under se to prevent overwriting | bench 1342782 2026-09-30 20:01:33 +02:00
rektdie d593833e9e Merge pull request #188 from rektdie/qs-switch-fix
fix switch statements in qsearch | bench 1402552
2026-09-30 19:58:05 +02:00
rektdie a2297ed04e fix switch statements in qsearch | bench 1402552 2026-09-30 18:40:22 +02:00
rektdie ecd57607f3 Merge pull request #187 from rektdie/corrhist-fh
corrhist update on fail high | bench 1202015
2026-09-28 20:51:59 +02:00
rektdie be9982eb75 corrhist update on fail high | bench 1202015 2026-09-28 19:13:14 +02:00
rektdie babe3d0db0 Merge pull request #186 from rektdie/50mr-scaling
50 mr scaling | bench 1331806
2026-09-26 09:52:42 +02:00
rektdie 30e54c2b71 50 mr scaling | bench 1331806 2026-09-19 21:31:08 +02:00
rektdie 1470ad34a8 Merge pull request #185 from rektdie/more-stages
more stages in movepicker | bench 1468577
2026-09-19 21:22:25 +02:00
rektdie f23a59730b more stages in movepicker | bench 1468577 | bench 1468577 2026-09-19 15:59:05 +02:00
rektdie dbd56e0c21 Update README.md 2026-05-13 22:46:52 +02:00
rektdie 390ee23e75 updated version number | bench 1246472 2026-04-22 01:23:31 +02:00
rektdie 4ebdeb54f6 Merge pull request #183 from rektdie/windows-build-fix
windows builds with clang++ too | bench 1246472
2026-04-22 01:08:05 +02:00
rektdie 4e437d52fc windows builds with clang++ too | bench 1246472 2026-04-22 00:52:00 +02:00
rektdie a3255581fb Merge pull request #182 from rektdie/smp-crash-fix
smp crash fix | bench 1246472
2026-04-21 15:08:27 +02:00
rektdie 24a36414f8 smp crash fix | bench 1246472 2026-04-21 00:26:57 +02:00
rektdie f0b4e42f17 Update README.md 2026-04-18 17:49:55 +02:00
rektdie 4e95413c4d update version number | bench 1246472 2026-04-18 17:27:23 +02:00
rektdie 19ea29b902 Merge pull request #181 from rektdie/razoring-no-lower
prevent razoring when tt is lower bound | bench 1246472
2026-04-18 10:56:24 +02:00
rektdie 9fcef9c3c8 prevent razoring when tt is lower bound | bench 1246472 2026-04-17 12:33:24 +02:00
rektdie 7ab07c8c71 increase windows stack size | bench 1476617 2026-04-17 12:24:19 +02:00
rektdie 7e3287be71 Merge pull request #180 from rektdie/8-king-buckets
8 king input buckets | bench 1476617
2026-04-13 17:39:31 +02:00
rektdie 9642d606dc 8 king input buckets | bench 1476617 2026-04-10 07:06:08 +02:00
rektdie dc52b7846a Merge pull request #179 from rektdie/6-buckets
6 input buckets | bench 1228578
2026-04-09 05:18:11 +02:00
rektdie 0b18805f00 6 input buckets | bench 1228578 2026-04-08 21:19:37 +02:00
rektdie 469ff7237c using non normalised evaluation for staticeval in datagen
bench: 1181803
2026-04-05 03:13:52 +02:00
rektdie 0f410353d1 Removed comments
bench: 1181803
2026-04-05 03:09:20 +02:00
rektdie b2eb9ca81a Merge pull request #178 from rektdie/refactor
Refactor
bench: 1181803
2026-04-05 03:07:21 +02:00
rektdie e4d114a763 very small refactor | bench 1181803 2026-04-05 03:06:43 +02:00
rektdie 68d7dcbccb GetPromoPiece helper function | bench 1181803 2026-04-05 02:58:40 +02:00
rektdie 7db4fcf59c small refactor | bench 1181803 2026-04-05 02:52:47 +02:00
rektdie 00f0d06381 okay, actually disable it | bench 1181803 2026-04-04 12:44:42 +02:00
rektdie 0f849c1b7f disable material scaling in datagen
bench: 1181803
2026-04-04 12:33:06 +02:00
rektdie 4c4e6d15c8 Merge pull request #177 from rektdie/spsa
Spsa
bench 1181803
2026-04-04 00:12:51 +02:00
rektdie d1bcec29ce disabled tuning | bench 1181803 2026-04-04 00:12:28 +02:00
rektdie c4886db1fe 8k iters 5k games | bench 1181803 2026-04-03 19:34:52 +02:00
rektdie caac437db7 fixed rfp min max | bench 1398874 2026-04-02 00:44:40 +02:00
rektdie de6b96bbf8 removed poisonous parameters | bench 1398874 2026-04-02 00:37:18 +02:00
rektdie 34018414df more tunables | bench 1398874 2026-04-02 00:29:11 +02:00
rektdie d4ed1a3f40 reverted to previous nmp, rfp, fp tunables | bench 1398874 2026-04-02 00:05:48 +02:00
rektdie f9160084a7 set tunable min/max values | bench 1398874 2026-04-01 23:52:09 +02:00
rektdie 04b1187963 factorized some heuristics | bench 1398874 2026-04-01 23:52:09 +02:00
rektdie f69da36c7c spsa applier script | bench 1398874 2026-04-01 23:50:42 +02:00
rektdie e3184752c0 auto calculating r_end | bench 1398874 2026-04-01 19:55:45 +02:00
rektdie cfcd24318b re-init SEE values and LMR table on tuning | bench 1398874 2026-04-01 19:22:10 +02:00
rektdie 13cb768c67 Merge pull request #176 from rektdie/ldse
low depth se | bench 1398874
2026-04-01 01:55:05 +02:00
rektdie 372ab43e8b low depth se | bench 1398874 2026-03-31 19:28:36 +02:00
rektdie 65b809d115 Merge pull request #175 from rektdie/4-king-buckets
4 king buckets
bench 1156322
2026-03-31 18:47:48 +02:00
rektdie b239ce6bf0 retrained the 1536HL net with more data | bench 1156322 2026-03-31 14:36:01 +02:00
rektdie e69294dfa3 reduced HL size to 1024
bench: 1303636
2026-03-31 14:34:50 +02:00
rektdie 454d9e61c1 4 king input buckets in the net
bench: 1311861
2026-03-31 14:34:29 +02:00
rektdie 1f2bb52418 Merge pull request #174 from rektdie/net-with-old-data
retrained net with new + old data
bench: 1011350
2026-03-30 21:54:57 +02:00
rektdie e6ec17090b retrained net with new + old data
bench: 1011350
2026-03-30 19:47:09 +02:00
rektdie 67c9e59939 Merge pull request #173 from rektdie/linear-wdl-net
stage1 linear wdl 0.2->0.4
bench: 1335064
2026-03-29 21:43:29 +02:00
rektdie f1df87a22d stage1 linear wdl 0.2->0.4
bench: 1335064
2026-03-29 17:03:28 +02:00
rektdie 9c5335b4ef Delete nnue_visualizer.html
bench: 1252943
2026-03-29 16:53:21 +02:00
rektdie e98241cc7f Merge pull request #172 from rektdie/rootdepth-se
rootdepth condition in se
bench: 1252943
2026-03-29 16:37:52 +02:00
rektdie 740be80922 rootdepth condition in se
bench: 1252943
2026-03-29 00:09:17 +01:00
rektdie eb133efba1 Merge pull request #171 from rektdie/pvs-rewrite
Pvs rewrite
bench: 1279897
2026-03-28 04:18:23 +01:00
rektdie cfe58552f2 back to old clamping
bench: 1279897
2026-03-28 03:24:26 +01:00
rektdie 36640bfe7e using min and max for reduced
bench: 1304561
2026-03-28 03:20:07 +01:00
rektdie a6549e256a fix crash
bench: 1279897
2026-03-28 03:20:07 +01:00
rektdie 21a64294cf bugfix: used moveSeen incorrectly | bench 1279897 2026-03-28 03:20:07 +01:00
rektdie ba4ffca56f bugfix
bench: 3165561
2026-03-28 03:20:07 +01:00
rektdie 081d54dc55 reworked lmr condition | bench 1189490 2026-03-28 03:20:07 +01:00
rektdie 64981dad3e SP style pvs
bench: 1204778
2026-03-28 03:20:07 +01:00
rektdie a6472893a8 Merge pull request #170 from rektdie/faster-accumulator-update
dont update accumulators for no reason

Elo   | 6.88 +- 5.27 (95%)
SPRT  | 4.0+0.04s Threads=1 Hash=8MB
LLR   | 3.05 (-2.94, 2.94) [-5.00, 0.00]
Games | N: 4796 W: 1028 L: 933 D: 2835
Penta | [30, 509, 1238, 578, 43]
https://rektdie.pythonanywhere.com/test/4154/
2026-03-28 02:53:33 +01:00
rektdie 81a9a89ac8 dont update accumulators for no reason
bench: 1315668
2026-03-28 02:41:43 +01:00
rektdie f9e0f5db1a fix max depth crash
bench: 1315668
2026-03-27 03:34:38 +01:00
rektdie aafc6af697 Merge pull request #169 from rektdie/depth7-fp
depth 7 fp | bench 1315668
2026-03-26 13:57:56 +01:00
rektdie 82737f243f depth 7 fp | bench 1315668 2026-03-26 05:51:06 +01:00
rektdie 0250f9e954 Merge pull request #168 from rektdie/wdl-model
Wdl model bench: 1308674
2026-03-24 14:24:04 +01:00
rektdie b3ffc1f32f removed a comment
bench: 1308674
2026-03-24 14:23:19 +01:00
rektdie 5f8e143cf8 WDL model
bench: 1308674
2026-03-24 14:12:53 +01:00
rektdie 2e84a1e3ab Merge pull request #166 from rektdie/tt-adjusted-nmp
using tt adjusted eval in nmp bench 1308674
2026-03-24 02:16:41 +01:00
rektdie 9d7567dfea using tt adjusted eval in nmp
bench 1308674
2026-03-24 01:07:34 +01:00
rektdie c9f6ac3849 Merge pull request #165 from rektdie/simplify-to-single-killer
simplified a killer away | bench 1207250
2026-03-23 15:01:44 +01:00
rektdie feb441c380 simplified a killer away | bench 1207250 2026-03-23 10:50:40 +01:00
rektdie 0a7be07d0f Merge pull request #164 from rektdie/reorder-alpha-raise
place alpha raise above beta cutoff | bench 1136840
2026-03-23 10:46:18 +01:00
rektdie 61da1c4d58 place alpha raise above beta cutoff | bench 1136840 2026-03-23 02:55:59 +01:00
rektdie 2bde715482 removed unused fmt header | bench 1115526 2026-03-23 01:24:43 +01:00
rektdie 41b421ded5 Merge pull request #163 from rektdie/lmr-ttpv-fail-low
lmr ttpv fail low | bench 1115526
2026-03-22 14:17:35 +01:00
rektdie baf0741e0d lmr ttpv fail low | bench 1115526 2026-03-22 10:56:47 +01:00
rektdie d99a35fdf0 Merge pull request #162 from rektdie/qs-see-reorder
placed qs see above makemove | bench 1302405
2026-03-20 23:38:35 +01:00
rektdie 2e952b0f92 placed qs see above makemove | bench 1302405 2026-03-20 23:15:54 +01:00
rektdie b3c3182fec Merge pull request #161 from rektdie/reorder-pvs-see
placed pvs see above making move | bench 1326788
2026-03-20 22:14:39 +01:00
rektdie 20196cb545 placed pvs see above making move | bench 1326788 2026-03-20 21:51:37 +01:00
rektdie e33b88277b Merge pull request #160 from rektdie/no-fp-direct-check
prevent fp when move gives direct check | bench 1847720
2026-03-20 19:45:46 +01:00
rektdie 9885596770 prevent fp when move gives direct check | bench 1847720 2026-03-20 13:48:58 +01:00
rektdie 83c9a2c51c Merge pull request #159 from rektdie/rfp-return
changed rfp return value | bench 1833557
2026-03-20 12:01:59 +01:00
rektdie ad7041c0a4 changed rfp return value | bench 1735187 2026-03-20 12:01:02 +01:00
rektdie 73d2945e95 Merge pull request #158 from rektdie/clear-killers
before main search, clear killers of the next ply | bench 1508380
2026-03-20 09:35:46 +01:00
rektdie b1b7b8234d before main search, clear killers of the next ply | bench 1508380 2026-03-19 23:42:43 +01:00
rektdie 8a2ada7165 Merge pull request #157 from rektdie/net2.0
Net2.0 bench 1723589
2026-03-19 13:07:30 +01:00
rektdie 506487f396 set the fine-tuning init lr higher | bench 1576425 2026-03-19 00:18:04 +01:00
rektdie 05ce50e647 same config as last time | bench 1530246 2026-03-19 00:18:04 +01:00
rektdie c2f2730114 Merge pull request #156 from rektdie/redundant-mailbox
added a redundant mailbox to board class | bench 1538206
2026-03-16 23:21:06 +01:00
rektdie e06e1cdac1 added a redundant mailbox to board class | bench 1538206 2026-03-16 22:53:03 +01:00
rektdie 94eced67f6 Merge pull request #155 from rektdie/nmp-r-tt-capture
increase reduction if tt move is capture | bench 1538206
2026-03-15 20:34:39 +01:00
rektdie b5a34eda5e increase reduction if tt move is capture | bench 1538206 2026-03-15 16:04:02 +01:00
rektdie 8b2c55eae4 Merge pull request #154 from rektdie/material-scaling
material scaling | bench 1630597
2026-03-15 15:24:46 +01:00
rektdie aea6985817 material scaling | bench 1630597 2026-03-15 14:29:39 +01:00
rektdie e7731361cd Merge pull request #152 from rektdie/qs-tt-fix
fixed 2 wrong comparisons when setting bestScore | bench 1652455
2026-03-14 13:16:08 +01:00
rektdie 7586608aaa fixed 2 wrong comparisons when setting bestScore | bench 1652455 2026-03-14 03:03:08 +01:00
rektdie 1814cbc755 Merge pull request #151 from rektdie/fix-qs-tt
fixed tt usage in qs and added cutoffs too | bench 1606096
2026-03-14 02:38:58 +01:00
rektdie 020132ea3c fixed tt usage in qs and added cutoffs too | bench 1606096 2026-03-14 02:05:41 +01:00
rektdie 1bdedebf96 Merge pull request #150 from rektdie/history-bonus-fail-low
bench 1617873
2026-03-14 01:33:17 +01:00
rektdie 692ec62aac bench 1617873 2026-03-14 00:52:14 +01:00
rektdie ce3ed3b6d1 fixed windows compatibility | bench 1743358 2026-03-04 23:41:42 +01:00
rektdie 345c6d21d9 separate tt for datagen | bench 1743358 2026-03-03 20:45:18 +01:00
rektdie 0d126aa6a7 Merge pull request #149 from rektdie/tt-aging
tt aging | bench 1743358
2026-02-26 11:48:50 +01:00
rektdie 5ca125e336 tt aging | bench 1743358 2026-02-26 02:21:48 +01:00
rektdie 855e5c2377 Merge pull request #148 from rektdie/ttpv-no-rfp
prevent rfp in ttpv nodes | bench 2041087
2026-02-26 01:39:02 +01:00
rektdie 7e621311e6 prevent rfp in ttpv nodes | bench 1738647 2026-02-26 01:37:39 +01:00
rektdie b2a475ff5f Merge pull request #146 from rektdie/major-corrhist
major correction history | bench 1744326
2026-02-25 16:36:00 +01:00
rektdie 4b3e8020fa major correction history | bench 1744326 2026-02-25 10:57:33 +01:00
rektdie 194c3d3bc4 Merge pull request #145 from rektdie/lazy-smp
Lazy smp bench 1801941
2026-02-25 09:02:30 +01:00
rektdie b929963f91 added pseudo legality checking and testing tt move in movepicker | bench 1801941 2026-02-25 01:17:15 +01:00
rektdie 079959e6d4 Revert "maybe fixed crashes | bench 1801941"
This reverts commit 64b2e3d9b1.
2026-02-24 23:39:59 +01:00
rektdie 64b2e3d9b1 maybe fixed crashes | bench 1801941 2026-02-24 23:34:26 +01:00
rektdie eac21b424a old crashing lazy-smp | bench 1801941 2026-02-24 23:27:30 +01:00
rektdie cce6f5dd0c Delete results
bench 1801941
2026-02-24 22:24:13 +01:00
rektdie 7e4d5889a8 Merge pull request #144 from rektdie/nmp-verif
nmp verification search against zugzwangs | bench 1801941
2026-02-24 10:53:01 +01:00
rektdie 71d3b3309a nmp verification search against zugzwangs | bench 1801941 2026-02-23 00:08:36 +01:00
rektdie d662594814 Merge pull request #143 from rektdie/fix-reduntant-scoring
removed unneccessary move scoring | bench 1895470
2026-02-22 23:00:40 +01:00
rektdie 9be74da127 removed unneccessary move scoring | bench 1895470 2026-02-22 20:47:46 +01:00
rektdie 85cdb7e077 Merge pull request #142 from rektdie/incremental-sort
Incremental sort bench 1690249
2026-02-20 14:38:08 +01:00
rektdie a3d2f352d3 faster method | bench 1690249 2026-02-20 13:14:45 +01:00
rektdie 4dcf0d04a0 incremental sort | bench 1690249 2026-02-20 12:48:24 +01:00
rektdie 91b5062549 Merge pull request #141 from rektdie/movepicker
very simple movepicker with 2 stages | bench 1814124
2026-02-20 12:40:26 +01:00
rektdie a7ef4ee4a9 very simple movepicker with 2 stages | bench 1814124 2026-02-20 09:55:51 +01:00
rektdie 2e802d7dfe killerMoves were stored as ints | bench 1812688 2026-02-20 00:32:37 +01:00
rektdie 81bd4648e3 Merge pull request #140 from rektdie/is-legal
fixed rare ep legality bug | bench 1812688
2026-02-19 16:42:57 +01:00
rektdie 48bbfa7114 fixed rare ep legality bug | bench 1812688 2026-02-19 16:16:32 +01:00
rektdie 320c43cdd3 cleanup | bench 1812688 2026-02-19 15:12:17 +01:00
rektdie a9b51e384f isLegal function | bench 1812688 2026-02-19 15:06:57 +01:00
rektdie 1fb235fb3f added pinned and checker bitboard | bench 1812688 2026-02-19 12:49:49 +01:00
rektdie 0f748da56c Merge pull request #137 from rektdie/tt-buckets
tt buckets | bench 1783856
2026-02-15 19:51:26 +01:00
rektdie fd2168d529 Merge pull request #136 from rektdie/tt-adjusted-rfp
Tt adjusted rfp

bench 1774202
2026-02-15 08:44:14 +01:00
rektdie 41dabc2150 tt buckets | bench 1783856 2026-02-14 23:27:51 +01:00
rektdie f114a6d0bb tthit condition | bench 1774202 2026-02-14 21:15:33 +01:00
rektdie 7cf8b381ce removed no tthit condition | bench 1997703 2026-02-14 20:38:16 +01:00
rektdie 1f0b36764d returning staticeval | bench 1795203 2026-02-14 20:34:21 +01:00
rektdie 2fd3cf0d2a tt adjusted rfp | bench 4065988 2026-02-14 20:31:27 +01:00
rektdie 931b6fa999 Merge pull request #135 from rektdie/ttpv-lmr
Ttpv lmr bench 2066954
2026-01-08 08:30:35 +01:00
rektdie ba3505afc8 extend less | bench 2066954 2026-01-06 22:45:10 +01:00
rektdie 6ed9e882f8 ttpv lmr | bench 6760868 2026-01-06 22:44:07 +01:00
rektdie 0df0921c47 lowered bench depth | bench 1386177 2026-01-06 22:43:52 +01:00
rektdie 865eac5782 Update CCRL ratings in README.md
bench 4083464
2025-12-24 10:09:51 +01:00
rektdie 9421d254f7 Merge pull request #134 from rektdie/2ply-conthist
2ply conthist bench 4083464
2025-12-16 13:22:03 +01:00
rektdie d71e264bb9 adding instead of setting | bench 4083464 2025-12-16 07:09:30 +01:00
rektdie 031b5285ed 2ply conthist | bench 3966908 2025-12-16 06:23:25 +01:00
rektdie 9e5f131105 Merge pull request #133 from rektdie/capthist-lmr
capthist lmr | bench 4306521
2025-12-15 13:42:29 +01:00
rektdie f4bf94eb98 capthist lmr | bench 4306521 2025-12-15 03:44:32 +01:00
rektdie 75022da950 Merge pull request #132 from rektdie/capthist
Capthist bench 3395979
2025-12-13 23:53:44 +01:00
rektdie 5bc4459111 bugfix: used wrong index in malus | bench 3395979 2025-12-13 22:51:56 +01:00
rektdie 65f7b3f38a capthist | bench 3476414 2025-12-13 22:27:00 +01:00
rektdie 370dc43660 updated readme | 4094041 2025-12-05 03:21:01 +01:00
rektdie f1b99803a1 updated version number | bench 4094041 2025-12-05 03:18:46 +01:00
rektdie 7595b0a3fd Merge pull request #130 from rektdie/razoring
Razoring bench 4094041
2025-12-04 18:47:41 +01:00
rektdie cdedcbb5f5 no score check in razoring | bench 3942380 2025-12-04 01:48:05 +01:00
rektdie 49994dc480 moved razoring above nmp | bench 4070172 2025-12-04 01:48:05 +01:00
rektdie 6c8869040f razoring | bench 4070172 2025-12-04 01:48:05 +01:00
rektdie 6288bdc3f8 Merge pull request #129 from rektdie/net1.9-1536hl-finetuned
fine tuned version | bench 4341692
2025-12-03 14:20:14 +01:00
rektdie 9e068e3f7d fine tuned version | bench 4341692 2025-12-03 11:23:29 +01:00
rektdie 7ac8efa027 Enhance README with badges 2025-11-13 06:34:17 +01:00
rektdie 5754772a70 online datagen | bench 4699541 2025-11-11 00:52:34 +01:00
rektdie 90bdd3cc96 made datagen shutdown-safe | bench 4699541 2025-11-10 10:26:39 +01:00
rektdie d35eb66dbc datagen merges files | bench 4699541 2025-11-10 08:06:25 +01:00
rektdie 2e46f0d1cd a bit more efficient accumulator updating | bench 4699541 2025-11-07 10:55:31 +01:00
rektdie 9ce97946d5 Merge pull request #128 from rektdie/check-extensions-verif
not extending on checks during se verification | bench 4699541
2025-11-04 10:12:29 +01:00
rektdie 90cfd93135 not extending on checks during se verification | bench 4699541 2025-11-03 22:19:56 +01:00
rektdie a56e983bf7 Merge pull request #127 from rektdie/nmp-beta-margin
nmp beta margin | bench 4350979
2025-11-03 21:26:31 +01:00
rektdie 66865fa84e nmp beta margin | bench 4350979 2025-11-03 18:48:55 +01:00
rektdie acee84c134 datagen issues fixed | bench 4317404 2025-11-01 02:34:59 +01:00
rektdie 2474c13fe0 ShouldStop helper function | bench 4317404 2025-10-31 02:56:47 +01:00
rektdie d37ba0cdaa Merge pull request #126 from rektdie/corrplexity-lmr
added corrplexity to lmr | bench 4317404
2025-10-30 06:48:58 +01:00
rektdie 925289015f added corrplexity to lmr | bench 4317404 2025-10-29 23:48:57 +01:00
rektdie 318d52b2dd Merge pull request #125 from rektdie/lmrdepth-fp
Lmrdepth fp bench 4230568
2025-10-29 07:51:53 +01:00
rektdie 6ed9e6f0c8 forgot to change depth multiplier | bench 4230568 2025-10-29 02:35:52 +01:00
rektdie c6f2c3cacb added lmrdepth to fp | bench 5012961 2025-10-29 00:05:08 +01:00
rektdie b3472092e2 Merge pull request #124 from rektdie/lmr-rework
little lmr rework | bench 4738833
2025-10-26 22:31:27 +01:00
rektdie d76e7796bc little lmr rework | bench 4738833 2025-10-26 13:47:08 +01:00
rektdie 0d3c23ed73 little refactor | bench 5408634 2025-10-23 01:52:57 +02:00
rektdie 222a079c1f Merge pull request #121 from rektdie/cutnode-tweak
a bit tweak from furypasta2.0 | bench 5408634
2025-10-13 15:07:18 +02:00
rektdie d5d51c9888 a bit tweak from furypasta2.0 | bench 5408634 2025-10-13 01:46:30 +02:00
rektdie 3a02122fd4 Merge pull request #120 from rektdie/movegen-separation
added new movegen type: quiets | bench 5105878
2025-10-12 23:52:59 +02:00
rektdie e8aec47b71 added new movegen type: quiets | bench 5105878 2025-10-12 23:40:18 +02:00
rektdie 17a0a97896 removed unnecessary if condition in MakeMove | bench 5105878 2025-10-12 19:52:15 +02:00
rektdie be6585268b Merge pull request #119 from rektdie/probcut
added probcut, implementation taken from SP | bench 5105878
2025-10-12 12:24:28 +02:00
rektdie 916da35e4f added probcut, implementation taken from SP | bench 5105878 2025-10-12 01:30:08 +02:00
rektdie 5c247f5e1d Merge pull request #118 from rektdie/separate-lmr
Separate lmr bench 5478784
2025-10-08 23:13:54 +02:00
rektdie a8ac4c7feb diff values | bench 5478784 2025-10-08 11:40:20 +02:00
rektdie f71e6c20e1 bugfix: used wrong variable type | bench 5480424 2025-10-07 20:59:42 +02:00
rektdie 1e62f6adef separated quiets from noisies | bench 3663120 2025-10-07 19:52:11 +02:00
rektdie 0ff5a226ee Merge pull request #117 from rektdie/pretty-print
Pretty print bench 6238369
2025-10-07 13:32:00 +02:00
rektdie 670907dd8c added pretty printing | bench 6238369 2025-10-07 01:48:02 +02:00
rektdie 5c6d75e9ef separated printings | bench 6238369 2025-10-06 17:56:46 +02:00
rektdie 6b5c1bbaa7 Merge pull request #116 from rektdie/net1.8
Net1.8 bench 6238369
2025-10-02 14:01:14 +02:00
rektdie 480216e1c8 Merge pull request #115 from rektdie/higher-wdl
trained on 0.4 WDL | bench 6238369
2025-10-02 13:11:07 +02:00
rektdie 5358bd599e trained on 0.4 WDL | bench 6238369 2025-10-02 09:46:20 +02:00
rektdie 435805a207 Merge pull request #114 from rektdie/higher-wdl
0.3 wdl training | bench 6903485
2025-10-01 09:47:18 +02:00
rektdie 2ef378d4d2 0.3 wdl training | bench 6903485 2025-10-01 06:55:10 +02:00
rektdie 0dfbb1c27b new neural net, now with HM, trained on 11GB of viripack data| bench 6223715 2025-09-30 07:30:34 +02:00
rektdie b152fd40eb Merge pull request #113 from rektdie/qs-write
writing to tt in qs | bench 6088444
2025-09-21 19:52:58 +02:00
rektdie 93339c7728 writing to tt in qs | bench 6088444 2025-09-21 17:14:33 +02:00
rektdie 4a050aeddb Merge pull request #112 from rektdie/qs-fp
added qs fp | bench 6299890
2025-09-21 01:23:34 +02:00
rektdie 136af4adef added qs fp | bench 6299890 2025-09-21 00:05:26 +02:00
rektdie 307bbfede2 fixed nodes bestmove printing | bench 6448969 2025-09-18 14:17:37 +02:00
rektdie e7d8044745 Merge pull request #111 from rektdie/threats-hist
Threats hist bench 6448969
2025-09-17 01:34:44 +02:00
rektdie 10a0f502ae fixed threats hist? | bench 6448969 2025-09-17 01:06:37 +02:00
rektdie 1dd0e33d2b added threats hist | bench 5938098 2025-09-17 00:42:04 +02:00
rektdie 729d24c7c8 Merge pull request #110 from rektdie/cutnode-negext
negext on cutnodes | bench 5715860
2025-09-16 18:22:35 +02:00
rektdie e2eb763012 negext on cutnodes | bench 5715860 2025-09-16 12:43:26 +02:00
rektdie b4b804027c Merge pull request #109 from rektdie/tt-prefetch
prefetching tt for speedup | bench 5829415
2025-09-15 08:03:03 +02:00
rektdie 9d26dc028d prefetching tt for speedup | bench 5829415 2025-09-15 07:53:41 +02:00
rektdie ca51e59dd9 Merge pull request #108 from rektdie/2ply-lmr-conthist
extended conthist in lmr | bench 5829415
2025-09-15 07:27:33 +02:00
rektdie 0cb4ba1a29 extended conthist in lmr | bench 5829415 2025-09-14 21:28:15 +02:00
rektdie 83e36b0883 mate printing | bench 6813804 2025-09-14 21:22:30 +02:00
rektdie bf9b97aaba Merge pull request #107 from rektdie/node-tm
Node tm bench 6813804
2025-09-14 14:42:12 +02:00
rektdie 861a354215 depth condition for node tm | bench 6813804 2025-09-14 12:03:30 +02:00
rektdie c108bfa786 bugfix in division | bench 6813804 2025-09-14 01:29:35 +02:00
rektdie 271ec4dc2a added node tm scaling | bench 6813804 2025-09-14 01:06:26 +02:00
rektdie 78aa6e2338 Merge pull request #106 from rektdie/multicut
added multicut | bench 6813804
2025-09-13 18:36:53 +02:00
rektdie 5bf770c1a9 added multicut | bench 6813804 2025-09-13 12:06:35 +02:00
rektdie 32b2b9c92e Merge pull request #105 from rektdie/rfp-base
added a base to rfp | bench 6836864
2025-09-11 14:52:09 +02:00
rektdie 4c04bf2830 added a base to rfp | bench 6836864 2025-09-11 10:19:21 +02:00
rektdie 5519f300b5 Merge pull request #104 from rektdie/non-pawn-corrhist
enabled non pawn corrhist | bench 6547831
2025-09-10 15:08:47 +02:00
rektdie 1c4762e872 enabled non pawn corrhist | bench 6547831 2025-09-10 01:27:45 +02:00
rektdie 32691d2d65 reworked corrhist handling | bench 6409786 2025-09-10 01:26:42 +02:00
rektdie 3e652df8e8 Update README.md 2025-09-09 18:46:16 +02:00
rektdie f32251ac98 Merge pull request #103 from rektdie/depth-2-lmr
lowered LMR depth | bench 6409786
2025-09-09 13:39:17 +02:00
rektdie cabebb502e lowered LMR depth | bench 6409786 2025-09-09 09:05:56 +02:00
rektdie 6d2500428e Merge pull request #102 from rektdie/fp-improving
fp less when improving | bench 7573487
2025-09-09 08:35:15 +02:00
rektdie de2d441b0f fp less when improving | bench 7573487 2025-09-09 00:50:19 +02:00
rektdie 4123ab731f Merge pull request #101 from rektdie/lmp-improving
Lmp improving bench 6535365
2025-09-08 23:14:24 +02:00
rektdie 014d5e05b1 different formula | bench 6535365 2025-09-08 21:03:50 +02:00
rektdie f81a730994 changed lmp improving formula | bench 6706047 2025-09-08 20:49:01 +02:00
rektdie 07abe2529e lmp less when improving | bench 5654977 2025-09-08 18:06:37 +02:00
rektdie d2586bec7d resetting seldepth between ID iterations | bench 6293651 2025-09-08 18:01:27 +02:00
rektdie f5f51496b3 disabled tuning | bench 6293651 2025-09-08 17:53:23 +02:00
rektdie 4579172fab Merge pull request #100 from rektdie/lmp-formula
Lmp formula bench 6293651
2025-09-08 17:51:56 +02:00
rektdie a3d505aec4 changed lmp conditions | bench 6293651 2025-09-08 12:50:54 +02:00
rektdie 9b86aaa0a1 diff lmp formula | bench 6480665 2025-09-08 01:02:49 +02:00
rektdie 1ca2ba0352 Merge pull request #99 from rektdie/lmr-improving-more
reducing more when not improving | bench 6594120
2025-09-08 00:17:10 +02:00
rektdie 95945633f1 reducing more when not improving | bench 6594120 2025-09-07 22:30:19 +02:00
rektdie cc64cbd6a9 Merge pull request #98 from rektdie/asp-delta
lowered asp delta | bench 8401899
2025-09-07 22:25:10 +02:00
rektdie 875363376b lowered asp delta | bench 8401899 2025-09-07 21:31:07 +02:00
rektdie 21b64a271a Merge pull request #97 from rektdie/tuning
bench 8216434
2025-09-07 19:44:50 +02:00
rektdie cba880886b updated tunable list | bench 8216434 2025-09-05 01:55:31 +02:00
rektdie 768b8ed178 fixed ReadParam and setoption to accept doubles | bench 8216434 2025-09-04 23:43:40 +02:00
rektdie 4b2f342d85 fixed makefile for ARM linux | bench 8216434 2025-09-04 22:57:25 +02:00
rektdie cb9051c477 printing tunables on uci | bench 8216434 2025-09-04 22:13:35 +02:00
rektdie 9f28552643 fixed printing function | bench 8216434 2025-09-04 15:46:00 +02:00
rektdie 070528286c changed print function | bench 8216434 2025-09-04 15:42:08 +02:00
rektdie b6c9bbbb8d implemented tuning | bench 8216434 2025-09-04 15:20:29 +02:00
rektdie c365bd58d8 Merge pull request #96 from rektdie/corrhist
Corrhist bench 8216434
2025-09-03 14:22:30 +02:00
rektdie 40339b2d45 changed the pawnhist update function | bench 8216434 2025-09-03 01:21:16 +02:00
rektdie 6ccd416840 removed unnecessary condition | bench 4559188 2025-09-03 01:11:35 +02:00
rektdie 2e1f84bda5 bugfix: missing curly brackets | bench 4559188 2025-09-03 01:11:35 +02:00
rektdie bf7adcb06b added pawn corrhist | bench 4741642 2025-09-03 01:11:35 +02:00
rektdie 1cf5a2971d Update README.md 2025-08-31 14:13:04 +02:00
rektdie 8d552cefd6 Merge pull request #95 from rektdie/pv-less-lmr
reduce less if pv node | bench 9411909
2025-08-30 01:48:42 +02:00
rektdie 9bb603200c reduce less if pv node | bench 9411909 2025-08-29 23:12:10 +02:00
rektdie ee404a9992 Merge pull request #94 from rektdie/double-extensions
added double extensions | bench 7531311
2025-08-29 22:47:31 +02:00
rektdie cc8a9a625b added double extensions | bench 7531311 2025-08-28 16:51:24 +02:00
rektdie f788005e40 Merge pull request #93 from rektdie/2ply-fp-conthist
added 2ply conthist to fp | bench 7251156
2025-08-28 12:59:17 +02:00
rektdie 1e073bb30d added 2ply conthist to fp | bench 8879438 2025-08-28 12:57:10 +02:00
rektdie e46076116f Merge pull request #92 from rektdie/nmp-tweak
tweaked nmp reduction | bench 7750226
2025-08-28 03:33:13 +02:00
rektdie ab68f5a6b6 tweaked nmp reduction | bench 7750226 2025-08-28 01:46:21 +02:00
rektdie 769979cafe Merge pull request #91 from rektdie/fp-conthist
added 1 ply conthist to fp | bench 8636322
2025-08-26 22:41:27 +02:00
rektdie 06b24ef1f2 added 1 ply conthist to fp | bench 8636322 2025-08-26 15:08:46 +02:00
rektdie 3451f825bb Merge pull request #90 from rektdie/negext
added very simple negext | bench 9494407
2025-08-25 19:42:15 +02:00
rektdie a52bb1f967 added very simple negext | bench 9494407 2025-08-25 18:48:28 +02:00
rektdie 86590918e1 Update README.md 2025-08-24 19:59:40 +02:00
rektdie 5f0ce8c1cf Update README.md 2025-08-24 19:33:18 +02:00
rektdie e282098265 Update README.md 2025-08-24 19:19:23 +02:00
rektdie 3135f430ad fixed pthread bug on windows | bench 10419455 2025-08-23 23:57:36 +02:00
rektdie c07858dab4 added an import to uci.cpp | bench 10419455 2025-08-23 22:14:25 +02:00
rektdie 08ac91b842 changed uci print version | bench 10419455 2025-08-23 19:35:16 +02:00
rektdie 9cadd512cf increased max plies and depths | bench 10419455 2025-08-22 18:00:21 +02:00
rektdie 53cad5f0cb Merge pull request #89 from rektdie/tt-read-fix
Tt read fix bench 10419455
2025-08-22 14:31:24 +02:00
rektdie 817d589042 small bugfix in datagen | bench 10419455 2025-08-21 15:26:49 +02:00
rektdie ec46fddfe5 returning entry by copy instead of pointer | bench 10419455 2025-08-20 02:14:58 +02:00
rektdie 0fd1add2c4 Merge pull request #88 from rektdie/tthit-no-rfp
preventing rfp when tt hit | bench 10038648
2025-08-07 00:27:15 +02:00
rektdie d9f3d0f15f preventing rfp when tt hit | bench 10038648 2025-08-06 23:29:31 +02:00
rektdie da248009a4 Merge pull request #87 from rektdie/tt-test
Tt test bench 10099292
2025-08-06 16:53:28 +02:00
rektdie ff471034f7 changed thread stack size to 8MB | bench 10099292 2025-08-06 14:36:07 +02:00
rektdie 462cb5b8ef changed std::thread to pthread | bench 10099292 2025-08-06 14:17:52 +02:00
rektdie 82255ee46d debug build | bench 63246 2025-08-06 13:22:59 +02:00
rektdie 760894dd1a fixed ttHit bool | bench 10099292 2025-08-06 02:29:11 +02:00
rektdie 311fc28c1c removed ReadEntry function | bench 10412097 2025-08-06 01:54:04 +02:00
rektdie feb11b0b08 lowered bnch depth | bench 5442689 2025-08-05 15:57:33 +02:00
rektdie a4c1a87110 Merge pull request #86 from rektdie/lmr-conthist
added 1 ply conthist to lmr | bench 25271003
2025-08-05 12:00:49 +02:00
rektdie 5bd44bfd48 added 1 ply conthist to lmr | bench 25271003 2025-08-05 03:07:30 +02:00
rektdie 20f1202c45 Merge pull request #85 from rektdie/2-ply-conthist
contest helper functions bench 24146828
2025-08-05 02:57:49 +02:00
rektdie 0e88db9b4c removed git markers | bench 24146828 2025-08-05 02:57:11 +02:00
rektdie 21148655dd fixed move scores | bench 2451113 2025-08-05 02:54:12 +02:00
rektdie 092ca2a2d1 temporarily removed 2ply conthist | bench 24146828 2025-08-05 02:52:12 +02:00
rektdie b74f6f4cbb storing otherColor in stack | bench 2298837 2025-08-05 02:42:01 +02:00
rektdie f581d919b9 different indexing for conthist | bench 2298837 2025-08-05 02:42:01 +02:00
rektdie cdfb752bfa removed unused functions & variables | bench 24146828 2025-08-05 01:13:57 +02:00
rektdie f0280a77ff Update nnue.cpp
bench 24146828
2025-08-04 20:19:10 +02:00
rektdie 994f39421d added support for mac | bench 24146828 2025-08-04 19:46:55 +02:00
rektdie 8e56bd786b Merge pull request #84 from rektdie/net1.7
trained new 1024HL net on ~3b positions | bench 24146828
2025-08-02 19:53:24 +02:00
rektdie b60860b82d trained new 1024HL net on ~3b positions | bench 24146828 2025-08-02 13:46:23 +02:00
rektdie 720fd40176 removed adj and pruning disabling during datagen | bench 26088050 2025-07-31 07:34:34 +02:00
rektdie e6318f6ff4 added adj to datagen + skipping uneven starting positions + no pruninging in movesloop in datagen | bench 26088050 2025-07-30 09:48:13 +02:00
rektdie 7887e04cc5 renamed singular score variable | bench 26088050 2025-07-29 03:18:40 +02:00
rektdie efad38fb0f Merge pull request #83 from rektdie/SE
Se bench 26088050
2025-07-29 03:01:04 +02:00
rektdie dbeec1b9c6 removed cutnode from SE | bench 27398493 2025-07-28 23:37:02 +02:00
rektdie 68377cbf7b added cutnode to SE | bench 1894069 2025-07-28 23:10:51 +02:00
rektdie a077d9bd3e added SE | bench 3280769 2025-07-28 23:04:52 +02:00
rektdie 62b9e205fc printing remaining time during datagen | bench 2172902 2025-07-25 16:37:06 +02:00
rektdie eda2480d59 Merge pull request #82 from rektdie/nmp-improving
added including to nmp + lowered condition depth by one | bench 2172902
2025-07-23 08:17:42 +02:00
rektdie 31149c7450 added including to nmp + lowered condition depth by one | bench 2172902 2025-07-23 07:42:21 +02:00
rektdie 7dbde30f08 Merge pull request #81 from rektdie/lmr-move-number
changed lmr condition | bench 2450653
2025-07-22 07:36:38 +02:00
rektdie 82a4fcdeaf changed lmr condition | bench 2450653 2025-07-21 19:08:51 +02:00
rektdie 96411d9c8f Merge pull request #80 from rektdie/history-fp
added history to fp | bench 2298837
2025-07-21 12:47:03 +02:00
rektdie d85edd9faf added history to fp | bench 2298837 2025-07-21 12:26:15 +02:00
rektdie dbde65f083 reverted accidental push | bench 2985672 2025-07-20 15:07:40 +02:00
rektdie e435ae0818 Merge pull request #79 from rektdie/conthist
bench 2985672
2025-07-20 13:06:45 +02:00
rektdie f666d1ea05 bugfix: ScoreMove didnt score the passed move, but the last in the ss | bench 2985672 2025-07-20 12:14:35 +02:00
rektdie 1832d460c5 reverted lmp formula | bench 2734093 2025-07-20 04:45:49 +02:00
rektdie 43c59f29f9 diff lmp formula | bench 2941128 2025-07-20 04:45:49 +02:00
rektdie 20c636a3b4 added Eren's lmp formula too | bench 2097722 2025-07-20 04:45:49 +02:00
rektdie 33bafd461a changed move order values | bench 2734093 2025-07-20 04:45:49 +02:00
rektdie dab5bad089 forgot to reset on ucinewgame | bench 2533622 2025-07-20 04:45:49 +02:00
rektdie 2ab4868c75 resetting ss | bench 2533622 2025-07-20 04:45:49 +02:00
rektdie 4fe645ff1b changed move ordering values | bench 2533622 2025-07-20 04:45:49 +02:00
rektdie 2181d446bf changed move ordering values | bench 2589729 2025-07-20 04:45:49 +02:00
rektdie db565c6100 changed conthist max value to half of normal hist | bench 2646638 2025-07-20 04:45:49 +02:00
rektdie d7c4383783 changed conthist max value | bench 3012327 2025-07-20 04:45:49 +02:00
rektdie c58d29ac61 added conthist malus | bench 3731826 2025-07-20 04:45:49 +02:00
rektdie 84f2fd0ea8 added 1-ply conthist without malus | bench 3298447 2025-07-20 04:45:49 +02:00
rektdie 64a85bf780 bugfix: passed ctx as std::ref in ParseGo | bench 2695095 2025-07-20 04:45:10 +02:00
rektdie 8d6314aef3 Merge pull request #78 from rektdie/net1.6
new 512HL net trained on ~3billion positions | bench 2695095
2025-07-16 01:27:33 +02:00
rektdie 9979441138 new 512HL net trained on ~3billion positions | bench 2695095 2025-07-15 16:27:47 +02:00
rektdie 0e48eefc72 printing score cp correctly | bench 3509444 2025-06-09 13:11:11 +02:00
rektdie 5e4b1faa0a Merge pull request #76 from rektdie/tt-fix
storing currMove to tt when in cutnode | bench 3509444
2025-06-06 11:29:19 +02:00
rektdie c890b04a47 storing currMove to tt when in cutnode | bench 3509444 2025-06-06 11:16:40 +02:00
rektdie bec0f3275f Merge pull request #75 from rektdie/SE
minor rework in tt | bench 3415609
2025-06-06 09:58:43 +02:00
rektdie 4564d10bcf minor rework in tt | bench 3415609 2025-06-06 09:58:24 +02:00
rektdie dec219e4d7 changed raw ctx pointer to unique | bench 3415609 2025-06-06 06:18:57 +02:00
rektdie b1fd8e6021 Merge pull request #74 from rektdie/conthist
storing searchcontext on the heap instead of the stack | bench 3415609
2025-06-05 13:38:08 +02:00
rektdie 5a45d29f66 storing searchcontext on the heap instead of the stack | bench 3415609 2025-06-05 02:03:43 +02:00
38 changed files with 5065 additions and 10598 deletions

No files matched your search

+51 -17
View File
@@ -2,41 +2,76 @@
SRC_DIR := source
OBJ_DIR := obj
CXX := clang++
EXE ?= Eleanor
EVALFILE := ./nnue.bin
CXX := clang++
ifeq ($(OS),Windows_NT)
EXE_EXT := .exe
MKDIR := mkdir
RM := rmdir /s /q
DEL := del /q
UNAME_S := Windows
ARCH := x86_64
EXE_EXT := .exe
MKDIR := mkdir
RM := rmdir /s /q
DEL := del /q
PLATFORM := windows
else
EXE_EXT :=
MKDIR := mkdir -p
RM := rm -rf
DEL := rm -f
UNAME_S := $(shell uname -s)
ARCH := $(shell uname -m)
EXE_EXT :=
MKDIR := mkdir -p
RM := rm -rf
DEL := rm -f
ifeq ($(UNAME_S),Darwin)
PLATFORM := mac
else
PLATFORM := unix
endif
endif
CXX_BASE := $(notdir $(firstword $(CXX)))
CXX_DRIVER_FLAGS :=
CXXFLAGS := -std=c++20 -O3 -flto -Wall
LDFLAGS := -O3 -flto
ifeq ($(PLATFORM),mac)
ifeq ($(ARCH),arm64)
ARCH_FLAGS := -mcpu=apple-m1
else
ARCH_FLAGS := -march=native
endif
else ifeq ($(PLATFORM),windows)
ARCH_FLAGS := -march=native
CXX_DRIVER_FLAGS += --target=$(ARCH)-w64-windows-gnu
CXXFLAGS += -pthread
LDFLAGS += -pthread
LDFLAGS += -static -Wl,--stack,8388608
else
ifeq ($(ARCH),aarch64)
ARCH_FLAGS := -mcpu=native
else
ARCH_FLAGS := -march=native
LDFLAGS += -fuse-ld=lld -static
endif
endif
CXXFLAGS += $(ARCH_FLAGS)
LDFLAGS += $(ARCH_FLAGS)
MAKEFLAGS += -j
# Source and object files
SRCS := $(wildcard $(SRC_DIR)/*.cpp)
OBJS := $(patsubst $(SRC_DIR)/%.cpp, $(OBJ_DIR)/%.o, $(SRCS))
# Final binary
$(EXE)$(EXE_EXT): $(OBJS)
$(CXX) -DEVALFILE=\"$(EVALFILE)\" $^ ./external/fmt/format.cc -o $@ -O3 -fuse-ld=lld -march=native -flto -static
$(CXX) $(CXX_DRIVER_FLAGS) $(CXXFLAGS) -DEVALFILE=\"$(EVALFILE)\" $^ -o $@ $(LDFLAGS)
# Compile .cpp -> .o
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp | $(OBJ_DIR)
$(CXX) -std=c++20 -c -o $@ $< -O3 -march=native -flto -static
$(CXX) $(CXX_DRIVER_FLAGS) $(CXXFLAGS) -c -o $@ $<
# Create object directory
$(OBJ_DIR):
$(MKDIR) $(OBJ_DIR)
# Clean up and rebuild
.PHONY: clean
clean:
ifeq ($(OS),Windows_NT)
@@ -46,4 +81,3 @@ else
@$(RM) $(OBJ_DIR)
@$(DEL) $(EXE)$(EXE_EXT)
endif
$(MAKE)
+25 -26
View File
@@ -1,42 +1,39 @@
<p align="center">
<img src="https://i.postimg.cc/NjR2CdBB/Eleanor.png" alt="Eleanor Chess Engine">
<div align="center">
<p>
<img src="https://i.postimg.cc/bvDr095w/image.png" alt="Eleanor Chess Engine" width="300">
</p>
<h1 align="center">Eleanor Chess Engine</h1>
## Search Features
![GitHub License](https://img.shields.io/github/license/rektdie/Eleanor?style=for-the-badge&color=orange)
![GitHub commits since latest release](https://img.shields.io/github/commits-since/rektdie/Eleanor/latest?style=for-the-badge&color=orange)<br>
[![Testing Site](https://img.shields.io/badge/testing_site-%23413679?link=https%3A%2F%2Frektdie.pythonanywhere.com%2F)](https://rektdie.pythonanywhere.com/)
[![Datagen Dashboard](https://img.shields.io/badge/datagen_dashboard-%23413679?link=https%3A%2F%2Frektgen.online%2F)](https://rektgen.online/)<br>
![GitHub Downloads (all assets, all releases)](https://img.shields.io/github/downloads/rektdie/Eleanor/total?color=orange)
| Version | Release Date | [CCRL 40/15](https://www.computerchess.org.uk/ccrl/4040/cgi/compare_engines.cgi?family=Eleanor&print=Rating+list&print=Results+table&print=LOS+table&print=Ponder+hit+table&print=Eval+difference+table&print=Comopp+gamenum+table&print=Overlap+table&print=Score+with+common+opponents) | [CCRL Blitz](https://www.computerchess.org.uk/ccrl/404/cgi/compare_engines.cgi?family=Eleanor&print=Rating+list&print=Results+table&print=LOS+table&print=Ponder+hit+table&print=Eval+difference+table&print=Comopp+gamenum+table&print=Overlap+table&print=Score+with+common+opponents) | [CEGT 40/20](http://www.cegt.net/40_40%20Rating%20List/40_40%20SingleVersion/rangliste.html)
| --- | --- | --- | --- | --- |
| 4.1 | 2026-04-22 | 3528 (#60-61) | 3590 (#64) | 3443 (#59)
| 3.0 | 2025-12-05 | 3405 (#84) | 3495 (#79-80) | -
| 2.0 | 2025-08-23 | 3312 (#115) | 3392 (#105) | -
| 1.0 | 2025-06-02 | 2856 (#244) | 2759 (#256) | -
</div>
- Negamax
- Quiescent Search
- Transposition Table
- Move Ordering (TT, SEE + MVV-LVA, Killers, History)
- Iterative Deepening
- Aspiration Windows
- Principal Variation Search
- Reverse Futility Pruning
- Improving
- Null Move Pruning
- Late Move Reductions
- Log formula
- Cutnode
- History
- Late Move Pruning
- Futility Pruning
- QS SEE Pruning
- PVS SEE Pruning
## Evaluation
Eleanor uses a **fully neural network-based evaluation function**, entirely trained on self-play data from an initially simple HCE using the [bullet](https://github.com/jw1912/bullet) trainer.
**Architecture:** `(768 -> 256)x2 -> 1x8`
A basic 256-hidden-layer *perspective net* with 8 output buckets.
**Architecture:** `(768x8hm -> 1536)x2 -> 1x8`
A 1536-hidden-layer *perspective net* with 8 input buckets, 8 output buckets and horizontal mirroring.
## Installation
> **Prerequisites:**
> - `clang++` compiler
> - `clang++` compiler
> - On Windows, `clang++` must have access to a MinGW GNU toolchain/runtime because the build targets `x86_64-w64-windows-gnu`
> - Access to `make` command
1. Clone the repository
@@ -63,6 +60,8 @@ You can interact with the engine via these commands:
The engine can be used in any GUI with **UCI support**.
[Testing site](https://rektdie.pythonanywhere.com/)
## Sources I Used
- [Stockfish Discord Community](https://discord.com/invite/GWDRS3kU6R) — The best possible source for an engine dev.
@@ -73,4 +72,4 @@ The engine can be used in any GUI with **UCI support**.
**The project is a work in progress and actively developed. Contributions are highly appreciated.**
###### Last updated: 2025-06-02
###### Last updated: 2026-04-18
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env python3
from __future__ import annotations
import re
import sys
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_INPUT = SCRIPT_DIR / "spsa_output.txt"
DEFAULT_TARGET = SCRIPT_DIR.parent / "source" / "tunables.h"
VALUE_RE = re.compile(r"^\s*([A-Za-z0-9_]+)\s*,\s*([^\s,]+)\s*$")
LINE_RE = re.compile(
r"^(?P<indent>\s*)X_(?P<kind>INT|DOUBLE)\("
r"(?P<name>[A-Za-z0-9_]+),\s*"
r"(?P<default>[^,]+),\s*"
r"(?P<rest>.+)\)\s*(?P<continuation>\\)?$"
)
def update_line(line: str, updated_values: dict[str, str]) -> tuple[str, bool]:
match = LINE_RE.match(line)
if not match:
return line, False
name = match.group("name")
if name not in updated_values:
return line, False
continuation = " \\" if match.group("continuation") else ""
new_line = (
f"{match.group('indent')}X_{match.group('kind')}("
f"{name}, {updated_values[name]}, {match.group('rest')}){continuation}\n"
)
return new_line, True
def load_values(path: Path) -> dict[str, str]:
values = {}
for line in path.read_text().splitlines():
match = VALUE_RE.match(line)
if not match:
continue
values[match.group(1)] = match.group(2)
return values
def apply_updates(text: str, updated_values: dict[str, str]) -> tuple[str, set[str]]:
updated_lines: list[str] = []
seen: set[str] = set()
for line in text.splitlines(keepends=True):
new_line, changed = update_line(line, updated_values)
if changed:
match = LINE_RE.match(line)
if match:
seen.add(match.group("name"))
updated_lines.append(new_line)
return "".join(updated_lines), seen
def main() -> int:
input_path = Path(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_INPUT
target = Path(sys.argv[2]) if len(sys.argv) > 2 else DEFAULT_TARGET
if not input_path.exists():
print(f"Input file not found: {input_path}", file=sys.stderr)
return 1
updated_values = load_values(input_path)
if not updated_values:
print(f"No tunable values found in {input_path}", file=sys.stderr)
return 1
if not target.exists():
print(f"Target file not found: {target}", file=sys.stderr)
return 1
text = target.read_text()
updated_text, seen = apply_updates(text, updated_values)
missing = sorted(set(updated_values) - seen)
if missing:
print("Missing tunables:", ", ".join(missing), file=sys.stderr)
return 1
target.write_text(updated_text)
print(f"Updated {len(seen)} tunables in {target} from {input_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+68 -39
View File
@@ -1,45 +1,74 @@
[Event "?"]
[Site "?"]
[Date "2025.04.01"]
[Date "2026.03.26"]
[Round "1"]
[White "Eleanor-base"]
[Black "Eleanor-dev"]
[Result "1-0"]
[FEN "2r5/1k6/2p4p/4p3/3b1p1B/5B1P/2R5/7K b - - 0 1"]
[GameDuration "00:00:05"]
[GameEndTime "2025-04-01T18:10:20.331 Central Europe Daylight Time"]
[GameStartTime "2025-04-01T18:10:14.365 Central Europe Daylight Time"]
[PlyCount "58"]
[White "Eleanor-dev"]
[Black "Eleanor-base"]
[Result "0-1"]
[FEN "rn1qk1nr/pbp1ppbp/1p1p2p1/3P4/5P2/2N1P3/PPPB2PP/R2QKBNR b KQkq - 0 1"]
[GameDuration "00:00:14"]
[GameEndTime "2026-03-26T20:42:15.476 CET"]
[GameStartTime "2026-03-26T20:42:00.864 CET"]
[PlyCount "115"]
[SetUp "1"]
[Termination "abandoned"]
[TimeControl "2.53+0.03"]
[TimeControl "5.17+0.05"]
1... Kb6 {-0.43 11/0 127 176492} 2. Kg2 {+0.45 10/0 117 182773}
Kb5 {-0.43 10/0 139 43190} 3. Bf2 {+0.48 10/0 94 154681}
Rg8+ {-0.41 10/0 104 181006} 4. Kf1 {+0.43 11/0 137 107880}
c5 {-0.42 11/0 114 186919} 5. Ke2 {+0.42 10/0 131 26558}
Rd8 {-0.31 11/0 126 178073} 6. Rd2 {+0.36 8/0 129 64726}
c4 {+0.11 11/0 124 101858} 7. Bxd4 {-0.11 11/0 86 135900}
Rxd4 {+0.10 11/0 124 121262} 8. Rxd4 {-0.01 13/0 117 207646}
exd4 {0.00 14/0 95 197856} 9. h4 {0.00 13/0 105 197264}
Kb4 {0.00 14/0 91 195163} 10. Kd2 {0.00 13/0 111 105382}
Kc5 {0.00 13/0 109 62420} 11. h5 {0.00 14/0 78 150612} Kb4 {0.00 16/0 79 181784}
12. Bd1 {0.00 15/0 86 193192} Kc5 {0.00 16/0 97 111839}
13. Kc2 {0.00 17/0 90 192373} Kb4 {0.00 17/0 95 120438}
14. Bf3 {0.00 17/0 76 176571} Kc5 {0.00 17/0 101 66844}
15. Ba8 {0.00 18/0 75 165249} Kb4 {0.00 18/0 86 198233}
16. Bf3 {0.00 18/0 77 183908} d3+ {+0.01 16/0 69 164278}
17. Kd2 {-0.03 16/0 81 145118} Kb3 {0.00 17/0 84 107987}
18. Be4 {0.00 16/0 61 125373} f3 {+0.09 17/0 75 163654}
19. Bxd3 {-0.01 16/0 86 109653} cxd3 {+0.57 18/0 55 140500}
20. Kxd3 {-0.97 22/0 73 227257} f2 {+0.98 22/0 71 204108}
21. Ke2 {-0.99 20/0 81 29772} Kc4 {+1.48 22/0 62 180691}
22. Kxf2 {-2.11 23/0 59 175088} Kd4 {+2.51 27/0 52 189697}
23. Kf3 {-3.34 26/0 62 187791} Ke5 {+2.50 32/0 48 167062}
24. Ke3 {-2.24 28/0 54 178563} Kf5 {+2.15 31/0 72 166014}
25. Kf3 {-2.22 32/0 52 188757} Kg5 {0.00 35/0 49 143292}
26. Ke4 {-2.09 32/0 62 209505} Kxh5 {0.00 39/0 48 159744}
27. Kf5 {-2.09 33/0 70 226933} Kh4 {0.00 52/0 46 161548}
28. Kf4 {0.00 37/0 51 178144} h5 {0.00 64/0 29 95868}
29. Kf3 {0.00 51/0 46 165319} Kh3 {0.00 64/0 15 14259}
30. Kf4 {0.00 52/0 64 186059, Black disconnects} 1-0
1... Nf6 {+0.25 16/24 256 274740} 2. Bb5+ {-0.31 14/28 286 222469}
c6 {+0.30 14/30 154 175813} 3. dxc6 {-0.31 15/29 214 240246}
Nxc6 {+0.29 15/25 271 56301} 4. Nf3 {-0.25 16/25 174 198800}
O-O {+0.25 14/29 260 157287} 5. O-O {-0.28 15/26 245 287541}
a6 {+0.24 17/35 224 246704} 6. Bd3 {-0.22 14/27 136 153559}
b5 {+0.24 17/31 241 178951} 7. Qe1 {-0.24 14/28 245 274939}
Qb6 {+0.25 16/25 230 190364} 8. a3 {-0.25 14/25 207 226160}
e5 {+0.26 14/27 221 86623} 9. fxe5 {-0.10 14/27 158 172124}
Nxe5 {+0.28 13/27 214 129429} 10. Nxe5 {-0.39 13/24 170 177476}
dxe5 {+0.26 15/27 100 113069} 11. Kh1 {-0.18 13/23 121 136389}
e4 {+0.32 13/18 202 26644} 12. Be2 {-0.19 15/28 182 213316}
Rfc8 {+0.19 13/23 194 212538} 13. a4 {-0.12 13/24 207 126167}
b4 {+0.22 13/25 187 192683} 14. a5 {-0.18 14/26 101 112261}
Qd8 {+0.15 14/31 111 123537} 15. Na4 {-0.19 14/34 196 210792}
Nd5 {+0.23 15/29 157 177113} 16. Qf2 {-0.22 14/25 188 135679}
f5 {+0.22 15/28 130 130850} 17. c4 {-0.23 13/25 182 139155}
bxc3 {+0.24 15/25 98 105292} 18. bxc3 {-0.24 13/25 175 94316}
Bc6 {+0.23 14/17 166 18894} 19. Bc4 {-0.20 14/29 97 108937}
Bxa4 {+0.20 13/24 81 86007} 20. Rxa4 {-0.21 16/30 85 101741}
h5 {+0.25 13/20 159 95557} 21. Qe2 {-0.25 12/30 165 163762}
Kh7 {+0.36 12/21 98 103093} 22. Rxf5 {-0.39 12/27 159 75820}
gxf5 {+0.34 12/26 101 110999} 23. Qxh5+ {-0.45 13/38 107 119594}
Kg8 {+0.33 13/23 149 16142} 24. Qxf5 {-0.39 14/26 74 84084}
Rc5 {+0.40 13/23 144 140578} 25. Qe6+ {-0.37 12/36 150 138869}
Kf8 {+0.53 14/27 138 120201} 26. Bc1 {-0.45 14/30 144 132855}
Rb8 {+0.59 14/33 74 90173} 27. Ra1 {-0.55 14/36 130 123759}
Qf6 {+0.63 14/35 82 98374} 28. Qxf6+ {-0.21 14/39 132 146058}
Bxf6 {+0.61 15/35 100 125452} 29. Ba3 {-0.59 14/29 86 103103}
Nb4 {+0.57 16/29 129 51381} 30. Bxb4 {-0.57 15/25 64 80650}
Rxb4 {+0.53 14/29 91 125806} 31. cxb4 {-0.49 15/23 129 48919}
Rxc4 {+0.47 15/27 122 47840} 32. Rb1 {-0.45 15/30 67 91596}
Be7 {+0.46 14/24 92 126553} 33. g4 {-0.44 15/26 124 72397}
Rxb4 {+0.49 14/25 73 87941} 34. Rf1+ {-0.49 14/28 121 72810}
Ke8 {+0.45 15/36 89 113698} 35. Rf5 {-0.45 13/22 117 70248}
Kd7 {+0.45 14/30 115 74784} 36. Re5 {-0.45 13/22 82 101380}
Bd6 {+0.50 14/33 87 110879} 37. Rh5 {-0.45 12/34 113 72228}
Rb1+ {+0.50 15/32 56 64801} 38. Kg2 {-0.46 14/29 74 94136}
Rb2+ {+0.50 14/17 108 4246} 39. Kh1 {-0.48 15/25 108 48523}
Re2 {+0.53 14/27 78 96242} 40. Rh7+ {-0.56 13/28 105 70703}
Ke6 {+0.59 13/25 67 86840} 41. Rh6+ {-0.61 14/29 87 110057}
Kd5 {+0.59 15/27 91 103932} 42. Rh5+ {-0.65 14/28 100 108417}
Be5 {+0.70 14/33 94 110182} 43. Rh3 {-0.67 14/30 86 100550}
Kc4 {+0.83 13/27 100 123700} 44. Rh5 {-0.75 12/24 96 56083}
Bc3 {+0.88 12/26 47 63602} 45. Rh6 {-0.73 12/23 95 70966}
Rxe3 {+0.92 12/31 96 115497} 46. h4 {-0.83 10/24 91 46076}
Re1+ {+0.98 12/25 94 124212} 47. Kg2 {-0.92 13/29 45 57555}
Bd4 {+0.94 14/28 86 116606} 48. Rxa6 {-0.93 13/26 90 42707}
e3 {+0.95 13/23 90 44547} 49. Re6 {-0.92 12/40 88 86679}
e2 {+0.99 13/23 88 36470} 50. a6 {-0.96 13/40 86 89628}
Kd5 {+0.97 12/27 86 80236} 51. a7 {-0.97 12/30 84 17470}
Bxa7 {+1.08 13/30 84 33077} 52. Re7 {-1.12 12/28 82 71784}
Rg1+ {+1.17 13/28 53 70853} 53. Kf3 {-1.21 13/30 81 51340}
e1=Q {+1.21 13/30 83 51082} 54. Rxe1 {-1.51 14/31 59 80154}
Rxe1 {+1.25 13/29 41 59171} 55. h5 {-1.31 14/29 40 55864}
Bd4 {+1.29 12/29 81 48179} 56. g5 {-1.23 11/26 80 30276}
Rf1+ {+1.33 12/20 80 18531} 57. Kg2 {-3.99 12/39 78 76309}
Rf5 {+1.56 12/26 79 58979} 58. g6 {-M18 12/38 76 76733}
Ke4 {+M19 13/35 46 55731, White disconnects} 0-1
+42
View File
@@ -0,0 +1,42 @@
lmrBaseQuiet, 1.1029723689888005
lmrDivisorQuiet, 2.3063513397139945
lmrBaseNoisy, 0.451805556082857
lmrDivisorNoisy, 3.1355330830404338
lmrCutnode, 2005
lmrIsPV, 982
lmrTTPV, 936
lmrHistoryDivisor, 8377
lmrImproving, 1131
lmrCorrplexity, 830
lmrTTPVFailLow, 913
lmrDeeperBase, 46
rfpBase, 21
rfpMargin, 97
fpMargin, 86
probcutBetaMargin, 190
razoringScalar, 195
doubleExtMargin, 32
seeQuietThreshold, -81
seeNoisyThreshold, -32
aspInitialDelta, 26
nmpBetaMargin, 25
seePawnValue, 98
seeKnightValue, 301
seeBishopValue, 346
seeRookValue, 507
seeQueenValue, 924
seeQsThreshold, -13
seeOrderingThreshold, -102
ldseMargin, 26
historyBonusMultiplier, 306
historyBonusSub, 252
historyMalusMultiplier, 301
historyMalusSub, 250
contHistoryBonusMultiplier, 300
contHistoryBonusSub, 252
contHistoryMalusMultiplier, 300
contHistoryMalusSub, 249
captHistoryBonusMultiplier, 302
captHistoryBonusSub, 249
captHistoryMalusMultiplier, 300
captHistoryMalusSub, 249
-2985
View File
File diff suppressed because it is too large. Load diff
-1949
View File
File diff suppressed because it is too large. Load diff
-4244
View File
File diff suppressed because it is too large. Load diff
-46
View File
@@ -1,46 +0,0 @@
// Formatting library for C++
//
// Copyright (c) 2012 - 2016, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
#include "fmt/format-inl.h"
FMT_BEGIN_NAMESPACE
namespace detail {
template FMT_API auto dragonbox::to_decimal(float x) noexcept
-> dragonbox::decimal_fp<float>;
template FMT_API auto dragonbox::to_decimal(double x) noexcept
-> dragonbox::decimal_fp<double>;
#if FMT_USE_LOCALE
// DEPRECATED! locale_ref in the detail namespace
template FMT_API locale_ref::locale_ref(const std::locale& loc);
template FMT_API auto locale_ref::get<std::locale>() const -> std::locale;
#endif
// Explicit instantiations for char.
template FMT_API auto thousands_sep_impl(locale_ref)
-> thousands_sep_result<char>;
template FMT_API auto decimal_point_impl(locale_ref) -> char;
// DEPRECATED!
template FMT_API void buffer<char>::append(const char*, const char*);
// DEPRECATED!
template FMT_API void vformat_to(buffer<char>&, string_view,
typename vformat_args<>::type, locale_ref);
// Explicit instantiations for wchar_t.
template FMT_API auto thousands_sep_impl(locale_ref)
-> thousands_sep_result<wchar_t>;
template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t;
template FMT_API void buffer<wchar_t>::append(const wchar_t*, const wchar_t*);
} // namespace detail
FMT_END_NAMESPACE
+23
View File
@@ -0,0 +1,23 @@
// Stolen from Ciekce - Stormphrax
#pragma once
#include <array>
#include <stdlib.h>
namespace internal
{
template <typename T, size_t N, size_t ... Ns>
struct MultiArrayImpl
{
using Type = std::array<typename MultiArrayImpl<T, Ns...>::Type, N>;
};
template <typename T, size_t N>
struct MultiArrayImpl<T, N>
{
using Type = std::array<T, N>;
};
}
template <typename T, size_t ... Ns>
using MultiArray = typename internal::MultiArrayImpl<T, Ns...>::Type;
BIN
View File
Binary file not shown.
+154 -54
View File
@@ -4,83 +4,183 @@
namespace ACC {
int CalculateIndex(bool perspective, bool side, int pieceType, int square) {
int CalculateIndex(bool perspective, bool side, int pieceType, int square, bool mirrored) {
if (perspective == Black)
{
side = 1 - side; // Flip side
square = square ^ 0b111000; // Mirror square
side = 1 - side;
square = square ^ 0b111000;
}
if (mirrored)
square ^= 7;
return side * 64 * 6 + pieceType * 64 + square;
}
// All friendly, for quiets
void AccumulatorPair::addSub(bool stm, int add, int addPT, int sub, int subPT) {
int addW = CalculateIndex(White, stm, addPT, add);
int addB = CalculateIndex(Black, stm, addPT, add);
const int16_t* Row(int bucket, int index) {
return &NNUE::net.accumulator_weights[bucket][static_cast<size_t>(index) * NNUE::HL_SIZE];
}
int subW = CalculateIndex(White, stm, subPT, sub);
int subB = CalculateIndex(Black, stm, subPT, sub);
for (int i = 0; i < NNUE::HL_SIZE; i++) {
white[i] += NNUE::net.accumulator_weights[addW * NNUE::HL_SIZE + i];
black[i] += NNUE::net.accumulator_weights[addB * NNUE::HL_SIZE + i];
white[i] -= NNUE::net.accumulator_weights[subW * NNUE::HL_SIZE + i];
black[i] -= NNUE::net.accumulator_weights[subB * NNUE::HL_SIZE + i];
void FinnyTable::Reset() {
for (auto& perspective : entries) {
for (auto& mirror : perspective) {
for (auto& entry : mirror) {
entry.acc = NNUE::net.accumulator_biases;
for (auto& color : entry.bb)
for (auto& bb : color)
bb = 0;
}
}
}
}
// Captures
void AccumulatorPair::addSubSub(bool stm, int add, int addPT, int sub1, int subPT1, int sub2, int subPT2) {
int addW = CalculateIndex(White, stm, addPT, add);
int addB = CalculateIndex(Black, stm, addPT, add);
#if defined(_MSC_VER) && !defined(__clang__)
#define ACC_NOINLINE __declspec(noinline)
#else
#define ACC_NOINLINE __attribute__((noinline))
#endif
int subW1 = CalculateIndex(White, stm, subPT1, sub1);
int subB1 = CalculateIndex(Black, stm, subPT1, sub1);
#if defined(__AVX512F__) && defined(__AVX512BW__)
#include <immintrin.h>
using Vec = __m512i;
static inline Vec vLoad(const int16_t* p) { return _mm512_loadu_si512(p); }
static inline void vStore(int16_t* p, Vec v) { _mm512_storeu_si512(p, v); }
static inline Vec vAdd(Vec a, Vec b) { return _mm512_add_epi16(a, b); }
static inline Vec vSub(Vec a, Vec b) { return _mm512_sub_epi16(a, b); }
#define ACC_SIMD 1
#elif defined(__AVX2__)
#include <immintrin.h>
using Vec = __m256i;
static inline Vec vLoad(const int16_t* p) { return _mm256_loadu_si256(reinterpret_cast<const __m256i*>(p)); }
static inline void vStore(int16_t* p, Vec v) { _mm256_storeu_si256(reinterpret_cast<__m256i*>(p), v); }
static inline Vec vAdd(Vec a, Vec b) { return _mm256_add_epi16(a, b); }
static inline Vec vSub(Vec a, Vec b) { return _mm256_sub_epi16(a, b); }
#define ACC_SIMD 1
#elif defined(__SSE2__) || defined(_M_X64) || defined(_M_AMD64)
#include <immintrin.h>
using Vec = __m128i;
static inline Vec vLoad(const int16_t* p) { return _mm_loadu_si128(reinterpret_cast<const __m128i*>(p)); }
static inline void vStore(int16_t* p, Vec v) { _mm_storeu_si128(reinterpret_cast<__m128i*>(p), v); }
static inline Vec vAdd(Vec a, Vec b) { return _mm_add_epi16(a, b); }
static inline Vec vSub(Vec a, Vec b) { return _mm_sub_epi16(a, b); }
#define ACC_SIMD 1
#elif defined(__aarch64__)
#include <arm_neon.h>
using Vec = int16x8_t;
static inline Vec vLoad(const int16_t* p) { return vld1q_s16(p); }
static inline void vStore(int16_t* p, Vec v) { vst1q_s16(p, v); }
static inline Vec vAdd(Vec a, Vec b) { return vaddq_s16(a, b); }
static inline Vec vSub(Vec a, Vec b) { return vsubq_s16(a, b); }
#define ACC_SIMD 1
#endif
int subW2 = CalculateIndex(White, !stm, subPT2, sub2);
int subB2 = CalculateIndex(Black, !stm, subPT2, sub2);
#ifdef ACC_SIMD
for (int i = 0; i < NNUE::HL_SIZE; i++) {
white[i] += NNUE::net.accumulator_weights[addW * NNUE::HL_SIZE + i];
black[i] += NNUE::net.accumulator_weights[addB * NNUE::HL_SIZE + i];
constexpr size_t LANES = sizeof(Vec) / sizeof(int16_t);
constexpr size_t TILE = 4;
constexpr size_t STEP = LANES * TILE;
static_assert(NNUE::HL_SIZE % STEP == 0, "HL size must be divisible by the SIMD tile size");
white[i] -= NNUE::net.accumulator_weights[subW1 * NNUE::HL_SIZE + i];
black[i] -= NNUE::net.accumulator_weights[subB1 * NNUE::HL_SIZE + i];
template <int NA, int NS>
ACC_NOINLINE static void ApplyKernel(int16_t* dst, const int16_t* src,
const int16_t* a1, const int16_t* a2,
const int16_t* s1, const int16_t* s2) {
for (size_t i = 0; i < NNUE::HL_SIZE; i += STEP) {
Vec r[TILE];
white[i] -= NNUE::net.accumulator_weights[subW2 * NNUE::HL_SIZE + i];
black[i] -= NNUE::net.accumulator_weights[subB2 * NNUE::HL_SIZE + i];
for (size_t u = 0; u < TILE; u++) r[u] = vLoad(src + i + u * LANES);
for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(a1 + i + u * LANES));
if constexpr (NA > 1)
for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(a2 + i + u * LANES));
for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(s1 + i + u * LANES));
if constexpr (NS > 1)
for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(s2 + i + u * LANES));
for (size_t u = 0; u < TILE; u++) vStore(dst + i + u * LANES, r[u]);
}
}
// Castling
void AccumulatorPair::addAddSubSub(bool stm, int add1, int addPT1, int add2, int addPT2, int sub1, int subPT1, int sub2, int subPT2) {
int addW1 = CalculateIndex(White, stm, addPT1, add1);
int addB1 = CalculateIndex(Black, stm, addPT1, add1);
ACC_NOINLINE static void InPlaceKernel(int16_t* acc, const int16_t* const* adds, int nAdds,
const int16_t* const* subs, int nSubs) {
for (size_t i = 0; i < NNUE::HL_SIZE; i += STEP) {
Vec r[TILE];
int addW2 = CalculateIndex(White, stm, addPT2, add2);
int addB2 = CalculateIndex(Black, stm, addPT2, add2);
for (size_t u = 0; u < TILE; u++) r[u] = vLoad(acc + i + u * LANES);
int subW1 = CalculateIndex(White, stm, subPT1, sub1);
int subB1 = CalculateIndex(Black, stm, subPT1, sub1);
for (int j = 0; j < nAdds; j++)
for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(adds[j] + i + u * LANES));
int subW2 = CalculateIndex(White, stm, subPT2, sub2);
int subB2 = CalculateIndex(Black, stm, subPT2, sub2);
for (int j = 0; j < nSubs; j++)
for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(subs[j] + i + u * LANES));
for (int i = 0; i < NNUE::HL_SIZE; i++) {
white[i] += NNUE::net.accumulator_weights[addW1 * NNUE::HL_SIZE + i];
black[i] += NNUE::net.accumulator_weights[addB1 * NNUE::HL_SIZE + i];
white[i] += NNUE::net.accumulator_weights[addW2 * NNUE::HL_SIZE + i];
black[i] += NNUE::net.accumulator_weights[addB2 * NNUE::HL_SIZE + i];
white[i] -= NNUE::net.accumulator_weights[subW1 * NNUE::HL_SIZE + i];
black[i] -= NNUE::net.accumulator_weights[subB1 * NNUE::HL_SIZE + i];
white[i] -= NNUE::net.accumulator_weights[subW2 * NNUE::HL_SIZE + i];
black[i] -= NNUE::net.accumulator_weights[subB2 * NNUE::HL_SIZE + i];
for (size_t u = 0; u < TILE; u++) vStore(acc + i + u * LANES, r[u]);
}
}
void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2) {
if (a2)
ApplyKernel<2, 2>(dst.data(), src.data(), a1, a2, s1, s2);
else if (s2)
ApplyKernel<1, 2>(dst.data(), src.data(), a1, nullptr, s1, s2);
else
ApplyKernel<1, 1>(dst.data(), src.data(), a1, nullptr, s1, nullptr);
}
void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs) {
InPlaceKernel(acc.data(), adds, nAdds, subs, nSubs);
}
void AddRow(Accumulator& acc, const int16_t* row) {
const int16_t* rows[1] = {row};
InPlaceKernel(acc.data(), rows, 1, nullptr, 0);
}
#else
using Ptr = int16_t* __restrict;
using CPtr = const int16_t* __restrict;
ACC_NOINLINE static void Kernel1p1m(Ptr dst, CPtr src, CPtr a, CPtr s) {
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
dst[i] = static_cast<int16_t>(src[i] + a[i] - s[i]);
}
ACC_NOINLINE static void Kernel1p2m(Ptr dst, CPtr src, CPtr a, CPtr s1, CPtr s2) {
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
dst[i] = static_cast<int16_t>(src[i] + a[i] - s1[i] - s2[i]);
}
ACC_NOINLINE static void Kernel2p2m(Ptr dst, CPtr src, CPtr a1, CPtr a2, CPtr s1, CPtr s2) {
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
dst[i] = static_cast<int16_t>(src[i] + a1[i] + a2[i] - s1[i] - s2[i]);
}
void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2) {
if (a2)
Kernel2p2m(dst.data(), src.data(), a1, a2, s1, s2);
else if (s2)
Kernel1p2m(dst.data(), src.data(), a1, s1, s2);
else
Kernel1p1m(dst.data(), src.data(), a1, s1);
}
void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs) {
int16_t* p = acc.data();
for (int j = 0; j < nAdds; j++)
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
p[i] = static_cast<int16_t>(p[i] + adds[j][i]);
for (int j = 0; j < nSubs; j++)
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
p[i] = static_cast<int16_t>(p[i] - subs[j][i]);
}
void AddRow(Accumulator& acc, const int16_t* row) {
const int16_t* rows[1] = {row};
ApplyInPlace(acc, rows, 1, nullptr, 0);
}
#endif
}
+85 -7
View File
@@ -1,20 +1,98 @@
#pragma once
#include <array>
#include <vector>
#include <cstdint>
#include "nnue.h"
namespace ACC {
struct BucketPair {
int white;
int black;
};
using Accumulator = std::array<int16_t, NNUE::HL_SIZE>;
struct AccumulatorPair {
alignas(32) Accumulator white;
alignas(32) Accumulator black;
alignas(ALIGNMENT) Accumulator white;
alignas(ALIGNMENT) Accumulator black;
// yoinked from Quinniboi - Prelude
void addSub(bool stm, int add, int addPT, int sub, int subPT);
void addSubSub(bool stm, int add, int addPT, int sub1, int subPT1, int sub2, int subPT2);
void addAddSubSub(bool stm, int add1, int addPT1, int add2, int addPT2, int sub1, int subPT1, int sub2, int subPT2);
Accumulator& get(bool perspective) { return perspective ? black : white; }
const Accumulator& get(bool perspective) const { return perspective ? black : white; }
};
int CalculateIndex(bool perspective, bool side, int pieceType, int square);
enum class UpdateType : uint8_t {
None,
Refresh,
Copy,
Delta
};
struct Update {
UpdateType type = UpdateType::None;
uint8_t refreshMask = 0;
bool stm = false;
bool sub2Opp = false;
uint8_t nAdd = 0, nSub = 0;
int8_t add1 = 0, addPT1 = 0, add2 = 0, addPT2 = 0;
int8_t sub1 = 0, subPT1 = 0, sub2 = 0, subPT2 = 0;
void setAddSub(bool s, int add, int addPT, int sub, int subPT) {
type = UpdateType::Delta;
stm = s; sub2Opp = false; nAdd = 1; nSub = 1;
add1 = add; addPT1 = addPT; sub1 = sub; subPT1 = subPT;
}
void setAddSubSub(bool s, int add, int addPT, int sub1_, int subPT1_, int sub2_, int subPT2_) {
type = UpdateType::Delta;
stm = s; sub2Opp = true; nAdd = 1; nSub = 2;
add1 = add; addPT1 = addPT;
sub1 = sub1_; subPT1 = subPT1_; sub2 = sub2_; subPT2 = subPT2_;
}
void setAddAddSubSub(bool s, int add1_, int addPT1_, int add2_, int addPT2_, int sub1_, int subPT1_, int sub2_, int subPT2_) {
type = UpdateType::Delta;
stm = s; sub2Opp = false; nAdd = 2; nSub = 2;
add1 = add1_; addPT1 = addPT1_; add2 = add2_; addPT2 = addPT2_;
sub1 = sub1_; subPT1 = subPT1_; sub2 = sub2_; subPT2 = subPT2_;
}
void setRefresh() {
*this = Update();
type = UpdateType::Refresh;
}
};
struct FinnyEntry {
alignas(ALIGNMENT) Accumulator acc;
uint64_t bb[2][6];
};
struct FinnyTable {
FinnyEntry entries[2][2][NNUE::INPUT_BUCKETS];
void Reset();
};
struct AccStack {
std::vector<AccumulatorPair> slots;
std::vector<const AccumulatorPair*> cur;
FinnyTable finny;
explicit AccStack(size_t n) : slots(n), cur(n, nullptr) { finny.Reset(); }
AccStack(const AccStack& other) : AccStack(other.slots.size()) {}
AccStack& operator=(const AccStack&) { return *this; }
};
int CalculateIndex(bool perspective, bool side, int pieceType, int square, bool mirrored);
const int16_t* Row(int bucket, int index);
void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2);
void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs);
void AddRow(Accumulator& acc, const int16_t* row);
}
+6 -4
View File
@@ -1,6 +1,7 @@
#include <cstring>
#include <string_view>
#include <array>
#include <memory>
#include "benchmark.h"
#include "search.h"
#include "stopwatch.h"
@@ -62,15 +63,16 @@ constexpr std::array<std::string_view, 50> fenPositions = {
void RunBenchmark() {
Board board;
int depth = BENCH_DEPTH;
SearchContext ctx;
TTable BenchTT;
auto ctx = std::make_unique<SearchContext>();
ctx->TT = &BenchTT;
Stopwatch sw;
for (int i = 0; i < fenPositions.size(); i++) {
board.SetByFen(fenPositions[i]);
SearchPosition<bench>(board, SearchParams(), ctx);
SearchPosition<bench>(board, SearchParams(), ctx.get());
}
std::cout << ctx.nodes << " nodes " << int(ctx.nodes/sw.GetElapsedSec()) << " nps" << std::endl;
std::cout << ctx->nodes << " nodes " << int(ctx->nodes/sw.GetElapsedSec()) << " nps" << std::endl;
}
+617 -116
View File
@@ -1,25 +1,39 @@
#include <bit>
#include "board.h"
#include "accumulator.h"
#include "movegen.h"
#include "nnue.h"
#include "tt.h"
#include <iostream>
#include <ranges>
#include <string_view>
#include <cassert>
#include "types.h"
#include "utils.h"
void Board::Reset() {
castlingRights = 0;
enPassantTarget = noEPTarget;
halfMoves = 0;
fullMoves = 1;
sideToMove = White;
occupied = 0ULL;
checkers = 0ULL;
mailbox = std::array<int, 64>();
mailbox.fill(nullPieceType);
pinned = std::array<Bitboard, 2>();
pieces = std::array<Bitboard, 6>();
colors = std::array<Bitboard, 2>();
accPair = ACC::AccumulatorPair();
accUpdate.setRefresh();
mirroredWhite = false;
mirroredBlack = false;
pieceThreats = std::array<Bitboard, 6>();
colorThreats = std::array<Bitboard, 2>();
@@ -31,12 +45,16 @@ void Board::Reset() {
currentMoveIndex = 0;
hashKey = 0ULL;
pawnKey = 0ULL;
nonPawnKey = 0ULL;
majorKey = 0ULL;
checkZones = std::array<Bitboard, 4>();
}
void Board::SetByFen(std::string_view fen) {
Reset();
// Starting from top left
int currSquare = a8;
std::vector<std::string> tokens = UTILS::split(fen, ' ');
@@ -54,8 +72,7 @@ void Board::SetByFen(std::string_view fen) {
bool side = std::islower(piece);
int pieceType = pieceTypes.find(std::tolower(piece));
colors[side].SetBit(currSquare);
pieces[pieceType].SetBit(currSquare);
SetPiece(pieceType, currSquare, side);
currSquare++;
}
@@ -73,81 +90,98 @@ void Board::SetByFen(std::string_view fen) {
if (tokens[3] != "-") enPassantTarget = UTILS::parseSquare(tokens[3]);
// full and half move
if (tokens.size() > 4) {
halfMoves = std::stoi(tokens[4]);
fullMoves = std::stoi(tokens[5]);
}
pawnKey = 0ULL;
nonPawnKey = 0ULL;
majorKey = 0ULL;
occupied = colors[White] | colors[Black];
hashKey = UTILS::GetHashKey(*this);
checkers = CalcCheckers();
pinned = {CalcPinned(White), CalcPinned(Black)};
CalcCheckers();
MOVEGEN::GenThreatMaps(*this);
MOVEGEN::GenerateMoves<All>(*this);
ResetAccPair();
MOVEGEN::GenerateMoves<All>(*this, true);
int whiteKingFile = (pieces[King] & colors[White]).getLS1BIndex() % 8;
int blackKingFile = (pieces[King] & colors[Black]).getLS1BIndex() % 8;
if (whiteKingFile > 3) {
mirroredWhite = true;
}
if (blackKingFile > 3) {
mirroredBlack = true;
}
accUpdate.setRefresh();
}
std::string Board::GetFen() {
std::ostringstream fen;
for (int rank = 7; rank >= 0; --rank) {
int emptyCount = 0;
for (int file = 0; file < 8; ++file) {
int square = rank * 8 + file;
const uint64_t squareBit = 1ULL << square;
if (!(occupied & squareBit)) {
++emptyCount;
continue;
}
if (emptyCount > 0) {
fen << emptyCount;
emptyCount = 0;
}
static constexpr std::array<char, 6> pieceChars = {'p', 'n', 'b', 'r', 'q', 'k'};
char pieceChar = '?';
for (size_t pieceType = 0; pieceType < pieceChars.size(); ++pieceType) {
if (pieces[pieceType] & squareBit) {
pieceChar = pieceChars[pieceType];
break;
}
}
fen << (colors[White] & squareBit ? static_cast<char>(std::toupper(pieceChar)) : pieceChar);
}
if (emptyCount > 0) {
fen << emptyCount;
}
if (rank > 0) {
fen << '/';
}
}
fen << ' ' << (sideToMove ? 'b' : 'w');
fen << ' ';
bool hasCastlingRights = false;
const std::array<std::pair<uint8_t, char>, 4> castlingOptions = {
{{whiteKingRight, 'K'}, {whiteQueenRight, 'Q'}, {blackKingRight, 'k'}, {blackQueenRight, 'q'}}
};
for (const auto& [right, symbol] : castlingOptions) {
if (castlingRights & right) {
fen << symbol;
hasCastlingRights = true;
}
}
if (!hasCastlingRights) {
fen << '-';
}
fen << ' ';
if (enPassantTarget == noEPTarget) {
fen << '-';
@@ -156,11 +190,11 @@ std::string Board::GetFen() {
const int rank = enPassantTarget / 8;
fen << static_cast<char>('a' + file) << (rank + 1);
}
fen << ' ' << halfMoves;
fen << ' ' << fullMoves;
return fen.str();
}
@@ -233,11 +267,11 @@ void Board::ResetMoves() {
void Board::ListMoves() {
int moveCount = 1;
for (int i = 0; i < currentMoveIndex; i++) {
Board copy = *this;
bool isLegal = copy.MakeMove(moveList[i]);
if (!IsLegal(moveList[i])) continue;
Board copy = *this;
copy.MakeMove(moveList[i]);
if (!isLegal)
continue;
std::cout << moveCount << ". ";
moveList[i].PrintMove();
@@ -248,11 +282,7 @@ void Board::ListMoves() {
}
int Board::GetPieceType(int square) {
for (int piece = Pawn; piece <= King; piece++) {
if (pieces[piece].IsSet(square)) return piece;
}
return nullPieceType;
return mailbox[square];
}
int Board::GetPieceColor(int square) {
@@ -270,7 +300,19 @@ void Board::SetPiece(int piece, int square, bool color) {
colors[color].SetBit(square);
occupied.SetBit(square);
mailbox[square] = piece;
hashKey ^= UTILS::zKeys[color][piece][square];
if (piece == Pawn) {
pawnKey ^= UTILS::zKeys[color][Pawn][square];
} else {
nonPawnKey ^= UTILS::zKeys[color][piece][square];
if (piece == King || piece == Rook || piece == Queen) {
majorKey ^= UTILS::zKeys[color][piece][square];
}
}
}
void Board::RemovePiece(int piece, int square, bool color) {
@@ -278,13 +320,23 @@ void Board::RemovePiece(int piece, int square, bool color) {
colors[color].PopBit(square);
occupied.PopBit(square);
mailbox[square] = nullPieceType;
hashKey ^= UTILS::zKeys[color][piece][square];
if (piece == Pawn) {
pawnKey ^= UTILS::zKeys[color][Pawn][square];
} else {
nonPawnKey ^= UTILS::zKeys[color][piece][square];
if (piece == King || piece == Rook || piece == Queen) {
majorKey ^= UTILS::zKeys[color][piece][square];
}
}
}
// Updates castling rights
static void UpdateCastlingRights(Board &board, int square, int type, int color) {
if (type == Rook) {
// Removing old rights
board.hashKey ^= UTILS::zCastle[board.castlingRights];
int queenSideRook = color ? a8 : a1;
int kingSideRook = color ? h8 : h1;
@@ -297,7 +349,6 @@ static void UpdateCastlingRights(Board &board, int square, int type, int color)
board.hashKey ^= UTILS::zCastle[board.castlingRights];
} else if (type == King) {
// Removing old rights
board.hashKey ^= UTILS::zCastle[board.castlingRights];
board.castlingRights &= color ? ~blackKingRight : ~whiteKingRight;
@@ -317,28 +368,28 @@ void Board::Promote(int square, int pieceType, int color, bool isCapture) {
SetPiece(pieceType, square, color);
}
bool Board::MakeMove(Move move) {
Board save = *this;
// Null Move
void Board::MakeMove(Move move) {
const bool accParentClean = accUpdate.type == ACC::UpdateType::None;
accUpdate = ACC::Update();
if (!move) {
if (accParentClean) accUpdate.type = ACC::UpdateType::Copy;
else accUpdate.setRefresh();
int newEpTarget = noEPTarget;
sideToMove = !sideToMove;
hashKey ^= UTILS::zSide;
if (enPassantTarget != noEPTarget) {
hashKey ^= UTILS::zEnPassant[enPassantTarget % 8];
}
if (newEpTarget != noEPTarget) {
hashKey ^= UTILS::zEnPassant[newEpTarget % 8];
}
enPassantTarget = newEpTarget;
return true;
return;
}
int newEpTarget = noEPTarget;
int attackerPiece = GetPieceType(move.MoveFrom());
@@ -349,30 +400,52 @@ bool Board::MakeMove(Move move) {
int endPiece = attackerPiece;
// Removing attacker piece from old position
uint8_t refreshMask = 0;
if (attackerPiece == King) {
const int toFile = move.MoveTo() % 8;
if (attackerColor == White) {
if ((toFile > 3) != mirroredWhite) {
mirroredWhite = !mirroredWhite;
refreshMask |= 1 << White;
}
} else {
if ((toFile > 3) != mirroredBlack) {
mirroredBlack = !mirroredBlack;
refreshMask |= 1 << Black;
}
}
if (NNUE::kingBuckets[attackerColor][move.MoveFrom()] != NNUE::kingBuckets[attackerColor][move.MoveTo()]) {
refreshMask |= 1 << attackerColor;
}
}
RemovePiece(attackerPiece, move.MoveFrom(), attackerColor);
if (move.IsPromo()) {
endPiece = move.GetPromoPiece();
if (move.IsCapture()) {
endPiece = move.GetFlags() - 9;
Promote(move.MoveTo(), endPiece, sideToMove, true);
} else {
endPiece = move.GetFlags() - 5;
Promote(move.MoveTo(), endPiece, sideToMove, false);
}
}
if (move.IsCapture()) {
if (move.GetFlags() != epCapture) {
accPair.addSubSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, move.MoveTo(), targetPiece);
} else {
accPair.addSubSub(sideToMove, enPassantTarget, endPiece, move.MoveFrom(), attackerPiece, move.MoveTo() - direction, Pawn);
}
} else {
if (move.GetFlags() != kingCastle && move.GetFlags() != queenCastle) {
accPair.addSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece);
}
}
{
if (move.IsCapture()) {
if (move.GetFlags() != epCapture) {
accUpdate.setAddSubSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, move.MoveTo(), targetPiece);
} else {
accUpdate.setAddSubSub(sideToMove, enPassantTarget, endPiece, move.MoveFrom(), attackerPiece, move.MoveTo() - direction, Pawn);
}
} else {
if (move.GetFlags() != kingCastle && move.GetFlags() != queenCastle) {
accUpdate.setAddSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece);
}
}
}
switch (move.GetFlags())
{
@@ -397,37 +470,45 @@ bool Board::MakeMove(Move move) {
case kingCastle:
{
int rookSquare = attackerColor ? h8 : h1;
// Removing rook from old position
RemovePiece(Rook, rookSquare, attackerColor);
// Setting rook on new position
SetPiece(Rook, rookSquare - 2, attackerColor);
SetPiece(attackerPiece, move.MoveTo(), attackerColor);
accPair.addAddSubSub(sideToMove, move.MoveTo(), King, rookSquare - 2, Rook, move.MoveFrom(), King, rookSquare, Rook);
{
accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, rookSquare - 2, Rook, move.MoveFrom(), King, rookSquare, Rook);
}
break;
}
case queenCastle:
{
int rookSquare = attackerColor ? a8 : a1;
// Removing rook from old position
RemovePiece(Rook, rookSquare, attackerColor);
// Setting rook on new position
SetPiece(Rook, rookSquare + 3, attackerColor);
SetPiece(attackerPiece, move.MoveTo(), attackerColor);
accPair.addAddSubSub(sideToMove, move.MoveTo(), King, rookSquare + 3, Rook, move.MoveFrom(), King, rookSquare, Rook);
break;
{
accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, rookSquare + 3, Rook, move.MoveFrom(), King, rookSquare, Rook);
}
break;
}
default:
break;
}
// Removing the right to castle on king and rook movement
if (!accParentClean || accUpdate.type == ACC::UpdateType::None) {
accUpdate.setRefresh();
} else {
accUpdate.refreshMask = refreshMask;
}
UpdateCastlingRights(*this, move.MoveFrom(), attackerPiece, attackerColor);
sideToMove = !attackerColor;
@@ -444,13 +525,10 @@ bool Board::MakeMove(Move move) {
enPassantTarget = newEpTarget;
MOVEGEN::GenThreatMaps(*this);
pinned = {CalcPinned(White), CalcPinned(Black)};
checkers = CalcCheckers();
CalcCheckZones();
sideToMove = !sideToMove;
if (InCheck()) {
*this = save;
return false;
}
sideToMove = !sideToMove;
if (attackerColor == Black) fullMoves++;
if (attackerPiece == Pawn || move.IsCapture()) {
@@ -458,16 +536,13 @@ bool Board::MakeMove(Move move) {
} else {
halfMoves++;
}
positionIndex++;
return true;
positionIndex++;
}
bool Board::InPossibleZug() {
Bitboard toCheck;
// For all pieces other than pawns and king
for (int piece = Knight; piece <= Queen; piece++) {
toCheck |= (pieces[piece] & colors[sideToMove]);
}
@@ -475,67 +550,493 @@ bool Board::InPossibleZug() {
return !toCheck;
}
void Board::ResetAccPair() {
Bitboard whitePieces = colors[White];
Bitboard blackPieces = colors[Black];
ACC::BucketPair Board::GetBuckets() {
int wKingSq = (pieces[King] & colors[White]).getLS1BIndex();
int bKingSq = (pieces[King] & colors[Black]).getLS1BIndex();
accPair.white = NNUE::net.accumulator_biases;
accPair.black = NNUE::net.accumulator_biases;
return {NNUE::kingBuckets[White][wKingSq],NNUE::kingBuckets[Black][bKingSq]};
}
while (whitePieces) {
int square = whitePieces.getLS1BIndex();
void Board::RefreshAccumulator(ACC::AccumulatorPair& out) const {
const int wKingSq = (pieces[King] & colors[White]).getLS1BIndex();
const int bKingSq = (pieces[King] & colors[Black]).getLS1BIndex();
const ACC::BucketPair bucketPair = {NNUE::kingBuckets[White][wKingSq], NNUE::kingBuckets[Black][bKingSq]};
int wInput = ACC::CalculateIndex(White, White, GetPieceType(square), square);
int bInput = ACC::CalculateIndex(Black, White, GetPieceType(square), square);
out.white = NNUE::net.accumulator_biases;
out.black = NNUE::net.accumulator_biases;
for (int i = 0; i < NNUE::HL_SIZE; i++) {
accPair.white[i] += NNUE::net.accumulator_weights[wInput * NNUE::HL_SIZE + i];
accPair.black[i] += NNUE::net.accumulator_weights[bInput * NNUE::HL_SIZE + i];
for (int color = White; color <= Black; color++) {
Bitboard bb = colors[color];
while (bb) {
int square = bb.getLS1BIndex();
int wInput = ACC::CalculateIndex(White, color, mailbox[square], square, mirroredWhite);
int bInput = ACC::CalculateIndex(Black, color, mailbox[square], square, mirroredBlack);
ACC::AddRow(out.white, &NNUE::net.accumulator_weights[bucketPair.white][wInput * NNUE::HL_SIZE]);
ACC::AddRow(out.black, &NNUE::net.accumulator_weights[bucketPair.black][bInput * NNUE::HL_SIZE]);
bb.PopBit(square);
}
}
}
whitePieces.PopBit(square);
void Board::RefreshPerspective(ACC::FinnyTable& finny, bool perspective, ACC::Accumulator& out) const {
const bool mirrored = perspective == White ? mirroredWhite : mirroredBlack;
const int kingSq = (pieces[King] & colors[perspective]).getLS1BIndex();
const int bucket = NNUE::kingBuckets[perspective][kingSq];
ACC::FinnyEntry& entry = finny.entries[perspective][mirrored][bucket];
const int16_t* adds[32];
const int16_t* subs[32];
int nAdds = 0;
int nSubs = 0;
for (int color = White; color <= Black; color++) {
for (int pt = Pawn; pt <= King; pt++) {
Bitboard tmp = pieces[pt] & colors[color];
const uint64_t now = tmp;
const uint64_t old = entry.bb[color][pt];
uint64_t added = now & ~old;
uint64_t removed = old & ~now;
while (added) {
const int square = std::countr_zero(added);
added &= added - 1;
adds[nAdds++] = ACC::Row(bucket, ACC::CalculateIndex(perspective, color, pt, square, mirrored));
}
while (removed) {
const int square = std::countr_zero(removed);
removed &= removed - 1;
subs[nSubs++] = ACC::Row(bucket, ACC::CalculateIndex(perspective, color, pt, square, mirrored));
}
entry.bb[color][pt] = now;
}
}
while (blackPieces) {
int square = blackPieces.getLS1BIndex();
ACC::ApplyInPlace(entry.acc, adds, nAdds, subs, nSubs);
out = entry.acc;
}
int wInput = ACC::CalculateIndex(White, Black, GetPieceType(square), square);
int bInput = ACC::CalculateIndex(Black, Black, GetPieceType(square), square);
void Board::ApplyDeltaPerspective(bool perspective, ACC::Accumulator& dst, const ACC::Accumulator& src) const {
const bool mirrored = perspective == White ? mirroredWhite : mirroredBlack;
const int kingSq = (pieces[King] & colors[perspective]).getLS1BIndex();
const int bucket = NNUE::kingBuckets[perspective][kingSq];
for (int i = 0; i < NNUE::HL_SIZE; i++) {
accPair.white[i] += NNUE::net.accumulator_weights[wInput * NNUE::HL_SIZE + i];
accPair.black[i] += NNUE::net.accumulator_weights[bInput * NNUE::HL_SIZE + i];
}
const bool stm = accUpdate.stm;
blackPieces.PopBit(square);
const int16_t* a1 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.addPT1, accUpdate.add1, mirrored));
const int16_t* a2 = nullptr;
const int16_t* s1 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.subPT1, accUpdate.sub1, mirrored));
const int16_t* s2 = nullptr;
if (accUpdate.nAdd == 2)
a2 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.addPT2, accUpdate.add2, mirrored));
if (accUpdate.nSub == 2)
s2 = ACC::Row(bucket, ACC::CalculateIndex(perspective, accUpdate.sub2Opp ? !stm : stm, accUpdate.subPT2, accUpdate.sub2, mirrored));
ACC::Apply(dst, src, a1, a2, s1, s2);
}
void Board::UpdateAccumulator(ACC::AccStack& stack, int ply) {
using ACC::UpdateType;
if (accUpdate.type == UpdateType::None) return;
if (accUpdate.type == UpdateType::Copy && ply > 0) {
stack.cur[ply] = stack.cur[ply - 1];
accUpdate.type = UpdateType::None;
return;
}
ACC::AccumulatorPair& dst = stack.slots[ply];
if (ply == 0 || accUpdate.type != UpdateType::Delta) {
RefreshPerspective(stack.finny, White, dst.white);
RefreshPerspective(stack.finny, Black, dst.black);
} else {
const ACC::AccumulatorPair& prev = *stack.cur[ply - 1];
for (int perspective = White; perspective <= Black; perspective++) {
if (accUpdate.refreshMask & (1 << perspective))
RefreshPerspective(stack.finny, perspective, dst.get(perspective));
else
ApplyDeltaPerspective(perspective, dst.get(perspective), prev.get(perspective));
}
}
stack.cur[ply] = &dst;
accUpdate.type = UpdateType::None;
}
Bitboard Board::AttacksTo(int square, Bitboard occupancy) {
Bitboard attacks;
// Pawn attacks
// Opponent attacks
attacks |= (MOVEGEN::pawnAttacks[sideToMove][square] & colors[!sideToMove] & pieces[Pawn]);
// Own piece attacks
attacks |= (MOVEGEN::pawnAttacks[!sideToMove][square] & colors[sideToMove] & pieces[Pawn]);
// Knight
attacks |= (MOVEGEN::knightAttacks[square] & pieces[Knight]);
// King
attacks |= (MOVEGEN::kingAttacks[square] & pieces[King]);
Bitboard bishopAttacks = MOVEGEN::getBishopAttack(square, occupancy);
Bitboard rookAttacks = MOVEGEN::getRookAttack(square, occupancy);
// Rook or queen
attacks |= (rookAttacks & (pieces[Rook] | pieces[Queen]));
// Bishop or queen
attacks |= (bishopAttacks & (pieces[Bishop] | pieces[Queen]));
return attacks;
}
static Bitboard rayBetween(int sq1, int sq2) {
if (sq1 == sq2) return 0ULL;
int f1 = sq1 % 8, r1 = sq1 / 8;
int f2 = sq2 % 8, r2 = sq2 / 8;
int df = (f2 > f1) - (f2 < f1);
int dr = (r2 > r1) - (r2 < r1);
if (df != 0 && dr != 0 && std::abs(f2 - f1) != std::abs(r2 - r1))
return 0ULL;
Bitboard ray = 0ULL;
int f = f1 + df;
int r = r1 + dr;
while (f != f2 || r != r2) {
ray |= 1ULL << (r * 8 + f);
f += df;
r += dr;
}
ray &= ~((1ULL << sq1) | (1ULL << sq2));
return ray;
}
static Bitboard fullRay(int from, int to) {
int df = (to % 8) - (from % 8);
int dr = (to / 8) - (from / 8);
if (df != 0) df /= std::abs(df);
if (dr != 0) dr /= std::abs(dr);
Bitboard ray = 0ULL;
int f = from % 8 + df;
int r = from / 8 + dr;
while (f >= 0 && f < 8 && r >= 0 && r < 8) {
ray |= 1ULL << (r * 8 + f);
f += df;
r += dr;
}
f = from % 8 - df;
r = from / 8 - dr;
while (f >= 0 && f < 8 && r >= 0 && r < 8) {
ray |= 1ULL << (r * 8 + f);
f -= df;
r -= dr;
}
ray |= 1ULL << from;
return ray;
}
bool Board::IsSquareThreatened(bool side, int square) {
return colorThreats[!side].IsSet(square);
}
Bitboard Board::CalcCheckers() {
return AttacksTo((colors[sideToMove] & pieces[King]).getLS1BIndex(), occupied) & colors[!sideToMove];
}
Bitboard Board::CalcPinned(bool color) {
Bitboard pinned;
int kingSquare = (pieces[King] & colors[color]).getLS1BIndex();
assert(kingSquare != -1);
Bitboard oppQueens = pieces[Queen] & colors[!color];
Bitboard potentialAttackers = MOVEGEN::getBishopAttack(kingSquare, colors[!color]) & (oppQueens | (pieces[Bishop] & colors[!color]))
| MOVEGEN::getRookAttack(kingSquare, colors[!color]) & (oppQueens | (pieces[Rook] & colors[!color]));
while (potentialAttackers) {
int attackerSquare = potentialAttackers.getLS1BIndex();
Bitboard isPinned = colors[color] & rayBetween(attackerSquare, kingSquare);
if (isPinned.PopCount() == 1)
pinned |= isPinned;
potentialAttackers.PopBit(attackerSquare);
}
return pinned;
}
bool Board::IsLegal(Move &move) {
assert(move != 0);
int us = sideToMove;
int them = !us;
int from = move.MoveFrom();
int to = move.MoveTo();
Bitboard king = pieces[King] & colors[us];
int kingSquare = king.getLS1BIndex();
int moveType = move.GetFlags();
if (moveType == epCapture) {
int epCapturedSquare = to + (us == White ? -8 : 8);
Bitboard occAfterEP = occupied ^ Bitboard::GetSquare(from) ^ Bitboard::GetSquare(to)
^ Bitboard::GetSquare(epCapturedSquare);
Bitboard theirQueens = pieces[Queen] & colors[them];
return (MOVEGEN::getBishopAttack(kingSquare, occAfterEP) & (theirQueens | (pieces[Bishop] & colors[them]))).PopCount() < 1
&& (MOVEGEN::getRookAttack(kingSquare, occAfterEP) & (theirQueens | (pieces[Rook] & colors[them]))).PopCount() < 1;
}
int movingPiece = GetPieceType(from);
if (movingPiece == King) {
Bitboard kinglessOcc = occupied ^ king;
Bitboard theirQueens = pieces[Queen] & colors[them];
return !colorThreats[them].IsSet(to)
&& (MOVEGEN::getBishopAttack(to, kinglessOcc) & (theirQueens | (pieces[Bishop] & colors[them]))).PopCount() == 0
&& (MOVEGEN::getRookAttack(to, kinglessOcc) & (theirQueens | (pieces[Rook] & colors[them]))).PopCount() == 0;
}
if (checkers.PopCount() > 1) {
return false;
}
if (pinned[us].IsSet(from) && !fullRay(kingSquare, from).IsSet(to))
return false;
if (checkers.PopCount() < 1)
return true;
int checkerSquare = checkers.getLS1BIndex();
return (rayBetween(kingSquare, checkerSquare) | checkers).IsSet(to);
}
bool Board::IsPseudoLegal(Move &move) {
if (!move) return true;
const int from = move.MoveFrom();
const int to = move.MoveTo();
const int flag = move.GetFlags();
if ((unsigned)from >= 64u || (unsigned)to >= 64u) return false;
const int us = sideToMove;
const int them = !sideToMove;
const int movingPiece = GetPieceType(from);
if (movingPiece == nullPieceType) return false;
if (!colors[us].IsSet(from)) return false;
if (colors[us].IsSet(to)) return false;
const bool isCapture = move.IsCapture();
const int targetPiece = GetPieceType(to);
if (flag == capture) {
if (targetPiece == nullPieceType) return false;
if (!colors[them].IsSet(to)) return false;
} else if (isCapture && flag != epCapture) {
if (targetPiece == nullPieceType) return false;
if (!colors[them].IsSet(to)) return false;
} else if (!isCapture) {
if (occupied.IsSet(to)) {
if (flag != kingCastle && flag != queenCastle) return false;
}
}
const int fromFile = from & 7;
const int toFile = to & 7;
const int fromRank = from >> 3;
const int toRank = to >> 3;
const int dir = us ? south : north;
auto isOneStepPawnPush = [&] {
return to == from + dir && !occupied.IsSet(to);
};
auto isPawnCaptureTo = [&] {
return (to == from + dir - 1 && toFile == fromFile - 1)
|| (to == from + dir + 1 && toFile == fromFile + 1);
};
switch (flag) {
case quiet:
case capture:
break;
case doublePawnPush: {
if (movingPiece != Pawn) return false;
if (!us) {
if (fromRank != 1) return false;
} else {
if (fromRank != 6) return false;
}
const int mid = from + dir;
if (to != from + 2 * dir) return false;
if (occupied.IsSet(mid) || occupied.IsSet(to)) return false;
return true;
}
case epCapture: {
if (movingPiece != Pawn) return false;
if (enPassantTarget == noEPTarget) return false;
if (to != enPassantTarget) return false;
if (!isPawnCaptureTo()) return false;
const int capSq = to - dir;
if (!colors[them].IsSet(capSq)) return false;
if (GetPieceType(capSq) != Pawn) return false;
if (occupied.IsSet(to)) return false;
return true;
}
case kingCastle:
case queenCastle: {
if (movingPiece != King) return false;
const int kingSquare = (colors[us] & pieces[King]).getLS1BIndex();
if (from != kingSquare) return false;
const int kingRight = us ? blackKingRight : whiteKingRight;
const int queenRight = us ? blackQueenRight : whiteQueenRight;
if (flag == kingCastle) {
if (!(castlingRights & kingRight)) return false;
const U64 KingSide = us ? 0xf000000000000000ULL : 0xf0ULL;
const U64 mask = us ? 0x7000000000000000ULL : 0x70ULL;
const int targetSq = us ? g8 : g1;
if (to != targetSq) return false;
if ((Bitboard(KingSide) & occupied).PopCount() != 2) return false;
if (mask & colorThreats[them]) return false;
return true;
} else {
if (!(castlingRights & queenRight)) return false;
const U64 QueenSide = us ? 0x1f00000000000000ULL : 0x1fULL;
const U64 mask = us ? 0x1c00000000000000ULL : 0x1cULL;
const int targetSq = us ? c8 : c1;
if (to != targetSq) return false;
if ((Bitboard(QueenSide) & occupied).PopCount() != 2) return false;
if (mask & colorThreats[them]) return false;
return true;
}
}
default:
if (!move.IsPromo()) return false;
if (movingPiece != Pawn) return false;
if (!us) {
if (toRank != 7) return false;
} else {
if (toRank != 0) return false;
}
if (move.IsCapture()) {
if (!isPawnCaptureTo()) return false;
if (!colors[them].IsSet(to)) return false;
} else {
if (!isOneStepPawnPush()) return false;
}
return true;
}
switch (movingPiece) {
case Pawn: {
if (!us) { if (toRank == 7) return false; }
else { if (toRank == 0) return false; }
if (move.IsCapture()) {
if (!isPawnCaptureTo()) return false;
return true;
} else {
return isOneStepPawnPush();
}
}
case Knight:
return (MOVEGEN::knightAttacks[from] & Bitboard::GetSquare(to)) != 0;
case Bishop: {
Bitboard att = MOVEGEN::getBishopAttack(from, occupied);
return (att & Bitboard::GetSquare(to)) != 0;
}
case Rook: {
Bitboard att = MOVEGEN::getRookAttack(from, occupied);
return (att & Bitboard::GetSquare(to)) != 0;
}
case Queen: {
Bitboard att = MOVEGEN::getBishopAttack(from, occupied) | MOVEGEN::getRookAttack(from, occupied);
return (att & Bitboard::GetSquare(to)) != 0;
}
case King:
return (MOVEGEN::kingAttacks[from] & Bitboard::GetSquare(to)) != 0;
default:
return false;
}
}
void Board::CalcCheckZones() {
int oppKingSquare = (colors[!sideToMove] & pieces[King]).getLS1BIndex();
checkZones[0] = MOVEGEN::pawnAttacks[!sideToMove][oppKingSquare];
checkZones[1] = MOVEGEN::knightAttacks[oppKingSquare];
checkZones[2] = MOVEGEN::getBishopAttack(oppKingSquare, occupied);
checkZones[3] = MOVEGEN::getRookAttack(oppKingSquare, occupied);
}
bool Board::GivesDirectCheck(Move &move) {
int attackerType = nullPieceType;
if (move.IsPromo()) {
attackerType = move.GetPromoPiece();
} else {
attackerType = GetPieceType(move.MoveFrom());
}
if (attackerType == King)
return false;
Bitboard checkZone = 0ULL;
if (attackerType == Queen) {
checkZone = checkZones[Bishop] | checkZones[Rook];
} else {
checkZone = checkZones[attackerType];
}
return checkZone.IsSet(move.MoveTo());
}
+33 -5
View File
@@ -16,12 +16,19 @@ public:
SetByFen(StartingFen);
}
std::array<int, 64> mailbox;
std::array<Bitboard, 6> pieces;
std::array<Bitboard, 2> colors;
Bitboard occupied;
ACC::AccumulatorPair accPair;
std::array<Bitboard, 2> pinned;
Bitboard checkers;
ACC::Update accUpdate;
bool mirroredWhite = false;
bool mirroredBlack = false;
std::array<Bitboard, 6> pieceThreats;
std::array<Bitboard, 2> colorThreats;
@@ -40,6 +47,11 @@ public:
int fullMoves = 1;
U64 hashKey = 0ULL;
U64 pawnKey = 0ULL;
U64 nonPawnKey = 0ULL;
U64 majorKey = 0ULL;
std::array<Bitboard, 4> checkZones;
void Reset();
void SetByFen(std::string_view fen);
@@ -52,20 +64,36 @@ public:
void ResetMoves();
void ListMoves();
void ResetAccPair();
ACC::BucketPair GetBuckets();
void RefreshAccumulator(ACC::AccumulatorPair& out) const;
void UpdateAccumulator(ACC::AccStack& stack, int ply);
void RefreshPerspective(ACC::FinnyTable& finny, bool perspective, ACC::Accumulator& out) const;
void ApplyDeltaPerspective(bool perspective, ACC::Accumulator& dst, const ACC::Accumulator& src) const;
void MarkAccumulatorDirty() { accUpdate.setRefresh(); }
int GetPieceType(int square);
int GetPieceColor(int square);
bool InCheck();
void SetPiece(int piece, int square, bool color);
void RemovePiece(int piece, int square, bool color);
void Promote(int square, int pieceType, int color, bool isCapture);
bool MakeMove(Move move);
void MakeMove(Move move);
bool InPossibleZug();
Bitboard AttacksTo(int square, Bitboard occupancy);
};
bool IsSquareThreatened(bool side, int square);
Bitboard CalcCheckers();
Bitboard CalcPinned(bool color);
void CalcCheckZones();
bool GivesDirectCheck(Move &move);
bool IsLegal(Move &move);
bool IsPseudoLegal(Move &move);
};
+704 -137
View File
@@ -2,18 +2,65 @@
#include <fstream>
#include <iomanip>
#include <thread>
#include <tuple>
#include <atomic>
#include <mutex>
#include <filesystem>
#include <iostream>
#include <string>
#include <chrono>
#include <sstream>
#include <csignal>
#include <cstdlib>
#include <cerrno>
#include "datagen.h"
#include "movegen.h"
#include "search.h"
#include "movegen.h"
#include "utils.h"
// OS-dependent threading includes
#ifdef _WIN32
#include <windows.h>
#include <windows.h>
#include <io.h>
#include <process.h>
#else
#include <pthread.h>
#include <unistd.h>
#endif
static std::filesystem::path MakeTempPath(const std::string& prefix, const std::string& ext) {
namespace fs = std::filesystem;
fs::path dir = fs::temp_directory_path();
std::random_device rd;
std::mt19937_64 gen(rd());
std::uniform_int_distribution<uint64_t> dist;
auto name = prefix + std::to_string(dist(gen)) + ext;
return dir / name;
}
static std::string ShellQuote(const std::string& s) {
#ifdef _WIN32
std::string out = "\"";
for (char c : s) {
if (c == '"') out += "\\\"";
else out += c;
}
out += "\"";
return out;
#else
std::string out = "'";
for (char c : s) {
if (c == '\'') out += "'\\''";
else out += c;
}
out += "'";
return out;
#endif
}
#ifdef _WIN32
static void HideCursor() {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
@@ -30,60 +77,209 @@ static void ShowCursor() {
cursorInfo.bVisible = TRUE;
SetConsoleCursorInfo(hConsole, &cursorInfo);
}
#else
static void HideCursor() { std::cout << "\033[?25l"; }
static void ShowCursor() { std::cout << "\033[?25h"; }
#endif
static void HideCursorLinux() {
std::cout << "\033[?25l";
}
static void ShowCursorLinux() {
std::cout << "\033[?25h";
}
namespace DATAGEN {
static std::mutex fileOpenMutex;
static bool IsGameOver(Board &board, SEARCH::SearchContext& ctx) {
static bool PostJSON(const std::string& url, const std::string& jsonBody, std::string& response) {
namespace fs = std::filesystem;
fs::path tempFile = MakeTempPath("datagen_request_", ".json");
fs::path responseFile = MakeTempPath("datagen_response_", ".txt");
std::ofstream out(tempFile);
if (!out) {
std::cerr << "Failed to create temp file for request: " << tempFile.string() << "\n";
return false;
}
out << jsonBody;
out.close();
std::ostringstream cmd;
cmd << "curl -s -X POST "
<< ShellQuote(url) << " "
<< "-H " << ShellQuote("Content-Type: application/json") << " "
<< "-d " << ShellQuote("@" + tempFile.string()) << " "
<< "-o " << ShellQuote(responseFile.string()) << " ";
#ifdef _WIN32
cmd << "2>nul";
#else
cmd << "2>/dev/null";
#endif
int result = system(cmd.str().c_str());
std::ifstream responseIn(responseFile);
if (responseIn) {
std::stringstream buffer;
buffer << responseIn.rdbuf();
response = buffer.str();
} else {
response.clear();
}
std::error_code ec;
fs::remove(tempFile, ec);
fs::remove(responseFile, ec);
return (result == 0);
}
static bool UploadFile(const std::string& url,
const std::string& filepath,
const std::string& username,
int positions) {
std::ostringstream cmd;
cmd << "curl -s -X POST "
<< ShellQuote(url) << " "
<< "-F " << ShellQuote("file=@" + filepath) << " "
<< "-F " << ShellQuote("user=" + username) << " "
<< "-F " << ShellQuote("positions=" + std::to_string(positions)) << " ";
#ifdef _WIN32
cmd << "2>nul";
#else
cmd << "2>/dev/null";
#endif
int result = system(cmd.str().c_str());
return (result == 0);
}
static std::string BuildStartJSON(const std::string& username, int targetPositions) {
std::ostringstream json;
json << "{"
<< "\"user\":\"" << username << "\","
<< "\"target\":" << targetPositions
<< "}";
return json.str();
}
static std::string BuildHeartbeatJSON(const std::string& username, int threads) {
std::ostringstream json;
json << "{"
<< "\"user\":\"" << username << "\","
<< "\"threads\":" << threads
<< "}";
return json.str();
}
static std::string ExtractJSONValue(const std::string& json, const std::string& key) {
std::string searchKey = "\"" + key + "\":";
size_t pos = json.find(searchKey);
if (pos == std::string::npos) return "";
pos += searchKey.length();
while (pos < json.length() && (json[pos] == ' ' || json[pos] == '\t' || json[pos] == '\n')) {
pos++;
}
if (pos >= json.length()) return "";
if (json[pos] == '"') {
pos++;
size_t endPos = json.find("\"", pos);
if (endPos == std::string::npos) return "";
return json.substr(pos, endPos - pos);
} else {
size_t endPos = pos;
while (endPos < json.length() && json[endPos] != ',' && json[endPos] != '}' && json[endPos] != ']') {
endPos++;
}
return json.substr(pos, endPos - pos);
}
}
static void HeartbeatThread(const std::string& username, int threads,
std::atomic<bool>& stopFlag, const std::string& serverUrl) {
while (!stopFlag) {
for (int i = 0; i < 15 && !stopFlag; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
if (stopFlag) break;
std::string response;
std::string heartbeatJSON = BuildHeartbeatJSON(username, threads);
PostJSON(serverUrl + "/api/session/heartbeat", heartbeatJSON, response);
}
}
// Signal handling globals
static std::atomic<bool> g_shutdownRequested(false);
static void SignalHandler(int signal) {
if (signal == SIGINT || signal == SIGTERM) {
std::cout << "\n\nShutdown signal received. Saving data safely...\n" << std::flush;
g_shutdownRequested.store(true);
}
}
static void SetupSignalHandlers() {
std::signal(SIGINT, SignalHandler);
std::signal(SIGTERM, SignalHandler);
#ifndef _WIN32
std::signal(SIGHUP, SignalHandler);
#endif
}
static bool IsGameOver(Board &board, SEARCH::SearchContext* ctx) {
if (SEARCH::IsDraw(board, ctx)) return true;
int moveSeen = 0;
for (int i = 0; i < board.currentMoveIndex; i++) {
if (!board.IsLegal(board.moveList[i])) continue;
Board copy = board;
bool isLegal = copy.MakeMove(board.moveList[i]);
if (!isLegal) continue;
moveSeen++;
copy.MakeMove(board.moveList[i]);
moveSeen++;
}
return moveSeen == 0;
}
static void PlayRandMoves(Board &board, SEARCH::SearchContext& ctx) {
static void PlayRandMoves(Board &board, SEARCH::SearchContext* ctx) {
std::random_device dev;
std::mt19937_64 rng(dev());
std::uniform_int_distribution<int> moveDist(0, 1);
bool plusOne = moveDist(rng);
for (int count = 0; count < RAND_MOVES + plusOne; count++) {
MOVEGEN::GenerateMoves<All>(board);
MOVEGEN::GenerateMoves<All>(board, true);
if (board.currentMoveIndex <= 0) {
break;
}
std::uniform_int_distribution<int> dist(0, board.currentMoveIndex - 1);
bool isLegal = board.MakeMove(board.moveList[dist(rng)]);
if (!isLegal) {
Move currMove = board.moveList[dist(rng)];
if (!board.IsLegal(currMove)) {
count--;
continue;
}
ctx.positionHistory[board.positionIndex] = board.hashKey;
MOVEGEN::GenerateMoves<All>(board);
board.MakeMove(currMove);
ctx->positionHistory[board.positionIndex] = board.hashKey;
MOVEGEN::GenerateMoves<All>(board, true);
if (IsGameOver(board, ctx)) break;
}
}
static void WriteToFile(std::vector<Game> &gamesBuffer, std::ofstream &file) {
static void WriteToFile(std::vector<Game> &gamesBuffer, const std::string& basePath, int& fileCounter) {
if (gamesBuffer.empty()) return;
int32_t zeroes = 0;
std::vector<char> buffer;
@@ -106,129 +302,482 @@ static void WriteToFile(std::vector<Game> &gamesBuffer, std::ofstream &file) {
buffer.insert(buffer.end(), zeroesPtr, zeroesPtr + sizeof(zeroes));
}
file.write(buffer.data(), buffer.size());
file.flush();
std::string tmpFileName = basePath + std::to_string(fileCounter) + ".tmp";
std::string finalFileName = basePath + std::to_string(fileCounter) + ".binpack";
std::ofstream tmpFile(tmpFileName, std::ios::binary);
if (!tmpFile.is_open()) {
std::cerr << "Failed to create temporary file: " << tmpFileName << std::endl;
return;
}
tmpFile.write(buffer.data(), buffer.size());
tmpFile.flush();
#ifdef _WIN32
tmpFile.close();
#else
tmpFile.close();
sync();
#endif
std::error_code ec;
std::filesystem::rename(tmpFileName, finalFileName, ec);
if (ec) {
std::cerr << "Failed to rename " << tmpFileName << " to " << finalFileName
<< ": " << ec.message() << std::endl;
std::filesystem::remove(tmpFileName, ec);
return;
}
fileCounter++;
}
static std::string MergeThreadFiles() {
namespace fs = std::filesystem;
fs::create_directories("data");
auto now = std::chrono::system_clock::now();
std::time_t now_time = std::chrono::system_clock::to_time_t(now);
std::tm tm = *std::localtime(&now_time);
std::ostringstream oss;
oss << "data/datagen_"
<< std::put_time(&tm, "%Y-%m-%d_%H-%M")
<< ".binpack";
std::string finalFileName = oss.str();
std::ofstream finalFile(finalFileName, std::ios::binary);
if (!finalFile.is_open()) {
std::cerr << "Failed to create final merged file: " << finalFileName << std::endl;
return "";
}
fs::path dataDir("data");
for (const auto& entry : fs::directory_iterator(dataDir)) {
if (!entry.is_regular_file()) continue;
std::string filename = entry.path().filename().string();
if (filename.find("thread") == 0 && filename.find(".binpack") != std::string::npos) {
std::ifstream threadFile(entry.path(), std::ios::binary);
if (!threadFile.is_open()) {
std::cerr << "Failed to open " << filename << std::endl;
continue;
}
finalFile << threadFile.rdbuf();
threadFile.close();
std::error_code ec;
fs::remove(entry.path(), ec);
if (ec) {
std::cerr << "Failed to delete " << filename << ": " << ec.message() << std::endl;
}
}
}
for (const auto& entry : fs::directory_iterator(dataDir)) {
if (!entry.is_regular_file()) continue;
std::string filename = entry.path().filename().string();
if (filename.find("thread") == 0 && filename.find(".tmp") != std::string::npos) {
std::error_code ec;
fs::remove(entry.path(), ec);
if (ec) {
std::cerr << "Failed to delete incomplete temp file " << filename << ": " << ec.message() << std::endl;
}
}
}
finalFile.close();
std::cout << "Merged all thread files into: " << finalFileName << std::endl;
return finalFileName;
}
static void PlayGames(int id, std::atomic<int>& positions, std::atomic<bool>& stopFlag) {
std::vector<Game> gamesBuffer;
gamesBuffer.reserve(GAME_BUFFER);
std::string fileName = "thread" + std::to_string(id) + ".binpack";
std::filesystem::create_directories("data");
std::ofstream file;
{
std::lock_guard<std::mutex> lock(fileOpenMutex);
file.open(fileName, std::ios::app | std::ios::binary);
std::string basePath = "data/thread" + std::to_string(id) + "_";
int fileCounter = 0;
const int evenityMargin = 200;
try {
while (!stopFlag && !g_shutdownRequested) {
Board board;
TTable DatagenTT;
auto ctx = std::make_unique<SEARCH::SearchContext>();
ctx->TT = &DatagenTT;
PlayRandMoves(board, ctx.get());
if (IsGameOver(board, ctx.get())) continue;
const int startingScore = SEARCH::SearchPosition<SEARCH::datagen>(board, SearchParams(), ctx.get()).score;
if (std::abs(startingScore) >= evenityMargin) continue;
ctx->nodes = 0;
Game game;
Board startpos = board;
SearchResults safeResults;
int staticEval = UTILS::ConvertToWhiteRelative(board, NNUE::net.Evaluate(board, true));
int wdl = 1;
while (!IsGameOver(board, ctx.get())) {
if (g_shutdownRequested) break;
SearchResults results = SEARCH::SearchPosition<SEARCH::datagen>(board, SearchParams(), ctx.get());
if (!results.bestMove) break;
safeResults = results;
game.moves.emplace_back(ScoredMove(results.bestMove.ConvertToViriMoveFormat(),
UTILS::ConvertToWhiteRelative(board, results.score)));
board.MakeMove(results.bestMove);
ctx->positionHistory[board.positionIndex] = board.hashKey;
positions++;
MOVEGEN::GenerateMoves<All>(board, true);
}
if (!SEARCH::IsDraw(board, ctx.get())) {
wdl = board.sideToMove ? 2 : 0;
}
game.format.packFrom(startpos, staticEval, wdl);
gamesBuffer.emplace_back(game);
if (gamesBuffer.size() >= GAME_BUFFER) {
WriteToFile(gamesBuffer, basePath, fileCounter);
gamesBuffer.clear();
}
}
} catch (...) {
if (!gamesBuffer.empty()) {
WriteToFile(gamesBuffer, basePath, fileCounter);
}
throw;
}
if (!file.is_open()) {
std::cerr << "Failed to open file: " << fileName << std::endl;
exit(-1);
}
while (!stopFlag) {
Game game;
Board board;
SEARCH::SearchContext ctx;
PlayRandMoves(board, ctx);
if (IsGameOver(board, ctx)) continue;
Board startpos = board;
SearchResults safeResults;
int staticEval = UTILS::ConvertToWhiteRelative(board, NNUE::net.Evaluate(board));
int wdl = 1;
while (!IsGameOver(board, ctx)) {
SearchResults results = SEARCH::SearchPosition<SEARCH::datagen>(board, SearchParams(), ctx);
if (!results.bestMove) break;
safeResults = results;
game.moves.emplace_back(ScoredMove(results.bestMove.ConvertToViriMoveFormat(),
UTILS::ConvertToWhiteRelative(board, results.score)));
board.MakeMove(results.bestMove);
ctx.positionHistory[board.positionIndex] = board.hashKey;
positions++;
MOVEGEN::GenerateMoves<All>(board);
}
if (!SEARCH::IsDraw(board, ctx)) {
wdl = board.sideToMove ? 2 : 0;
}
game.format.packFrom(startpos, staticEval, wdl);
gamesBuffer.emplace_back(game);
if (gamesBuffer.size() >= GAME_BUFFER) {
WriteToFile(gamesBuffer, file);
gamesBuffer.clear();
}
}
// Write remaining games to file
if (gamesBuffer.size() > 0) {
WriteToFile(gamesBuffer, file);
if (!gamesBuffer.empty()) {
WriteToFile(gamesBuffer, basePath, fileCounter);
gamesBuffer.clear();
}
if (!stopFlag.load() && !g_shutdownRequested.load()) {
std::abort();
}
}
#ifdef _WIN32
struct WinThreadArgs {
int id;
std::atomic<int>* positions;
std::atomic<bool>* stopFlag;
};
static unsigned __stdcall WinThreadEntry(void* p) {
std::unique_ptr<WinThreadArgs> args(static_cast<WinThreadArgs*>(p));
PlayGames(args->id, *args->positions, *args->stopFlag);
_endthreadex(0);
return 0;
}
static bool CreateWorkerThread(int id,
std::atomic<int>& positions,
std::atomic<bool>& stopFlag,
std::vector<HANDLE>& threads,
size_t stackSizeBytes) {
auto* args = new WinThreadArgs{ id, &positions, &stopFlag };
unsigned tid = 0;
HANDLE h = reinterpret_cast<HANDLE>(
_beginthreadex(
nullptr,
static_cast<unsigned>(stackSizeBytes),
&WinThreadEntry,
args,
0,
&tid
)
);
if (!h) {
std::cerr << "Failed to create thread " << id << " (errno=" << errno << ")\n";
delete args;
return false;
}
threads.push_back(h);
return true;
}
static void JoinWorkerThreads(std::vector<HANDLE>& threads) {
for (HANDLE h : threads) {
if (h) {
WaitForSingleObject(h, INFINITE);
CloseHandle(h);
}
}
threads.clear();
}
#else
static void* ThreadFunc(void* arg) {
auto* tup = static_cast<std::tuple<int, std::atomic<int>*, std::atomic<bool>*>*>(arg);
PlayGames(std::get<0>(*tup), *std::get<1>(*tup), *std::get<2>(*tup));
delete tup;
return nullptr;
}
#endif
void Run(int targetPositions, int threads) {
#ifdef _WIN32
system("cls");
HideCursor();
#else
std::cout << "\033[2J\033[H";
HideCursorLinux();
#endif
SetupSignalHandlers();
#ifdef _WIN32
system("cls");
HideCursor();
#else
std::cout << "\033[2J\033[H";
HideCursor();
#endif
std::atomic<int> positions = 0;
std::atomic<bool> stopFlag = false;
std::vector<std::thread> workerThreads;
#ifdef _WIN32
std::vector<HANDLE> workerThreads;
workerThreads.reserve((threads > 1) ? (threads - 1) : 0);
// Start N-1 threads
for (int i = 0; i < threads-1; i++) {
workerThreads.emplace_back(std::thread(PlayGames, i, std::ref(positions), std::ref(stopFlag)));
const size_t stackSizeBytes = 8ull * 1024ull * 1024ull;
for (int i = 0; i < threads - 1; ++i) {
CreateWorkerThread(i, positions, stopFlag, workerThreads, stackSizeBytes);
}
#else
std::vector<pthread_t> workerThreads;
for (int i = 0; i < threads - 1; ++i) {
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024);
auto* args = new std::tuple<int, std::atomic<int>*, std::atomic<bool>*>(i, &positions, &stopFlag);
pthread_t thread;
if (pthread_create(&thread, &attr, ThreadFunc, args) == 0) {
workerThreads.push_back(thread);
} else {
std::cerr << "Failed to create thread " << i << "\n";
delete args;
}
pthread_attr_destroy(&attr);
}
#endif
Stopwatch sw;
while (positions < targetPositions) {
while (positions < targetPositions && !g_shutdownRequested) {
PrintProgress(positions, targetPositions, sw, threads);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
PrintProgress(positions, targetPositions, sw, threads);
stopFlag = true;
for (auto& thread : workerThreads) {
if (thread.joinable()) {
thread.join();
std::cout << "\n\nWaiting for threads to finish writing..." << std::endl;
#ifdef _WIN32
JoinWorkerThreads(workerThreads);
#else
for (pthread_t& thread : workerThreads) {
pthread_join(thread, nullptr);
}
#endif
std::cout << "All threads completed. Merging files..." << std::endl;
MergeThreadFiles();
#ifdef _WIN32
ShowCursor();
#else
ShowCursor();
#endif
std::cout << "\nShutdown complete. All data saved safely." << std::endl;
}
void RunOnline(const std::string& username, int targetPositions, int threads) {
const std::string SERVER_URL = "http://13.60.26.163:3000";
SetupSignalHandlers();
std::cout << "=== ONLINE MODE ===" << std::endl;
std::cout << "User: " << username << std::endl;
std::cout << "Target positions per cycle: " << targetPositions << std::endl;
std::cout << "Threads: " << threads << std::endl;
std::cout << "===================" << std::endl << std::endl;
while (!g_shutdownRequested) {
std::cout << "Sending heartbeat..." << std::endl;
std::string heartbeatResponse;
std::string heartbeatJSON = BuildHeartbeatJSON(username, threads);
if (!PostJSON(SERVER_URL + "/api/session/heartbeat", heartbeatJSON, heartbeatResponse)) {
std::cerr << "Failed to send heartbeat. Retrying in 10 seconds..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(10));
continue;
}
std::cout << "Heartbeat response: " << heartbeatResponse << std::endl;
std::string startResponse;
std::string startJSON = BuildStartJSON(username, targetPositions);
std::cout << "Starting new session..." << std::endl;
if (!PostJSON(SERVER_URL + "/api/session/start", startJSON, startResponse)) {
std::cerr << "Failed to start session. Retrying in 10 seconds..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(10));
continue;
}
std::cout << "Server response: " << startResponse << std::endl;
std::string sessionId = ExtractJSONValue(startResponse, "session_id");
if (sessionId.empty()) {
std::cerr << "Failed to parse session ID. Retrying..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(10));
continue;
}
std::cout << "Session ID: " << sessionId << std::endl;
std::atomic<bool> heartbeatStop(false);
std::thread heartbeat(HeartbeatThread, username, threads, std::ref(heartbeatStop), SERVER_URL);
#ifdef _WIN32
system("cls");
HideCursor();
#else
std::cout << "\033[2J\033[H";
HideCursor();
#endif
std::atomic<int> positions = 0;
std::atomic<bool> stopFlag = false;
#ifdef _WIN32
std::vector<HANDLE> workerThreads;
workerThreads.reserve((threads > 1) ? (threads - 1) : 0);
const size_t stackSizeBytes = 8ull * 1024ull * 1024ull;
for (int i = 0; i < threads - 1; ++i) {
CreateWorkerThread(i, positions, stopFlag, workerThreads, stackSizeBytes);
}
#else
std::vector<pthread_t> workerThreads;
for (int i = 0; i < threads - 1; ++i) {
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024);
auto* args = new std::tuple<int, std::atomic<int>*, std::atomic<bool>*>(i, &positions, &stopFlag);
pthread_t thread;
if (pthread_create(&thread, &attr, ThreadFunc, args) == 0) {
workerThreads.push_back(thread);
} else {
std::cerr << "Failed to create thread " << i << "\n";
delete args;
}
pthread_attr_destroy(&attr);
}
#endif
Stopwatch sw;
while (positions < targetPositions && !g_shutdownRequested) {
PrintProgress(positions, targetPositions, sw, threads);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
PrintProgress(positions, targetPositions, sw, threads);
stopFlag = true;
std::cout << "\n\nWaiting for threads to finish writing..." << std::endl;
#ifdef _WIN32
JoinWorkerThreads(workerThreads);
#else
for (pthread_t& thread : workerThreads) {
pthread_join(thread, nullptr);
}
#endif
heartbeatStop = true;
if (heartbeat.joinable()) {
heartbeat.join();
}
if (g_shutdownRequested) break;
std::cout << "All threads completed. Merging files..." << std::endl;
std::string mergedFile = MergeThreadFiles();
#ifdef _WIN32
ShowCursor();
#else
ShowCursor();
#endif
if (!mergedFile.empty()) {
std::cout << "Uploading file to server..." << std::endl;
std::string uploadUrl = SERVER_URL + "/api/upload/" + sessionId;
if (UploadFile(uploadUrl, mergedFile, username, positions.load())) {
std::cout << "Upload successful!" << std::endl;
std::error_code ec;
std::filesystem::remove(mergedFile, ec);
if (!ec) {
std::cout << "Local file cleaned up." << std::endl;
}
} else {
std::cerr << "Upload failed. File kept locally: " << mergedFile << std::endl;
}
}
if (g_shutdownRequested) break;
std::cout << "\n=== Starting next cycle ===" << std::endl << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
}
#ifdef _WIN32
ShowCursor();
#else
ShowCursorLinux();
#endif
std::cout << "\nOnline mode shutdown complete." << std::endl;
}
void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int threads) {
// Define ANSI escape codes for colors as std::string
const std::string COLOR_RESET = "\033[0m";
const std::string COLOR_TITLE = "\033[1;36m"; // Bright cyan
const std::string COLOR_SECTION = "\033[1;33m"; // Bright yellow
const std::string COLOR_VALUE = "\033[1;32m"; // Bright green
const std::string COLOR_BAR = "\033[1;34m"; // Bright blue
const std::string COLOR_TITLE = "\033[1;36m";
const std::string COLOR_SECTION = "\033[1;33m";
const std::string COLOR_VALUE = "\033[1;32m";
const std::string COLOR_BAR = "\033[1;34m";
static double lastPositions = 0;
static double lastElapsed = 0;
@@ -243,45 +792,67 @@ void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int
lastElapsed = elapsed;
}
int positionsInThousands = static_cast<int>(round(positions / 1000.0));
int targetInThousands = static_cast<int>(round(targetPositions / 1000.0));
std::cout << "\033[H";
int width = 60;
std::string title = "Eleanor - Datagen";
int titlePadding = (width - title.length()) / 2;
std::cout << COLOR_TITLE << std::setw(titlePadding + title.length()) << title << COLOR_RESET << std::endl;
int titlePadding = (width - static_cast<int>(title.length())) / 2;
std::cout << COLOR_TITLE << std::setw(titlePadding + static_cast<int>(title.length())) << title << COLOR_RESET << std::endl;
std::cout << std::string(width, '=') << std::endl;
std::cout << std::endl;
std::cout << std::fixed << std::setprecision(0);
std::ostringstream datagenTextStream;
datagenTextStream << std::fixed << std::setprecision(2)
<< "Positions processed: " << positions / 1000.0 << "K | Target: " << targetPositions / 1000.0 << "K";
datagenTextStream << std::fixed << std::setprecision(2)
<< "Positions processed: " << positions / 1000.0 << "K | Target: " << targetPositions / 1000.0 << "K";
std::string datagenText = datagenTextStream.str();
int datagenPadding = (width - datagenText.length()) / 2;
std::cout << COLOR_SECTION << std::setw(datagenPadding + datagenText.length()) << datagenText << COLOR_RESET << std::endl;
int datagenPadding = (width - static_cast<int>(datagenText.length())) / 2;
std::cout << COLOR_SECTION << std::setw(datagenPadding + static_cast<int>(datagenText.length())) << datagenText << COLOR_RESET << std::endl;
std::cout << std::endl;
std::string elapsedText = "Elapsed Time: " + std::to_string(static_cast<int>(round(elapsed))) + " sec";
int elapsedPadding = (width - elapsedText.length()) / 2;
std::cout << COLOR_SECTION << std::setw(elapsedPadding + elapsedText.length()) << elapsedText << COLOR_RESET << std::endl;
int elapsedPadding = (width - static_cast<int>(elapsedText.length())) / 2;
std::cout << COLOR_SECTION << std::setw(elapsedPadding + static_cast<int>(elapsedText.length())) << elapsedText << COLOR_RESET << std::endl;
std::string positionsPerSecText = "Positions/sec: " + std::to_string(static_cast<int>(round(positionsPerSec)));
int positionsPerSecPadding = (width - positionsPerSecText.length()) / 2;
std::cout << COLOR_VALUE << std::setw(positionsPerSecPadding + positionsPerSecText.length()) << positionsPerSecText << COLOR_RESET << std::endl;
int positionsPerSecPadding = (width - static_cast<int>(positionsPerSecText.length())) / 2;
std::cout << COLOR_VALUE << std::setw(positionsPerSecPadding + static_cast<int>(positionsPerSecText.length())) << positionsPerSecText << COLOR_RESET << std::endl;
std::cout << std::endl;
std::string threadsText = "Threads: " + std::to_string(static_cast<int>(threads));
int threadsTextPadding = (width - threadsText.length()) / 2;
std::cout << COLOR_SECTION << std::setw(threadsTextPadding + threadsText.length()) << threadsText << COLOR_RESET << std::endl;
int threadsTextPadding = (width - static_cast<int>(threadsText.length())) / 2;
std::cout << COLOR_SECTION << std::setw(threadsTextPadding + static_cast<int>(threadsText.length())) << threadsText << COLOR_RESET << std::endl;
std::cout << std::endl;
double remainingTime = 0.0;
if (positions > 0 && elapsed > 0.0) {
double pps = positions / elapsed;
remainingTime = (targetPositions - positions) / pps;
}
remainingTime = (std::max)(0.0, remainingTime);
int remainingHours = static_cast<int>(remainingTime) / 3600;
int remainingMinutes = (static_cast<int>(remainingTime) % 3600) / 60;
int remainingSeconds = static_cast<int>(remainingTime) % 60;
std::ostringstream remainingTimeStream;
remainingTimeStream << "Estimated Time Left: "
<< std::setfill('0') << std::setw(2) << remainingHours << "h "
<< std::setw(2) << remainingMinutes << "m "
<< std::setw(2) << remainingSeconds << "s";
std::string remainingTimeText = remainingTimeStream.str();
int remainingPadding = (width - static_cast<int>(remainingTimeText.length())) / 2;
std::cout << COLOR_SECTION
<< std::setw(remainingPadding + static_cast<int>(remainingTimeText.length()))
<< remainingTimeText << COLOR_RESET << std::endl;
std::cout << std::endl;
@@ -292,22 +863,18 @@ void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int
std::string progressBar = "[";
for (int i = 0; i < barWidth; ++i) {
if (i < pos) {
progressBar += "=";
} else if (i == pos) {
progressBar += ">";
} else {
progressBar += " ";
}
if (i < pos) progressBar += "=";
else if (i == pos) progressBar += ">";
else progressBar += " ";
}
progressBar += "] " + std::to_string(static_cast<int>(round(progress * 100.0))) + " %";
int progressPadding = (width - progressBar.length()) / 2;
std::cout << COLOR_BAR << std::setw(progressPadding + progressBar.length()) << progressBar << COLOR_RESET << std::endl;
int progressPadding = (width - static_cast<int>(progressBar.length())) / 2;
std::cout << COLOR_BAR << std::setw(progressPadding + static_cast<int>(progressBar.length()))
<< progressBar << COLOR_RESET << std::endl;
std::cout << std::endl;
}
}
} // namespace DATAGEN
+2 -20
View File
@@ -6,7 +6,7 @@
namespace DATAGEN {
constexpr int GAME_BUFFER = 1000;
constexpr int GAME_BUFFER = 500;
constexpr int SOFT_NODES = 5000;
constexpr int HARD_NODES = 100000;
constexpr int RAND_MOVES = 8;
@@ -34,25 +34,6 @@ struct MarlinFormat {
this->wdl = wdl;
extra = 0;
}
void writeToFile(const std::string& filename) const {
std::ofstream outFile(filename, std::ios::binary);
if (!outFile) {
std::cerr << "Error opening file for writing!" << std::endl;
return;
}
outFile.write(reinterpret_cast<const char*>(&occupancy), sizeof(occupancy));
outFile.write(reinterpret_cast<const char*>(&pieces), sizeof(pieces));
outFile.write(reinterpret_cast<const char*>(&stmEPSquare), sizeof(stmEPSquare));
outFile.write(reinterpret_cast<const char*>(&halfmoveClock), sizeof(halfmoveClock));
outFile.write(reinterpret_cast<const char*>(&fullmoveNumber), sizeof(fullmoveNumber));
outFile.write(reinterpret_cast<const char*>(&eval), sizeof(eval));
outFile.write(reinterpret_cast<const char*>(&wdl), sizeof(wdl));
outFile.write(reinterpret_cast<const char*>(&extra), sizeof(extra));
outFile.close();
}
};
struct ScoredMove {
@@ -80,6 +61,7 @@ struct Game {
};
void Run(int targetPositions, int threads);
void RunOnline(const std::string& username, int targetPositions, int threads);
void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int threads);
}
+22 -8
View File
@@ -44,12 +44,16 @@ int main(int argc, char* argv[]) {
MOVEGEN::initLeaperAttacks();
MOVEGEN::initSliderAttacks();
UTILS::InitZobrist();
SEARCH::InitLMRTable();
Board board;
MOVEGEN::initLeaperAttacks();
MOVEGEN::initSliderAttacks();
UTILS::InitZobrist();
#ifdef TUNING
SEARCH::RefreshTunableCaches();
#else
SEARCH::InitLMRTable();
#endif
Board board;
if (argc > 1) {
if (std::string(argv[1]) == "bench") {
@@ -57,14 +61,24 @@ int main(int argc, char* argv[]) {
} else if (std::string(argv[1]) == "datagen") {
int positions = 1;
int threads = 1;
std::string username = "";
if (argc > 2) {
positions = std::stoi(argv[2]) * 1000;
if (argc > 3) {
threads = std::stoi(argv[3]);
if (argc > 4) {
username = argv[4];
}
}
}
DATAGEN::Run(positions, threads);
if (!username.empty()) {
DATAGEN::RunOnline(username, positions, threads);
} else {
DATAGEN::Run(positions, threads);
}
}
} else {
UCILoop(board);
+32 -1
View File
@@ -64,6 +64,10 @@ public:
return (GetFlags() >= knightPromotion);
}
bool IsCastle() {
return (GetFlags() == kingCastle || GetFlags() == queenCastle);
}
void PrintMove() {
std::cout << squareCoords[MoveFrom()] << squareCoords[MoveTo()];
@@ -80,10 +84,29 @@ public:
}
}
std::string GetMoveString() {
std::string result = squareCoords[MoveFrom()];
result += squareCoords[MoveTo()];
int flags = GetFlags();
if (flags == knightPromotion || flags == knightPromoCapture) {
result += 'n';
} else if (flags == bishopPromotion || flags == bishopPromoCapture) {
result += 'b';
} else if (flags == rookPromotion || flags == rookPromoCapture) {
result += 'r';
} else if (flags == queenPromotion || flags == queenPromoCapture) {
result += 'q';
}
return result;
}
uint16_t ConvertToViriMoveFormat() {
uint16_t viriMove = 0;
int flags = GetFlags();
viriMove = MoveFrom();
if (flags == kingCastle || flags == queenCastle) {
@@ -127,6 +150,14 @@ public:
return viriMove;
}
int GetPromoPiece() {
if (IsCapture()) {
return GetFlags() - 9;
} else {
return GetFlags() - 5;
}
}
operator uint16_t() {
return m_move;
}
-114
View File
@@ -299,120 +299,6 @@ Bitboard getPawnPushes(int square, bool color, Bitboard &occupancy) {
return pushes;
}
// Returns the direction to target from square
static int GetDirection(int square, int target) {
int rankDiff = (target / 8) - (square / 8);
int fileDiff = (target % 8) - (square % 8);
// Main directions
if (rankDiff == 0 && fileDiff < 0) {
return west;
} else if (rankDiff == 0 && fileDiff > 0) {
return east;
} else if (rankDiff < 0 && fileDiff == 0) {
return south;
} else if (rankDiff > 0 && fileDiff == 0) {
return north;
}
// Diagonals
if (abs(rankDiff) == abs(fileDiff)) {
if (rankDiff < 0 && fileDiff < 0) {
return soWe;
} else if (rankDiff < 0 && fileDiff > 0) {
return soEa;
} else if (rankDiff > 0 && fileDiff < 0) {
return noWe;
} else if (rankDiff > 0 && fileDiff > 0) {
return noEa;
}
}
return 0;
}
// Returns a bitboard of the squares from attacker to target
static Bitboard SliderRayToSquare(int attacker, int target) {
Bitboard ray;
int direction = GetDirection(attacker, target);
if (direction) {
while (attacker != target) {
ray.SetBit(attacker);
attacker += direction;
}
ray.SetBit(target);
}
return ray;
}
static Bitboard GetPinningRay(Board &board, int square, int direction) {
Bitboard ray;
int currentSquare = (board.pieces[King] & board.colors[board.sideToMove]).getLS1BIndex();
int previousRank = currentSquare / 8;
currentSquare += direction;
while (currentSquare < 64 && currentSquare >= 0) {
int currentRank = currentSquare / 8;
int difference = abs(currentRank - previousRank);
if ((abs(direction) == 7 || abs(direction) == 9)
&& difference != 1) {
break;
} else if (abs(direction) == 1 && difference) {
break;
}
previousRank = currentRank;
ray.SetBit(currentSquare);
if (board.occupied.IsSet(currentSquare)) {
if (currentSquare == square) {
currentSquare += direction;
continue;
}
int attackerType = board.GetPieceType(currentSquare);
int attackerColor = board.GetPieceColor(currentSquare);
if (attackerColor != board.sideToMove) {
// Pinned by rook or queen
if (abs(direction) == 1 || abs(direction) == 8) {
if (attackerType == Rook || attackerType == Queen) {
return ray;
}
// Pinned by bishop or queen
} else if (direction % 2 != 0) {
if (attackerType == Bishop || attackerType == Queen) {
return ray;
}
}
}
break;
}
currentSquare += direction;
}
return 0ULL;
}
static bool IsPinned(Board &board, int square) {
int kingSquare = (board.colors[board.sideToMove] & board.pieces[King]).getLS1BIndex();
int directionToKing = GetDirection(square, kingSquare);
if (directionToKing) {
// Checking if there are any pieces between square and kingSquare
if ((SliderRayToSquare(square, kingSquare)
& board.occupied).PopCount() != 2) {
return false;
}
return GetPinningRay(board, square, -directionToKing).PopCount();
}
return false;
}
void GenThreatMaps(Board &board) {
for (int color = White; color <= Black; color++) {
board.colorThreats[color] = 0ULL;
+203 -202
View File
@@ -1,202 +1,203 @@
#pragma once
#include "bitboard.h"
#include "move.h"
#include "board.h"
enum MovegenMode {
All,
Noisy
};
namespace MOVEGEN {
inline Bitboard pawnAttacks[2][64];
inline Bitboard knightAttacks[64];
inline Bitboard kingAttacks[64];
void initLeaperAttacks();
void initSliderAttacks();
Bitboard getBishopAttack(int square, U64 occupancy);
Bitboard getRookAttack(int square, U64 occupancy);
Bitboard getQueenAttack(int square, U64 occupancy);
Bitboard getPawnPushes(int square, bool color, Bitboard &occupancy);
Bitboard getPieceAttacks(int square, int piece, int color, U64 occupancy);
template <MovegenMode mode>
void GenPawnMoves(Board &board);
template <MovegenMode mode>
void GenKnightMoves(Board &board);
template <MovegenMode mode>
void GenRookMoves(Board &board);
template <MovegenMode mode>
void GenBishopMoves(Board &board);
template <MovegenMode mode>
void GenQueenMoves(Board &board);
template <MovegenMode mode>
void GenKingMoves(Board &board);
template <MovegenMode mode>
void GenerateMoves(Board &board);
void GenThreatMaps(Board &board);
// bishop relevant occupancy bit count
constexpr int bishopRelevantBits[64] = {
6, 5, 5, 5, 5, 5, 5, 6,
5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 7, 7, 7, 7, 5, 5,
5, 5, 7, 9, 9, 7, 5, 5,
5, 5, 7, 9, 9, 7, 5, 5,
5, 5, 7, 7, 7, 7, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5,
6, 5, 5, 5, 5, 5, 5, 6
};
// rook relevant occupancy bit count
constexpr int rookRelevantBits[64] = {
12, 11, 11, 11, 11, 11, 11, 12,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
12, 11, 11, 11, 11, 11, 11, 12
};
constexpr U64 rookMagicNumbers[64] = {
0x8a80104000800020ULL,
0x140002000100040ULL,
0x2801880a0017001ULL,
0x100081001000420ULL,
0x200020010080420ULL,
0x3001c0002010008ULL,
0x8480008002000100ULL,
0x2080088004402900ULL,
0x800098204000ULL,
0x2024401000200040ULL,
0x100802000801000ULL,
0x120800800801000ULL,
0x208808088000400ULL,
0x2802200800400ULL,
0x2200800100020080ULL,
0x801000060821100ULL,
0x80044006422000ULL,
0x100808020004000ULL,
0x12108a0010204200ULL,
0x140848010000802ULL,
0x481828014002800ULL,
0x8094004002004100ULL,
0x4010040010010802ULL,
0x20008806104ULL,
0x100400080208000ULL,
0x2040002120081000ULL,
0x21200680100081ULL,
0x20100080080080ULL,
0x2000a00200410ULL,
0x20080800400ULL,
0x80088400100102ULL,
0x80004600042881ULL,
0x4040008040800020ULL,
0x440003000200801ULL,
0x4200011004500ULL,
0x188020010100100ULL,
0x14800401802800ULL,
0x2080040080800200ULL,
0x124080204001001ULL,
0x200046502000484ULL,
0x480400080088020ULL,
0x1000422010034000ULL,
0x30200100110040ULL,
0x100021010009ULL,
0x2002080100110004ULL,
0x202008004008002ULL,
0x20020004010100ULL,
0x2048440040820001ULL,
0x101002200408200ULL,
0x40802000401080ULL,
0x4008142004410100ULL,
0x2060820c0120200ULL,
0x1001004080100ULL,
0x20c020080040080ULL,
0x2935610830022400ULL,
0x44440041009200ULL,
0x280001040802101ULL,
0x2100190040002085ULL,
0x80c0084100102001ULL,
0x4024081001000421ULL,
0x20030a0244872ULL,
0x12001008414402ULL,
0x2006104900a0804ULL,
0x1004081002402ULL
};
constexpr U64 bishopMagicNumbers[64] = {
0x40040844404084ULL,
0x2004208a004208ULL,
0x10190041080202ULL,
0x108060845042010ULL,
0x581104180800210ULL,
0x2112080446200010ULL,
0x1080820820060210ULL,
0x3c0808410220200ULL,
0x4050404440404ULL,
0x21001420088ULL,
0x24d0080801082102ULL,
0x1020a0a020400ULL,
0x40308200402ULL,
0x4011002100800ULL,
0x401484104104005ULL,
0x801010402020200ULL,
0x400210c3880100ULL,
0x404022024108200ULL,
0x810018200204102ULL,
0x4002801a02003ULL,
0x85040820080400ULL,
0x810102c808880400ULL,
0xe900410884800ULL,
0x8002020480840102ULL,
0x220200865090201ULL,
0x2010100a02021202ULL,
0x152048408022401ULL,
0x20080002081110ULL,
0x4001001021004000ULL,
0x800040400a011002ULL,
0xe4004081011002ULL,
0x1c004001012080ULL,
0x8004200962a00220ULL,
0x8422100208500202ULL,
0x2000402200300c08ULL,
0x8646020080080080ULL,
0x80020a0200100808ULL,
0x2010004880111000ULL,
0x623000a080011400ULL,
0x42008c0340209202ULL,
0x209188240001000ULL,
0x400408a884001800ULL,
0x110400a6080400ULL,
0x1840060a44020800ULL,
0x90080104000041ULL,
0x201011000808101ULL,
0x1a2208080504f080ULL,
0x8012020600211212ULL,
0x500861011240000ULL,
0x180806108200800ULL,
0x4000020e01040044ULL,
0x300000261044000aULL,
0x802241102020002ULL,
0x20906061210001ULL,
0x5a84841004010310ULL,
0x4010801011c04ULL,
0xa010109502200ULL,
0x4a02012000ULL,
0x500201010098b028ULL,
0x8040002811040900ULL,
0x28000010020204ULL,
0x6000020202d0240ULL,
0x8918844842082200ULL,
0x4010011029020020ULL
};
#include "movegen.tpp"
}
#pragma once
#include "bitboard.h"
#include "move.h"
#include "board.h"
enum MovegenMode {
Quiet,
Noisy,
All
};
namespace MOVEGEN {
inline Bitboard pawnAttacks[2][64];
inline Bitboard knightAttacks[64];
inline Bitboard kingAttacks[64];
void initLeaperAttacks();
void initSliderAttacks();
Bitboard getBishopAttack(int square, U64 occupancy);
Bitboard getRookAttack(int square, U64 occupancy);
Bitboard getQueenAttack(int square, U64 occupancy);
Bitboard getPawnPushes(int square, bool color, Bitboard &occupancy);
Bitboard getPieceAttacks(int square, int piece, int color, U64 occupancy);
template <MovegenMode mode>
void GenPawnMoves(Board &board);
template <MovegenMode mode>
void GenKnightMoves(Board &board);
template <MovegenMode mode>
void GenRookMoves(Board &board);
template <MovegenMode mode>
void GenBishopMoves(Board &board);
template <MovegenMode mode>
void GenQueenMoves(Board &board);
template <MovegenMode mode>
void GenKingMoves(Board &board);
template <MovegenMode mode>
void GenerateMoves(Board &board, bool clear, bool recalcThreats = true);
void GenThreatMaps(Board &board);
// bishop relevant occupancy bit count
constexpr int bishopRelevantBits[64] = {
6, 5, 5, 5, 5, 5, 5, 6,
5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 7, 7, 7, 7, 5, 5,
5, 5, 7, 9, 9, 7, 5, 5,
5, 5, 7, 9, 9, 7, 5, 5,
5, 5, 7, 7, 7, 7, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5,
6, 5, 5, 5, 5, 5, 5, 6
};
// rook relevant occupancy bit count
constexpr int rookRelevantBits[64] = {
12, 11, 11, 11, 11, 11, 11, 12,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
12, 11, 11, 11, 11, 11, 11, 12
};
constexpr U64 rookMagicNumbers[64] = {
0x8a80104000800020ULL,
0x140002000100040ULL,
0x2801880a0017001ULL,
0x100081001000420ULL,
0x200020010080420ULL,
0x3001c0002010008ULL,
0x8480008002000100ULL,
0x2080088004402900ULL,
0x800098204000ULL,
0x2024401000200040ULL,
0x100802000801000ULL,
0x120800800801000ULL,
0x208808088000400ULL,
0x2802200800400ULL,
0x2200800100020080ULL,
0x801000060821100ULL,
0x80044006422000ULL,
0x100808020004000ULL,
0x12108a0010204200ULL,
0x140848010000802ULL,
0x481828014002800ULL,
0x8094004002004100ULL,
0x4010040010010802ULL,
0x20008806104ULL,
0x100400080208000ULL,
0x2040002120081000ULL,
0x21200680100081ULL,
0x20100080080080ULL,
0x2000a00200410ULL,
0x20080800400ULL,
0x80088400100102ULL,
0x80004600042881ULL,
0x4040008040800020ULL,
0x440003000200801ULL,
0x4200011004500ULL,
0x188020010100100ULL,
0x14800401802800ULL,
0x2080040080800200ULL,
0x124080204001001ULL,
0x200046502000484ULL,
0x480400080088020ULL,
0x1000422010034000ULL,
0x30200100110040ULL,
0x100021010009ULL,
0x2002080100110004ULL,
0x202008004008002ULL,
0x20020004010100ULL,
0x2048440040820001ULL,
0x101002200408200ULL,
0x40802000401080ULL,
0x4008142004410100ULL,
0x2060820c0120200ULL,
0x1001004080100ULL,
0x20c020080040080ULL,
0x2935610830022400ULL,
0x44440041009200ULL,
0x280001040802101ULL,
0x2100190040002085ULL,
0x80c0084100102001ULL,
0x4024081001000421ULL,
0x20030a0244872ULL,
0x12001008414402ULL,
0x2006104900a0804ULL,
0x1004081002402ULL
};
constexpr U64 bishopMagicNumbers[64] = {
0x40040844404084ULL,
0x2004208a004208ULL,
0x10190041080202ULL,
0x108060845042010ULL,
0x581104180800210ULL,
0x2112080446200010ULL,
0x1080820820060210ULL,
0x3c0808410220200ULL,
0x4050404440404ULL,
0x21001420088ULL,
0x24d0080801082102ULL,
0x1020a0a020400ULL,
0x40308200402ULL,
0x4011002100800ULL,
0x401484104104005ULL,
0x801010402020200ULL,
0x400210c3880100ULL,
0x404022024108200ULL,
0x810018200204102ULL,
0x4002801a02003ULL,
0x85040820080400ULL,
0x810102c808880400ULL,
0xe900410884800ULL,
0x8002020480840102ULL,
0x220200865090201ULL,
0x2010100a02021202ULL,
0x152048408022401ULL,
0x20080002081110ULL,
0x4001001021004000ULL,
0x800040400a011002ULL,
0xe4004081011002ULL,
0x1c004001012080ULL,
0x8004200962a00220ULL,
0x8422100208500202ULL,
0x2000402200300c08ULL,
0x8646020080080080ULL,
0x80020a0200100808ULL,
0x2010004880111000ULL,
0x623000a080011400ULL,
0x42008c0340209202ULL,
0x209188240001000ULL,
0x400408a884001800ULL,
0x110400a6080400ULL,
0x1840060a44020800ULL,
0x90080104000041ULL,
0x201011000808101ULL,
0x1a2208080504f080ULL,
0x8012020600211212ULL,
0x500861011240000ULL,
0x180806108200800ULL,
0x4000020e01040044ULL,
0x300000261044000aULL,
0x802241102020002ULL,
0x20906061210001ULL,
0x5a84841004010310ULL,
0x4010801011c04ULL,
0xa010109502200ULL,
0x4a02012000ULL,
0x500201010098b028ULL,
0x8040002811040900ULL,
0x28000010020204ULL,
0x6000020202d0240ULL,
0x8918844842082200ULL,
0x4010011029020020ULL
};
#include "movegen.tpp"
}
+82 -142
View File
@@ -11,8 +11,8 @@ void GenPawnMoves(Board &board) {
Bitboard lastRank = board.sideToMove ? ranks[r_1] : ranks[r_8];
if constexpr (mode == Noisy) {
pushes &= lastRank;
if constexpr (mode == Noisy || mode == All) {
Bitboard noisyPushes = pushes & lastRank;
if (board.enPassantTarget != noEPTarget) {
if (attacks.IsSet(board.enPassantTarget)) {
@@ -35,8 +35,8 @@ void GenPawnMoves(Board &board) {
captures.PopBit(targetSquare);
}
while (pushes) {
int pushSquare = pushes.getLS1BIndex();
while (noisyPushes) {
int pushSquare = noisyPushes.getLS1BIndex();
// Only promotions because NOISY
board.AddMove(Move(square, pushSquare, knightPromotion));
@@ -44,29 +44,17 @@ void GenPawnMoves(Board &board) {
board.AddMove(Move(square, pushSquare, rookPromotion));
board.AddMove(Move(square, pushSquare, queenPromotion));
pushes.PopBit(pushSquare);
noisyPushes.PopBit(pushSquare);
}
pawns.PopBit(square);
continue;
} else {
// Checking for en passant
if (board.enPassantTarget != noEPTarget) {
if (attacks.IsSet(board.enPassantTarget)) {
board.AddMove(Move(square, board.enPassantTarget, epCapture));
}
}
}
if constexpr (mode == Quiet || mode == All) {
while (pushes) {
int pushSquare = pushes.getLS1BIndex();
// Checking for promotion
if (lastRank.IsSet(pushSquare)) {
board.AddMove(Move(square, pushSquare, knightPromotion));
board.AddMove(Move(square, pushSquare, bishopPromotion));
board.AddMove(Move(square, pushSquare, rookPromotion));
board.AddMove(Move(square, pushSquare, queenPromotion));
} else {
if (!lastRank.IsSet(pushSquare)) {
if (std::abs(square - pushSquare) == 16) {
board.AddMove(Move(square, pushSquare, doublePawnPush));
} else {
@@ -76,22 +64,6 @@ void GenPawnMoves(Board &board) {
pushes.PopBit(pushSquare);
}
while (captures) {
int targetSquare = captures.getLS1BIndex();
// Checking for promotion
if (lastRank.IsSet(targetSquare)) {
board.AddMove(Move(square, targetSquare, knightPromoCapture));
board.AddMove(Move(square, targetSquare, bishopPromoCapture));
board.AddMove(Move(square, targetSquare, rookPromoCapture));
board.AddMove(Move(square, targetSquare, queenPromoCapture));
} else {
board.AddMove(Move(square, targetSquare, capture));
}
captures.PopBit(targetSquare);
}
}
pawns.PopBit(square);
@@ -108,7 +80,7 @@ void GenKnightMoves(Board &board) {
Bitboard captures = moves & board.colors[!board.sideToMove];
moves &= ~captures;
if constexpr (mode == Noisy) {
if constexpr (mode == Noisy || mode == All) {
while (captures) {
int targetSquare = captures.getLS1BIndex();
@@ -118,25 +90,18 @@ void GenKnightMoves(Board &board) {
}
knights.PopBit(square);
continue;
} else {
while (moves) {
int targetSquare = moves.getLS1BIndex();
board.AddMove(Move(square, targetSquare, quiet));
moves.PopBit(targetSquare);
}
while (captures) {
int targetSquare = captures.getLS1BIndex();
board.AddMove(Move(square, targetSquare, capture));
captures.PopBit(targetSquare);
}
}
if constexpr (mode == Quiet || mode == All) {
while (moves) {
int targetSquare = moves.getLS1BIndex();
board.AddMove(Move(square, targetSquare, quiet));
moves.PopBit(targetSquare);
}
}
knights.PopBit(square);
}
}
@@ -151,7 +116,7 @@ void GenRookMoves(Board &board) {
Bitboard captures = moves & board.colors[!board.sideToMove];
moves &= ~captures;
if constexpr (mode == Noisy) {
if constexpr (mode == Noisy || mode == All) {
while (captures) {
int targetSquare = captures.getLS1BIndex();
@@ -161,24 +126,17 @@ void GenRookMoves(Board &board) {
}
rooks.PopBit(square);
continue;
}
while (moves) {
int targetSquare = moves.getLS1BIndex();
if constexpr (mode == Quiet || mode == All) {
while (moves) {
int targetSquare = moves.getLS1BIndex();
board.AddMove(Move(square, targetSquare, quiet));
board.AddMove(Move(square, targetSquare, quiet));
moves.PopBit(targetSquare);
}
while (captures) {
int targetSquare = captures.getLS1BIndex();
board.AddMove(Move(square, targetSquare, capture));
captures.PopBit(targetSquare);
}
moves.PopBit(targetSquare);
}
}
rooks.PopBit(square);
}
@@ -194,7 +152,7 @@ void GenBishopMoves(Board &board) {
Bitboard captures = moves & board.colors[!board.sideToMove];
moves &= ~captures;
if constexpr (mode == Noisy) {
if constexpr (mode == Noisy || mode == All) {
while (captures) {
int targetSquare = captures.getLS1BIndex();
@@ -204,24 +162,17 @@ void GenBishopMoves(Board &board) {
}
bishops.PopBit(square);
continue;
}
while (moves) {
int targetSquare = moves.getLS1BIndex();
if constexpr (mode == Quiet || mode == All) {
while (moves) {
int targetSquare = moves.getLS1BIndex();
board.AddMove(Move(square, targetSquare, quiet));
board.AddMove(Move(square, targetSquare, quiet));
moves.PopBit(targetSquare);
}
while (captures) {
int targetSquare = captures.getLS1BIndex();
board.AddMove(Move(square, targetSquare, capture));
captures.PopBit(targetSquare);
}
moves.PopBit(targetSquare);
}
}
bishops.PopBit(square);
}
@@ -237,7 +188,7 @@ void GenQueenMoves(Board &board) {
Bitboard captures = moves & board.colors[!board.sideToMove];
moves &= ~captures;
if constexpr (mode == Noisy) {
if constexpr (mode == Noisy || mode == All) {
while (captures) {
int targetSquare = captures.getLS1BIndex();
@@ -247,24 +198,17 @@ void GenQueenMoves(Board &board) {
}
queens.PopBit(square);
continue;
}
while (moves) {
int targetSquare = moves.getLS1BIndex();
if constexpr (mode == Quiet || mode == All) {
while (moves) {
int targetSquare = moves.getLS1BIndex();
board.AddMove(Move(square, targetSquare, quiet));
board.AddMove(Move(square, targetSquare, quiet));
moves.PopBit(targetSquare);
}
while (captures) {
int targetSquare = captures.getLS1BIndex();
board.AddMove(Move(square, targetSquare, capture));
captures.PopBit(targetSquare);
}
moves.PopBit(targetSquare);
}
}
queens.PopBit(square);
}
@@ -277,7 +221,7 @@ void GenKingMoves(Board &board) {
Bitboard captures = moves & board.colors[!board.sideToMove];
moves &= ~board.colors[!board.sideToMove];
if constexpr (mode == Noisy) {
if constexpr (mode == Noisy || mode == All) {
while (captures) {
int square = captures.getLS1BIndex();
@@ -286,58 +230,54 @@ void GenKingMoves(Board &board) {
captures.PopBit(square);
}
return;
}
while (moves) {
int square = moves.getLS1BIndex();
if constexpr (mode == Quiet || mode == All) {
while (moves) {
int square = moves.getLS1BIndex();
board.AddMove(Move(kingSquare, square, quiet));
moves.PopBit(square);
}
while (captures) {
int square = captures.getLS1BIndex();
Move move(kingSquare, square, capture);
board.AddMove(move);
captures.PopBit(square);
}
// Generating castles
int kingRight = board.sideToMove ? blackKingRight : whiteKingRight;
int queenRight = board.sideToMove ? blackQueenRight : whiteQueenRight;
if (board.castlingRights & queenRight) {
U64 QueenSide = board.sideToMove ? 0x1f00000000000000 : 0x1f;
U64 mask = board.sideToMove ? 0x1c00000000000000 : 0x1c;
int targetSquare = board.sideToMove ? c8 : c1;
if ((Bitboard(QueenSide) & board.occupied).PopCount() == 2
&& !(mask & board.colorThreats[!board.sideToMove])) {
board.AddMove(Move(kingSquare, targetSquare, queenCastle));
board.AddMove(Move(kingSquare, square, quiet));
moves.PopBit(square);
}
}
if (board.castlingRights & kingRight) {
U64 KingSide = board.sideToMove ? 0xf000000000000000 : 0xf0;
U64 mask = board.sideToMove ? 0x7000000000000000 : 0x70;
int targetSquare = board.sideToMove ? g8 : g1;
if ((Bitboard(KingSide) & board.occupied).PopCount() == 2
&& !(mask & board.colorThreats[!board.sideToMove])) {
board.AddMove(Move(kingSquare, targetSquare, kingCastle));
// Generating castles
int kingRight = board.sideToMove ? blackKingRight : whiteKingRight;
int queenRight = board.sideToMove ? blackQueenRight : whiteQueenRight;
if (board.castlingRights & queenRight) {
U64 QueenSide = board.sideToMove ? 0x1f00000000000000 : 0x1f;
U64 mask = board.sideToMove ? 0x1c00000000000000 : 0x1c;
int targetSquare = board.sideToMove ? c8 : c1;
if ((Bitboard(QueenSide) & board.occupied).PopCount() == 2
&& !(mask & board.colorThreats[!board.sideToMove])) {
board.AddMove(Move(kingSquare, targetSquare, queenCastle));
}
}
if (board.castlingRights & kingRight) {
U64 KingSide = board.sideToMove ? 0xf000000000000000 : 0xf0;
U64 mask = board.sideToMove ? 0x7000000000000000 : 0x70;
int targetSquare = board.sideToMove ? g8 : g1;
if ((Bitboard(KingSide) & board.occupied).PopCount() == 2
&& !(mask & board.colorThreats[!board.sideToMove])) {
board.AddMove(Move(kingSquare, targetSquare, kingCastle));
}
}
}
}
template <MovegenMode mode>
void GenerateMoves(Board &board) {
board.ResetMoves();
board.pieceThreats = std::array<Bitboard, 6>();
board.colorThreats = std::array<Bitboard, 2>();
GenThreatMaps(board);
void GenerateMoves(Board &board, bool clear, bool recalcThreats) {
if (clear) {
board.ResetMoves();
}
if (recalcThreats) {
GenThreatMaps(board);
}
GenPawnMoves<mode>(board);
GenKnightMoves<mode>(board);
+209
View File
@@ -0,0 +1,209 @@
#include "movepicker.h"
#include "search.h"
#include "tunables.h"
#include <utility>
namespace SEARCH {
template <MovegenMode mode>
MovePicker<mode>::MovePicker(Board &b, SearchContext *c, int p, Move tt)
: board(b), ctx(c), ply(p), ttMove(tt), killerMove(), stage(PickStage::TTMove) {
if (!ttMove || !board.IsPseudoLegal(ttMove)) {
ttMove = Move();
}
if constexpr (mode == Noisy) {
if (ttMove && !(ttMove.IsCapture() || ttMove.IsPromo())) {
ttMove = Move();
}
} else {
Move killer = ctx->killerMoves[ply];
if (killer && killer != ttMove && !killer.IsCapture() && !killer.IsPromo()
&& board.IsPseudoLegal(killer)) {
killerMove = killer;
}
}
}
template <MovegenMode mode>
int MovePicker<mode>::ScoreNoisyMove(Move move) {
int score = MoveEstimatedValue(board, move) * noisyScoreScale;
if (move.IsCapture()) {
int attackerType = board.GetPieceType(move.MoveFrom());
int targetType = (move.GetFlags() == epCapture) ? Pawn : board.GetPieceType(move.MoveTo());
score += ctx->capthist[board.sideToMove][attackerType][targetType][move.MoveTo()];
}
return score;
}
template <MovegenMode mode>
int MovePicker<mode>::ScoreQuietMove(Move move) {
bool sourceThreatened = board.IsSquareThreatened(board.sideToMove, move.MoveFrom());
bool targetThreatened = board.IsSquareThreatened(board.sideToMove, move.MoveTo());
int score = ctx->history[board.sideToMove][move.MoveFrom()][move.MoveTo()][sourceThreatened][targetThreatened];
if (ply > 0) score += ctx->conthist.GetNPly(board, move, ctx, ply, 1);
if (ply > 1) score += ctx->conthist.GetNPly(board, move, ctx, ply, 2);
return score;
}
template <MovegenMode mode>
void MovePicker<mode>::ScoreNoisyRange() {
noisyStart = 0;
MOVEGEN::GenerateMoves<Noisy>(board, true, false);
int rawEnd = board.currentMoveIndex;
int write = noisyStart;
for (int read = noisyStart; read < rawEnd; read++) {
Move m = board.moveList[read];
if (m == ttMove || m == killerMove) continue;
board.moveList[write] = m;
scores[write] = ScoreNoisyMove(m);
write++;
}
noisyEnd = write;
board.currentMoveIndex = noisyEnd;
int goodWrite = noisyStart;
for (int i = noisyStart; i < noisyEnd; i++) {
Move m = board.moveList[i];
if (SEE(board, m, seeOrderingThreshold)) {
if (i != goodWrite) {
std::swap(board.moveList[i], board.moveList[goodWrite]);
std::swap(scores[i], scores[goodWrite]);
}
goodWrite++;
}
}
goodNoisyEnd = goodWrite;
noisyCursor = noisyStart;
badNoisyCursor = goodNoisyEnd;
}
template <MovegenMode mode>
void MovePicker<mode>::ScoreQuietRange() {
quietStart = noisyEnd;
MOVEGEN::GenerateMoves<Quiet>(board, false, false);
int rawEnd = board.currentMoveIndex;
int write = quietStart;
for (int read = quietStart; read < rawEnd; read++) {
Move m = board.moveList[read];
if (m == ttMove || m == killerMove) continue;
board.moveList[write] = m;
scores[write] = ScoreQuietMove(m);
write++;
}
quietEnd = write;
board.currentMoveIndex = quietEnd;
quietCursor = quietStart;
}
template <MovegenMode mode>
Move MovePicker<mode>::PopBest(int &cursor, int end) {
if (cursor >= end) return Move();
int bestIdx = cursor;
for (int i = cursor + 1; i < end; i++) {
if (scores[i] > scores[bestIdx]) bestIdx = i;
}
if (bestIdx != cursor) {
std::swap(board.moveList[bestIdx], board.moveList[cursor]);
std::swap(scores[bestIdx], scores[cursor]);
}
Move best = board.moveList[cursor];
cursor++;
return best;
}
template <MovegenMode mode>
Move MovePicker<mode>::Next() {
while (true) {
switch (stage) {
case PickStage::TTMove: {
stage = PickStage::GenNoisy;
if (ttMove) return ttMove;
continue;
}
case PickStage::GenNoisy: {
ScoreNoisyRange();
stage = PickStage::GoodNoisy;
continue;
}
case PickStage::GoodNoisy: {
Move m = PopBest(noisyCursor, goodNoisyEnd);
if (m) return m;
if constexpr (mode == Noisy) {
stage = PickStage::BadNoisy;
} else {
stage = PickStage::Killer;
}
continue;
}
case PickStage::Killer: {
stage = PickStage::GenQuiet;
if (killerMove) return killerMove;
continue;
}
case PickStage::GenQuiet: {
ScoreQuietRange();
stage = PickStage::Quiet;
continue;
}
case PickStage::Quiet: {
Move m = PopBest(quietCursor, quietEnd);
if (m) return m;
stage = PickStage::BadNoisy;
continue;
}
case PickStage::BadNoisy: {
Move m = PopBest(badNoisyCursor, noisyEnd);
if (m) return m;
stage = PickStage::Finished;
return Move();
}
case PickStage::Finished:
return Move();
default:
return Move();
}
}
}
template class MovePicker<Noisy>;
template class MovePicker<All>;
}
+61
View File
@@ -0,0 +1,61 @@
#pragma once
#include <array>
#include "board.h"
#include "movegen.h"
namespace SEARCH {
class SearchContext;
enum class PickStage {
TTMove,
GenNoisy,
GoodNoisy,
Killer,
GenQuiet,
Quiet,
BadNoisy,
Finished
};
template <MovegenMode mode>
class MovePicker {
public:
MovePicker(Board &board, SearchContext *ctx, int ply, Move ttMove);
Move Next();
private:
Board &board;
SearchContext *ctx;
int ply;
Move ttMove;
Move killerMove;
PickStage stage;
int noisyStart = 0;
int noisyEnd = 0;
int goodNoisyEnd = 0;
int quietStart = 0;
int quietEnd = 0;
int noisyCursor = 0;
int badNoisyCursor = 0;
int quietCursor = 0;
std::array<int, MAX_MOVES> scores{};
void ScoreNoisyRange();
void ScoreQuietRange();
int ScoreNoisyMove(Move move);
int ScoreQuietMove(Move move);
Move PopBest(int &cursor, int end);
};
}
+66 -25
View File
@@ -15,27 +15,25 @@ void Network::Load(const std::string& path) {
std::cerr << "Failed to open file " + path << std::endl;
}
// HL weights
for (size_t i = 0; i < accumulator_weights.size(); i++) {
file.read(reinterpret_cast<char*>(&accumulator_weights[i]), sizeof(int16_t));
for (size_t j = 0; j < accumulator_weights[i].size(); j++) {
file.read(reinterpret_cast<char*>(&accumulator_weights[i][j]), sizeof(int16_t));
}
}
// HL biases
for (size_t i = 0; i < accumulator_biases.size(); i++) {
file.read(reinterpret_cast<char*>(&accumulator_biases[i]), sizeof(int16_t));
}
// Output weights
for (size_t i = 0; i < output_weights.size(); i++) {
for (size_t j = 0; j < output_weights[i].size(); j++) {
file.read(reinterpret_cast<char*>(&output_weights[i][j]), sizeof(int16_t));
}
}
// Output biases
for (size_t i = 0; i < output_bias.size(); i++) {
file.read(reinterpret_cast<char*>(&output_bias[i]), sizeof(int16_t));
}
}
}
#if defined(__x86_64__) || defined(__amd64__) || (defined(_WIN64) && (defined(_M_X64) || defined(_M_AMD64)))
@@ -74,7 +72,6 @@ using nativeVector = __m256i;
}
#else
#pragma message("Using SSE NNUE inference")
// Assumes SSE support here
using nativeVector = __m128i;
#define set1_epi16 _mm_set1_epi16
#define load_epi16 _mm_load_si128
@@ -93,12 +90,53 @@ using nativeVector = __m128i;
}
#endif
static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t outputBucket) {
#elif defined(__aarch64__)
#pragma message("Using ARM64 (NEON) NNUE inference")
#include <arm_neon.h>
using nativeVector = int16x8_t;
static inline nativeVector set1_epi16(int16_t v) {
return vdupq_n_s16(v);
}
static inline nativeVector load_epi16(const nativeVector* ptr) {
return *ptr;
}
static inline nativeVector min_epi16(nativeVector a, nativeVector b) {
return vminq_s16(a, b);
}
static inline nativeVector max_epi16(nativeVector a, nativeVector b) {
return vmaxq_s16(a, b);
}
static inline int32x4_t madd_epi16(nativeVector a, nativeVector b) {
int32x4_t lo = vmull_s16(vget_low_s16(a), vget_low_s16(b));
int32x4_t hi = vmull_s16(vget_high_s16(a), vget_high_s16(b));
int32x4_t sum_lo = vpaddq_s32(lo, lo);
int32x4_t sum_hi = vpaddq_s32(hi, hi);
return vcombine_s32(vget_low_s32(sum_lo), vget_low_s32(sum_hi));
}
static inline nativeVector mullo_epi16(nativeVector a, nativeVector b) {
return vmulq_s16(a, b);
}
static inline int32x4_t add_epi32(int32x4_t a, int32x4_t b) {
return vaddq_s32(a, b);
}
static inline int reduce_epi32(int32x4_t v) {
int32x2_t pair = vadd_s32(vget_low_s32(v), vget_high_s32(v));
int32x2_t total = vpadd_s32(pair, pair);
return vget_lane_s32(total, 0);
}
#else
#pragma message("Using fallback scalar NNUE inference")
using nativeVector = void*;
#endif
static int32_t VectorizedSCReLU(const Board& board, const ACC::AccumulatorPair& acc, const Network& net, size_t outputBucket) {
const size_t VECTOR_SIZE = sizeof(nativeVector) / sizeof(int16_t);
static_assert(HL_SIZE % VECTOR_SIZE == 0, "HL size must be divisible by the native register size of your CPU for vectorization to work");
const ACC::Accumulator& stmAcc = board.sideToMove == White ? board.accPair.white : board.accPair.black;
const ACC::Accumulator& nstmAcc = !board.sideToMove == White ? board.accPair.white : board.accPair.black;
const ACC::Accumulator& stmAcc = board.sideToMove == White ? acc.white : acc.black;
const ACC::Accumulator& nstmAcc = !board.sideToMove == White ? acc.white : acc.black;
const nativeVector VEC_QA = set1_epi16(QA);
const nativeVector VEC_ZERO = set1_epi16(0);
@@ -106,19 +144,15 @@ static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t o
nativeVector accumulator{};
for (int i = 0; i < HL_SIZE; i += VECTOR_SIZE) {
// Load accumulators
const nativeVector stmAccumValues = load_epi16(reinterpret_cast<const nativeVector*>(&stmAcc[i]));
const nativeVector nstmAccumValues = load_epi16(reinterpret_cast<const nativeVector*>(&nstmAcc[i]));
// Clamp values
const nativeVector stmClamped = min_epi16(VEC_QA, max_epi16(stmAccumValues, VEC_ZERO));
const nativeVector nstmClamped = min_epi16(VEC_QA, max_epi16(nstmAccumValues, VEC_ZERO));
// Load weights
const nativeVector stmWeights = load_epi16(reinterpret_cast<const nativeVector*>(&net.output_weights[outputBucket][i]));
const nativeVector nstmWeights = load_epi16(reinterpret_cast<const nativeVector*>(&net.output_weights[outputBucket][i + HL_SIZE]));
// SCReLU activation
const nativeVector stmActivated = madd_epi16(stmClamped, mullo_epi16(stmClamped, stmWeights));
const nativeVector nstmActivated = madd_epi16(nstmClamped, mullo_epi16(nstmClamped, nstmWeights));
@@ -128,31 +162,38 @@ static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t o
return reduce_epi32(accumulator);
}
#endif
int Forward(const Board& board, const Network& net) {
bool stm = board.sideToMove;
static int Forward(const Board& board, const ACC::AccumulatorPair& acc, const Network& net) {
const size_t divisor = 32 / OUTPUT_BUCKETS;
const size_t outputBucket = (board.occupied.PopCount() - 2) / divisor;
const ACC::Accumulator& stmACC = stm ? board.accPair.white : board.accPair.black;
const ACC::Accumulator& nstmACC = !stm ? board.accPair.white : board.accPair.black;
int64_t eval = 0;
eval = VectorizedSCReLU(board, net, outputBucket);
eval = VectorizedSCReLU(board, acc, net, outputBucket);
eval /= QA;
eval += net.output_bias[outputBucket];
return (eval * SCALE) / (QA * QB);
}
int16_t Network::Evaluate(const Board& board) {
return std::clamp(Forward(board, *this), (-SEARCH::MATE_SCORE + SEARCH::MAX_PLY),
(SEARCH::MATE_SCORE - SEARCH::MAX_PLY));
int16_t Network::Evaluate(const Board& board, const ACC::AccumulatorPair& acc, bool datagen) {
const int materialScale = datagen ? 4096 : 2048
+ 90 * board.pieces[Knight].PopCount()
+ 90 * board.pieces[Bishop].PopCount()
+ 180 * board.pieces[Rook].PopCount()
+ 360 * board.pieces[Queen].PopCount();
return std::clamp(Forward(board, acc, *this) * materialScale / 4096, (-SEARCH::MATE_SCORE + SEARCH::MAX_DEPTH),
(SEARCH::MATE_SCORE - SEARCH::MAX_DEPTH));
}
int16_t Network::Evaluate(const Board& board, bool datagen) {
ACC::AccumulatorPair acc;
board.RefreshAccumulator(acc);
return Evaluate(board, acc, datagen);
}
}
+36 -7
View File
@@ -3,12 +3,14 @@
#include <string>
#include <array>
#include "../external/fmt/fmt/format.h"
class Board;
namespace ACC {
struct AccumulatorPair;
}
#ifdef __AVX512F__
constexpr usize ALIGNMENT = 64;
constexpr size_t ALIGNMENT = 64;
#else
constexpr size_t ALIGNMENT = 32;
#endif
@@ -16,22 +18,49 @@ constexpr size_t ALIGNMENT = 32;
namespace NNUE {
constexpr size_t INPUT_SIZE = 768;
constexpr size_t HL_SIZE = 256;
constexpr size_t HL_SIZE = 1536;
constexpr size_t INPUT_BUCKETS = 8;
constexpr size_t OUTPUT_BUCKETS = 8;
constexpr int16_t SCALE = 400;
constexpr int16_t QA = 255;
constexpr int16_t QB = 64;
constexpr int kingBuckets[2][64] = {
{
0, 1, 2, 3, 3, 2, 1, 0,
4, 4, 5, 5, 5, 5, 4, 4,
6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6,
7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7
},
{
7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7,
6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6,
4, 4, 5, 5, 5, 5, 4, 4,
0, 1, 2, 3, 3, 2, 1, 0,
}
};
struct Network {
alignas(ALIGNMENT) std::array<int16_t, HL_SIZE * INPUT_SIZE> accumulator_weights;
alignas(ALIGNMENT) std::array<std::array<int16_t, HL_SIZE * INPUT_SIZE>, INPUT_BUCKETS> accumulator_weights;
alignas(ALIGNMENT) std::array<int16_t, HL_SIZE> accumulator_biases;
alignas(ALIGNMENT) std::array<std::array<int16_t, 2 * HL_SIZE>, OUTPUT_BUCKETS> output_weights;
std::array<int16_t, OUTPUT_BUCKETS> output_bias;
void Load(const std::string& path);
int16_t Evaluate(const Board& board);
int16_t Evaluate(const Board& board, const ACC::AccumulatorPair& acc, bool datagen = false);
int16_t Evaluate(const Board& board, bool datagen = false);
};
inline Network net;
+11 -7
View File
@@ -1,33 +1,37 @@
#include "perft.h"
#include "stopwatch.h"
#include "movegen.h"
#include <cassert>
static U64 HelperPerft(Board board, int depth) {
MOVEGEN::GenerateMoves<All>(board);
static U64 HelperPerft(Board &board, int depth) {
MOVEGEN::GenerateMoves<All>(board, true);
if (depth == 0) return 1ULL;
U64 nodes = 0;
for (int i = 0; i < board.currentMoveIndex; i++) {
if (!board.IsLegal(board.moveList[i])) continue;
Board copy = board;
bool isLegal = copy.MakeMove(board.moveList[i]);
if (!isLegal) continue;
copy.MakeMove(board.moveList[i]);
nodes += HelperPerft(copy, depth - 1);
}
return nodes;
}
void Perft(Board &board, int depth) {
MOVEGEN::GenerateMoves<All>(board);
//board.SetByFen(StartingFen);
MOVEGEN::GenerateMoves<All>(board, true);
U64 totalNodes = 0;
Stopwatch sw;
for (int i = 0; i < board.currentMoveIndex; i++) {
if (!board.IsLegal(board.moveList[i])) continue;
Board copy = board;
bool isLegal = copy.MakeMove(board.moveList[i]);
if (!isLegal) continue;
copy.MakeMove(board.moveList[i]);
U64 nodeCount = HelperPerft(copy, depth - 1);
totalNodes += nodeCount;
board.moveList[i].PrintMove();
+760 -312
View File
File diff suppressed because it is too large. Load diff
+182 -44
View File
@@ -5,8 +5,12 @@
#include "move.h"
#include <algorithm>
#include "stopwatch.h"
#include "tunables.h"
#include "termcolor.hpp"
#include "tt.h"
#include "../external/multi_array.h"
namespace SEARCH {
enum searchMode {
@@ -17,39 +21,142 @@ enum searchMode {
};
constexpr int MATE_SCORE = 32767;
constexpr int MAX_DEPTH = 64;
constexpr int MAX_PLY = 128;
constexpr int MAX_DEPTH = 256;
constexpr int MAX_HISTORY = 16384;
constexpr int WIN_SCORE = 30000;
constexpr int CORRHIST_WEIGHT_SCALE = 256;
constexpr int CORRHIST_GRAIN = 256;
constexpr int CORRHIST_LIMIT = 1024;
constexpr int CORRHIST_SIZE = 16384;
constexpr int CORRHIST_MAX = 16384;
constexpr int32_t ScoreNone = -255000;
constexpr int inf = 100000;
inline int lmrTable[MAX_DEPTH+1][MAX_MOVES];
inline int ScoreToTT(int score, int ply) {
if (score >= MATE_SCORE - MAX_DEPTH)
return score + ply;
if (score <= -MATE_SCORE + MAX_DEPTH)
return score - ply;
return score;
}
constexpr std::array<int, 6> SEEPieceValues = {
100, 300, 350, 500, 900, 0
inline int ScoreFromTT(int score, int ply) {
if (score >= MATE_SCORE - MAX_DEPTH)
return score - ply;
if (score <= -MATE_SCORE + MAX_DEPTH)
return score + ply;
return score;
}
inline int lmrTable[2][MAX_DEPTH+1][MAX_MOVES];
#ifdef TUNING
inline std::array<int, 6> SEEPieceValues = {
seePawnValue, seeKnightValue, seeBishopValue, seeRookValue, seeQueenValue, 0
};
#else
constexpr std::array<int, 6> SEEPieceValues = {
seePawnValue, seeKnightValue, seeBishopValue, seeRookValue, seeQueenValue, 0
};
#endif
void InitLMRTable();
class History {
#ifdef TUNING
void InitSEEPieceValues();
void RefreshTunableCaches();
#endif
class SearchContext;
class CaptHistory {
private:
int historyMoves[2][64][64];
MultiArray<int, 2, 6, 6, 64> historyMoves;
public:
void Update(bool stm, Move move, int bonus) {
void Update(bool stm, int moving, int capture, int to, int bonus) {
int clampedBonus = std::clamp(bonus, -MAX_HISTORY, MAX_HISTORY);
historyMoves[stm][move.MoveFrom()][move.MoveTo()] +=
clampedBonus - historyMoves[stm][move.MoveFrom()][move.MoveTo()] * std::abs(clampedBonus) / MAX_HISTORY;
historyMoves[stm][moving][capture][to] +=
clampedBonus - historyMoves[stm][moving][capture][to] * std::abs(clampedBonus) / MAX_HISTORY;
}
void Clear() {
for (auto &side : historyMoves) {
for (auto &from : side) {
for (auto &to : from) {
to = 0;
}
}
}
std::fill(&historyMoves[0][0][0][0], &historyMoves[0][0][0][0] + sizeof(historyMoves) / sizeof(int), 0);
}
auto& operator[](int index) {
return historyMoves[index];
}
};
class CorrHist {
private:
MultiArray<int, 2, CORRHIST_SIZE> pawnHist;
MultiArray<int, 2, CORRHIST_SIZE> nonPawnHist;
MultiArray<int, 2, CORRHIST_SIZE> majorHist;
public:
void Update(Board& board, int depth, int diff, int* entry) {
const int scaledDiff = diff * CORRHIST_GRAIN;
const int newWeight = std::min(depth * depth + 2 * depth + 1, 128);
*entry = (*entry * (CORRHIST_WEIGHT_SCALE - newWeight) + scaledDiff * newWeight) / CORRHIST_WEIGHT_SCALE;
*entry = std::clamp(*entry, -CORRHIST_MAX, CORRHIST_MAX);
}
void UpdateAll(Board& board, int depth, int diff) {
Update(board, depth, diff, &pawnHist[board.sideToMove][board.pawnKey % CORRHIST_SIZE]);
Update(board, depth, diff, &nonPawnHist[board.sideToMove][board.nonPawnKey % CORRHIST_SIZE]);
Update(board, depth, diff, &majorHist[board.sideToMove][board.majorKey % CORRHIST_SIZE]);
}
int GetAllHist(Board& board) {
return pawnHist[board.sideToMove][board.pawnKey % CORRHIST_SIZE]
+ nonPawnHist[board.sideToMove][board.nonPawnKey % CORRHIST_SIZE]
+ majorHist[board.sideToMove][board.majorKey % CORRHIST_SIZE];
}
void Clear() {
std::fill(&pawnHist[0][0], &pawnHist[0][0] + sizeof(pawnHist) / sizeof(int), 0);
std::fill(&nonPawnHist[0][0], &nonPawnHist[0][0] + sizeof(nonPawnHist) / sizeof(int), 0);
std::fill(&majorHist[0][0], &majorHist[0][0] + sizeof(majorHist) / sizeof(int), 0);
}
};
class ContHistory {
private:
MultiArray<int16_t, 2, 6, 64, 2, 6, 64> contHistMoves;
public:
void Update(bool stm, bool otherColor, int prevType, int prevTo, int type, int to, int bonus) {
int clampedBonus = std::clamp(bonus, -MAX_HISTORY, MAX_HISTORY);
contHistMoves[otherColor][prevType][prevTo][stm][type][to] +=
clampedBonus - contHistMoves[otherColor][prevType][prevTo][stm][type][to] * std::abs(clampedBonus) / MAX_HISTORY;
}
void Clear() {
std::fill(&contHistMoves[0][0][0][0][0][0], &contHistMoves[0][0][0][0][0][0] + sizeof(contHistMoves) / sizeof(int16_t), 0);
}
int16_t GetNPly(Board& board, Move& move, SearchContext* ctx, int ply, int n);
auto& operator[](int index) {
return contHistMoves[index];
}
};
class History {
private:
MultiArray<int, 2, 64, 64, 2, 2> historyMoves;
public:
void Update(bool stm, Move move, bool source, bool target, int bonus) {
int clampedBonus = std::clamp(bonus, -MAX_HISTORY, MAX_HISTORY);
historyMoves[stm][move.MoveFrom()][move.MoveTo()][source][target] +=
clampedBonus - historyMoves[stm][move.MoveFrom()][move.MoveTo()][source][target] * std::abs(clampedBonus) / MAX_HISTORY;
}
void Clear() {
std::fill(&historyMoves[0][0][0][0][0], &historyMoves[0][0][0][0][0] + sizeof(historyMoves) / sizeof(int), 0);
}
auto& operator[](int index) {
@@ -59,8 +166,8 @@ public:
class PVLine {
private:
int length[MAX_PLY] = {};
Move table[MAX_PLY][MAX_PLY] = {};
int length[MAX_DEPTH] = {};
Move table[MAX_DEPTH][MAX_DEPTH] = {};
public:
void SetLength(int ply) {
length[ply] = ply;
@@ -75,12 +182,34 @@ public:
length[ply] = length[ply + 1];
}
void Print(int n) {
void Print(int n, bool isEven = false) {
for (int i = 0; i < length[n]; i++) {
table[n][i].PrintMove();
if (i == 0 && !UCIEnabled) {
std::cout << termcolor::bright_cyan;
table[n][i].PrintMove();
std::cout << termcolor::reset;
if (isEven) {
std::cout << termcolor::color<247>;
} else {
std::cout << termcolor::color<251>;
}
} else {
table[n][i].PrintMove();
}
std::cout << ' ';
}
}
}
std::string GetLine(int n) {
std::string result = "";
for (int i = 0; i < length[n]; i++) {
result += table[n][i].GetMoveString();
result += ' ';
}
return result;
}
void Clear() {
@@ -92,62 +221,71 @@ public:
class Stack {
public:
int32_t eval = ScoreNone;
int pieceType = -1;
int moveTo = -1;
bool side = -1;
};
class SearchContext {
public:
bool doPrint = false;
U64 nodes = 0;
U64 nodesToGo = 0;
int timeToSearch = 0;
std::array<U64, 4096> nodesTable{};
int seldepth = 0;
bool doingNullMove = false;
bool searchStopped = false;
int rootDepth = 0;
Move excluded = Move();
int minNmpPly = 0;
PVLine pvLine;
History history;
ContHistory conthist;
CorrHist corrhist;
CaptHistory capthist;
std::array<std::array<int, MAX_PLY>, 2> killerMoves{};
std::array<Move, MAX_DEPTH> killerMoves{};
std::vector<U64> positionHistory;
TTable TT;
TTable* TT = &SharedTT;
std::array<Stack, MAX_PLY> ss{};
std::array<Stack, MAX_DEPTH> ss{};
ACC::AccStack accStack{MAX_DEPTH + 2};
Stopwatch sw;
SearchContext(){
pvLine.Clear();
history.Clear();
TT.Clear();
conthist.Clear();
corrhist.Clear();
capthist.Clear();
sw.Restart();
killerMoves = {};
positionHistory.reserve(1000);
ss = {};
positionHistory.resize(1000);
}
};
bool SEE(Board& board, Move& move, int threshold);
template <bool isPV, searchMode mode>
SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchContext& ctx, bool cutnode);
SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchContext* ctx, bool cutnode);
template <searchMode mode>
SearchResults SearchPosition(Board &board, SearchParams params, SearchContext& ctx);
SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* ctx);
bool IsDraw(Board &board, SearchContext& ctx);
bool IsDraw(Board &board, SearchContext* ctx);
constexpr int moveScoreTable[6][6] = {
105, 205, 305, 405, 505, 605,
104, 204, 304, 404, 504, 604,
103, 203, 303, 403, 503, 603,
102, 202, 302, 402, 502, 602,
101, 201, 301, 401, 501, 601,
100, 200, 300, 400, 500, 600
};
void ListScores(Board &board, SearchContext& ctx);
void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, int depth, int elapsed);
int MoveEstimatedValue(Board& board, Move& move);
}
+940
View File
@@ -0,0 +1,940 @@
//!
//! termcolor
//! ~~~~~~~~~
//!
//! termcolor is a header-only c++ library for printing colored messages
//! to the terminal. Written just for fun with a help of the Force.
//!
//! :copyright: (c) 2013 by Ihor Kalnytskyi
//! :license: BSD, see LICENSE for details
//!
#ifndef TERMCOLOR_HPP_
#define TERMCOLOR_HPP_
#include <cstdint>
#include <iostream>
// Detect target's platform and set some macros in order to wrap platform
// specific code this library depends on.
#if defined(_WIN32) || defined(_WIN64)
# define TERMCOLOR_TARGET_WINDOWS
#elif defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))
# define TERMCOLOR_TARGET_POSIX
#endif
// If implementation has not been explicitly set, try to choose one based on
// target platform.
#if !defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES) && !defined(TERMCOLOR_USE_WINDOWS_API) && !defined(TERMCOLOR_USE_NOOP)
# if defined(TERMCOLOR_TARGET_POSIX)
# define TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES
# define TERMCOLOR_AUTODETECTED_IMPLEMENTATION
# elif defined(TERMCOLOR_TARGET_WINDOWS)
# define TERMCOLOR_USE_WINDOWS_API
# define TERMCOLOR_AUTODETECTED_IMPLEMENTATION
# endif
#endif
// These headers provide isatty()/fileno() functions, which are used for
// testing whether a standard stream refers to the terminal.
#if defined(TERMCOLOR_TARGET_POSIX)
# include <unistd.h>
#elif defined(TERMCOLOR_TARGET_WINDOWS)
# include <io.h>
# include <windows.h>
#endif
namespace termcolor
{
// Forward declaration of the `_internal` namespace.
// All comments are below.
namespace _internal
{
inline int colorize_index();
inline FILE* get_standard_stream(const std::ostream& stream);
inline FILE* get_standard_stream(const std::wostream& stream);
template <typename CharT>
bool is_colorized(std::basic_ostream<CharT>& stream);
template <typename CharT>
bool is_atty(const std::basic_ostream<CharT>& stream);
#if defined(TERMCOLOR_TARGET_WINDOWS)
template <typename CharT>
void win_change_attributes(std::basic_ostream<CharT>& stream, int foreground, int background = -1);
#endif
}
template <typename CharT>
std::basic_ostream<CharT>& colorize(std::basic_ostream<CharT>& stream)
{
stream.iword(_internal::colorize_index()) = 1L;
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& nocolorize(std::basic_ostream<CharT>& stream)
{
stream.iword(_internal::colorize_index()) = 0L;
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& reset(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[00m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1, -1);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& bold(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[1m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& dark(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[2m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& italic(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[3m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& underline(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[4m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1, COMMON_LVB_UNDERSCORE);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& blink(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[5m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& reverse(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[7m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& concealed(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[8m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& crossed(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[9m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
#endif
}
return stream;
}
template <uint8_t code, typename CharT>
std::basic_ostream<CharT>& color(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[38;5;" << +code << "m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
#endif
}
return stream;
}
template <uint8_t code, typename CharT>
std::basic_ostream<CharT>& on_color(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[48;5;" << +code << "m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
#endif
}
return stream;
}
template <uint8_t r, uint8_t g, uint8_t b, typename CharT>
std::basic_ostream<CharT>& color(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[38;2;" << +r << ";" << +g << ";" << +b << "m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
#endif
}
return stream;
}
template <uint8_t r, uint8_t g, uint8_t b, typename CharT>
std::basic_ostream<CharT>& on_color(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[48;2;" << +r << ";" << +g << ";" << +b << "m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& grey(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[30m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
0 // grey (black)
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& red(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[31m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
FOREGROUND_RED
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& green(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[32m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
FOREGROUND_GREEN
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& yellow(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[33m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
FOREGROUND_GREEN | FOREGROUND_RED
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& blue(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[34m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
FOREGROUND_BLUE
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& magenta(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[35m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
FOREGROUND_BLUE | FOREGROUND_RED
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& cyan(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[36m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
FOREGROUND_BLUE | FOREGROUND_GREEN
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& white(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[37m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& bright_grey(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[90m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
0 | FOREGROUND_INTENSITY // grey (black)
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& bright_red(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[91m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
FOREGROUND_RED | FOREGROUND_INTENSITY
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& bright_green(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[92m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
FOREGROUND_GREEN | FOREGROUND_INTENSITY
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& bright_yellow(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[93m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& bright_blue(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[94m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
FOREGROUND_BLUE | FOREGROUND_INTENSITY
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& bright_magenta(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[95m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& bright_cyan(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[96m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& bright_white(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[97m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream,
FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_grey(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[40m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
0 // grey (black)
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_red(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[41m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
BACKGROUND_RED
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_green(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[42m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_yellow(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[43m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN | BACKGROUND_RED
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_blue(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[44m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
BACKGROUND_BLUE
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_magenta(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[45m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
BACKGROUND_BLUE | BACKGROUND_RED
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_cyan(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[46m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN | BACKGROUND_BLUE
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_white(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[47m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_RED
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_bright_grey(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[100m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
0 | BACKGROUND_INTENSITY // grey (black)
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_bright_red(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[101m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
BACKGROUND_RED | BACKGROUND_INTENSITY
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_bright_green(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[102m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN | BACKGROUND_INTENSITY
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_bright_yellow(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[103m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_bright_blue(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[104m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
BACKGROUND_BLUE | BACKGROUND_INTENSITY
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_bright_magenta(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[105m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
BACKGROUND_BLUE | BACKGROUND_RED | BACKGROUND_INTENSITY
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_bright_cyan(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[106m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY
);
#endif
}
return stream;
}
template <typename CharT>
std::basic_ostream<CharT>& on_bright_white(std::basic_ostream<CharT>& stream)
{
if (_internal::is_colorized(stream))
{
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
stream << "\033[107m";
#elif defined(TERMCOLOR_USE_WINDOWS_API)
_internal::win_change_attributes(stream, -1,
BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_RED | BACKGROUND_INTENSITY
);
#endif
}
return stream;
}
//! Since C++ hasn't a way to hide something in the header from
//! the outer access, I have to introduce this namespace which
//! is used for internal purpose and should't be access from
//! the user code.
namespace _internal
{
// An index to be used to access a private storage of I/O streams. See
// colorize / nocolorize I/O manipulators for details. Due to the fact
// that static variables ain't shared between translation units, inline
// function with local static variable is used to do the trick and share
// the variable value between translation units.
inline int colorize_index()
{
static int colorize_index = std::ios_base::xalloc();
return colorize_index;
}
//! Since C++ hasn't a true way to extract stream handler
//! from the a given `std::ostream` object, I have to write
//! this kind of hack.
inline
FILE* get_standard_stream(const std::ostream& stream)
{
if (&stream == &std::cout)
return stdout;
else if (&stream == &std::cerr || &stream == &std::clog)
return stderr;
return nullptr;
}
//! Since C++ hasn't a true way to extract stream handler
//! from the a given `std::wostream` object, I have to write
//! this kind of hack.
inline
FILE* get_standard_stream(const std::wostream& stream)
{
if (&stream == &std::wcout)
return stdout;
else if (&stream == &std::wcerr || &stream == &std::wclog)
return stderr;
return nullptr;
}
// Say whether a given stream should be colorized or not. It's always
// true for ATTY streams and may be true for streams marked with
// colorize flag.
template <typename CharT>
bool is_colorized(std::basic_ostream<CharT>& stream)
{
return is_atty(stream) || static_cast<bool>(stream.iword(colorize_index()));
}
//! Test whether a given `std::ostream` object refers to
//! a terminal.
template <typename CharT>
bool is_atty(const std::basic_ostream<CharT>& stream)
{
FILE* std_stream = get_standard_stream(stream);
// Unfortunately, fileno() ends with segmentation fault
// if invalid file descriptor is passed. So we need to
// handle this case gracefully and assume it's not a tty
// if standard stream is not detected, and 0 is returned.
if (!std_stream)
return false;
#if defined(TERMCOLOR_TARGET_POSIX)
return ::isatty(fileno(std_stream));
#elif defined(TERMCOLOR_TARGET_WINDOWS)
return ::_isatty(_fileno(std_stream));
#else
return false;
#endif
}
#if defined(TERMCOLOR_TARGET_WINDOWS)
//! same hack as used in get_standard_stream function, but for Windows with `std::ostream`
inline HANDLE get_terminal_handle(std::ostream& stream)
{
if (&stream == &std::cout)
return GetStdHandle(STD_OUTPUT_HANDLE);
else if (&stream == &std::cerr || &stream == &std::clog)
return GetStdHandle(STD_ERROR_HANDLE);
return nullptr;
}
//! same hack as used in get_standard_stream function, but for Windows with `std::wostream`
inline HANDLE get_terminal_handle(std::wostream& stream)
{
if (&stream == &std::wcout)
return GetStdHandle(STD_OUTPUT_HANDLE);
else if (&stream == &std::wcerr || &stream == &std::wclog)
return GetStdHandle(STD_ERROR_HANDLE);
return nullptr;
}
//! Change Windows Terminal colors attribute. If some
//! parameter is `-1` then attribute won't changed.
template <typename CharT>
void win_change_attributes(std::basic_ostream<CharT>& stream, int foreground, int background)
{
// yeah, i know.. it's ugly, it's windows.
static WORD defaultAttributes = 0;
// Windows doesn't have ANSI escape sequences and so we use special
// API to change Terminal output color. That means we can't
// manipulate colors by means of "std::stringstream" and hence
// should do nothing in this case.
if (!_internal::is_atty(stream))
return;
// get terminal handle
HANDLE hTerminal = INVALID_HANDLE_VALUE;
hTerminal = get_terminal_handle(stream);
// save default terminal attributes if it unsaved
if (!defaultAttributes)
{
CONSOLE_SCREEN_BUFFER_INFO info;
if (!GetConsoleScreenBufferInfo(hTerminal, &info))
return;
defaultAttributes = info.wAttributes;
}
// restore all default settings
if (foreground == -1 && background == -1)
{
SetConsoleTextAttribute(hTerminal, defaultAttributes);
return;
}
// get current settings
CONSOLE_SCREEN_BUFFER_INFO info;
if (!GetConsoleScreenBufferInfo(hTerminal, &info))
return;
if (foreground != -1)
{
info.wAttributes &= ~(info.wAttributes & 0x0F);
info.wAttributes |= static_cast<WORD>(foreground);
}
if (background != -1)
{
info.wAttributes &= ~(info.wAttributes & 0xF0);
info.wAttributes |= static_cast<WORD>(background);
}
SetConsoleTextAttribute(hTerminal, info.wAttributes);
}
#endif // TERMCOLOR_TARGET_WINDOWS
} // namespace _internal
} // namespace termcolor
#undef TERMCOLOR_TARGET_POSIX
#undef TERMCOLOR_TARGET_WINDOWS
#if defined(TERMCOLOR_AUTODETECTED_IMPLEMENTATION)
# undef TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES
# undef TERMCOLOR_USE_WINDOWS_API
#endif
#endif // TERMCOLOR_HPP_
+38 -18
View File
@@ -1,30 +1,50 @@
#include "tt.h"
SearchResults TTable::ReadEntry(U64 &hashKey, int depth, int alpha, int beta) {
TTEntry *current = &table[hashKey % table.size()];
TTable SharedTT;
if (current->hashKey == hashKey) {
if (current->depth >= depth) {
if (current->nodeType == PV){
return {current->score, current->bestMove};
} else if (current->nodeType == AllNode && current->score <= alpha) {
return current->score;
} else if (current->nodeType == CutNode && current->score >= beta) {
return current->score;
}
void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv) {
TTBucket *bucket = &table[hashKey % table.size()];
TTEntry *current = nullptr;
if (bucket->depthPreferred && bucket->depthPreferred.hashKey == hashKey) {
current = &bucket->depthPreferred;
} else if (bucket->alwaysReplace && bucket->alwaysReplace.hashKey == hashKey) {
current = &bucket->alwaysReplace;
} else if (!bucket->alwaysReplace) {
current = &bucket->alwaysReplace;
} else if (!bucket->depthPreferred) {
current = &bucket->depthPreferred;
} else if (ttpv) {
current = &bucket->depthPreferred;
} else {
const int depthPreferredValue = GetReplacementValue(bucket->depthPreferred);
const int alwaysReplaceValue = GetReplacementValue(bucket->alwaysReplace);
if (depthPreferredValue <= alwaysReplaceValue) {
current = &bucket->depthPreferred;
} else {
current = &bucket->alwaysReplace;
}
}
// returning invalid value
return invalidEntry;
}
const bool samePosition = current->hashKey == hashKey;
const bool exactBound = nodeType == PV;
const bool entryFromCurrentAge = current->age == age;
const int writeDepth = depth + 4 + ttpv * 2;
void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove) {
TTEntry *current = &table[hashKey % table.size()];
if (samePosition && !exactBound && entryFromCurrentAge && writeDepth <= current->depth) {
return;
}
current->hashKey = hashKey;
current->nodeType = nodeType;
current->score = score;
current->depth = depth;
current->bestMove = bestMove;
}
if (bestMove || !samePosition) {
current->bestMove = bestMove;
}
current->age = age;
current->ttpv = ttpv;
}
+50 -17
View File
@@ -26,38 +26,71 @@ public:
Move bestMove = Move();
uint8_t depth = 0;
uint8_t nodeType = 0;
uint8_t age = 0;
bool ttpv = false;
TTEntry() {}
TTEntry(int16_t score) {
this->score = score;
}
operator U64() {
return hashKey;
}
};
// 64 MB
constexpr U64 maxHash = (1024 * 1000000) / sizeof(TTEntry);
// 5 MB
constexpr U64 defaultHash = (8 * 1000000) / sizeof(TTEntry);
class TTBucket {
public:
TTEntry depthPreferred;
TTEntry alwaysReplace;
};
constexpr int invalidEntry = 111111;
// 1024 MB
constexpr U64 maxHash = (1024 * 1000000) / sizeof(TTBucket);
// 8 MB
constexpr U64 defaultHash = (8 * 1000000) / sizeof(TTBucket);
constexpr int16_t invalidEntry = 11111;
class TTable {
private:
std::vector<TTEntry> table;
std::vector<TTBucket> table;
uint8_t age = 0;
int GetReplacementValue(const TTEntry& entry) const {
const int ageDelta = uint8_t(age - entry.age);
return entry.depth - ageDelta * 4 + entry.ttpv * 2;
}
public:
TTable() : table(defaultHash) {};
void Resize(U64 size) {
table.resize(size);
table.assign(size, {});
}
void Clear() {
U64 size = table.size();
table.clear();
table.resize(size);
std::fill(table.begin(), table.end(), TTBucket());
}
TTEntry* GetRawEntry(U64 &hashKey) {
TTEntry *current = &table[hashKey % table.size()];
return current;
void PrefetchEntry(U64 &hashKey) {
__builtin_prefetch(&table[hashKey % table.size()]);
}
void IncreaseAge() {
age++;
}
TTEntry GetEntry(U64 &hashKey) {
TTBucket *current = &table[hashKey % table.size()];
if (current->depthPreferred.hashKey == hashKey) {
return current->depthPreferred;
} else if (current->alwaysReplace.hashKey == hashKey) {
return current->alwaysReplace;
}
return TTEntry();
}
// returns used space per mill
@@ -65,13 +98,13 @@ public:
int count = 0;
for (int i = 0; i < 1000; i++) {
if (table[i]) count++;
if (table[i].depthPreferred || table[i].alwaysReplace) count++;
}
return count;
}
SearchResults ReadEntry(U64 &hashKey, int depth, int alpha, int beta);
void WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move besteMove);
void WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv);
};
extern TTable SharedTT;
+120
View File
@@ -0,0 +1,120 @@
#pragma once
#include <algorithm>
#include <iostream>
//#define TUNING
#define AUTO_STEP(min_val, max_val) ((max_val - min_val) / 20.0)
#define AUTO_R_END_INT(min_val, max_val) \
(0.002 / (std::min(0.5, static_cast<double>(AUTO_STEP(min_val, max_val))) / 0.5))
#define AUTO_R_END_FLOAT 0.002
#define TUNABLE_LIST \
X_DOUBLE(lmrBaseQuiet, 1.1029723689888005, 0.6, 1.6) \
X_DOUBLE(lmrDivisorQuiet, 2.3063513397139945, 1.6, 3.6) \
X_DOUBLE(lmrBaseNoisy, 0.451805556082857, 0.1, 1.1) \
X_DOUBLE(lmrDivisorNoisy, 3.1355330830404338, 2.0, 4.5) \
X_INT(lmrCutnode, 2005, 1024, 3072) \
X_INT(lmrIsPV, 982, 256, 2048) \
X_INT(lmrTTPV, 936, 256, 2048) \
X_INT(lmrHistoryDivisor, 8377, 4096, 16384) \
X_INT(lmrImproving, 1131, 256, 2048) \
X_INT(lmrCorrplexity, 830, 256, 2048) \
X_INT(lmrTTPVFailLow, 913, 256, 2048) \
X_INT(lmrDeeperBase, 46, 0, 96) \
X_INT(rfpBase, 21, 0, 100) \
X_INT(rfpMargin, 97, 50, 200) \
X_INT(fpMargin, 86, 50, 200) \
X_INT(qsFPMargin, 100, 50, 200) \
X_INT(probcutBetaMargin, 190, 100, 300) \
X_INT(razoringScalar, 195, 80, 320) \
X_INT(doubleExtMargin, 32, 8, 64) \
X_INT(seeQuietThreshold, -81, -160, 0) \
X_INT(seeNoisyThreshold, -32, -120, 40) \
X_INT(aspInitialDelta, 26, 8, 96) \
X_INT(nmpBetaMargin, 25, 8, 96) \
X_INT(seePawnValue, 98, 80, 140) \
X_INT(seeKnightValue, 301, 240, 420) \
X_INT(seeBishopValue, 346, 250, 450) \
X_INT(seeRookValue, 507, 400, 700) \
X_INT(seeQueenValue, 924, 700, 1300) \
X_INT(seeQsThreshold, -13, -120, 120) \
X_INT(seeOrderingThreshold, -102, -200, 0) \
X_INT(ldseMargin, 26, 0, 96) \
X_INT(noisyScoreScale, 32, 0, 96) \
X_INT(historyBonusMultiplier, 306, 280, 320) \
X_INT(historyBonusSub, 252, 235, 265) \
X_INT(historyMalusMultiplier, 301, 280, 320) \
X_INT(historyMalusSub, 250, 235, 265) \
X_INT(contHistoryBonusMultiplier, 300, 280, 320) \
X_INT(contHistoryBonusSub, 252, 235, 265) \
X_INT(contHistoryMalusMultiplier, 300, 280, 320) \
X_INT(contHistoryMalusSub, 249, 235, 265) \
X_INT(captHistoryBonusMultiplier, 302, 280, 320) \
X_INT(captHistoryBonusSub, 249, 235, 265) \
X_INT(captHistoryMalusMultiplier, 300, 280, 320) \
X_INT(captHistoryMalusSub, 249, 235, 265) \
X_INT(fiftyMoveScaleBase, 200, 100, 400)
#ifdef TUNING
#define X_DOUBLE(name, default_val, min_val, max_val) \
inline double name = default_val; \
constexpr double name##_step = AUTO_STEP(min_val, max_val);
#define X_INT(name, default_val, min_val, max_val) \
inline int name = default_val; \
constexpr double name##_step = AUTO_STEP(min_val, max_val);
#else
#define X_DOUBLE(name, default_val, min_val, max_val) \
constexpr double name = default_val; \
constexpr double name##_step = AUTO_STEP(min_val, max_val);
#define X_INT(name, default_val, min_val, max_val) \
constexpr int name = default_val; \
constexpr double name##_step = AUTO_STEP(min_val, max_val);
#endif
TUNABLE_LIST
#undef X_DOUBLE
#undef X_INT
inline void PrintTunables() {
#define X_DOUBLE(name, default_val, min_val, max_val) \
std::cout << #name << ", float, " << name \
<< ", " << min_val \
<< ", " << max_val \
<< ", " << name##_step \
<< ", " << AUTO_R_END_FLOAT << std::endl;
#define X_INT(name, default_val, min_val, max_val) \
std::cout << #name << ", int, " << name \
<< ", " << min_val \
<< ", " << max_val \
<< ", " << name##_step \
<< ", " << AUTO_R_END_INT(min_val, max_val) << std::endl;
TUNABLE_LIST
#undef X_DOUBLE
#undef X_INT
}
inline void PrintTunablesUCI() {
#define X_DOUBLE(name, default_val, min_val, max_val) \
std::cout << "option name " #name \
<< " type string default " << name \
<< " min " << min_val \
<< " max " << max_val \
<< std::endl;
#define X_INT(name, default_val, min_val, max_val) \
std::cout << "option name " #name \
<< " type spin default " << name \
<< " min " << min_val \
<< " max " << max_val \
<< std::endl;
TUNABLE_LIST
#undef X_DOUBLE
#undef X_INT
}
+266 -50
View File
@@ -1,9 +1,10 @@
#include "uci.h"
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <thread>
#include <tuple>
#include <memory>
#include <algorithm>
#include "types.h"
#include "movegen.h"
#include "search.h"
@@ -11,10 +12,64 @@
#include "perft.h"
#include "utils.h"
#include "datagen.h"
#include "tunables.h"
static void ParsePosition(Board &board, std::string_view command, SEARCH::SearchContext& ctx) {
// OS-dependent threading includes
#ifdef _WIN32
#include <thread>
#else
#include <pthread.h>
#endif
namespace {
constexpr size_t DefaultPositionHistorySize = 1000;
static void EnsurePositionHistory(SEARCH::SearchContext* ctx, int positionIndex) {
if (positionIndex >= static_cast<int>(ctx->positionHistory.size())) {
ctx->positionHistory.resize(positionIndex + 100);
}
}
static void ResetPositionHistory(SEARCH::SearchContext* ctx, const Board& board) {
const size_t historySize = std::max(DefaultPositionHistorySize, static_cast<size_t>(board.positionIndex + 100));
ctx->positionHistory.assign(historySize, 0);
ctx->positionHistory[board.positionIndex] = board.hashKey;
}
#ifdef _WIN32
static std::vector<std::thread> searchThreads;
#else
static std::vector<pthread_t> searchThreads;
#endif
static void JoinSearchThreads() {
#ifdef _WIN32
for (auto& thread : searchThreads) {
if (thread.joinable()) {
thread.join();
}
}
#else
for (pthread_t& thread : searchThreads) {
pthread_join(thread, nullptr);
}
#endif
searchThreads.clear();
}
static void StopSearchThreads() {
searchStopped.store(true, std::memory_order_relaxed);
JoinSearchThreads();
}
} // namespace
static void ParsePosition(Board &board, std::string_view command, SEARCH::SearchContext* ctx) {
if (command.find("startpos") != std::string::npos) {
board.SetByFen(StartingFen);
ResetPositionHistory(ctx, board);
}
int fenIndex = command.find("fen");
@@ -26,50 +81,138 @@ static void ParsePosition(Board &board, std::string_view command, SEARCH::Search
} else {
board.SetByFen(command.substr(fenIndex + 4, command.length() - (fenIndex + 3)));
}
ResetPositionHistory(ctx, board);
}
if (movesIndex != std::string::npos) {
std::vector<std::string> moves = UTILS::split(command.substr(movesIndex + 6, command.length() - (movesIndex + 5)), ' ');
for (std::string_view move : moves) {
bool isLegal = board.MakeMove(UTILS::parseMove(board, move));
ctx.positionHistory[board.positionIndex] = board.hashKey;
board.MakeMove(UTILS::parseMove(board, move));
EnsurePositionHistory(ctx, board.positionIndex);
ctx->positionHistory[board.positionIndex] = board.hashKey;
}
}
MOVEGEN::GenerateMoves<All>(board);
MOVEGEN::GenerateMoves<All>(board, true);
}
static int ReadParam(std::string param, std::string &command) {
static double ReadParam(const std::string& param, const std::string &command) {
size_t pos = command.find(param);
if (pos != std::string::npos) {
pos += param.length() + 1;
bool isNegative = false;
std::string result = "";
if (pos == std::string::npos)
return 0.0;
// Check for negative sign
if (pos < command.length() && command[pos] == '-') {
isNegative = true;
pos++;
pos += param.length() + 1; // skip "param "
std::string result;
// optional sign
if (pos < command.length() && (command[pos] == '-' || command[pos] == '+')) {
result += command[pos];
pos++;
}
// digits and optional decimal point
bool decimalSeen = false;
while (pos < command.length() && (std::isdigit(command[pos]) || command[pos] == '.')) {
if (command[pos] == '.') {
if (decimalSeen) break; // only one decimal point
decimalSeen = true;
}
result += command[pos++];
}
// Extract digits
while (pos < command.length() && std::isdigit(command[pos])) {
result += command[pos];
pos++;
}
// Ensure result is not empty before calling stoi
if (!result.empty()) {
int value = std::stoi(result);
return isNegative ? -value : value;
if (!result.empty()) {
try {
return std::stod(result);
} catch (const std::out_of_range&) {
return (result[0] == '-') ? -1e308 : 1e308; // clamp to double range
} catch (const std::invalid_argument&) {
return 0.0;
}
}
return 0;
return 0.0;
}
static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext& ctx) {
#ifdef _WIN32
// Windows implementation using std::thread
template <SEARCH::searchMode mode>
static void ThreadFunc(Board board, SearchParams params, SEARCH::SearchContext* ctx) {
SEARCH::SearchPosition<mode>(board, params, ctx);
delete ctx;
}
static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchContext* ctx, int id) {
SEARCH::SearchContext* ctxCopy = new SEARCH::SearchContext(*ctx);
if (id == 0)
ctxCopy->doPrint = true;
if (params.nodes) {
searchThreads.emplace_back(ThreadFunc<SEARCH::nodesMode>, board, params, ctxCopy);
} else {
searchThreads.emplace_back(ThreadFunc<SEARCH::normal>, board, params, ctxCopy);
}
}
#else
// Unix/Linux implementation using pthread
template <SEARCH::searchMode mode>
static void* ThreadFunc(void* arg) {
auto* tup = static_cast<std::tuple<Board, SearchParams, SEARCH::SearchContext*>*>(arg);
SEARCH::SearchContext* ctx = std::get<2>(*tup);
SEARCH::SearchPosition<mode>(std::get<0>(*tup), std::get<1>(*tup), ctx);
delete ctx;
delete tup;
return nullptr;
}
static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchContext* ctx, int id) {
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024); // 8 MB stack
SEARCH::SearchContext* ctxCopy = new SEARCH::SearchContext(*ctx);
if (id == 0)
ctxCopy->doPrint = true;
pthread_t thread;
int rc = 0;
if (params.nodes) {
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*>(board, params, ctxCopy);
rc = pthread_create(&thread, &attr, ThreadFunc<SEARCH::nodesMode>, arg);
if (rc != 0) {
delete std::get<2>(*arg);
delete arg;
ctxCopy = nullptr;
}
} else {
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*>(board, params, ctxCopy);
rc = pthread_create(&thread, &attr, ThreadFunc<SEARCH::normal>, arg);
if (rc != 0) {
delete std::get<2>(*arg);
delete arg;
ctxCopy = nullptr;
}
}
pthread_attr_destroy(&attr);
if (rc == 0) {
searchThreads.push_back(thread);
} else {
delete ctxCopy;
}
}
#endif
static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* ctx) {
StopSearchThreads();
searchStopped.store(false, std::memory_order_relaxed);
ctx->TT->IncreaseAge();
SearchParams params;
params.wtime = ReadParam("wtime", command);
@@ -82,36 +225,99 @@ static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext& c
if (command.find("movetime") != std::string::npos) {
params.wtime = ReadParam("movetime", command);
params.btime = ReadParam("movetime", command);
} else if (command.find("infinite") != std::string::npos) {
params.wtime = 99999999;
params.btime = 99999999;
}
if (params.nodes) {
auto worker = std::thread(SEARCH::SearchPosition<SEARCH::nodesMode>, std::ref(board), params, std::ref(ctx));
worker.detach();
} else {
auto worker = std::thread(SEARCH::SearchPosition<SEARCH::normal>, std::ref(board), params, std::ref(ctx));
worker.detach();
searchThreads.reserve(threads);
for (int i = 0; i < threads; i++) {
StartSearchThread(board, params, ctx, i);
}
}
static void SetOption(std::string &command, SEARCH::SearchContext& ctx) {
static void SetOption(std::string& command, SEARCH::SearchContext* ctx) {
StopSearchThreads();
if (command.find("Hash") != std::string::npos) {
U64 hashSize = (ReadParam("value", command) * 1000000) / sizeof(TTEntry);
ctx.TT.Resize(hashSize);
U64 hashSize = (ReadParam("value", command) * 1000000ULL) / sizeof(TTEntry);
ctx->TT->Resize(hashSize);
return;
}
if (command.find("Threads") != std::string::npos) {
threads = ReadParam("value", command);
return;
}
if (command.find("UCI_ShowWDL") != std::string::npos) {
UCIShowWDL = command.find("value true") != std::string::npos
|| command.find("value 1") != std::string::npos;
return;
}
#ifdef TUNING
size_t namePos = command.find("name");
if (namePos == std::string::npos)
return;
namePos += 5; // skip "name "
size_t valuePos = command.find(" value");
if (valuePos == std::string::npos)
return;
std::string name = command.substr(namePos, valuePos - namePos);
name.erase(0, name.find_first_not_of(' '));
name.erase(name.find_last_not_of(' ') + 1);
double rawValue = ReadParam("value", command);
#define X_DOUBLE(paramName, default_val, min_val, max_val) \
if (name == #paramName) { \
double v = rawValue; \
if (v < min_val) v = min_val; \
if (v > max_val) v = max_val; \
paramName = v; \
SEARCH::RefreshTunableCaches(); \
return; \
}
#define X_INT(paramName, default_val, min_val, max_val) \
if (name == #paramName) { \
int v = static_cast<int>(rawValue); \
if (v < min_val) v = min_val; \
if (v > max_val) v = max_val; \
paramName = v; \
SEARCH::RefreshTunableCaches(); \
return; \
}
TUNABLE_LIST
#undef X_DOUBLE
#undef X_INT
#endif
}
static void PrintEngineInfo() {
std::cout << "id name Eleanor v1.0" << std::endl;
std::cout << "id name Eleanor v4.1" << std::endl;
std::cout << "id author rektdie" << std::endl;
std::cout << "option name Hash type spin default 8 min 1 max 1024" << std::endl;
std::cout << "option name Threads type spin default 1 min 1 max 1" << std::endl;
std::cout << "option name Threads type spin default 1 min 1 max 512" << std::endl;
std::cout << "option name UCI_ShowWDL type check default false" << std::endl;
#ifdef TUNING
PrintTunablesUCI();
#endif
std::cout << "uciok" << std::endl;
}
void UCILoop(Board &board) {
std::string input = "";
SEARCH::SearchContext ctx;
auto ctx = std::make_unique<SEARCH::SearchContext>();
// main loop
while (true) {
@@ -125,53 +331,58 @@ void UCILoop(Board &board) {
// parse UCI "position" command
if (input.find("position") != std::string::npos) {
ParsePosition(board, input, ctx);
ParsePosition(board, input, ctx.get());
continue;
}
// parse UCI "ucinewgame" command
if (input.find("ucinewgame") != std::string::npos) {
StopSearchThreads();
board.SetByFen(StartingFen);
// Clearing
ctx.TT.Clear();
ctx.killerMoves = {};
ctx.history.Clear();
ctx.positionHistory = {};
ctx->TT->Clear();
ctx->killerMoves = {};
ctx->history.Clear();
ctx->conthist.Clear();
ctx->corrhist.Clear();
ResetPositionHistory(ctx.get(), board);
ctx->ss = {};
continue;
}
// parse UCI "go" command
if (input.find("go") != std::string::npos) {
ParseGo(board, input, ctx);
ParseGo(board, input, ctx.get());
continue;
}
// parse UCI "quit" command
if (input.find("quit") != std::string::npos) {
StopSearchThreads();
// stop the loop
break;
}
// parse UCI "stop" command
if (input.find("stop") != std::string::npos) {
// stop the loop
ctx.searchStopped = true;
StopSearchThreads();
continue;
}
// parse UCI "uci" command
if (input.find("uci") != std::string::npos) {
UCIEnabled = true;
// print engine info
PrintEngineInfo();
continue;
}
if (input.find("setoption") != std::string::npos) {
SetOption(input, ctx);
SetOption(input, ctx.get());
continue;
}
@@ -201,6 +412,11 @@ void UCILoop(Board &board) {
continue;
}
if (input.find("tunables") != std::string::npos) {
PrintTunables();
continue;
}
if (input.find("datagen") != std::string::npos) {
DATAGEN::Run(500000*2, 22);
continue;
+8
View File
@@ -1,7 +1,13 @@
#pragma once
#include <atomic>
#include "move.h"
#include "board.h"
inline bool UCIEnabled = false;
inline bool UCIShowWDL = false;
inline int threads = 1;
inline std::atomic<bool> searchStopped = false;
class SearchParams {
public:
int wtime = 0;
@@ -11,6 +17,8 @@ public:
int movesToGo = 0;
int nodes = 0;
int threads = 1;
SearchParams(){}
};
+2 -2
View File
@@ -111,7 +111,7 @@ int parseSquare(std::string_view str) {
}
Move parseMove(Board &board, std::string_view str) {
MOVEGEN::GenerateMoves<All>(board);
MOVEGEN::GenerateMoves<All>(board, true);
int from = parseSquare(str.substr(0, 2));
int to = parseSquare(str.substr(2, 2));
@@ -202,4 +202,4 @@ int ConvertToWhiteRelative(Board &board, int score) {
return board.sideToMove == White ? score : -score;
}
}
}
+71
View File
@@ -0,0 +1,71 @@
#pragma once
#include <algorithm>
#include <cmath>
#include "board.h"
struct WinRateParams {
double a;
double b;
};
// From SF
inline WinRateParams winRateParams(const Board& board) {
int material = board.pieces[Pawn].PopCount() +
3 * board.pieces[Knight].PopCount() +
3 * board.pieces[Bishop].PopCount() +
5 * board.pieces[Rook].PopCount() +
9 * board.pieces[Queen].PopCount();
// The fitted model only uses data for material counts in [17, 78], and is anchored at count 58.
double m = std::clamp(material, 17, 78) / 58.0;
// Return a = p_a(material) and b = p_b(material), see github.com/official-stockfish/WDL_model
constexpr double as[] = {-977.81543545, 2519.99289616, -2279.71042020, 1197.60065700};
constexpr double bs[] = {-224.61509659, 557.03359920, -440.33347428, 226.68436468};
double a = (((as[0] * m + as[1]) * m + as[2]) * m) + as[3];
double b = (((bs[0] * m + bs[1]) * m + bs[2]) * m) + bs[3];
return {a, b};
}
// The win rate model is 1 / (1 + exp((a - eval) / b)), where a = p_a(material) and b = p_b(material).
// It fits the LTC fishtest statistics rather accurately.
inline int winRateModel(int v, const Board& board) {
auto [a, b] = winRateParams(board);
// Return the win rate in per mille units, rounded to the nearest integer.
return int(0.5 + 1000 / (1 + std::exp((a - static_cast<double>(v)) / b)));
}
struct WDLTriplet {
int wins;
int draws;
int losses;
};
inline WDLTriplet getWDL(int v, const Board& board) {
int wins = std::clamp(winRateModel(v, board), 0, 1000);
int losses = std::clamp(winRateModel(-v, board), 0, 1000);
int draws = 1000 - wins - losses;
if (draws < 0) {
if (wins >= losses) {
wins += draws;
} else {
losses += draws;
}
draws = 0;
}
return {wins, draws, losses};
}
inline int scaleEval(int eval, const Board& board) {
auto [a, b] = winRateParams(board);
return std::round(100 * eval / a);
}