├── LICENSE.txt ├── README.md ├── batch_first ├── __init__.py ├── anns │ ├── ann_creation_helper.py │ ├── database_creator.py │ ├── evaluation_ann.py │ └── move_evaluation_ann.py ├── chestimator.py ├── classes_and_structs.py ├── engine.py ├── global_open_priority_nodes.py ├── numba_board.py ├── numba_negamax_zero_window.py └── transposition_table.py ├── code_testing.py └── playing_chess.py /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Batch First 2 | Batch First is a JIT compiled chess engine which traverses the search tree in batches in a best-first manner, allowing for neural network batching, asynchronous GPU use, and vectorized CPU computations. Utilizing NumPy's powerful ndarray for representing boards, TensorFlow for neural networks computations, and Numba to JIT compile it all, Batch First balances the rapid prototyping desired in artificial intelligence with the runtime efficiency needed for a competitive chess engine. 3 | 4 | 5 | ### Engine Characteristics 6 | The following table highlights a few key aspects of the Batch First engine. 7 | 8 | *Characteristic* | *Explanation / Reasoning* 9 | :---: | --- 10 | **Written in Python** | Python is both easily readable and extremely flexible, but it's runtime speed has historically prevented it's use in competitive chess engines. Through the use of high level packages, Batch First balances runtime speed and code readability 11 | **JIT Compiled** | To avoid the execution time of Python, Numba is used to JIT compile the Python code to native machine instructions using the LLVM compiler infrastructure 12 | **Batched ANN Inference** | By using a `K-best-first search` algorithm, evaluation of boards and moves can be done in batches, both minimizing the effect of latency and maximizing the throughput for GPUs 13 | **Priority Bins** | Best-first algorithms such as SSS* are often disregarded due to the cost of maintaining a global list of open nodes in priority order. This is addressed by instead using a pseudo-priority order, separating nodes based on their binned heuristic values 14 | **Vectorized Asynchronous CPU Operations** | Through a combination of NumPy and Numba, the array oriented computations are vectorized and compiled to run while the ANNs are being evaluated, and with the Python GIL released 15 | 16 | 17 | ## Board Evaluation CNN 18 | 19 | ### Input Features/Training Data 20 | Boards are given to the ANN as an 8x8x15 one-hot encoding, which consists of 12 feature planes for each piece and color, 21 | 2 for each player's rooks with the ability to castle, and 1 for en passant capture squares. The label for each board 22 | is the precomputed value of the board by an established engine (currently StockFish is used). 23 | 24 | 25 | ### Input Layers 26 | To model the movement of chess pieces, a novel architecture is used where the ANNs 'first layer' is 27 | replaced with 9 convolutional layers. When concatenated, the squares considered by the input convolutions 28 | centered at any given square are the squares which could contain a piece able to threaten that square, 29 | and the square itself. 30 | 31 | This is accomplished by a set of dilated padded convolutional layers, and can be explained in two parts. 32 | - An n-dilated convolutional layer with kernel size 3x3 will consider all potential rank, file, 33 | and diagonal threats n squares away from the kernel's center. Having 7 of these 34 | with dilation factors of 1-7 encompasses all potential movement of every piece but the knight. 35 | 36 | - To capture the movement of the knight, two convolutional layers with kernel size 2x2 and dilation factor 37 | 2x4 and 4x2 are used. Combined, the kernels of these two layers consider only 38 | the squares a knight has the potential to move to. 39 | 40 | The following diagram shows the structure of the input layers: 41 | 42 | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 43 | |:-----------------:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| 44 | | **Kernel Size** | 3x3 | 3x3 | 3x3 | 3x3 | 3x3 | 3x3 | 3x3 | 2x2 | 2x2 | 45 | |**Dilation Factor**| 1x1 | 2x2 | 3x3 | 4x4 | 5x5 | 6x6 | 7x7 | 2x4 | 4x2 | 46 | 47 | 48 | ### Loss 49 | The network learns to score boards through classification methods, this is accomplished by learning 50 | an ordinal representation of the training boards. More specifically, it learns to classify pairs of boards as having 51 | the first or second board be preferable. 52 | 53 | Extending this to batches of data, the calculated value of each board is compared against every other board in the batch 54 | (with unequal desired score). 55 | 56 | Thus for a training batch B with desired and computed values D and C (shaped \[1,n\]), the network learns by 57 | minimizing the following: 58 | 59 | 62 | ![equation](https://latex.codecogs.com/svg.latex?LowerTriangular%28D-D%5ET%5Cneq0%29*CrossEntropy%28S%28C-C%5ET%29%2CD-D%5ET%3E0%29) 63 | 64 | Where S is the sigmoid function, CrossEntropy is a function who's first and second parameters are logits and labels 65 | respectively, LowerTriangular is a function which replaces entries above the main diagonal with zeros, 66 | multiplication is done element-wise (Hadamard product), and subtraction is calculated using broadcasting 67 | (similar to NumPy's broadcasting). 68 | 69 | If the values of D are unique, batch B will produce n(n-1)/2 pairs of boards to compare. 70 | 71 | 72 | ## Dependencies 73 | The versions listed are known to work, but are not necessarily the only versions which will work. 74 | - [TensorFlow](https://github.com/tensorflow/tensorflow) v1.10.0 75 | - [NumPy](https://github.com/numpy/numpy) v1.14.3 76 | - [Numba](https://github.com/numba/numba) v0.40.0 77 | - [SciPy](https://github.com/scipy/scipy) v1.1.0 78 | - [python-chess](https://github.com/niklasf/python-chess) v0.20.1 79 | - [khash_numba](https://github.com/synapticarbors/khash_numba) 80 | 81 | The tools listed below can be used, but are not needed. They provide _significant_ speed improvements to the engine. 82 | - [TensorRT](https://developers.googleblog.com/2018/03/tensorrt-integration-with-tensorflow.html) to optimize TensorFlow graphs for inference 83 | - [Intel Python Distribution](https://software.intel.com/en-us/distribution-for-python) for speed improvements to NumPy and Numba 84 | 85 | 86 | ## Miscellaneous Information 87 | - If you use this engine or the ideas it's built around to build or experiment with something interesting, please be vocal about it! 88 | - If you have any questions, ideas, or just want to say hi, feel free to get in contact with me! 89 | - Trained neural networks are not yet included (they still have some room to improve), but can/will be added if requested 90 | - Special thanks to the [python-chess](https://github.com/niklasf/python-chess) package which is heavily relied upon throughout the engine, and which most of the move generation code is based on 91 | 92 | 93 | ## License 94 | Batch First is licensed under the GPL 3. The full text can be found in the LICENSE.txt file. 95 | -------------------------------------------------------------------------------- /batch_first/__init__.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import numba as nb 3 | 4 | from numba import njit 5 | 6 | import chess 7 | import itertools 8 | import functools 9 | 10 | from chess.polyglot import POLYGLOT_RANDOM_ARRAY, zobrist_hash 11 | 12 | from numba import cffi_support 13 | from cffi import FFI 14 | 15 | ffi = FFI() 16 | 17 | import khash_numba._khash_ffi as khash_ffi 18 | 19 | cffi_support.register_module(khash_ffi) 20 | 21 | khash_init = khash_ffi.lib.khash_int2int_init 22 | khash_get = khash_ffi.lib.khash_int2int_get 23 | khash_set = khash_ffi.lib.khash_int2int_set 24 | khash_destroy = khash_ffi.lib.khash_int2int_destroy 25 | 26 | 27 | @njit 28 | def create_index_table(ids): 29 | table = khash_init() 30 | for j in range(len(ids)): 31 | khash_set(table, ids[j], j) 32 | return table 33 | 34 | 35 | def get_table_and_array_for_set_of_dicts(dicts): 36 | unique_keys = sorted(set(itertools.chain.from_iterable(dicts))) 37 | 38 | # The sorted is so that the index of 0 will always be 0 39 | index_lookup_table = create_index_table(np.array(sorted([np.uint64(key) for key in unique_keys]), dtype=np.uint64)) 40 | 41 | array = np.zeros(shape=[len(dicts), len(unique_keys)], dtype=np.uint64) 42 | 43 | for square_num, dict in enumerate(dicts): 44 | for key, value in dict.items(): 45 | index_to_set = khash_get(ffi.cast("void *", index_lookup_table), np.uint64(key), np.uint64(0)) 46 | array[square_num, index_to_set] = np.uint64(value) 47 | 48 | return index_lookup_table, array 49 | 50 | 51 | def generate_move_filter_table(): 52 | """ 53 | Generate a lookup table for the policy encoding described in the following paper: 54 | 55 | 'Mastering Chess and Shogi by Self-Play with a General Reinforcement Learning Algorithm' 56 | https://arxiv.org/pdf/1712.01815.pdf 57 | 58 | So in the returned table, the value at index (f,t,p) is the index of the policy plane (in the move scoring ann) 59 | associated with the chess move described as moving a piece from square f to square t and being promoted to piece p. 60 | """ 61 | diffs = {} 62 | for j in range(1, 8): 63 | diffs[(0, j)] = j - 1 64 | diffs[(0, -j)] = j + 6 65 | diffs[(j, 0)] = j + 13 66 | diffs[(-j, 0)] = j + 20 67 | diffs[(j, j)] = j + 27 68 | diffs[(j, -j)] = j + 34 69 | diffs[(-j, j)] = j + 41 70 | diffs[(-j, -j)] = j + 48 71 | 72 | diffs[(1, 2)] = 56 73 | diffs[(1, -2)] = 57 74 | diffs[(-1, 2)] = 58 75 | diffs[(-1, -2)] = 59 76 | diffs[(2, 1)] = 60 77 | diffs[(2, -1)] = 61 78 | diffs[(-2, 1)] = 62 79 | diffs[(-2, -1)] = 63 80 | 81 | filter_table = np.zeros([64,64,6], dtype=np.uint8) 82 | 83 | for square1 in chess.SQUARES: 84 | for square2 in chess.SQUARES: 85 | file_diff = chess.square_file(square2) - chess.square_file(square1) 86 | rank_diff = chess.square_rank(square2) - chess.square_rank(square1) 87 | if not diffs.get((file_diff, rank_diff)) is None: 88 | filter_table[square1, square2] = diffs[(file_diff, rank_diff)] 89 | 90 | if rank_diff == 1 and file_diff in [1,0,-1]: 91 | filter_table[square1, square2, 2:5] = 3*(1+file_diff) + np.arange(64,67) 92 | return filter_table 93 | 94 | 95 | MOVE_FILTER_LOOKUP = generate_move_filter_table() 96 | 97 | 98 | numpy_move_dtype = np.dtype([("from_square", np.uint8), ("to_square", np.uint8), ("promotion", np.uint8)]) 99 | move_type = nb.from_dtype(numpy_move_dtype) 100 | 101 | RANDOM_ARRAY = np.array(POLYGLOT_RANDOM_ARRAY, dtype=np.uint64) 102 | 103 | BB_DIAG_MASKS = np.array(chess.BB_DIAG_MASKS, dtype=np.uint64) 104 | BB_FILE_MASKS = np.array(chess.BB_FILE_MASKS, dtype=np.uint64) 105 | BB_RANK_MASKS = np.array(chess.BB_RANK_MASKS, dtype=np.uint64) 106 | 107 | DIAG_ATTACK_INDEX_LOOKUP_TABLE, DIAG_ATTACK_ARRAY = get_table_and_array_for_set_of_dicts(chess.BB_DIAG_ATTACKS) 108 | FILE_ATTACK_INDEX_LOOKUP_TABLE, FILE_ATTACK_ARRAY = get_table_and_array_for_set_of_dicts(chess.BB_FILE_ATTACKS) 109 | RANK_ATTACK_INDEX_LOOKUP_TABLE, RANK_ATTACK_ARRAY = get_table_and_array_for_set_of_dicts(chess.BB_RANK_ATTACKS) 110 | 111 | BB_KNIGHT_ATTACKS = np.array(chess.BB_KNIGHT_ATTACKS, dtype=np.uint64) 112 | BB_KING_ATTACKS = np.array(chess.BB_KING_ATTACKS, dtype=np.uint64) 113 | 114 | BB_PAWN_ATTACKS = np.array(chess.BB_PAWN_ATTACKS, dtype=np.uint64) 115 | 116 | BB_RAYS = np.array(chess.BB_RAYS, dtype=np.uint64) 117 | BB_BETWEEN = np.array(chess.BB_BETWEEN, dtype=np.uint64) 118 | 119 | MIN_FLOAT32_VAL = np.finfo(np.float32).min 120 | MAX_FLOAT32_VAL = np.finfo(np.float32).max 121 | ALMOST_MIN_FLOAT_32_VAL = np.nextafter(MIN_FLOAT32_VAL, MAX_FLOAT32_VAL) 122 | ALMOST_MAX_FLOAT_32_VAL = np.nextafter(MAX_FLOAT32_VAL, MIN_FLOAT32_VAL) 123 | 124 | 125 | # The maximum number of moves which can be stored/assessed by the engine 126 | MAX_MOVES_LOOKED_AT = 100 127 | 128 | # The maximum depth the engine is allowed to go 129 | MAX_SEARCH_DEPTH = 100 130 | 131 | # This value is used for indicating that a given node has/had a legal move in the transposition table that it will/would 132 | # expand prior to it's full move generation and scoring. 133 | NEXT_MOVE_IS_FROM_TT_VAL = np.uint8(254) 134 | 135 | # This value is used for indicating that the next move index of a board is actually a dummy variable, and there are no more moves left 136 | NO_MORE_MOVES_VALUE = np.uint8(255) 137 | 138 | # This value is used for indicating that a move in a transposition table entry is not being stored. 139 | NO_TT_MOVE_VALUE = np.uint8(255) 140 | 141 | # This value is used for indicating that no entry in the transposition table exists for that hash. It is stored as the 142 | # entries depth. 143 | NO_TT_ENTRY_VALUE = np.uint8(255) 144 | 145 | # This value is the value used to assigned a node who's next move was found in the TT to the desired bin. 146 | TT_MOVE_SCORE_VALUE = ALMOST_MAX_FLOAT_32_VAL 147 | 148 | # This value is used when there is no current ep square. It (obviously) does not indicate that square 0 is an ep square 149 | NO_EP_SQUARE = np.uint8(0) 150 | 151 | # The value to set a move's promotion to if no promotion is done 152 | NO_PROMOTION_VALUE = np.uint8(0) 153 | 154 | TIE_RESULT_SCORE = np.float32(0) 155 | 156 | 157 | # This is used in times when a value should be 'None', but Numba won't let it. To appease the compiler 158 | # this array is given, and it's first value checked against MIN_FLOAT32_VAL to see if it's the 'None' situation. 159 | # Ideally this will be removed eventually. 160 | INT_ARRAY_NONE = np.array([MIN_FLOAT32_VAL]) 161 | 162 | # The win/loss arrays are such that the magnitudes of the win/loss decrease as the index in the array increases. 163 | # This is so depth can be used to index the arrays 164 | WIN_RESULT_SCORES = np.full(MAX_SEARCH_DEPTH, np.nextafter(ALMOST_MAX_FLOAT_32_VAL, MIN_FLOAT32_VAL)) 165 | LOSS_RESULT_SCORES = np.full(MAX_SEARCH_DEPTH, np.nextafter(ALMOST_MIN_FLOAT_32_VAL, MAX_FLOAT32_VAL)) 166 | 167 | for j in range(1, MAX_SEARCH_DEPTH): 168 | WIN_RESULT_SCORES[j] = np.nextafter(WIN_RESULT_SCORES[j - 1], MIN_FLOAT32_VAL) 169 | LOSS_RESULT_SCORES[j] = np.nextafter(LOSS_RESULT_SCORES[j - 1], MAX_FLOAT32_VAL) 170 | 171 | 172 | SIZE_EXPONENT_OF_TWO_FOR_TT_INDICES = np.uint8(30) 173 | TT_HASH_MASK = np.uint64(2 ** (SIZE_EXPONENT_OF_TWO_FOR_TT_INDICES) - 1) 174 | 175 | 176 | COLORS = [WHITE, BLACK] = np.array([1, 0], dtype=np.uint8) 177 | TURN_COLORS = [TURN_WHITE, TURN_BLACK] = [True, False] 178 | PIECE_TYPES = [PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING] = np.arange(1, 7, dtype=np.uint8) 179 | 180 | 181 | SQUARES = [ 182 | A1, B1, C1, D1, E1, F1, G1, H1, 183 | A2, B2, C2, D2, E2, F2, G2, H2, 184 | A3, B3, C3, D3, E3, F3, G3, H3, 185 | A4, B4, C4, D4, E4, F4, G4, H4, 186 | A5, B5, C5, D5, E5, F5, G5, H5, 187 | A6, B6, C6, D6, E6, F6, G6, H6, 188 | A7, B7, C7, D7, E7, F7, G7, H7, 189 | A8, B8, C8, D8, E8, F8, G8, H8] = np.arange(64, dtype=np.uint8) 190 | 191 | SQUARES_180 = SQUARES ^ 0x38 192 | 193 | BB_VOID = np.uint64(0) 194 | BB_ALL = np.uint64(0xffffffffffffffff) 195 | 196 | BB_SQUARES = [ 197 | BB_A1, BB_B1, BB_C1, BB_D1, BB_E1, BB_F1, BB_G1, BB_H1, 198 | BB_A2, BB_B2, BB_C2, BB_D2, BB_E2, BB_F2, BB_G2, BB_H2, 199 | BB_A3, BB_B3, BB_C3, BB_D3, BB_E3, BB_F3, BB_G3, BB_H3, 200 | BB_A4, BB_B4, BB_C4, BB_D4, BB_E4, BB_F4, BB_G4, BB_H4, 201 | BB_A5, BB_B5, BB_C5, BB_D5, BB_E5, BB_F5, BB_G5, BB_H5, 202 | BB_A6, BB_B6, BB_C6, BB_D6, BB_E6, BB_F6, BB_G6, BB_H6, 203 | BB_A7, BB_B7, BB_C7, BB_D7, BB_E7, BB_F7, BB_G7, BB_H7, 204 | BB_A8, BB_B8, BB_C8, BB_D8, BB_E8, BB_F8, BB_G8, BB_H8 205 | ] = np.array([np.uint64(1) << sq for sq in SQUARES], dtype=np.uint64) 206 | 207 | BB_CORNERS = BB_A1 | BB_H1 | BB_A8 | BB_H8 208 | 209 | BB_LIGHT_SQUARES = np.uint64(0x55aa55aa55aa55aa) 210 | BB_DARK_SQUARES = np.uint64(0xaa55aa55aa55aa55) 211 | 212 | 213 | BB_FILES = [ 214 | BB_FILE_A, 215 | BB_FILE_B, 216 | BB_FILE_C, 217 | BB_FILE_D, 218 | BB_FILE_E, 219 | BB_FILE_F, 220 | BB_FILE_G, 221 | BB_FILE_H 222 | ] = np.array([np.uint64(0x0101010101010101) << np.uint8(i) for i in range(8)], dtype=np.uint64) 223 | 224 | BB_RANKS = [ 225 | BB_RANK_1, 226 | BB_RANK_2, 227 | BB_RANK_3, 228 | BB_RANK_4, 229 | BB_RANK_5, 230 | BB_RANK_6, 231 | BB_RANK_7, 232 | BB_RANK_8 233 | ] = np.array([np.uint64(0xff) << np.uint8(8 * i) for i in range(8)], dtype=np.uint64) 234 | 235 | 236 | BB_BACKRANKS = BB_RANK_1 | BB_RANK_8 237 | 238 | INITIAL_BOARD_FEN = chess.STARTING_FEN 239 | 240 | def generate_move_to_enumeration_dict(): 241 | """ 242 | Generates a dictionary where the keys are (from_square, to_square) and their values are the move number 243 | that move has been assigned. It is done in a way such that for move number N from board B, if you were to flip B 244 | vertically, the same move would have number 1792-N. (there are 1792 moves recognized) 245 | 246 | 247 | IMPORTANT NOTES: 248 | 1) This ignores the fact that not all pawn promotions are the same, this effects the number of logits 249 | in the move scoring ANN 250 | """ 251 | possible_moves = {} 252 | 253 | board = chess.Board('8/8/8/8/8/8/8/8 w - - 0 1') 254 | for square in chess.SQUARES[:len(SQUARES) // 2]: 255 | for piece in [chess.Piece(chess.KNIGHT, True), chess.Piece(chess.QUEEN, True)]: 256 | board.set_piece_at(square, piece) 257 | for move in board.generate_legal_moves(): 258 | if possible_moves.get((move.from_square, move.to_square)) is None: 259 | possible_moves[move.from_square, move.to_square] = len(possible_moves) 260 | 261 | board.remove_piece_at(square) 262 | 263 | switch_square_fn = lambda x: x ^ 0x38 264 | 265 | total_possible_moves = len(possible_moves) * 2 - 1 266 | 267 | for (from_square, to_square), move_num in list(possible_moves.items()): 268 | possible_moves[switch_square_fn(from_square), switch_square_fn(to_square)] = total_possible_moves - move_num 269 | 270 | return possible_moves 271 | 272 | 273 | MOVE_TO_INDEX_ARRAY = np.zeros(shape=[64, 64], dtype=np.int32) 274 | OLD_REVERSED_MOVE_TO_INDEX_ARRAY = np.zeros(shape=[64, 64], dtype=np.int32) 275 | REVERSED_MOVE_TO_INDEX_ARRAY = np.zeros(shape=[64, 64], dtype=np.int32) 276 | 277 | dict_keys, dict_values = list(zip(*generate_move_to_enumeration_dict().items())) 278 | dict_keys = np.array(dict_keys) 279 | 280 | MOVE_TO_INDEX_ARRAY[dict_keys[:,0], dict_keys[:,1]] = dict_values 281 | 282 | reversed_keys = dict_keys ^ 0x38 283 | REVERSED_MOVE_TO_INDEX_ARRAY[reversed_keys[:,0], reversed_keys[:,1]] = dict_values 284 | 285 | 286 | REVERSED_EP_LOOKUP_ARRAY = SQUARES_180.copy() 287 | REVERSED_EP_LOOKUP_ARRAY[0] = NO_EP_SQUARE 288 | 289 | 290 | def power_set(iterable): 291 | s = list(iterable) 292 | return itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s) + 1)) 293 | 294 | flip_vert_const_1 = np.uint64(0x00FF00FF00FF00FF) 295 | flip_vert_const_2 = np.uint64(0x0000FFFF0000FFFF) 296 | 297 | @nb.vectorize([nb.uint64(nb.uint64)], nopython=True) 298 | def flip_vertically(bb): 299 | bb = ((bb >> 8) & flip_vert_const_1) | ((bb & flip_vert_const_1) << 8) 300 | bb = ((bb >> 16) & flip_vert_const_2) | ((bb & flip_vert_const_2) << 16) 301 | bb = ( bb >> 32) | ( bb << 32) 302 | return bb 303 | 304 | def get_castling_lookup_tables(): 305 | possible_castling_rights = np.zeros(2 ** 4, dtype=np.uint64) 306 | for j, set in enumerate(power_set([BB_A1, BB_H1, BB_A8, BB_H8])): 307 | possible_castling_rights[j] = np.uint64(functools.reduce(lambda x, y: x | y, set, np.uint64(0))) 308 | 309 | white_turn_castling_tables = create_index_table(possible_castling_rights) 310 | black_turn_castling_tables = create_index_table(flip_vertically(possible_castling_rights)) 311 | 312 | return white_turn_castling_tables, black_turn_castling_tables, possible_castling_rights 313 | 314 | 315 | WHITE_CASTLING_RIGHTS_LOOKUP_TABLE, BLACK_CASTLING_RIGHTS_LOOKUP_TABLE, POSSIBLE_CASTLING_RIGHTS = get_castling_lookup_tables() 316 | -------------------------------------------------------------------------------- /batch_first/anns/ann_creation_helper.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | 4 | from tensorflow.contrib import layers 5 | from tensorflow.python import training 6 | 7 | import chess 8 | 9 | from functools import reduce 10 | 11 | from google.protobuf import text_format 12 | 13 | from batch_first.numba_board import popcount 14 | 15 | 16 | from tensorflow.contrib import tensorrt as trt 17 | 18 | 19 | 20 | 21 | def parse_into_ann_input_inference(max_boards, convert_to_nhwc=False): 22 | """ 23 | NOTES: 24 | 1) If a constant/operation is typed in a confusing manor, it's so the entirely of this can be done on GPU 25 | """ 26 | possible_lookup_nums = np.arange(2 ** 16, dtype=np.uint16) 27 | num_bits = popcount(possible_lookup_nums.astype(np.uint64)) 28 | 29 | location_lookup_ary = np.array([[[chess.square_rank(loc), chess.square_file(loc)] for loc in chess.SQUARES_180]], np.int32) 30 | location_lookup_ary = np.ones([max_boards, 1, 1], np.int32) * location_lookup_ary 31 | 32 | location_lookup_ary = location_lookup_ary.reshape([max_boards, 8, 8, 2])[:, ::-1] 33 | location_lookup_ary = location_lookup_ary.reshape([max_boards, 4, 16, 2]) 34 | 35 | mask_getter = lambda n: np.unpackbits(np.frombuffer(n, dtype=np.uint8)[::-1])[::-1] 36 | masks_to_gather_ary = np.array(list(map(mask_getter, possible_lookup_nums)), dtype=np.bool_) 37 | 38 | pieces_from_nums = lambda n: [n >> 4, (n & np.uint8(0x0F))] 39 | piece_lookup_ary = np.array(list(map(pieces_from_nums, possible_lookup_nums)), dtype=np.int32) 40 | 41 | range_repeater = numpy_style_repeat_1d_creator(max_multiple=33, max_to_repeat=max_boards, out_type=tf.int64) 42 | 43 | popcount_lookup = tf.constant(num_bits, tf.int64) 44 | locations_for_masking = tf.constant(location_lookup_ary, tf.int64) 45 | occupancy_mask_table = tf.constant(masks_to_gather_ary, tf.half) 46 | piece_lookup_table = tf.constant(piece_lookup_ary, tf.int64) 47 | 48 | ones_to_slice = tf.constant(np.ones(33 * max_boards), dtype=tf.float32) # This is used since there seems to be no simple/efficient way to broadcast for scatter_nd 49 | 50 | piece_indicators = tf.placeholder(tf.int32, shape=[None], name="piece_filters") #Given as an array of uint8s 51 | occupied_bbs = tf.placeholder(tf.int64, shape=[None], name="occupied_bbs") #Given as an array of uint64s 52 | 53 | # The code below this comment defines ops which are run during inference 54 | 55 | occupied_bitcasted = tf.cast(tf.bitcast(occupied_bbs, tf.uint16), dtype=tf.int32) 56 | 57 | partial_popcounts = tf.gather(popcount_lookup, occupied_bitcasted, "byte_popcount_loopkup") 58 | partial_popcounts = tf.cast(partial_popcounts, tf.int32) 59 | occupied_popcounts = tf.reduce_sum(partial_popcounts, axis=-1, name="popcount_lookup_sum") 60 | 61 | location_mask = tf.gather(occupancy_mask_table, occupied_bitcasted, "gather_location_mask") 62 | location_mask = tf.cast(location_mask, tf.bool) 63 | piece_coords = tf.boolean_mask(locations_for_masking, location_mask, "mask_desired_locations") 64 | 65 | gathered_pieces = tf.gather(piece_lookup_table, piece_indicators, "gather_pieces") 66 | piece_filter_indices = tf.reshape(gathered_pieces, [-1, 1]) 67 | 68 | repeated_board_numbers = range_repeater(occupied_popcounts) 69 | board_numbers_for_concat = tf.expand_dims(repeated_board_numbers, -1) 70 | 71 | # Removes either the last piece filter, or no filters (based on if the number of filters was odd and half of the final uint8 was padding) 72 | piece_filter_indices = piece_filter_indices[:tf.shape(board_numbers_for_concat)[0]] 73 | 74 | one_indices = tf.concat([board_numbers_for_concat, piece_filter_indices, piece_coords], axis=-1) #Should figure out how this can be done with (or similarly to) tf.parallel_stack 75 | 76 | boards = tf.scatter_nd( 77 | indices=one_indices, 78 | updates=ones_to_slice[:tf.shape(one_indices)[0]], 79 | shape=[tf.shape(occupied_bbs, out_type=tf.int64)[0], 15, 8, 8]) 80 | 81 | if convert_to_nhwc: 82 | boards = tf.transpose(boards, [0,2,3,1]) 83 | 84 | return (piece_indicators, occupied_bbs), boards 85 | 86 | 87 | def vec_and_transpose_op(vector, operation, output_type=None): 88 | """ 89 | Equivalent to running tf.cast(operation(tf.expand_dims(vector, 1), tf.expand_dims(vector, 0)), output_type) 90 | 91 | :param output_type: An optional parameter, if given the tensor will be cast to the given type before being returned 92 | """ 93 | to_return = operation(tf.expand_dims(vector, 1), tf.expand_dims(vector, 0)) 94 | if not output_type is None: 95 | return tf.cast(to_return, output_type) 96 | return to_return 97 | 98 | 99 | def kendall_rank_correlation_coefficient(logits, labels): 100 | """ 101 | A function to calculate Kendall's Tau-a rank correlation coefficient. 102 | 103 | NOTES: 104 | 1) This TensorFlow implementation is extremely fast for small quantities, but scales poorly (It's O[N^2]). 105 | The intended use is during training, to avoid running non-graph operations and keep computations on GPU. 106 | """ 107 | quantity = tf.shape(logits, out_type=tf.float32)[0] 108 | 109 | diffs_sign_helper = lambda t : tf.sign(vec_and_transpose_op(t, tf.subtract, tf.float32)) 110 | 111 | sign_product = diffs_sign_helper(logits) * diffs_sign_helper(labels) 112 | concordant_minus_discordant = tf.reduce_sum(tf.matrix_band_part(sign_product, -1, 0)) 113 | 114 | return concordant_minus_discordant/(quantity*(quantity-1)/2) 115 | 116 | 117 | def py_func_scipy_rank_helper_creator(logits, labels): 118 | """ 119 | A function to make it easier to use SciPy rank correlation functions from within a TensorFlow graph. 120 | """ 121 | def helper_to_return(function): 122 | return tf.py_func( 123 | function, 124 | [logits, labels], 125 | [tf.float64, tf.float64], 126 | stateful=False) 127 | return helper_to_return 128 | 129 | 130 | def combine_graphdefs(graphdef_filenames, output_model_path, output_filename, output_node_names, name_prefixes=None): 131 | if name_prefixes is None: 132 | name_prefixes = len(graphdef_filenames) * [""] 133 | 134 | with tf.Session() as sess: 135 | for filename, prefix in zip(graphdef_filenames, name_prefixes): 136 | tf.saved_model.loader.load(sess, ['serve'], filename, import_scope=prefix) 137 | 138 | constant_graph_def = tf.graph_util.convert_variables_to_constants( 139 | sess, 140 | tf.get_default_graph().as_graph_def(), 141 | ["%s/%s"%(prefix,name) for name, prefix in zip(output_node_names, name_prefixes)]) 142 | 143 | tf.train.write_graph( 144 | constant_graph_def, 145 | output_model_path, 146 | output_filename) 147 | 148 | 149 | def remap_inputs(model_path, output_model_path, output_filename, max_batch_size=None): 150 | with tf.Session() as sess: 151 | with tf.device('/GPU:0'): 152 | with tf.name_scope("input_parser"): 153 | placeholders, formatted_data = parse_into_ann_input_inference(max_batch_size) 154 | 155 | with open(model_path, 'r') as f: 156 | graph_def = text_format.Parse(f.read(), tf.GraphDef()) 157 | 158 | tf.import_graph_def( 159 | graph_def, 160 | input_map={"policy_network/FOR_INPUT_MAPPING_transpose" : formatted_data, 161 | "value_network/FOR_INPUT_MAPPING_transpose" : formatted_data}, 162 | name="") 163 | 164 | tf.train.write_graph( 165 | sess.graph_def, 166 | output_model_path, 167 | output_filename, 168 | as_text=True) 169 | 170 | 171 | def save_trt_graphdef(model_path, output_model_path, output_filename, output_node_names, 172 | trt_memory_fraction=.5, total_video_memory=1.1e10, 173 | max_batch_size=1000, write_as_text=True): 174 | 175 | #This would ideally be 1 instead of .85, but the GPU that this is running on is responsible for things like graphics 176 | with tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=.85 - trt_memory_fraction))) as sess: 177 | 178 | with open(model_path, 'r') as f: 179 | txt = f.read() 180 | model_graph_def = text_format.Parse(txt, tf.GraphDef()) 181 | 182 | trt_graph = trt.create_inference_graph( 183 | model_graph_def, 184 | output_node_names, 185 | max_batch_size=max_batch_size, 186 | precision_mode="FP32", 187 | max_workspace_size_bytes=int(trt_memory_fraction*total_video_memory)) 188 | 189 | tf.train.write_graph(trt_graph, output_model_path, output_filename, as_text=write_as_text) 190 | 191 | 192 | def create_input_convolutions_shared_weights(the_input, kernel_initializer, data_format, mode, 193 | undilated_kernels=64, num_unique_filters=[32,32,24,24,20,20,24,24]): 194 | """ 195 | This function creates a set of 9 convolutional layers which together model the movement of chess pieces (more 196 | information about this is in the README). After concatenation of the convolutions, batch normalization 197 | and ReLu are applied. 198 | 199 | 200 | :param data_format: A string of either "NHWC" or "NCHW" 201 | :param undilated_kernels: The number of filters to use in the one undilated 3x3 convolution (including those 202 | shared with the dilated filters) 203 | :param num_unique_filters: An iterable of the number of filters to be used for the 8 dilated convolutions (dilation 2-7, knight filters) 204 | :return: The concatenated output of the convolutions (after bach normalization and ReLu) 205 | """ 206 | with tf.variable_scope("input_module"): 207 | channel_axis = 3 if data_format == "NHWC" else 1 208 | layer_channel_str = "channels_last" if data_format == "NHWC" else "channels_first" 209 | 210 | path_outputs = [ 211 | tf.layers.conv2d(the_input, 212 | undilated_kernels, 213 | kernel_size=3, 214 | padding='same', 215 | data_format=layer_channel_str, 216 | use_bias=False, 217 | kernel_initializer=kernel_initializer(), 218 | name="3x3_adjacency_filter")] 219 | 220 | 221 | dilations = [[d,d] for d in range(2,8)] + [(2,4),(4,2)] 222 | filter_sizes = (len(dilations) - 2) * [3] + 2 * [2] 223 | 224 | for j, (rate, filter_size, num_filters) in enumerate(zip(dilations, filter_sizes, num_unique_filters)): 225 | path_outputs.append( 226 | tf.layers.conv2d(the_input, 227 | num_filters, 228 | filter_size, 229 | padding='same', 230 | data_format=layer_channel_str, 231 | dilation_rate=rate, 232 | use_bias=False, 233 | kernel_initializer=kernel_initializer(), 234 | name="input_%dx%d_with_%dx%d_dilation" % (filter_size, filter_size, rate[0], rate[1]) 235 | ) 236 | ) 237 | 238 | all_convs = tf.concat(path_outputs, axis=channel_axis) 239 | 240 | batch_normalized = tf.layers.batch_normalization( 241 | all_convs, 242 | axis=channel_axis, 243 | scale=False, 244 | training=(mode == tf.estimator.ModeKeys.TRAIN), 245 | trainable=True, 246 | fused=True) 247 | 248 | convolutional_module_outputs = tf.nn.relu(batch_normalized, name='first_layers_relu') 249 | 250 | tf.contrib.layers.summarize_activation(convolutional_module_outputs) 251 | 252 | return convolutional_module_outputs 253 | 254 | 255 | 256 | def build_convolutional_module_with_batch_norm(the_input, module, kernel_initializer, mode, 257 | num_previously_built_inception_modules=0, make_trainable=True, 258 | weight_regularizer=None, data_format="NHWC"): 259 | """ 260 | Builds a convolutional module based on a given design using batch normalization and the rectifier activation. 261 | It returns the final layer/layers in the module. 262 | 263 | The following are a few examples of what can be used in the 'module' parameter (explanation follows): 264 | 265 | example_1_module = [[[35,1], (1024, 8)]] 266 | 267 | example_2_module = [[[30, 1]], 268 | [[15, 1], [30, 3]], 269 | [[15, 1], [30, 3, 2]], 270 | [[15, 1], [30, 3, 3]], # <-- This particular path does a 1x1 convolution on the module's 271 | [[10, 1], [20, 3, 4]], # input with 15 filters, followed by a 3x3 'same' padded 272 | [[8, 1], [16, 3, 5]], # convolution with dilation factor of 3. It is concatenated 273 | [[8, 1], [16, 2, (2, 4)]], # with the output of the other paths, and then returned 274 | [[8, 1], [16, 2, (4, 2)]]] 275 | 276 | 277 | :param module: A list (representing the module's shape), of lists (each representing the shape of a 'path' from the 278 | input to the output of the module), of either tuples or lists of size 2 or 3 (representing individual layers). 279 | If a tuple is used, it indicates that the layer should use 'valid' padding, and if a list is used it will use a 280 | padding of 'same'. The contents of the innermost list or tuple will be the number of filters to create for a layer, 281 | followed by the information to pass to conv2d as kernel_size, and then optionally, a third element which is 282 | to be passed to conv2d as a dilation factor. 283 | """ 284 | if weight_regularizer is None: 285 | weight_regularizer = lambda:None 286 | 287 | path_outputs = [None for _ in range(len(module))] 288 | to_summarize = [] 289 | cur_input = None 290 | for j, path in enumerate(module): 291 | with tf.variable_scope("module_" + str(num_previously_built_inception_modules + 1) + "/path_" + str(j + 1)): 292 | for i, section in enumerate(path): 293 | if i == 0: 294 | if j != 0: 295 | path_outputs[j - 1] = cur_input 296 | 297 | cur_input = the_input 298 | 299 | cur_conv_output = tf.layers.conv2d( 300 | inputs=cur_input, 301 | filters=section[0], 302 | kernel_size=section[1], 303 | padding='valid' if isinstance(section, tuple) else 'same', 304 | dilation_rate = 1 if len(section) < 3 else section[-1], 305 | use_bias=False, 306 | kernel_initializer=kernel_initializer(), 307 | kernel_regularizer=weight_regularizer(), 308 | trainable=make_trainable, 309 | data_format="channels_last" if data_format == "NHWC" else "channels_first", 310 | name="layer_" + str(i + 1)) 311 | 312 | cur_batch_normalized = tf.layers.batch_normalization(cur_conv_output, 313 | axis=-1 if data_format == "NHWC" else 1, 314 | scale=False, 315 | training=(mode == tf.estimator.ModeKeys.TRAIN), 316 | trainable=make_trainable, 317 | fused=True) 318 | 319 | cur_input = tf.nn.relu(cur_batch_normalized) 320 | 321 | to_summarize.append(cur_input) 322 | 323 | path_outputs[-1] = cur_input 324 | 325 | list(layers.summarize_activation(layer) for layer in to_summarize) 326 | 327 | with tf.variable_scope("module_" + str(num_previously_built_inception_modules + 1)): 328 | if len(path_outputs) == 1: 329 | return path_outputs[0] 330 | 331 | return tf.concat([temp_input for temp_input in path_outputs], -1 if data_format == "NHWC" else 1) 332 | 333 | 334 | def build_convolutional_modules(input, modules, mode, kernel_initializer, kernel_regularizer, make_trainable=True, 335 | num_previous_modules=0, data_format="NHWC"): 336 | """ 337 | Creates a desired set of convolutional modules. Primarily the modules are created through the 338 | build_convolutional_module_with_batch_norm function, but if it's functionality proves insufficient, a function can be 339 | given in place of a module shape, which will accept the previous modules output as input, and who's output will 340 | be given to the next module for input (or returned). (A detailed example is given below, and more information about the 341 | shape of a module can be found in the comment for the build_convolutional_module_with_batch_norm function) 342 | 343 | 344 | Below is an example of what may be given for the 'modules' parameter, along with a detailed explanation of what 345 | each component does. 346 | 347 | 348 | #Assume the input is such that the following holds true 349 | tf.shape(input) == [-1, 8, 8, 15] 350 | 351 | 352 | modules = [ 353 | [[[20, 3]], # The following 7 layers with 3x3 kernels and increasing dilation factors are such that 354 | [[20, 3, 2]], # their combined filters centered at any given square will consider only the squares in 355 | [[20, 3, 3]], # which a queen could possibly attack from, and the central square itself (and padding) 356 | [[20, 3, 4]], 357 | [[10, 3, 5]], 358 | [[10, 3, 6]], 359 | [[10, 3, 7]], 360 | [[8, 2, (2, 4)]], # For any given square, this and the following layer collectively consider all possible 361 | [[8, 2, (4, 2)]]], # squares in which a knight could attack from (and padding when needed), 362 | 363 | # After the module's 9 input layers are created, their outputs are concatenated together, and the module's 364 | # output will have the shape : [-1, 8, 8, 126] 365 | 366 | 367 | # Now a module is created which applies a 1x1 convolution, followed by a an 8x8 convolution with valid padding 368 | [[[32,1], (1024, 8)]], 369 | 370 | 371 | # To prepare the outputs from the convolutional modules for the fully connected layers, they are reshaped from 372 | # rank 4 and shape [-1, 1, 1, 1024], to rank 2 with shape [-1, 1024] 373 | lambda x: tf.reshape(x, [-1, 1024]), 374 | ] 375 | 376 | #The shape [-1, 1024] tensor would then be returned by this function. 377 | 378 | 379 | 380 | :param modules: A list which sequentially represents the graph operations to be created. It may contain 381 | any combination of either functions which accept the previous module's output and return the desired input for 382 | the next module, or shapes of modules which can be given to the build_convolutional_module_with_batch_norm method 383 | """ 384 | if isinstance(make_trainable, bool): 385 | make_trainable = [make_trainable]*len(modules) 386 | 387 | cur_inception_module = input 388 | 389 | for module_num, (module_shape, trainable) in enumerate(zip(modules, make_trainable)): 390 | if callable(module_shape): 391 | cur_inception_module = module_shape(cur_inception_module) 392 | else: 393 | cur_inception_module = build_convolutional_module_with_batch_norm( 394 | cur_inception_module, 395 | module_shape, 396 | kernel_initializer, 397 | mode, 398 | make_trainable=trainable, 399 | num_previously_built_inception_modules=module_num + num_previous_modules, 400 | weight_regularizer=kernel_regularizer, 401 | data_format=data_format) 402 | 403 | if isinstance(cur_inception_module, list): 404 | inception_module_paths_flattened = [ 405 | tf.reshape( 406 | path, 407 | [-1, reduce(lambda a, b: a * b, path.get_shape().as_list()[1:])] 408 | ) for path in cur_inception_module] 409 | return tf.concat(inception_module_paths_flattened, 1) 410 | 411 | return cur_inception_module 412 | 413 | 414 | def build_fully_connected_layers_with_batch_norm(the_input, shape, kernel_initializer, mode, scope_prefix=""): 415 | """ 416 | Builds fully connected layers with batch normalization onto the computational graph of the desired shape. 417 | 418 | 419 | The following are a few examples of the shapes that can be given, and how the layers are built 420 | 421 | shape = [512, 256, 128] 422 | result: input --> 512 --> 256 --> 128 423 | 424 | shape = [[25, 75], [200], 100, 75] 425 | result: concat((input --> 25 --> 75), (input --> 200)) --> 100 --> 75 426 | 427 | More complicated shapes can be used by defining modules recursively like the following 428 | shape = [[[100], [50, 50]], [200, 50], [75], 100, 20] 429 | """ 430 | if len(shape) == 0: 431 | return the_input 432 | 433 | module_outputs = [] 434 | for j, inner_modules in enumerate(shape): 435 | if isinstance(inner_modules, list): 436 | output = build_fully_connected_layers_with_batch_norm( 437 | the_input, 438 | inner_modules, 439 | kernel_initializer, 440 | mode, 441 | scope_prefix="%sfc_module_%d/" % (scope_prefix, j + 1)) 442 | module_outputs.append(output) 443 | else: 444 | if len(module_outputs) == 1: 445 | the_input = module_outputs[0] 446 | elif len(module_outputs) > 1: 447 | the_input = tf.concat(module_outputs, axis=1) 448 | 449 | for i, layer_shape in enumerate(shape[j:]): 450 | 451 | with tf.variable_scope(scope_prefix + "FC_" + str(i + 1)): 452 | pre_activation = tf.layers.dense( 453 | inputs=the_input, 454 | units=layer_shape, 455 | use_bias=False, 456 | kernel_initializer=kernel_initializer(), 457 | name="layer") 458 | 459 | batch_normalized = tf.layers.batch_normalization(pre_activation, 460 | scale=False, 461 | training=(mode == tf.estimator.ModeKeys.TRAIN), 462 | fused=True) 463 | 464 | the_input = tf.nn.relu(batch_normalized) 465 | layers.summarize_activation(the_input) 466 | 467 | module_outputs = [the_input] 468 | break 469 | 470 | if len(module_outputs) == 1: 471 | return module_outputs[0] 472 | 473 | return tf.concat(module_outputs, axis=1) 474 | 475 | 476 | def metric_dict_creator(the_dict): 477 | metric_dict = {} 478 | for key, value in the_dict.items(): 479 | if isinstance(value, tuple): # Given a tuple (tensor, summary) 480 | metric_dict[key] = (tf.reduce_mean(value[0]), value[1]) 481 | else: #Given a tensor 482 | mean_value = tf.reduce_mean(value) 483 | metric_dict[key] = (mean_value, tf.summary.scalar(key, mean_value)) 484 | 485 | return metric_dict 486 | 487 | 488 | def numpy_style_repeat_1d_creator(max_multiple=100, max_to_repeat=10000, out_type=tf.int32): 489 | board_num_lookup_ary = np.repeat( 490 | np.arange(max_to_repeat), 491 | np.full([max_to_repeat], max_multiple)) 492 | board_num_lookup_ary = board_num_lookup_ary.reshape(max_to_repeat, max_multiple) 493 | 494 | def fn_to_return(multiples): 495 | board_num_lookup_tensor = tf.constant(board_num_lookup_ary, dtype=out_type) 496 | 497 | if multiples.dtype != tf.int32: 498 | multiples = tf.cast(multiples, dtype=tf.int32) 499 | 500 | padded_multiples = tf.pad( 501 | multiples, 502 | [[0, max_to_repeat - tf.shape(multiples)[0]]]) 503 | 504 | padded_multiples = tf.cast(padded_multiples, tf.int32) 505 | to_return = tf.boolean_mask( 506 | board_num_lookup_tensor, 507 | tf.sequence_mask(padded_multiples, maxlen=max_multiple)) 508 | return to_return 509 | 510 | return fn_to_return 511 | 512 | 513 | def count_tfrecords(filename): 514 | return sum(1 for _ in tf.python_io.tf_record_iterator(filename)) 515 | 516 | 517 | class ValidationRunHook(tf.train.SessionRunHook): 518 | """ 519 | A subclass of tf.train.SessionRunHook to be used to evaluate validation data 520 | efficiently during an Estimator's training run. 521 | 522 | 523 | TO DO: 524 | 1) Figure out how to handle steps to do one complete epoch 525 | 2) Have this not call the evaluate function because it has to restore from a 526 | checkpoint, it will likely be faster if I evaluate it on the current training graph 527 | 3) Implement an epoch counter to be printed along with the validation results 528 | """ 529 | def __init__(self, step_increment, estimator, input_fn_creator, temp_num_steps_in_epoch=None, 530 | recall_input_fn_creator_after_evaluate=False): 531 | self.step_increment = step_increment 532 | self.estimator = estimator 533 | self.input_fn_creator = input_fn_creator 534 | self.recall_input_fn_creator_after_evaluate = recall_input_fn_creator_after_evaluate 535 | self.temp_num_steps_in_epoch = temp_num_steps_in_epoch 536 | 537 | def begin(self): 538 | self._global_step_tensor = tf.train.get_global_step() 539 | 540 | if self._global_step_tensor is None: 541 | raise RuntimeError("Global step should be created to use ValidationRunHook.") 542 | 543 | self._input_fn = self.input_fn_creator() 544 | 545 | def after_create_session(self, session, coord): 546 | self._step_started = session.run(self._global_step_tensor) 547 | 548 | def before_run(self, run_context): 549 | return training.session_run_hook.SessionRunArgs(self._global_step_tensor) 550 | 551 | def after_run(self, run_context, run_values): 552 | if (run_values.results - self._step_started) % self.step_increment == 0 and run_values.results != 0: 553 | print(self.estimator.evaluate( 554 | input_fn=self._input_fn, 555 | steps=self.temp_num_steps_in_epoch)) 556 | 557 | if self.recall_input_fn_creator_after_evaluate: 558 | self._input_fn = self.input_fn_creator() -------------------------------------------------------------------------------- /batch_first/anns/database_creator.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | 3 | import re 4 | import pickle 5 | import time 6 | import chess.pgn 7 | 8 | from batch_first.numba_board import * 9 | 10 | 11 | 12 | 13 | def game_iterator(pgn_filename): 14 | """ 15 | Iterates through the games stored on the given pgn file (as python-chess Game objects). 16 | """ 17 | with open(pgn_filename) as pgn_file: 18 | while True: 19 | game = chess.pgn.read_game(pgn_file) 20 | if game is None: 21 | break 22 | 23 | yield game 24 | 25 | 26 | def get_gamenode_after_moves(game, num_moves): 27 | """ 28 | Get the node from a given game after a specified number of moves has been made. 29 | """ 30 | for _ in range(num_moves): 31 | game = game.variations[0] 32 | return game 33 | 34 | 35 | def get_py_board_info_tuple(board): 36 | return np.array([board.kings, board.queens, board.rooks, board.bishops, board.knights, board.pawns, 37 | board.castling_rights, 0 if board.ep_square is None else BB_SQUARES[np.int32(board.ep_square)], 38 | board.occupied_co[board.turn], board.occupied_co[not board.turn], board.occupied], dtype=np.uint64) 39 | 40 | 41 | def get_feature_array(white_info): 42 | """ 43 | NOTES: 44 | 1) For the method used here to work (iterating over the masks), rook indices must always be set before 45 | castling_rights, and unoccupied must be set before the ep_square. 46 | """ 47 | answer = np.zeros(64,dtype=np.uint8) 48 | 49 | occupied_colors = np.array([[white_info[8]], [white_info[9]]]) 50 | piece_info = np.array([white_info[:7]]) 51 | 52 | masks = np.unpackbits(np.bitwise_and(occupied_colors, piece_info).reshape(14).view(np.uint8)).reshape( 53 | [14, 8, 8]).view(np.bool_)[..., ::-1].reshape(14, 64) 54 | 55 | for j, mask in enumerate(masks): 56 | answer[mask] = j + 2 57 | 58 | #Set the ep square 59 | if white_info[7] !=0: 60 | answer[msb(white_info[7])] = 1 61 | 62 | return answer 63 | 64 | 65 | def additional_move_features(board_features): 66 | return {"move_from_square": tf.train.Feature(int64_list=tf.train.Int64List(value=[board_features[1]])), 67 | "move_to_square": tf.train.Feature(int64_list=tf.train.Int64List(value=[board_features[2]])), 68 | "move_filter": tf.train.Feature(int64_list=tf.train.Int64List(value=[board_features[3]]))} 69 | 70 | 71 | def serializer_creator(additional_feature_dict_fn=None): 72 | """ 73 | A convenience function to aid in the use of the combine_pickles_and_create_tfrecords function. 74 | 75 | :param additional_feature_dict_fn: A function which returns a dictionary mapping feature names (strings) 76 | to tf.train.Feature objects. The features given in this dict will be serialized along with the "board" and 77 | "score" features 78 | :return: A function to be given to the combine_pickles_and_create_tfrecords function as 79 | the serializer parameter 80 | """ 81 | def serializer_to_return(board_features, score): 82 | feature_input = board_features[0] if isinstance(board_features[0], tuple) else board_features 83 | feature_dict = { 84 | "board": tf.train.Feature(int64_list=tf.train.Int64List(value=get_feature_array(feature_input))), 85 | "score": tf.train.Feature(int64_list=tf.train.Int64List(value=[score]))} 86 | 87 | if additional_feature_dict_fn: 88 | feature_dict.update(additional_feature_dict_fn(board_features)) 89 | 90 | example = tf.train.Example(features=tf.train.Features(feature=feature_dict)) 91 | return example.SerializeToString() 92 | 93 | return serializer_to_return 94 | 95 | 96 | def get_nodes_value(node, board_turn, max_win_value=1000000): 97 | """ 98 | Gets the value of the given node, or None if no value is stored. 99 | 100 | :param node: The node who's value is to be returned 101 | :param board_turn: If this parameter is False, it will multiply the score by -1 (changing the score to be with 102 | respect to the other player) 103 | :param win_value: The value for a depth-0 winning board. The value of a depth-1 win would thus be one less, 104 | and depth-n would be n less 105 | """ 106 | re_search_results = re.search(r'\[\%eval (.*?)\]', node.comment) 107 | if re_search_results is None: 108 | return None 109 | 110 | sf_score_str = re_search_results.group(1) 111 | 112 | # If a mate is found, store the win/loss value, 113 | # scaled such that the magnitude of the win/loss value will decrease as the depth from the mate 114 | # increases. 115 | if sf_score_str[0] == '#': 116 | mate_depth = np.int64(int(sf_score_str[1:])) 117 | 118 | mate_value = max_win_value if mate_depth > 0 else -max_win_value 119 | 120 | sf_score = mate_value - mate_depth 121 | else: 122 | sf_score = np.int64(float(sf_score_str) * 100) # converts the score to the traditional centi-pawn scores used by StockFish 123 | 124 | if not board_turn: 125 | sf_score *= -1 126 | 127 | return sf_score 128 | 129 | 130 | def get_data_from_pgns(pgn_filenames, output_filename, get_board_for_game_fn, print_interval=10000): 131 | """ 132 | Creates a pickle database from the data in the given pgn files. One example is produced per game, and is done so 133 | by a given function. 134 | 135 | 136 | :param pgn_filenames: An iterable of the names/paths of pgn files to have data gathered from 137 | :param output_filename: A string used as the name of the output pickle database 138 | :param get_board_for_game_fn: A function that accepts a python-chess Game, and returns a length two tuple. That tuple's 139 | first element is either the board's representation (a tuple), or a tuple with it's representation as it's first 140 | value (followed by any other desired information) (All of this information is used to ensure that each example is unique). 141 | The second element of the returned tuple is the score associated with the example 142 | :param print_interval: The number of games checked between printing the progress 143 | """ 144 | eval_boards = {} 145 | num_checked = 0 146 | for j, filename in enumerate(pgn_filenames): 147 | if print_interval: 148 | print("Starting file %d"%j) 149 | last_print = time.time() 150 | 151 | for returns in map(get_board_for_game_fn, game_iterator(filename)): 152 | if not returns is None: 153 | if eval_boards.get(returns[0]) is None: 154 | eval_boards[returns[0]] = returns[1] 155 | 156 | num_checked += 1 157 | 158 | if print_interval and num_checked % print_interval == 0: 159 | print("%d boards have been checked, generating %d usable boards, with %f time since the last print"%(num_checked, len(eval_boards), time.time() - last_print)) 160 | last_print = time.time() 161 | 162 | with open(output_filename, 'wb') as writer: 163 | pickle.dump(eval_boards, writer, pickle.HIGHEST_PROTOCOL) 164 | 165 | 166 | def combine_pickles_and_create_tfrecords(filenames, output_filenames, output_ratios, serializer): 167 | """ 168 | Combines the information in the given pickle files (maintaining uniqueness), serializes the data, then saves it 169 | as a set of tfrecords files (in the desired ratios). 170 | 171 | :param filenames: An iterable of pickled filenames (produced by get_data_from_pgns) to serialize and combine 172 | :param output_filenames: An iterable of filenames to save the serialized tfrecords to 173 | :param output_ratios: The ratios of the combined data to be saved to each of the files in output_filenames 174 | :param serializer: A function which returns a serialized TensorFlow Example, the details of it's two parameters 175 | are described in the get_data_from_pgns's comments as the return of the get_board_for_game_fn parameter 176 | (the serializer_creator function can be used to generate this parameter) 177 | """ 178 | combined_dict = {} 179 | for name in filenames: 180 | with open(name, "rb") as to_read: 181 | for key, value in pickle.load(to_read).items(): 182 | if combined_dict.get(key) is None: 183 | combined_dict[key] = value 184 | 185 | break_indices = np.r_[0, (len(combined_dict) * np.cumsum(np.array(output_ratios))[:-1]).astype(np.int32),len(combined_dict)] 186 | dict_iterator = iter(combined_dict) 187 | 188 | key_arrays = ([next(dict_iterator) for _ in range(j-i)] for i,j in zip(break_indices[:-1],break_indices[1:])) 189 | serialized_examples = (map(serializer, keys, (combined_dict[k] for k in keys)) for keys in key_arrays) 190 | 191 | for filename, examples in zip(output_filenames, serialized_examples): 192 | with tf.python_io.TFRecordWriter(filename) as writer: 193 | for example in examples: 194 | writer.write(example) 195 | 196 | 197 | def create_board_eval_board_from_game_fn(min_start_moves=6, for_testing=False): 198 | random_number_starter = min_start_moves - 1 199 | min_boards_in_game = min_start_moves + 1 200 | def get_board_for_game(game): 201 | num_boards_in_game = len(list(game.main_line())) 202 | 203 | if num_boards_in_game <= min_boards_in_game: 204 | return None 205 | 206 | desired_game_node = get_gamenode_after_moves(game, np.random.randint(random_number_starter, num_boards_in_game-1)) 207 | py_board = desired_game_node.board() 208 | 209 | if for_testing: 210 | sf_score = 0 211 | else: 212 | sf_score = get_nodes_value(desired_game_node, py_board.turn) 213 | if sf_score is None: 214 | return None 215 | 216 | if py_board.turn: 217 | white_info = tuple(get_py_board_info_tuple(py_board)) 218 | else: 219 | white_info = tuple(flip_vertically(get_py_board_info_tuple(py_board))) 220 | 221 | return white_info, sf_score 222 | return get_board_for_game 223 | 224 | 225 | def create_move_scoring_board_from_game_fn(min_start_moves=6): 226 | random_number_starter = min_start_moves - 1 227 | min_boards_in_game = min_start_moves + 1 228 | def get_board_for_game(game): 229 | num_boards_in_game = len(list(game.main_line())) 230 | 231 | if num_boards_in_game <= min_boards_in_game: 232 | return None 233 | 234 | desired_game_node = get_gamenode_after_moves(game, np.random.randint(random_number_starter, num_boards_in_game-1)) 235 | 236 | py_board = desired_game_node.board() 237 | 238 | next_node = desired_game_node.variations[0] 239 | next_value = get_nodes_value(next_node, py_board.turn) 240 | 241 | if next_value is None: 242 | return None 243 | 244 | # Store the move and flip it if the board was converted from black's perspective 245 | move_made = next_node.move 246 | if not py_board.turn: 247 | move_made.from_square = chess.square_mirror(move_made.from_square) 248 | move_made.to_square = chess.square_mirror(move_made.to_square) 249 | 250 | if move_made.promotion is None or move_made.promotion == chess.QUEEN: 251 | move_promotion = NO_PROMOTION_VALUE 252 | else: 253 | move_promotion = move_made.promotion 254 | 255 | move_filter = MOVE_FILTER_LOOKUP[ 256 | move_made.from_square, 257 | move_made.to_square, 258 | move_promotion] 259 | 260 | if py_board.turn: 261 | white_info = tuple(get_py_board_info_tuple(py_board)) 262 | else: 263 | white_info = tuple(flip_vertically(get_py_board_info_tuple(py_board))) 264 | 265 | return (white_info, move_made.from_square, move_made.to_square, move_filter), next_value 266 | 267 | return get_board_for_game 268 | 269 | 270 | def save_all_boards_from_game_as_npy(pgn_file, output_filename, max_games=100000, print_interval=5000): 271 | """ 272 | Goes through the games in a pgn file and saves the unique boards in NumPy file format 273 | (with dtype numpy_node_info_dtype). Prior to being saved the legal move arrays are set up. 274 | 275 | :param pgn_file: The pgn file to gather boards from 276 | :param output_filename: The name for the database file to be created 277 | :param max_games: The maximum number of games to go through 278 | :param print_interval: The number of games between each progress update 279 | 280 | NOTES: 281 | 1) This function uses a large amount of memory (mainly caused by np.unique) 282 | """ 283 | prev_time = time.time() 284 | root_struct = create_node_info_from_python_chess_board(chess.Board()) 285 | 286 | collected = [] 287 | for j, game in enumerate(game_iterator(pgn_file)): 288 | 289 | if j == max_games: 290 | break 291 | 292 | if j % print_interval == 0: 293 | print("%d games complete with %d boards collected (not unique) with %f time since last print."%(j, len(collected), time.time() - prev_time)) 294 | prev_time = time.time() 295 | 296 | struct = root_struct.copy() 297 | 298 | move_iterator = (np.array([[move.from_square, move.to_square, 0 if move.promotion is None else move.promotion]]) for move in game.main_line()) 299 | for move_ary in move_iterator: 300 | push_moves(struct, move_ary) 301 | collected.append(struct.copy()) 302 | 303 | print("Completed board acquisition") 304 | 305 | unique_structs = np.unique(np.array(collected)) 306 | 307 | print("%d unique boards produced." % len(unique_structs)) 308 | 309 | set_up_move_arrays(unique_structs) 310 | 311 | structs_with_less_than_max_moves = unique_structs[unique_structs['children_left'] <= MAX_MOVES_LOOKED_AT] 312 | 313 | print("Moves have now been set up.") 314 | 315 | np.save(output_filename, structs_with_less_than_max_moves) 316 | 317 | 318 | def get_zero_valued_boards(filename, output_filename, print_interval=25000): 319 | def iterate_zero_value_nodes(): 320 | num_done = 0 321 | for game in game_iterator(filename): 322 | while len(game.variations) == 1: 323 | game = game.variations[0] 324 | if get_nodes_value(game, True) == 0: 325 | num_done += 1 326 | if num_done % print_interval == 0: 327 | print("Zero valued boards gathered:", num_done) 328 | yield game.board() 329 | 330 | 331 | to_return = np.array([create_node_info_from_python_chess_board(b) for b in iterate_zero_value_nodes()]) 332 | unique_boards = np.unique(to_return) 333 | 334 | np.save(output_filename, unique_boards) 335 | 336 | 337 | def get_locations_of_lines_that_pass_filters(filename, filters, print_interval=1e7): 338 | """ 339 | Gets the line numbers of the lines in a given file that pass a set of filters. 340 | """ 341 | def passes(line): 342 | for filter in filters: 343 | if filter(line): 344 | return False 345 | return True 346 | 347 | with open(filename, 'r') as f: 348 | prev_time = time.time() 349 | line_nums = [] 350 | for j,line in enumerate(iter(f.readline, '')): 351 | if passes(line): 352 | line_nums.append(f.tell()) 353 | 354 | if j % print_interval == 0: 355 | print("%d lines completed so far with %d lines found in %f time since last print"%(j, len(line_nums), time.time() - prev_time)) 356 | prev_time = time.time() 357 | 358 | return line_nums 359 | 360 | 361 | def clean_pgn_file(pgn_to_filter, output_filename, line_filters=[], header_filters=[]): 362 | def passes_header_filters(headers): 363 | for filter in header_filters: 364 | if filter(headers): 365 | return False 366 | return True 367 | 368 | line_nums = get_locations_of_lines_that_pass_filters( 369 | pgn_to_filter, 370 | line_filters) 371 | line_nums = line_nums[: -1] #the last game isn't used because if it's the last game in the file the array indexing to follow will cause an error 372 | 373 | line_nums = np.array(line_nums) 374 | print("Desired line numbers have been found.") 375 | with open(output_filename, 'w') as writer: 376 | with open(pgn_to_filter, 'r') as f: 377 | temp_stuff = [(offset, passes_header_filters(header)) for offset, header in chess.pgn.scan_headers(f)] 378 | 379 | offsets, should_write = zip(*temp_stuff) 380 | 381 | should_write = np.array(list(should_write), dtype=np.bool_) 382 | 383 | game_offsets = np.array(list(offsets)) 384 | 385 | print("Game offsets calculated and headers collected") 386 | 387 | temp_indices = np.searchsorted(game_offsets, line_nums) 388 | 389 | 390 | actual_offset_indices = temp_indices - 1 391 | 392 | should_write = should_write[actual_offset_indices] 393 | 394 | amount_to_write = game_offsets[temp_indices] - game_offsets[actual_offset_indices] 395 | filtered_start_lines = game_offsets[actual_offset_indices] 396 | 397 | print("Starting to write the new file.") 398 | 399 | for offset, amount in zip(filtered_start_lines[should_write], amount_to_write[should_write]): 400 | f.seek(offset) 401 | writer.write(f.read(amount)) 402 | 403 | 404 | def combine_numpy_files_and_make_unique(filenames, output_name): 405 | combined = np.concatenate([np.load(file) for file in filenames]) 406 | unique_boards = np.unique(combined) 407 | np.save(output_name, unique_boards) 408 | 409 | 410 | if __name__ == "__main__": 411 | """ 412 | The commented out code throughout the rest of this file is how the ANN training databases are created, 413 | as well as any other database used in Batch First. 414 | """ 415 | 416 | 417 | def add_path_fn_creator(path): 418 | return lambda x : [path + y for y in x] 419 | 420 | PGN_FILENAMES_WITHOUT_PATHS = [ 421 | "lichess_db_standard_rated_2018-06.pgn", 422 | "lichess_db_standard_rated_2018-05.pgn", 423 | "lichess_db_standard_rated_2018-04.pgn", 424 | "lichess_db_standard_rated_2018-03.pgn", 425 | "lichess_db_standard_rated_2018-02.pgn", 426 | "lichess_db_standard_rated_2018-01.pgn", 427 | "lichess_db_standard_rated_2017-12.pgn", 428 | "lichess_db_standard_rated_2017-11.pgn", 429 | "lichess_db_standard_rated_2017-10.pgn", 430 | "lichess_db_standard_rated_2017-09.pgn", 431 | "lichess_db_standard_rated_2017-08.pgn", 432 | "lichess_db_standard_rated_2017-07.pgn", 433 | "lichess_db_standard_rated_2017-06.pgn", 434 | "lichess_db_standard_rated_2017-05.pgn", 435 | "lichess_db_standard_rated_2017-04.pgn", 436 | "lichess_db_standard_rated_2017-03.pgn", 437 | "lichess_db_standard_rated_2017-02.pgn", 438 | "lichess_db_standard_rated_2017-01.pgn", 439 | "lichess_db_standard_rated_2016-12.pgn", 440 | "lichess_db_standard_rated_2016-11.pgn", 441 | "lichess_db_standard_rated_2016-10.pgn", 442 | "lichess_db_standard_rated_2016-09.pgn", 443 | "lichess_db_standard_rated_2016-08.pgn", 444 | "lichess_db_standard_rated_2016-07.pgn", 445 | "lichess_db_standard_rated_2016-06.pgn", 446 | "lichess_db_standard_rated_2016-05.pgn", 447 | "lichess_db_standard_rated_2016-04.pgn", 448 | "lichess_db_standard_rated_2016-03.pgn", 449 | "lichess_db_standard_rated_2016-02.pgn", 450 | "lichess_db_standard_rated_2016-01.pgn",][::-1] 451 | 452 | PICKLE_FILENAMES = list(map(lambda s : s[:-3] + "pkl", PGN_FILENAMES_WITHOUT_PATHS)) 453 | 454 | PGN_FILENAMES = add_path_fn_creator("/srv/databases/lichess/original_pgns/")(PGN_FILENAMES_WITHOUT_PATHS) 455 | 456 | FILTERED_FILENAMES = add_path_fn_creator("/srv/databases/lichess/filtered_pgns/")(PGN_FILENAMES_WITHOUT_PATHS) 457 | FILTERED_FILENAMES = list(map(lambda f: "%s_filtered.pgn" % f[:-4], FILTERED_FILENAMES)) 458 | 459 | 460 | TFRECORDS_FILENAMES = [ 461 | "lichess_training.tfrecords", 462 | "lichess_validation.tfrecords", 463 | "lichess_testing.tfrecords"] 464 | 465 | TFRECORDS_OUTPUT_RATIOS = [.85, .1, .05] 466 | 467 | 468 | 469 | 470 | 471 | 472 | pgn_not_used_for_ann_training = "/srv/databases/lichess/lichess_db_standard_rated_2018-07.pgn" 473 | npy_output_filename = "/srv/databases/lichess/lichess_db_standard_rated_2018-07_first_100k_games" 474 | # save_all_boards_from_game_as_npy(pgn_not_used_for_ann_training, npy_output_filename) 475 | 476 | 477 | file_index = -6 478 | OUTPUT_FILTERED_FILENAME = add_path_fn_creator("/srv/databases/has_zero_valued_board/")(PGN_FILENAMES_WITHOUT_PATHS)[file_index] 479 | # clean_pgn_file( 480 | # FILTERED_FILENAMES[file_index], 481 | # OUTPUT_FILTERED_FILENAME, 482 | # [lambda s: s[0] != '1', 483 | # lambda s: not "%eval 0.0" in s], 484 | # [lambda h: h['Termination'] != "Normal"]) 485 | 486 | 487 | file_index = -2 488 | INPUT_FILENAME = FILTERED_FILENAMES[file_index] 489 | OUTPUT_FILENAME = INPUT_FILENAME[:-4] + "_zero_boards" 490 | # get_zero_valued_boards(INPUT_FILENAME, OUTPUT_FILENAME) 491 | 492 | 493 | ########################The commented out code below is used for the move scoring database################### 494 | file_index = 6 495 | OUTPUT_FILENAME = add_path_fn_creator("/srv/databases/lichess_just_move_scoring_fixed_ag_promotion/")(PGN_FILENAMES_WITHOUT_PATHS)[file_index][:-3] + "pkl" 496 | OUTPUT_FILENAME = OUTPUT_FILENAME[:-4] + "_second_pass.pkl" 497 | 498 | CUR_MOVE_PGN_FILENAME = FILTERED_FILENAMES[file_index] 499 | # get_data_from_pgns( 500 | # [CUR_MOVE_PGN_FILENAME], 501 | # OUTPUT_FILENAME, 502 | # create_move_scoring_board_from_game_fn(5)) 503 | 504 | 505 | #########################The commented out code below is used for the board evaluation database################### 506 | file_index = 6 507 | CUR_EVAL_PGN_FILENAME = FILTERED_FILENAMES[file_index] 508 | OUTPUT_FILENAME = add_path_fn_creator("/srv/databases/lichess_combined_methods_eval_databases/")(PGN_FILENAMES_WITHOUT_PATHS)[file_index][:-3] + "pkl" 509 | # OUTPUT_FILENAME = OUTPUT_FILENAME[:-4] + "_second_pass.pkl" 510 | # get_data_from_pgns( 511 | # [CUR_EVAL_PGN_FILENAME], 512 | # OUTPUT_FILENAME, 513 | # create_board_eval_board_from_game_fn()) 514 | 515 | 516 | 517 | #########################The commented out code below is used for the board evaluation database######################### 518 | eval_path_adder = add_path_fn_creator("/srv/databases/lichess_combined_methods_eval_databases/") 519 | 520 | EVAL_PICKLE_FILES = eval_path_adder(PICKLE_FILENAMES) 521 | # EVAL_PICKLE_FILES += list(map(lambda s: s[:-4] + "_second_pass.pkl", EVAL_PICKLE_FILES)) 522 | 523 | EVAL_OUTPUT_TFRECORDS_FILES = eval_path_adder(TFRECORDS_FILENAMES) 524 | 525 | # combine_pickles_and_create_tfrecords( 526 | # EVAL_PICKLE_FILES, 527 | # EVAL_OUTPUT_TFRECORDS_FILES, 528 | # TFRECORDS_OUTPUT_RATIOS, 529 | # serializer_creator()) 530 | 531 | 532 | #########################The commented out code below is used for the move scoring database################### 533 | policy_path_adder = add_path_fn_creator("/srv/databases/lichess_just_move_scoring_fixed_ag_promotion/") 534 | MOVE_SCORING_PICKLE_FILES = policy_path_adder(PICKLE_FILENAMES) 535 | # MOVE_SCORING_PICKLE_FILES += list(map(lambda s: s[:-4] + "_second_pass.pkl", MOVE_SCORING_PICKLE_FILES)) 536 | POLICY_OUTPUT_TFRECORDS_FILES = policy_path_adder(TFRECORDS_FILENAMES) 537 | 538 | # combine_pickles_and_create_tfrecords( 539 | # MOVE_SCORING_PICKLE_FILES, 540 | # POLICY_OUTPUT_TFRECORDS_FILES, 541 | # TFRECORDS_OUTPUT_RATIOS, 542 | # serializer_creator(additional_move_features)) 543 | 544 | -------------------------------------------------------------------------------- /batch_first/anns/evaluation_ann.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | 3 | from scipy.stats import kendalltau, weightedtau, spearmanr 4 | 5 | import batch_first.anns.ann_creation_helper as ann_h 6 | 7 | tf.logging.set_verbosity(tf.logging.INFO) 8 | 9 | 10 | 11 | def diag_comparison_model_fn(features, labels, mode, params): 12 | """ 13 | Generates an EstimatorSpec for a model which scores chess boards. It learns by maximizing the difference between 14 | board evaluation values, where one is intended to be greater than the other based on some pre-calculated 15 | scoring system (e.g. StockFish evaluations). 16 | """ 17 | convolutional_module_outputs=ann_h.create_input_convolutions_shared_weights( 18 | features['board'], 19 | params['kernel_initializer'], 20 | params['data_format'], 21 | mode, 22 | num_unique_filters=[32, 20, 20, 18, 18, 16, 24, 24]) #236 with the 64 undilated included 23 | 24 | if len(params['convolutional_modules']): 25 | convolutional_module_outputs = ann_h.build_convolutional_modules( 26 | convolutional_module_outputs, 27 | params['convolutional_modules'], 28 | mode, 29 | params['kernel_initializer'], 30 | params['kernel_regularizer'], 31 | params['trainable_cnn_modules'], 32 | num_previous_modules=1, 33 | data_format=params['data_format']) 34 | 35 | logits = tf.layers.conv2d( 36 | inputs=convolutional_module_outputs, 37 | filters=1, 38 | kernel_size=[1,1], 39 | padding="valid", 40 | data_format="channels_last" if params['data_format']=="NHWC" else "channels_first", 41 | use_bias=False, 42 | kernel_initializer=params['kernel_initializer'](), 43 | kernel_regularizer=params['kernel_regularizer'](), 44 | name="logit_layer") 45 | 46 | logits = tf.squeeze(logits, axis=[1,2,3]) 47 | 48 | loss = None 49 | train_op = None 50 | 51 | 52 | # Calculate loss 53 | if mode != tf.estimator.ModeKeys.PREDICT: 54 | with tf.variable_scope("loss"): 55 | calculated_diff_matrix = ann_h.vec_and_transpose_op(logits, tf.subtract) 56 | 57 | label_matrix = features['label_matrix'] 58 | weight_matrix = features['weight_matrix'] 59 | 60 | loss = tf.losses.sigmoid_cross_entropy(label_matrix, calculated_diff_matrix, weights=weight_matrix) 61 | loss_summary = tf.summary.scalar("loss", loss) 62 | 63 | 64 | # Configure the Training Op 65 | if mode == tf.estimator.ModeKeys.TRAIN: 66 | global_step = tf.train.get_global_step() 67 | learning_rate = params['learning_decay_function'](global_step) 68 | tf.summary.scalar("learning_rate", learning_rate) 69 | train_op = tf.contrib.layers.optimize_loss( 70 | loss=loss, 71 | global_step=global_step, 72 | learning_rate=learning_rate, 73 | optimizer=params['optimizer'], 74 | summaries=params['train_summaries']) 75 | 76 | predictions = {"scores" : logits} 77 | the_export_outputs = {"serving_default" : tf.estimator.export.RegressionOutput(value=logits)} 78 | 79 | validation_metrics = None 80 | training_hooks = [] 81 | 82 | # Create the metrics 83 | if mode == tf.estimator.ModeKeys.TRAIN: 84 | tau_a = ann_h.kendall_rank_correlation_coefficient(logits, features['score']) 85 | 86 | to_create_metric_dict = { 87 | "loss/loss": (loss, loss_summary), 88 | "metrics/mean_evaluation_value" : logits, 89 | "metrics/mean_abs_evaluation_value": tf.abs(logits), 90 | "metrics/kendall_tau-a" : tau_a, 91 | } 92 | 93 | validation_metrics = ann_h.metric_dict_creator(to_create_metric_dict) 94 | 95 | tf.contrib.layers.summarize_tensors(tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)) 96 | training_hooks.append( 97 | tf.train.SummarySaverHook( 98 | save_steps=params['log_interval'], 99 | output_dir=params['model_dir'], 100 | summary_op=tf.summary.merge_all())) 101 | 102 | elif mode == tf.estimator.ModeKeys.EVAL: 103 | the_logits, update1 = tf.contrib.metrics.streaming_concat(logits) 104 | the_labels, update2 = tf.contrib.metrics.streaming_concat(features['score']) 105 | 106 | BIGGER_THAN_CP_LESS_THAN_WIN_VAL = tf.constant(100000, dtype=features['score'].dtype) 107 | 108 | mate_mask = tf.greater(tf.abs(the_labels), BIGGER_THAN_CP_LESS_THAN_WIN_VAL) 109 | mate_logits = tf.boolean_mask(the_logits, mate_mask) 110 | mate_labels = tf.boolean_mask(the_labels, mate_mask) 111 | 112 | non_mate_mask = tf.logical_not(mate_mask) 113 | non_mate_logits = tf.boolean_mask(the_logits, non_mate_mask) 114 | non_mate_labels = tf.boolean_mask(the_labels, non_mate_mask) 115 | 116 | mate_tau_b, mate_tau_b_p_value = ann_h.py_func_scipy_rank_helper_creator(mate_logits, mate_labels)(kendalltau) 117 | 118 | non_mate_coef_creator = ann_h.py_func_scipy_rank_helper_creator(non_mate_logits, non_mate_labels) 119 | non_mate_tau_b, non_mate_tau_b_p_value = non_mate_coef_creator(kendalltau) 120 | non_mate_weighted_tau_b, non_mate_weighted_tau_b_p_value= non_mate_coef_creator(weightedtau) 121 | 122 | update = tf.group(update1, update2) 123 | 124 | scipy_rank_coef_creator = ann_h.py_func_scipy_rank_helper_creator(the_logits, the_labels) 125 | 126 | tau_b, tau_b_p_value = scipy_rank_coef_creator(kendalltau) 127 | rho, rho_p_value = scipy_rank_coef_creator(spearmanr) 128 | 129 | validation_metrics = { 130 | "metrics/mean_evaluation_value" : tf.metrics.mean(logits), 131 | "metrics/mean_abs_evaluation_value" : tf.metrics.mean(tf.abs(logits)), 132 | "metrics/kendall_tau-b": (tau_b, update), 133 | "metrics/kendall_tau-b_p_value": (tau_b_p_value, update), 134 | "metrics/kendall_tau-b_mate_only" : (mate_tau_b, update), 135 | "metrics/non_mate_kendall_tau-b" : (non_mate_tau_b, update), 136 | "metrics/non_mate_weighted_tau-b": (non_mate_weighted_tau_b, update), 137 | "metrics/non_mate_weighted_kendall_tau-b_p_value": (non_mate_weighted_tau_b_p_value, update), 138 | "metrics/spearman_rho": (rho, update), 139 | "metrics/spearman_rho_p_value": (rho_p_value, update), 140 | } 141 | 142 | return tf.estimator.EstimatorSpec( 143 | mode=mode, 144 | predictions=predictions, 145 | loss=loss, 146 | train_op=train_op, 147 | training_hooks=training_hooks, 148 | export_outputs=the_export_outputs, 149 | eval_metric_ops=validation_metrics) 150 | 151 | 152 | def lower_diag_score_comparison_input_fn(filename_pattern, batch_size, include_unoccupied=True, shuffle_buffer_size=None, 153 | num_things_in_parallel=None, num_things_to_prefetch=None, shuffle_seed=None, 154 | data_format="NHWC"): 155 | if num_things_to_prefetch is None: 156 | num_things_to_prefetch = tf.contrib.data.AUTOTUNE #IMPORTANT NOTE: This seems to make the program crash after a few iterations (at least it does on my computer) 157 | 158 | dataset = tf.data.TFRecordDataset(filename_pattern) 159 | 160 | if shuffle_buffer_size: 161 | dataset = dataset.apply(tf.contrib.data.shuffle_and_repeat(shuffle_buffer_size,seed=shuffle_seed)) 162 | 163 | dataset = dataset.batch(batch_size, drop_remainder=True) 164 | 165 | def process_batch(records): 166 | keys_to_features = {"board": tf.FixedLenFeature([8 * 8], tf.int64), 167 | "score": tf.FixedLenFeature([], tf.int64)} 168 | 169 | parsed_examples = tf.parse_example(records, keys_to_features) 170 | 171 | reshaped_boards = tf.reshape(parsed_examples['board'], [-1, 8, 8]) 172 | 173 | omit_unoccupied_decrement = 0 if include_unoccupied else 1 174 | boards = tf.one_hot( 175 | reshaped_boards - omit_unoccupied_decrement, 176 | 16 - omit_unoccupied_decrement, 177 | axis=-1 if data_format=="NHWC" else 1) 178 | 179 | desired_diff_matrix = ann_h.vec_and_transpose_op(parsed_examples['score'], tf.subtract, tf.float32) 180 | 181 | lower_diag_diff_matrix = tf.matrix_band_part(desired_diff_matrix, -1, 0) 182 | 183 | lower_diag_sign = tf.sign(lower_diag_diff_matrix) 184 | weight_mask = tf.abs(lower_diag_sign) 185 | bool_weight_mask = tf.cast(weight_mask, tf.bool) 186 | 187 | comparison_indices = tf.where(bool_weight_mask) 188 | 189 | # value_larger_than_centipawn_less_than_mate = 100000 190 | # desired_found_mate = tf.greater(tf.abs(parsed_examples['score']), value_larger_than_centipawn_less_than_mate) 191 | 192 | # both_found_mate = ann_h.vec_and_transpose_op(desired_found_mate, tf.logical_and) 193 | 194 | # desired_signs = tf.sign(parsed_examples['score']) 195 | 196 | # same_sign_matrix = ann_h.vec_and_transpose_op(desired_signs, tf.equal) 197 | 198 | # both_same_player_mates = tf.logical_and(both_found_mate, same_sign_matrix) 199 | 200 | # both_same_mate_and_nonzero_weight = tf.logical_and(both_same_player_mates, bool_weight_mask) 201 | 202 | # same_mate_depth_diff_decrement = .95 203 | 204 | # weight_helper = same_mate_depth_diff_decrement * tf.cast(both_same_mate_and_nonzero_weight, tf.float32) 205 | 206 | # mate_adjusted_weight_mask = weight_mask - weight_helper 207 | 208 | label_matrix = (lower_diag_sign + weight_mask)/2 209 | 210 | # return boards, parsed_examples['score'], label_matrix, mate_adjusted_weight_mask, comparison_indices 211 | return boards, parsed_examples['score'], label_matrix, weight_mask, comparison_indices 212 | 213 | 214 | dataset = dataset.map(process_batch, num_parallel_calls=num_things_in_parallel) 215 | 216 | dataset = dataset.apply(tf.contrib.data.prefetch_to_device('/gpu:0', buffer_size=num_things_to_prefetch)) 217 | 218 | iterator = dataset.make_one_shot_iterator() 219 | 220 | features = iterator.get_next() 221 | 222 | feature_dict = {"board": features[0], "score": features[1], "label_matrix": features[2], "weight_matrix": features[3]} 223 | 224 | return feature_dict, None 225 | 226 | 227 | def board_eval_serving_input_receiver(data_format="NCHW"): 228 | def fn_to_return(): 229 | placeholder_shape = [None, 15, 8, 8] if data_format=="NCHW" else [None, 8, 8, 15] 230 | 231 | for_remapping = tf.placeholder(tf.float32, placeholder_shape, "FOR_INPUT_MAPPING_transpose") 232 | 233 | receiver_tensors = {"board": for_remapping} 234 | return tf.estimator.export.ServingInputReceiver(receiver_tensors, receiver_tensors) 235 | return fn_to_return 236 | 237 | 238 | def main(unused_par): 239 | 240 | SAVE_MODEL_DIR = "/srv/tmp/diag_loss_3/pre_commit_test_2534111" 241 | TRAINING_FILENAME_PATTERN = "/srv/databases/lichess_combined_methods_eval_databases/lichess_training.tfrecords" 242 | VALIDATION_FILENAME_PATTERN = "/srv/databases/lichess_combined_methods_eval_databases/lichess_validation.tfrecords" 243 | TRAIN_OP_SUMMARIES = ["gradient_norm", "gradients"] 244 | NUM_INPUT_FILTERS = 15 245 | OPTIMIZER = 'Adam' 246 | TRAINING_SHUFFLE_BUFFER_SIZE = 16800000 247 | TRAINING_BATCH_SIZE = 512 #The effective batch size used for the loss = n(n-1)/2 (where n is the number of boards in the batch) 248 | VALIDATION_BATCH_SIZE = 1000 249 | LOG_ITERATION_INTERVAL = 2500 250 | LEARNING_RATE = 2.5e-3 251 | KERNEL_REGULARIZER = lambda: None 252 | KERNEL_INITIALIZER = lambda: tf.contrib.layers.variance_scaling_initializer() 253 | TRAINABLE_CNN_MODULES = True 254 | DATA_FORMAT = "NCHW" 255 | SAME_MATE_DEPTH_DIFF_LOSS_WEIGHT_DECREMENT = .95 256 | VALUE_LARGER_THAN_CENTIPAWN_LESS_THAN_MATE = 100000 257 | 258 | num_examples_in_training_file = 16851682 259 | num_examples_in_validation_file = 1982551 260 | 261 | BATCHES_IN_TRAINING_EPOCH = num_examples_in_training_file // TRAINING_BATCH_SIZE 262 | BATCHES_IN_VALIDATION_EPOCH = num_examples_in_validation_file // VALIDATION_BATCH_SIZE 263 | 264 | # learning_decay_function = lambda gs: LEARNING_RATE 265 | learning_decay_function = lambda gs : tf.train.exponential_decay(LEARNING_RATE, gs, 266 | BATCHES_IN_TRAINING_EPOCH, 0.96, staircase=True) 267 | 268 | CONVOLUTIONAL_MODULES = [[[[512, 1], [128, 1]] + 6 * [[32, 3]] + [(16, 8)]]] 269 | 270 | 271 | # Create the Estimator 272 | the_estimator = tf.estimator.Estimator( 273 | model_fn=diag_comparison_model_fn, 274 | model_dir=SAVE_MODEL_DIR, 275 | config=tf.estimator.RunConfig().replace( 276 | save_checkpoints_steps=LOG_ITERATION_INTERVAL, 277 | save_summary_steps=LOG_ITERATION_INTERVAL), 278 | params={ 279 | "optimizer": OPTIMIZER, 280 | "log_interval": LOG_ITERATION_INTERVAL, 281 | "model_dir": SAVE_MODEL_DIR, 282 | "convolutional_modules" : CONVOLUTIONAL_MODULES, 283 | "learning_rate": LEARNING_RATE, 284 | "train_summaries": TRAIN_OP_SUMMARIES, 285 | "learning_decay_function" : learning_decay_function, 286 | "num_input_filters" : NUM_INPUT_FILTERS, 287 | "kernel_initializer" : KERNEL_INITIALIZER, 288 | "kernel_regularizer" : KERNEL_REGULARIZER, 289 | "trainable_cnn_modules" : TRAINABLE_CNN_MODULES, 290 | "same_mate_depth_diff_decrement" : SAME_MATE_DEPTH_DIFF_LOSS_WEIGHT_DECREMENT, 291 | "value_larger_than_centipawn_less_than_mate" : VALUE_LARGER_THAN_CENTIPAWN_LESS_THAN_MATE, 292 | "data_format" : DATA_FORMAT, 293 | }) 294 | 295 | 296 | validation_hook = ann_h.ValidationRunHook( 297 | step_increment=BATCHES_IN_TRAINING_EPOCH, 298 | estimator=the_estimator, 299 | input_fn_creator=lambda: lambda : lower_diag_score_comparison_input_fn( 300 | VALIDATION_FILENAME_PATTERN, 301 | VALIDATION_BATCH_SIZE, 302 | include_unoccupied=NUM_INPUT_FILTERS == 16, 303 | num_things_to_prefetch=5, 304 | num_things_in_parallel=12, 305 | data_format=DATA_FORMAT, 306 | ), 307 | temp_num_steps_in_epoch=BATCHES_IN_VALIDATION_EPOCH) 308 | 309 | the_estimator.train( 310 | input_fn=lambda : lower_diag_score_comparison_input_fn( 311 | TRAINING_FILENAME_PATTERN, 312 | TRAINING_BATCH_SIZE, 313 | shuffle_buffer_size=TRAINING_SHUFFLE_BUFFER_SIZE, 314 | include_unoccupied=NUM_INPUT_FILTERS == 16, 315 | num_things_in_parallel=12, 316 | num_things_to_prefetch=36, 317 | data_format=DATA_FORMAT, 318 | shuffle_seed=12312312, 319 | ), 320 | hooks=[validation_hook], 321 | # max_steps=1, 322 | ) 323 | 324 | # Save the model for inference 325 | the_estimator.export_savedmodel(SAVE_MODEL_DIR, board_eval_serving_input_receiver()) 326 | 327 | 328 | 329 | 330 | if __name__ == "__main__": 331 | tf.app.run() 332 | -------------------------------------------------------------------------------- /batch_first/anns/move_evaluation_ann.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | 3 | from scipy.stats import kendalltau, weightedtau, spearmanr 4 | 5 | import batch_first.anns.ann_creation_helper as ann_h 6 | 7 | tf.logging.set_verbosity(tf.logging.INFO) 8 | 9 | 10 | def lower_diag_policy_comparison_model_fn(features, labels, mode, params): 11 | """ 12 | Generates an EstimatorSpec for a model which scores pairs of chess boards and moves. It learns by maximizing the 13 | difference between the board/move paris, where one is intended to be greater than the other based on 14 | some pre-calculated scoring system (e.g. StockFish evaluations). 15 | 16 | The value should be the value of the board after the given move has been made. 17 | """ 18 | convolutional_module_outputs = ann_h.create_input_convolutions_shared_weights( 19 | features['board'], 20 | params['kernel_initializer'], 21 | params['data_format'], 22 | mode, 23 | num_unique_filters=[32, 20, 20, 18, 18, 16, 24, 24]) #236 with the 64 undilated included 24 | 25 | if len(params['convolutional_modules']): 26 | convolutional_module_outputs = ann_h.build_convolutional_modules( 27 | convolutional_module_outputs, 28 | params['convolutional_modules'], 29 | mode, 30 | params['kernel_initializer'], 31 | params['kernel_regularizer'], 32 | params['trainable_cnn_modules'], 33 | num_previous_modules=1, 34 | data_format=params['data_format']) 35 | 36 | original_logits = tf.layers.conv2d( 37 | inputs=convolutional_module_outputs, 38 | filters=params['num_logit_filters'], 39 | kernel_size=1, 40 | padding="valid", 41 | data_format="channels_last" if params['data_format']=="NHWC" else "channels_first", 42 | use_bias=False, 43 | kernel_initializer=params['kernel_initializer'](), 44 | kernel_regularizer=params['kernel_regularizer'](), 45 | name="logit_layer") 46 | 47 | 48 | lookup_str = "move_to_square" if params['num_logit_filters']==64 else "move_filter" 49 | if params['data_format'] == "NHWC": 50 | new_logit_shape = [-1, 64, params['num_logit_filters']] 51 | first_square = "move_from_square" 52 | second_square = lookup_str 53 | else: 54 | new_logit_shape = [-1, params['num_logit_filters'], 64] 55 | first_square = lookup_str 56 | second_square = "move_from_square" 57 | 58 | 59 | move_reshaped_logits = tf.reshape(original_logits, new_logit_shape) 60 | 61 | if mode == tf.estimator.ModeKeys.PREDICT: 62 | range_repeater = ann_h.numpy_style_repeat_1d_creator(out_type=tf.int64) 63 | board_indices = range_repeater(features['moves_per_board']) 64 | else: 65 | num_moves = tf.shape(features['move_from_square'])[0] 66 | board_indices = tf.range(num_moves, dtype=tf.int32) 67 | 68 | indices_to_gather = tf.stack([ 69 | board_indices, 70 | tf.cast(features[first_square], dtype=board_indices.dtype), 71 | tf.cast(features[second_square], dtype=board_indices.dtype)], axis=1) 72 | 73 | logits = tf.gather_nd(move_reshaped_logits, indices_to_gather, name="requested_move_scores") 74 | 75 | 76 | loss = None 77 | train_op = None 78 | 79 | # Calculate loss 80 | if mode != tf.estimator.ModeKeys.PREDICT: 81 | with tf.variable_scope("loss"): 82 | calculated_diff_matrix = ann_h.vec_and_transpose_op(logits, tf.subtract) 83 | label_matrix = features['label_matrix'] 84 | weight_matrix = features['weight_matrix'] 85 | 86 | loss = tf.losses.sigmoid_cross_entropy(label_matrix, calculated_diff_matrix, weights=weight_matrix) 87 | loss_summary = tf.summary.scalar("loss", loss) 88 | 89 | 90 | # Configure the Training Op 91 | if mode == tf.estimator.ModeKeys.TRAIN: 92 | global_step = tf.train.get_global_step() 93 | learning_rate = params['learning_decay_function'](global_step) 94 | tf.summary.scalar("learning_rate", learning_rate) 95 | train_op = tf.contrib.layers.optimize_loss( 96 | loss=loss, 97 | global_step=global_step, 98 | learning_rate=learning_rate, 99 | optimizer=params['optimizer'], 100 | summaries=params['train_summaries']) 101 | 102 | predictions = {"scores" : logits} 103 | the_export_outputs = {"serving_default" : tf.estimator.export.RegressionOutput(value=logits)} 104 | 105 | validation_metrics = None 106 | training_hooks = [] 107 | 108 | # Create the metrics 109 | if mode == tf.estimator.ModeKeys.TRAIN: 110 | tau_a = ann_h.kendall_rank_correlation_coefficient(logits, features['score']) 111 | 112 | to_create_metric_dict = { 113 | "loss/loss": (loss, loss_summary), 114 | "metrics/mean_evaluation_value" : logits, 115 | "metrics/mean_abs_evaluation_value": tf.abs(logits), 116 | "metrics/kendall_tau-a" : tau_a, 117 | } 118 | 119 | validation_metrics = ann_h.metric_dict_creator(to_create_metric_dict) 120 | 121 | tf.contrib.layers.summarize_tensors(tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)) 122 | training_hooks.append( 123 | tf.train.SummarySaverHook( 124 | save_steps=params['log_interval'], 125 | output_dir=params['model_dir'], 126 | summary_op=tf.summary.merge_all())) 127 | 128 | elif mode == tf.estimator.ModeKeys.EVAL: 129 | the_logits, update1 = tf.contrib.metrics.streaming_concat(logits) 130 | the_labels, update2 = tf.contrib.metrics.streaming_concat(features['score']) 131 | 132 | update = tf.group(update1, update2) 133 | 134 | scipy_rank_coef_creator = ann_h.py_func_scipy_rank_helper_creator(the_logits, the_labels) 135 | 136 | tau_b, tau_b_p_value = scipy_rank_coef_creator(kendalltau) 137 | weighted_tau_b, weighted_tau_b_p_value = scipy_rank_coef_creator(weightedtau) 138 | rho, rho_p_value = scipy_rank_coef_creator(spearmanr) 139 | 140 | validation_metrics = { 141 | "metrics/mean_evaluation_value" : tf.metrics.mean(logits), 142 | "metrics/mean_abs_evaluation_value" : tf.metrics.mean(tf.abs(logits)), 143 | "metrics/kendall_tau-b": (tau_b, update), 144 | "metrics/kendall_tau-b_p_value": (tau_b_p_value, update), 145 | "metrics/weighted_kendall_tau-b": (weighted_tau_b, update), 146 | "metrics/weighted_kendall_tau-b_p_value": (weighted_tau_b_p_value, update), 147 | "metrics/spearman_rho": (rho, update), 148 | "metrics/spearman_rho_p_value": (rho_p_value, update), 149 | } 150 | 151 | return tf.estimator.EstimatorSpec( 152 | mode=mode, 153 | predictions=predictions, 154 | loss=loss, 155 | train_op=train_op, 156 | training_hooks=training_hooks, 157 | export_outputs=the_export_outputs, 158 | eval_metric_ops=validation_metrics) 159 | 160 | 161 | def simpler_lower_diag_score_comparison_input_fn(filename_pattern, batch_size, include_unoccupied=True, shuffle_buffer_size=None, 162 | num_things_in_parallel=None, num_things_to_prefetch=None, shuffle_seed=None, 163 | data_format="NHWC"): 164 | if num_things_to_prefetch is None: 165 | num_things_to_prefetch = tf.contrib.data.AUTOTUNE #IMPORTANT NOTE: This seems to make the program crash after a few iterations (at least it does on my computer) 166 | 167 | dataset = tf.data.TFRecordDataset(filename_pattern) 168 | 169 | if shuffle_buffer_size: 170 | dataset = dataset.apply(tf.contrib.data.shuffle_and_repeat(shuffle_buffer_size,seed=shuffle_seed)) 171 | 172 | dataset = dataset.batch(batch_size, drop_remainder=True) 173 | 174 | def process_batch(records): 175 | keys_to_features = {"board": tf.FixedLenFeature([8 * 8], tf.int64), 176 | "score": tf.FixedLenFeature([], tf.int64), 177 | "move_from_square": tf.FixedLenFeature([], tf.int64), 178 | "move_to_square": tf.FixedLenFeature([], tf.int64), 179 | "move_filter": tf.FixedLenFeature([], tf.int64)} 180 | 181 | parsed_examples = tf.parse_example(records, keys_to_features) 182 | 183 | reshaped_boards = tf.reshape(parsed_examples['board'], [-1, 8, 8]) 184 | 185 | omit_unoccupied_decrement = 0 if include_unoccupied else 1 186 | boards = tf.one_hot( 187 | reshaped_boards - omit_unoccupied_decrement, 188 | 16 - omit_unoccupied_decrement, 189 | axis=-1 if data_format=="NHWC" else 1) 190 | 191 | desired_diff_matrix = ann_h.vec_and_transpose_op(parsed_examples['score'], tf.subtract, tf.float32) 192 | 193 | lower_diag_diff_matrix = tf.matrix_band_part(desired_diff_matrix, -1, 0) 194 | 195 | lower_diag_sign = tf.sign(lower_diag_diff_matrix) 196 | weight_mask = tf.abs(lower_diag_sign) 197 | # bool_weight_mask = tf.cast(weight_mask, tf.bool) 198 | # 199 | # value_larger_than_centipawn_less_than_mate = 100000 200 | # desired_found_mate = tf.greater(tf.abs(parsed_examples['score']), value_larger_than_centipawn_less_than_mate) 201 | # 202 | # both_found_mate = ann_h.vec_and_transpose_op(desired_found_mate, tf.logical_and) 203 | # 204 | # desired_signs = tf.sign(parsed_examples['score']) 205 | # 206 | # same_sign_matrix = ann_h.vec_and_transpose_op(desired_signs, tf.equal) 207 | # 208 | # both_same_player_mates = tf.logical_and(both_found_mate, same_sign_matrix) 209 | # 210 | # both_same_mate_and_nonzero_weight = tf.logical_and(both_same_player_mates, bool_weight_mask) 211 | # 212 | # same_mate_depth_diff_decrement = .95 213 | # weight_helper = same_mate_depth_diff_decrement * tf.cast(both_same_mate_and_nonzero_weight, tf.float32) 214 | # 215 | # mate_adjusted_weight_mask = weight_mask - weight_helper 216 | 217 | label_matrix = (lower_diag_sign + weight_mask)/2 218 | 219 | # return (boards, parsed_examples['score'], label_matrix, mate_adjusted_weight_mask, 220 | # parsed_examples['move_filter'], parsed_examples['move_to_square'], parsed_examples['move_filter']) 221 | 222 | return (boards, parsed_examples['score'], label_matrix, weight_mask, 223 | parsed_examples['move_filter'], parsed_examples['move_to_square'], parsed_examples['move_filter']) 224 | 225 | 226 | dataset = dataset.map(process_batch, num_parallel_calls=num_things_in_parallel) 227 | 228 | dataset = dataset.apply(tf.contrib.data.prefetch_to_device('/gpu:0', buffer_size=num_things_to_prefetch)) 229 | 230 | iterator = dataset.make_one_shot_iterator() 231 | 232 | features = iterator.get_next() 233 | 234 | feature_names = ["board", "score", "label_matrix", "weight_matrix", "move_from_square", "move_to_square", "move_filter"] 235 | 236 | feature_dict = dict(zip(feature_names, features)) 237 | return feature_dict, None 238 | 239 | 240 | def move_scoring_serving_input_receiver(data_format="NCHW"): 241 | def fn_to_return(): 242 | placeholder_shape = [None, 15, 8, 8] if data_format == "NCHW" else [None, 8, 8, 15] 243 | for_remapping = tf.placeholder(tf.float32, placeholder_shape, "FOR_INPUT_MAPPING_transpose") 244 | 245 | moves_per_board = tf.placeholder(tf.uint8, shape=[None], name="moves_per_board_placeholder") 246 | from_squares = tf.placeholder(tf.uint8, shape=[None], name="from_square_placeholder") 247 | move_filters = tf.placeholder(tf.uint8, shape=[None], name="move_filter_placeholder") 248 | 249 | receiver_tensors = { 250 | "board": for_remapping, 251 | "move_from_square": from_squares, 252 | "move_filter": move_filters, 253 | "moves_per_board": moves_per_board, 254 | } 255 | 256 | return tf.estimator.export.ServingInputReceiver(receiver_tensors, receiver_tensors) 257 | return fn_to_return 258 | 259 | 260 | 261 | 262 | def main(unused_par): 263 | SAVE_MODEL_DIR = "/srv/tmp/diag_move_loss_314/pre_commit_test_1" 264 | TRAINING_FILENAME_PATTERN = "/srv/databases/lichess_just_move_scoring_fixed_ag_promotion/lichess_training.tfrecords" 265 | VALIDATION_FILENAME_PATTERN = "/srv/databases/lichess_just_move_scoring_fixed_ag_promotion/lichess_validation.tfrecords" 266 | TRAIN_OP_SUMMARIES = ["gradient_norm", "gradients"] 267 | NUM_INPUT_FILTERS = 15 268 | OPTIMIZER = 'Adam' 269 | TRAINING_SHUFFLE_BUFFER_SIZE = 17100000 270 | TRAINING_BATCH_SIZE = 512 #The effective batch size used for the loss = n(n-1)/2 (where n is the number of boards in the batch) 271 | VALIDATION_BATCH_SIZE = 1024 272 | LOG_ITERATION_INTERVAL = 2500 273 | LEARNING_RATE = 5e-3 274 | KERNEL_REGULARIZER = lambda: None 275 | KERNEL_INITIALIZER = lambda: tf.contrib.layers.variance_scaling_initializer() 276 | TRAINABLE_CNN_MODULES = True 277 | DATA_FORMAT = "NCHW" 278 | 279 | 280 | NUM_LOGIT_FILTERS = 73 #64 281 | 282 | num_examples_in_training_file = 17106078 283 | num_examples_in_validation_file = 2012480 284 | 285 | BATCHES_IN_TRAINING_EPOCH = num_examples_in_training_file // TRAINING_BATCH_SIZE 286 | BATCHES_IN_VALIDATION_EPOCH = num_examples_in_validation_file // VALIDATION_BATCH_SIZE 287 | 288 | learning_decay_function = lambda gs: LEARNING_RATE 289 | 290 | 291 | CONVOLUTIONAL_MODULES = [[[[512, 1], [128, 1]] + 6 * [[32, 3]]]] 292 | 293 | # Create the Estimator 294 | the_estimator = tf.estimator.Estimator( 295 | model_fn=lower_diag_policy_comparison_model_fn, 296 | model_dir=SAVE_MODEL_DIR, 297 | config=tf.estimator.RunConfig().replace( 298 | save_checkpoints_steps=LOG_ITERATION_INTERVAL, 299 | save_summary_steps=LOG_ITERATION_INTERVAL), 300 | params={ 301 | "optimizer": OPTIMIZER, 302 | "log_interval": LOG_ITERATION_INTERVAL, 303 | "model_dir": SAVE_MODEL_DIR, 304 | "convolutional_modules" : CONVOLUTIONAL_MODULES, 305 | "learning_rate": LEARNING_RATE, 306 | "train_summaries": TRAIN_OP_SUMMARIES, 307 | "learning_decay_function" : learning_decay_function, 308 | "num_input_filters" : NUM_INPUT_FILTERS, 309 | "kernel_initializer" : KERNEL_INITIALIZER, 310 | "kernel_regularizer" : KERNEL_REGULARIZER, 311 | "trainable_cnn_modules" : TRAINABLE_CNN_MODULES, 312 | "data_format" : DATA_FORMAT, 313 | "num_logit_filters" : NUM_LOGIT_FILTERS, 314 | }) 315 | 316 | 317 | validation_hook = ann_h.ValidationRunHook( 318 | step_increment=BATCHES_IN_TRAINING_EPOCH//2, 319 | estimator=the_estimator, 320 | input_fn_creator=lambda: lambda : simpler_lower_diag_score_comparison_input_fn( 321 | VALIDATION_FILENAME_PATTERN, 322 | VALIDATION_BATCH_SIZE, 323 | include_unoccupied=NUM_INPUT_FILTERS == 16, 324 | num_things_to_prefetch=1, 325 | num_things_in_parallel=12, 326 | data_format=DATA_FORMAT), 327 | temp_num_steps_in_epoch=BATCHES_IN_VALIDATION_EPOCH) 328 | 329 | the_estimator.train( 330 | input_fn=lambda : simpler_lower_diag_score_comparison_input_fn( 331 | TRAINING_FILENAME_PATTERN, 332 | TRAINING_BATCH_SIZE, 333 | shuffle_buffer_size=TRAINING_SHUFFLE_BUFFER_SIZE, 334 | include_unoccupied=NUM_INPUT_FILTERS == 16, 335 | num_things_in_parallel=12, 336 | num_things_to_prefetch=1, 337 | data_format=DATA_FORMAT), 338 | hooks=[validation_hook], 339 | # max_steps=1, 340 | ) 341 | 342 | # Save the model for inference 343 | the_estimator.export_savedmodel(SAVE_MODEL_DIR, move_scoring_serving_input_receiver()) 344 | 345 | 346 | 347 | 348 | 349 | if __name__ == "__main__": 350 | tf.app.run() 351 | 352 | 353 | 354 | -------------------------------------------------------------------------------- /batch_first/chestimator.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | 3 | from google.protobuf import text_format 4 | from tensorflow.python.platform import gfile 5 | 6 | from tensorflow.contrib import tensorrt as trt 7 | 8 | 9 | 10 | def get_predictors(session, graphdef_filename, eval_output_tensor, move_output_stages_tensor_names, move_input_tensor_names, eval_input_tensor_names): 11 | """ 12 | All ANN interactions should be called through C/C++ functions for speed (hopefully will be addressed soon) 13 | """ 14 | if graphdef_filename[-3:] == ".pb": 15 | with gfile.FastGFile(graphdef_filename, 'rb') as f: 16 | model_graph_def = tf.GraphDef() 17 | model_graph_def.ParseFromString(f.read()) 18 | else: 19 | with open(graphdef_filename, 'r') as f: 20 | txt = f.read() 21 | model_graph_def = text_format.Parse(txt, tf.GraphDef()) 22 | 23 | desired_tensors = tf.import_graph_def( 24 | model_graph_def, 25 | return_elements=[eval_output_tensor] + move_output_stages_tensor_names + move_input_tensor_names + eval_input_tensor_names, 26 | name="") 27 | 28 | eval_output = desired_tensors[0] 29 | move_outputs = desired_tensors[1:len(move_output_stages_tensor_names) + 1] 30 | move_inputs = desired_tensors[len(move_output_stages_tensor_names) + 1:-len(eval_input_tensor_names)] 31 | eval_inputs = desired_tensors[-len(eval_input_tensor_names):] 32 | 33 | with tf.device('/GPU:0'): 34 | with tf.control_dependencies([move_outputs[0]]): 35 | dummy_operation = tf.constant([0], dtype=tf.float32, name="dummy_const") 36 | 37 | 38 | board_predictor = session.make_callable(eval_output_tensor, eval_input_tensor_names) 39 | 40 | def start_move_prediction(*board_inputs): 41 | handle = session.partial_run_setup([dummy_operation, move_outputs[1]], eval_inputs + move_inputs) 42 | session.partial_run(handle, dummy_operation, dict(zip(eval_inputs, board_inputs))) 43 | 44 | return lambda move_info: session.partial_run(handle, 45 | move_outputs[1], 46 | dict(zip(move_inputs[-3:], move_info))) 47 | 48 | return board_predictor, start_move_prediction 49 | 50 | 51 | def get_inference_functions(graphdef_filename, session_gpu_memory=.4): 52 | sess = tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=session_gpu_memory))) 53 | 54 | path_adder = lambda p, l : list(map(lambda st : "%s/%s"%(p, st), l)) 55 | eval_output_tensor_name = "value_network/Squeeze:0" 56 | eval_input_tensor_names = ["piece_filters:0", "occupied_bbs:0"] 57 | 58 | move_scoring_stages_names = ["Reshape", "requested_move_scores:0"] 59 | 60 | move_scoring_input_tensor_names = ["from_square_placeholder:0", "move_filter_placeholder:0", "moves_per_board_placeholder:0"] 61 | 62 | eval_input_tensor_names = path_adder("input_parser", eval_input_tensor_names) 63 | 64 | move_scoring_stages_names = path_adder("policy_network", move_scoring_stages_names) 65 | move_scoring_input_tensor_names = path_adder("policy_network", move_scoring_input_tensor_names) 66 | 67 | predictors = get_predictors( 68 | sess, 69 | graphdef_filename, 70 | eval_output_tensor_name, move_scoring_stages_names, move_scoring_input_tensor_names, eval_input_tensor_names) 71 | 72 | closer_fn = lambda: sess.close() 73 | 74 | return predictors[0], predictors[1], closer_fn 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /batch_first/classes_and_structs.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | from . import * 4 | 5 | 6 | 7 | numpy_node_info_dtype = np.dtype( 8 | [("pawns", np.uint64), 9 | ("knights", np.uint64), 10 | ("bishops", np.uint64), 11 | ("rooks", np.uint64), 12 | ("queens", np.uint64), 13 | ("kings", np.uint64), 14 | ("occupied_co", np.uint64, (2)), 15 | ("occupied", np.uint64), 16 | ("turn", np.int8), 17 | ("castling_rights", np.uint64), 18 | ("ep_square", np.uint8), 19 | ("halfmove_clock", np.uint8), 20 | ("hash", np.uint64), 21 | ("terminated", np.bool_), 22 | ("separator", np.float32), 23 | ("depth", np.uint8), 24 | ("best_value", np.float32), 25 | ("unexplored_moves", np.uint8, (MAX_MOVES_LOOKED_AT, 3)), 26 | ("unexplored_move_scores", np.float32, (MAX_MOVES_LOOKED_AT)), 27 | ('prev_move', np.uint8, (3)), 28 | ("next_move_index", np.uint8), 29 | ("children_left", np.uint8)]) 30 | 31 | 32 | numba_node_info_type = nb.from_dtype(numpy_node_info_dtype) 33 | 34 | 35 | def create_node_info_from_python_chess_board(board, depth=255, separator=0): 36 | return np.array( 37 | [(board.pawns, 38 | board.knights, 39 | board.bishops, 40 | board.rooks,board.queens, 41 | board.kings, 42 | board.occupied_co, 43 | board.occupied, 44 | np.int8(board.turn), 45 | board.castling_rights, 46 | board.ep_square if not board.ep_square is None else NO_EP_SQUARE, 47 | board.halfmove_clock, 48 | zobrist_hash(board), 49 | False, # terminated 50 | separator, 51 | depth, 52 | MIN_FLOAT32_VAL, # best_value 53 | np.full([MAX_MOVES_LOOKED_AT, 3], 255, dtype=np.uint8), # unexplored moves 54 | np.full([MAX_MOVES_LOOKED_AT], MIN_FLOAT32_VAL, dtype=np.float32), # unexplored move scores 55 | np.full([3], 255, dtype=np.uint8), # The move made to reach the position this board represents 56 | 0, # next_move_index (the index in the stored moves where the next move to make is) 57 | 0)], # children_left (the number of children which have yet to returne a value, or be created) 58 | dtype=numpy_node_info_dtype) 59 | 60 | 61 | def create_node_info_from_fen(fen, depth, separator): 62 | return create_node_info_from_python_chess_board(chess.Board(fen), depth, separator) 63 | 64 | 65 | 66 | game_node_type = nb.deferred_type() 67 | 68 | gamenode_spec = OrderedDict() 69 | 70 | gamenode_spec["board_struct"] = numba_node_info_type[:] 71 | gamenode_spec["parent"] = nb.optional(game_node_type) 72 | 73 | 74 | 75 | 76 | @nb.jitclass(gamenode_spec) 77 | class GameNode: 78 | def __init__(self, board_struct, parent): 79 | self.board_struct = board_struct 80 | 81 | # Eventually this should be some sort of list, so that updating multiple parents is possible 82 | # when handling transpositions which are open at the same time. 83 | self.parent = parent 84 | 85 | @property 86 | def struct(self): 87 | return self.board_struct[0] 88 | 89 | 90 | game_node_type.define(GameNode.class_type.instance_type) 91 | 92 | 93 | 94 | game_node_holder_type = nb.deferred_type() 95 | 96 | game_node_holder_spec = OrderedDict() 97 | 98 | game_node_holder_spec["held_node"] = GameNode.class_type.instance_type 99 | game_node_holder_spec["next_holder"] = nb.optional(game_node_holder_type) 100 | 101 | @nb.jitclass(game_node_holder_spec) 102 | class GameNodeHolder: 103 | """ 104 | A jitclass used for representing a linked list of GameNode objects. (this is mainly used for compilation purposes) 105 | 106 | NOTES: 107 | 1) This shouldn't be needed at all and a 'next' SOMETHING should just be added to the GameNode class, but 108 | Numba won't let that happen (yet) 109 | """ 110 | def __init__(self, held_node, next_holder): 111 | self.held_node = held_node 112 | self.next_holder = next_holder 113 | 114 | @property 115 | def struct(self): 116 | return self.held_node.struct 117 | 118 | game_node_holder_type.define(GameNodeHolder.class_type.instance_type) 119 | 120 | 121 | 122 | game_node_holder_holder_type = nb.deferred_type() 123 | 124 | game_node_holder_holder_spec = OrderedDict() 125 | 126 | game_node_holder_holder_spec["held"] = GameNodeHolder.class_type.instance_type 127 | game_node_holder_holder_spec["next"] = nb.optional(game_node_holder_holder_type) 128 | 129 | @nb.jitclass(game_node_holder_holder_spec) 130 | class GameNodeHolderHolder: 131 | """ 132 | This is a temporary class used to avoid the time required for Numba's boxing and unboxing when using Lists of 133 | JitClass objects. It will be removed when more JIT coverage allows. 134 | 135 | """ 136 | def __init__(self, held, next): 137 | self.held = held 138 | self.next = next 139 | 140 | game_node_holder_holder_type.define(GameNodeHolderHolder.class_type.instance_type) 141 | 142 | 143 | 144 | @njit 145 | def get_list_from_holder_holder(holder): 146 | to_return = [] 147 | while not holder is None: 148 | to_return.append(holder.held) 149 | holder = holder.next 150 | return to_return 151 | 152 | @njit 153 | def get_holder_holder_from_list(lst): 154 | next_holder = None 155 | for sub_holder in lst[::-1]: 156 | next_holder = GameNodeHolderHolder(sub_holder, next_holder) 157 | return next_holder 158 | 159 | @njit 160 | def clear_holder_holder(holder): 161 | dummy_sub_holder = create_dummy_node_holder() 162 | while not holder is None: 163 | holder.held = dummy_sub_holder 164 | holder = holder.next 165 | 166 | 167 | 168 | @njit 169 | def len_node_holder(ll): 170 | count = 0 171 | while not ll is None: 172 | count += 1 173 | ll = ll.next_holder 174 | return count 175 | 176 | 177 | @njit 178 | def create_dummy_node_holder(): 179 | return GameNodeHolder(GameNode(np.empty(1, numpy_node_info_dtype), None), None) 180 | 181 | 182 | @njit 183 | def filter_holders_then_append(root, holder, mask, append_to_end): 184 | if holder is None: 185 | root.next_holder = append_to_end 186 | return 0 187 | 188 | root.next_holder = holder 189 | 190 | holder = root 191 | mask_index = 0 192 | total_kept = 0 193 | while not holder.next_holder is None: 194 | if mask[mask_index]: 195 | holder = holder.next_holder 196 | total_kept += 1 197 | else: 198 | holder.next_holder = holder.next_holder.next_holder 199 | mask_index += 1 200 | 201 | holder.next_holder = append_to_end 202 | return total_kept 203 | -------------------------------------------------------------------------------- /batch_first/engine.py: -------------------------------------------------------------------------------- 1 | from . import * 2 | 3 | from .transposition_table import get_empty_hash_table, clear_hash_table 4 | from .numba_negamax_zero_window import iterative_deepening_mtd_f, start_move_scoring, start_board_evaluations 5 | from .global_open_priority_nodes import PriorityBins 6 | 7 | 8 | 9 | def generate_bin_ranges(filename, move_eval_fn, percentiles=None, max_batch_size=1000, output_filename=None, print_info=False): 10 | """ 11 | Generate values representing the boundaries for the bins in the PriorityBins class based on a given 12 | move evaluation function. It also calculates the mean (zero-shift) for the move values. 13 | 14 | :param filename: The filename for the binary file (in NumPy .npy format) containing board structs. 15 | It's used for computing a sample of move scores 16 | :param move_eval_fn: The move evaluation function to be used when searching the tree 17 | :param percentiles: The percentiles desired from the sample of move scores computed 18 | :param max_batch_size: The maximum batch size to be given to the move_eval_fn 19 | :param output_filename: The filename to save the computed bins to, or None if saving the bins is not desired 20 | :param print_info: A boolean value indicating if info about the computations should be printed 21 | :return: An ndarray of the values at the given percentiles 22 | """ 23 | def bin_helper_move_scoring_fn(struct_array): 24 | move_thread, move_score_getter, _, _ = start_move_scoring( 25 | struct_array, 26 | struct_array[:1], 27 | np.ones(len(struct_array), dtype=np.bool_), 28 | np.zeros(1, dtype=np.bool_), 29 | move_eval_fn) 30 | 31 | to_concat_from_squares = [] 32 | to_concat_filters = [] 33 | 34 | for struct in struct_array: 35 | relevant_moves = struct['unexplored_moves'][:struct['children_left']] 36 | 37 | if not struct['turn']: 38 | relevant_moves[:,:2] = SQUARES_180[relevant_moves[:,:2]] 39 | 40 | to_concat_filters.append(MOVE_FILTER_LOOKUP[relevant_moves[:, 0], relevant_moves[:, 1], relevant_moves[:, 2]]) 41 | to_concat_from_squares.append(relevant_moves[:,0]) 42 | 43 | move_filters = np.concatenate(to_concat_filters) 44 | from_squares = np.concatenate(to_concat_from_squares) 45 | 46 | 47 | move_thread.join() 48 | 49 | to_return = move_score_getter[0]([move_filters, from_squares, struct_array['children_left']]) 50 | 51 | return to_return 52 | 53 | 54 | if percentiles is None: 55 | percentiles = np.arange(0, 100, .02) 56 | 57 | if print_info: 58 | print("Loading data from file for bin calculations") 59 | 60 | struct_array = np.load(filename) 61 | 62 | if print_info: 63 | print("Loaded %d BoardInfo structs"%len(struct_array)) 64 | 65 | 66 | increment = max_batch_size 67 | struct_array = struct_array[:- (len(struct_array) % increment)] 68 | 69 | combined_results = np.concatenate( 70 | [bin_helper_move_scoring_fn(struct_array[j * increment:(j + 1) * increment]) for j in range((len(struct_array)-1)//increment)]) 71 | 72 | zero_shift = np.mean(combined_results) 73 | 74 | combined_results -= zero_shift 75 | combined_results = np.abs(combined_results) 76 | 77 | if print_info: 78 | print("Computed %d move evaluations"%len(combined_results)) 79 | 80 | bins = np.percentile(combined_results, percentiles) 81 | 82 | if not output_filename is None: 83 | np.save(output_filename, bins) 84 | np.save(output_filename + "_shift", zero_shift) 85 | 86 | if print_info: 87 | print("Saved bins to file") 88 | 89 | return bins, zero_shift 90 | 91 | 92 | def calculate_eval_zero_shift(filename, board_eval_fn, max_batch_size=5000, output_filename="draw_board_mean", print_info=False): 93 | """ 94 | Calculates the mean evaluation value of boards which have the 'expected' value of 0 (currently decided by StockFish). 95 | The calculated mean can then be used to shift the evaluation function so that it values tie games 96 | at 0 (the new evaluation is calculated: f'(x)=f(x)-mean). 97 | 98 | Zero-shifting the evaluation function is crucial since negamax is used rather than minimax, and because 99 | it maintains the accuracy of the stored draw value. 100 | 101 | 102 | :param filename: The filename for the binary file (in NumPy .npy format) containing board structs which each 103 | have a 'desired' value of 0 (according to StockFish). 104 | It's used for computing a sample of move scores 105 | :param board_eval_fn: The board evaluation function to be used when searching the tree 106 | :param max_batch_size: The maximum batch size to be given to the board_eval_fn 107 | :param output_filename: The filename to save the computed bins to, or None if saving the bins is not desired 108 | :param print_info: A boolean value indicating if info about the computations should be printed 109 | :return: The mean evaluation value 110 | """ 111 | def eval_helper(struct_array): 112 | thread, scores = start_board_evaluations( 113 | struct_array, 114 | np.ones(len(struct_array), dtype=np.bool_), 115 | board_eval_fn) 116 | 117 | thread.join() 118 | 119 | return scores 120 | 121 | if print_info: 122 | print("Loading data from file for zero-shift calculations") 123 | 124 | struct_array = np.load(filename) 125 | 126 | if print_info: 127 | print("Loaded %d BoardInfo structs"%len(struct_array)) 128 | 129 | struct_array = struct_array[:- (len(struct_array) % max_batch_size)] 130 | 131 | num_batches = (len(struct_array)-1)//max_batch_size 132 | 133 | combined_results = np.concatenate( 134 | [eval_helper( 135 | struct_array[j * max_batch_size:(j + 1) * max_batch_size]) for j in range(num_batches)]) 136 | 137 | if print_info: 138 | print("Computed %d board evaluations"%len(combined_results)) 139 | 140 | mean = np.float32(np.mean(combined_results)) 141 | 142 | if print_info: 143 | print("The mean calculated board evaluation value is: %f"%mean) 144 | 145 | if not output_filename is None: 146 | np.save(output_filename, mean) 147 | 148 | if print_info: 149 | print("Saved mean to file") 150 | 151 | return mean 152 | 153 | 154 | def get_previous_board_map_from_py_board(board): 155 | """ 156 | SPEED IMPROVEMENTS TO MAKE: 157 | 1) Stop going backward if castling rights are changed 158 | 2) Stop using the python-chess board implementation 159 | 3) Stop using a dictionary so it can be JIT compiled 160 | """ 161 | board = board.copy() #Just in case the board shouldn't be modified 162 | 163 | hash_dict = {zobrist_hash(board):1} 164 | 165 | while board.move_stack and board.halfmove_clock: 166 | board.pop() 167 | 168 | cur_hash = np.int64(np.uint64(zobrist_hash(board))) 169 | if cur_hash in hash_dict: 170 | hash_dict[cur_hash] += 1 171 | else: 172 | hash_dict[cur_hash] = 1 173 | 174 | to_pass_on = np.array(list(zip(*hash_dict.items())), dtype=np.uint64) 175 | 176 | return to_pass_on[:, np.argsort(to_pass_on[0])] 177 | 178 | 179 | 180 | 181 | class ChessEngine(object): 182 | 183 | def pick_move(self, Board): 184 | """ 185 | Given a Python-Chess Board object, return a Python-Chess Move object representing the move 186 | the engine would like to make. 187 | """ 188 | raise NotImplementedError("This method must be implemented!") 189 | 190 | def start_new_game(self): 191 | """ 192 | Run at the start of each new game 193 | """ 194 | pass 195 | 196 | def ready_engine(self): 197 | """ 198 | Set up whatever is needed to choose a move (used if resources must be released after each move). 199 | """ 200 | pass 201 | 202 | def release_resources(self): 203 | """ 204 | Release the resources currently used by the engine (like GPU memory or large chunks of RAM). 205 | """ 206 | pass 207 | 208 | 209 | 210 | 211 | class BatchFirstEngine(ChessEngine): 212 | 213 | def __init__(self, search_depth, board_eval_fn, move_eval_fn, bin_database_file=None, bin_output_filename=None, 214 | first_guess_fn=None, max_batch_size=5000, zero_valued_boards_file=None, saved_zero_shift_file=None): 215 | """ 216 | :param bin_database_file: If bin_output_filename is not None, then this is the NumPy database of boards to have 217 | bins be created from. If bin_output_filename is None, then this is the NumPy file containing an array of bins. 218 | :param bin_output_filename: The name of the (NumPy) file which will be saved containing the bins computed, or None 219 | if the bins should not be saved. 220 | """ 221 | if saved_zero_shift_file is None and zero_valued_boards_file is None: 222 | raise ValueError("Either saved_zero_shift_file or zero_valued_boards_file must be specified, but both are None!") 223 | 224 | if bin_database_file is None and bin_output_filename is None: 225 | raise ValueError("Either bin_database_file or bin_output_filename must be specified but both are None!") 226 | 227 | 228 | if first_guess_fn is None: 229 | self.first_guess_fn = lambda x : 0 230 | else: 231 | self.first_guess_fn = first_guess_fn 232 | 233 | self.search_depth = search_depth 234 | 235 | self.board_evaluator = board_eval_fn 236 | self.move_evaluator = move_eval_fn 237 | 238 | if bin_output_filename is None: 239 | self.bins = np.load(bin_database_file) 240 | move_zero_shift = np.load(bin_database_file[:-4] + "_shift.npy") 241 | else: 242 | self.bins, move_zero_shift = generate_bin_ranges( 243 | bin_database_file, 244 | self.move_evaluator, 245 | max_batch_size=int(1.25*max_batch_size), 246 | output_filename=bin_output_filename, 247 | print_info=True) 248 | 249 | 250 | if zero_valued_boards_file is None: 251 | zero_shift = np.load(saved_zero_shift_file) 252 | else: 253 | zero_shift = calculate_eval_zero_shift( 254 | zero_valued_boards_file, 255 | self.board_evaluator, 256 | max_batch_size=int(1.25*max_batch_size), 257 | output_filename=saved_zero_shift_file, 258 | print_info=True) 259 | 260 | self.board_evaluator = lambda *args : board_eval_fn(*args) - zero_shift 261 | 262 | self.open_node_holder = PriorityBins( 263 | self.bins, 264 | max_batch_size, 265 | zero_shift=move_zero_shift, 266 | # save_info=True, #Must be set to True if printing info about the searches! 267 | ) 268 | 269 | self.hash_table = get_empty_hash_table() 270 | 271 | def start_new_game(self): 272 | clear_hash_table(self.hash_table) 273 | 274 | def pick_move(self, board): 275 | returned_score, move_to_return, self.hash_table = iterative_deepening_mtd_f( 276 | fen=board.fen(), 277 | depths_to_search=np.arange(1,self.search_depth+1), 278 | open_node_holder=self.open_node_holder, 279 | board_eval_fn=self.board_evaluator, 280 | move_eval_fn=self.move_evaluator, 281 | hash_table=self.hash_table, 282 | 283 | previous_board_map=get_previous_board_map_from_py_board(board), 284 | 285 | # print_info=True, #If this is True, the save_info parameter for the PriorityBins must be True (in the __init__ function) (better connection of these values to come)! 286 | ) 287 | 288 | return move_to_return 289 | 290 | -------------------------------------------------------------------------------- /batch_first/global_open_priority_nodes.py: -------------------------------------------------------------------------------- 1 | from .classes_and_structs import * 2 | 3 | 4 | @njit 5 | def should_not_terminate(game_node): 6 | cur_node = game_node 7 | while cur_node is not None: 8 | if cur_node.struct.terminated: 9 | return False 10 | cur_node = cur_node.parent 11 | return True 12 | 13 | 14 | @njit 15 | def append_non_terminating(to_check, root): 16 | while not to_check is None: 17 | if should_not_terminate(to_check.held_node): 18 | root.next_holder = to_check 19 | root = root.next_holder 20 | 21 | to_check = to_check.next_holder 22 | 23 | root.next_holder = None 24 | return root 25 | 26 | 27 | @njit 28 | def append_non_terminating_with_counting(to_check, root, max_to_get): 29 | num_found = 0 30 | while not to_check is None: 31 | if should_not_terminate(to_check.held_node): 32 | root.next_holder = to_check 33 | root = root.next_holder 34 | 35 | num_found += 1 36 | if num_found == max_to_get: 37 | to_check = to_check.next_holder 38 | break 39 | 40 | to_check = to_check.next_holder 41 | 42 | root.next_holder = None 43 | return root, to_check, num_found 44 | 45 | 46 | 47 | class GlobalNodeList(object): 48 | def is_empty(self): 49 | """ 50 | Checks if the node list is empty. 51 | 52 | :return: A boolean value indicating if the list is empty. 53 | """ 54 | raise NotImplementedError("This method must be implemented!") 55 | 56 | def insert_nodes_and_get_next_batch(self, to_insert, scores): 57 | """ 58 | Inserts the given nodes into the stored list, and gets the next batch of nodes to be computed. 59 | 60 | :param to_insert: An ndarray of the nodes to be inserted into the list 61 | :param scores: An ndarray of the values used for prioritization, corresponding to the given nodes to insert 62 | :return: An ndarray of the nodes to be computed in the next batch 63 | """ 64 | raise NotImplementedError("This method must be implemented!") 65 | 66 | def clear_list(self): 67 | """ 68 | Clears the list so that it is empty. 69 | """ 70 | raise NotImplementedError("This method must be implemented!") 71 | 72 | 73 | 74 | @njit 75 | def insert_nodes(bins, bin_lls, bin_lengths, non_empty_mask, to_insert, scores, zero_shift): 76 | scores -= zero_shift 77 | scores = np.abs(scores) 78 | 79 | bin_indices = np.digitize(scores, bins) 80 | for j in range(len(scores)): 81 | temp_next = to_insert.next_holder 82 | 83 | if non_empty_mask[bin_indices[j]]: 84 | to_insert.next_holder = bin_lls[bin_indices[j]] 85 | else: 86 | to_insert.next_holder = None 87 | non_empty_mask[bin_indices[j]] = True 88 | 89 | bin_lengths[bin_indices[j]] += 1 90 | bin_lls[bin_indices[j]] = to_insert 91 | to_insert = temp_next 92 | 93 | 94 | @njit 95 | def get_batch(bin_lls, bin_lengths, non_empty_mask, max_batch_size_to_accept): 96 | dummy_root = create_dummy_node_holder() 97 | end_node = dummy_root 98 | num_found = 0 99 | 100 | temp_dummy_node = create_dummy_node_holder() 101 | for bin_index in np.where(non_empty_mask)[0]: 102 | end_node, bin_leftover, just_found = append_non_terminating_with_counting( 103 | bin_lls[bin_index], end_node, max_batch_size_to_accept - num_found) 104 | 105 | num_found += just_found 106 | 107 | if not bin_leftover is None: 108 | bin_lls[bin_index] = bin_leftover 109 | non_empty_mask[bin_index] = True 110 | bin_lengths[bin_index] = len_node_holder(bin_leftover) 111 | break 112 | 113 | bin_lls[bin_index] = temp_dummy_node 114 | non_empty_mask[bin_index] = False 115 | bin_lengths[bin_index] = 0 116 | 117 | if num_found == max_batch_size_to_accept: 118 | break 119 | 120 | return dummy_root.next_holder 121 | 122 | 123 | @njit 124 | def pop_all_non_terminating(bin_lls, bin_lengths, non_empty_mask): 125 | """ 126 | Set all the bin arrays to empty (by use of a mask), and return an array of all the nodes currently 127 | in a bin array that should not terminate. 128 | """ 129 | dummy_root = create_dummy_node_holder() 130 | end_ll_node = dummy_root 131 | 132 | temp_dummy_node = create_dummy_node_holder() 133 | for bin_index in np.where(non_empty_mask)[0]: 134 | end_ll_node = append_non_terminating(bin_lls[bin_index], end_ll_node) 135 | bin_lls[bin_index] = temp_dummy_node 136 | 137 | bin_lengths[non_empty_mask] = 0 138 | non_empty_mask[non_empty_mask] = False 139 | 140 | return dummy_root.next_holder, end_ll_node 141 | 142 | 143 | @njit 144 | def insert_and_get_batch(to_insert, scores, bins, bin_ll_holder, bin_lengths, non_empty_mask, max_batch_size_to_accept, zero_shift): 145 | own_len = np.sum(bin_lengths) 146 | 147 | # This should not be using self.max_batch_size_to_accept for the initial check (here), instead should probably 148 | # be using a value greater than that, because even if 0 nodes are terminating, the time saved will likely 149 | # be more than the time spent computing the extra nodes (though it's unlikely that 0 nodes will be terminated 150 | # in actual play) 151 | if len(scores) + own_len < max_batch_size_to_accept: 152 | if own_len == 0: 153 | dummy_root = create_dummy_node_holder() 154 | append_non_terminating(to_insert, dummy_root) 155 | return dummy_root.next_holder 156 | elif len(scores) == 0: 157 | bin_lls = get_list_from_holder_holder(bin_ll_holder) 158 | to_return = pop_all_non_terminating(bin_lls, bin_lengths, non_empty_mask)[0] 159 | else: 160 | bin_lls = get_list_from_holder_holder(bin_ll_holder) 161 | to_return, end_node = pop_all_non_terminating(bin_lls, bin_lengths, non_empty_mask) 162 | end_node.next_holder = to_insert 163 | 164 | clear_holder_holder(bin_ll_holder) 165 | return to_return 166 | 167 | bin_lls = get_list_from_holder_holder(bin_ll_holder) 168 | 169 | insert_nodes(bins, bin_lls, bin_lengths, non_empty_mask, to_insert, scores, zero_shift) 170 | 171 | batch_to_return = get_batch(bin_lls, bin_lengths, non_empty_mask, max_batch_size_to_accept) 172 | 173 | new_holder_holder = get_holder_holder_from_list(bin_lls) 174 | bin_ll_holder.held = new_holder_holder.held 175 | bin_ll_holder.next = new_holder_holder.next 176 | 177 | return batch_to_return 178 | 179 | 180 | 181 | class PriorityBins(GlobalNodeList): 182 | def __init__(self, bins, max_batch_size_to_accept, zero_shift=0, save_info=False): 183 | num_bins = (len(bins) + 1) 184 | 185 | self.bins = bins[::-1] 186 | 187 | self.bin_lengths = np.zeros(num_bins, dtype=np.int32) 188 | self.non_empty_mask = np.zeros(num_bins, dtype=np.bool_) 189 | 190 | temp_dummy_node = create_dummy_node_holder() 191 | self.holder_holder = get_holder_holder_from_list([temp_dummy_node for _ in range(num_bins)]) 192 | 193 | self.max_batch_size_to_accept = max_batch_size_to_accept 194 | self.zero_shift = zero_shift 195 | 196 | self.save_info = save_info 197 | 198 | if save_info: 199 | self.reset_logs() 200 | 201 | def reset_logs(self): 202 | self.total_in = 0 203 | self.total_out = 0 204 | 205 | def __len__(self): 206 | return np.sum(self.bin_lengths) 207 | 208 | def is_empty(self): 209 | return not np.any(self.non_empty_mask) 210 | 211 | def num_non_empty(self): 212 | return np.sum(self.non_empty_mask) 213 | 214 | def largest_bin(self): 215 | return np.max(self.bin_lengths) 216 | 217 | def clear_list(self): 218 | clear_holder_holder(self.holder_holder) 219 | 220 | self.bin_lengths[self.non_empty_mask] = 0 221 | self.non_empty_mask[self.non_empty_mask] = False 222 | 223 | def insert_nodes_and_get_next_batch(self, to_insert, scores): 224 | if self.save_info: 225 | self.total_in += len(scores) 226 | 227 | to_return = insert_and_get_batch( 228 | to_insert, 229 | scores, 230 | self.bins, 231 | self.holder_holder, 232 | self.bin_lengths, 233 | self.non_empty_mask, 234 | self.max_batch_size_to_accept, 235 | self.zero_shift) 236 | 237 | if self.save_info and to_return: 238 | self.total_out += len_node_holder(to_return) 239 | 240 | return to_return 241 | 242 | -------------------------------------------------------------------------------- /batch_first/numba_negamax_zero_window.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import time 3 | 4 | from .numba_board import * 5 | from . import transposition_table as tt 6 | 7 | from .classes_and_structs import * 8 | 9 | 10 | 11 | @njit 12 | def compress_square_array(to_compress): 13 | """ 14 | Given an array of uint8s which all have values less than 16, compress them by storing 15 | two values per uint8 (as opposed to one). 16 | """ 17 | to_compress[::2] <<= np.uint8(4) 18 | to_compress[::2] |= to_compress[1::2] 19 | return to_compress[::2] 20 | 21 | 22 | @njit 23 | def square_scanner_helper(bb, mirror_squares=False): 24 | if mirror_squares: 25 | for square in scan_reversed(bb): 26 | yield square_mirror(square) 27 | else: 28 | for square in scan_reversed(bb): 29 | yield square 30 | 31 | 32 | @njit 33 | def get_square_ary(struct, relevent_square_mask): 34 | """ 35 | Creates and returns an array of the ann filters indices corresponding to the given boards 'relevant' squares. 36 | A 'relevant' square is a square that's either occupied or an ep-capture square. 37 | """ 38 | squares = np.empty(popcount(relevent_square_mask), np.uint8) 39 | for j, square in enumerate(square_scanner_helper(relevent_square_mask, not struct['turn'])): 40 | type = piece_type_at(struct, square) 41 | 42 | if type: 43 | bb_square = BB_SQUARES[square] 44 | squares[j] = 7 if struct['occupied_co'][struct['turn']] & bb_square else 14 45 | if struct['castling_rights'] & bb_square == 0: 46 | squares[j] -= type 47 | else: 48 | squares[j] = 0 49 | 50 | return squares 51 | 52 | 53 | @njit 54 | def own_concat(lst, total_size): 55 | """ 56 | A customized implementation of np.concatenate (mainly used because Numba wouldn't let it use np.concatenate for some reason) 57 | """ 58 | to_return = np.empty(total_size + (total_size % 2), np.uint8) 59 | start_index = 0 60 | for to_place in lst: 61 | end_index = start_index + len(to_place) 62 | to_return[start_index:end_index] = to_place 63 | start_index = end_index 64 | 65 | if total_size % 2: #to fix the issues caused by part of the array staying 'empty' 66 | to_return[-1] = 0 67 | 68 | return to_return 69 | 70 | 71 | @njit 72 | def struct_array_to_ann_inputs(child_structs, not_child_structs, to_score_child_mask, to_score_not_child_mask, total_num_to_score): 73 | """ 74 | Uses ceil((popcnt(occupied)+int(has_ep))/2)*8+64=[80, 200] bits per board transferred. 75 | """ 76 | occupied_bbs = np.empty(total_num_to_score, dtype=np.uint64) 77 | 78 | total_squares = 0 79 | store_index = 0 80 | to_concat = [] 81 | for j in range(len(child_structs) + len(not_child_structs)): 82 | if j < len(child_structs): 83 | should_score = to_score_child_mask[j] 84 | struct = child_structs[j] 85 | else: 86 | should_score = to_score_not_child_mask[j - len(child_structs)] 87 | struct = not_child_structs[j - len(child_structs)] 88 | 89 | if should_score: 90 | occupied_bbs[store_index] = struct['occupied'] 91 | if struct['ep_square']: 92 | occupied_bbs[store_index] |= BB_SQUARES[struct['ep_square']] 93 | 94 | if not struct['turn']: 95 | occupied_bbs[store_index] = flip_vertically(occupied_bbs[store_index]) 96 | 97 | cur_squares = get_square_ary(struct, occupied_bbs[store_index]) 98 | 99 | total_squares += len(cur_squares) 100 | to_concat.append(cur_squares) 101 | 102 | store_index += 1 103 | compressed_squares = compress_square_array(own_concat(to_concat, total_squares)) 104 | 105 | return compressed_squares, occupied_bbs 106 | 107 | 108 | @njit 109 | def can_draw_from_repetition(board_struct, parent_node, previous_board_map): 110 | """ 111 | NOTES: 112 | 1) Look into if hash collisions are something thing I need to be checking for (type 1 collisions) 113 | """ 114 | if board_struct['halfmove_clock'] < 4: 115 | return False 116 | 117 | #Checks if the board is a repitition of a board which was made in the actual game (meaning prior to the current search) 118 | hash_index = np.searchsorted(previous_board_map[0], board_struct['hash']) 119 | if board_struct['hash'] == previous_board_map[hash_index, 0]: 120 | num_found_so_far = 1 + previous_board_map[hash_index, 1] 121 | else: 122 | num_found_so_far = 1 123 | 124 | 125 | if parent_node.parent is None: 126 | return False 127 | 128 | node = parent_node.parent 129 | 130 | if board_struct['hash'] == node.struct['hash']: 131 | num_found_so_far += 1 132 | 133 | if num_found_so_far >= 3: 134 | return True 135 | 136 | for num in range(node.struct['halfmove_clock'], 1, -2): 137 | if num < 3 and num_found_so_far == 1: 138 | return False 139 | elif node.parent is None or node.parent.parent is None: 140 | return False 141 | 142 | node = node.parent.parent 143 | 144 | if board_struct['hash'] == node.struct['hash']: 145 | num_found_so_far += 1 146 | 147 | if num_found_so_far >= 3: 148 | return True 149 | 150 | return False 151 | 152 | 153 | @njit 154 | def set_up_next_best_move(board_struct): 155 | board_struct['next_move_index'] = np.argmax(board_struct['unexplored_move_scores']) 156 | best_move_score = board_struct['unexplored_move_scores'][board_struct['next_move_index']] 157 | if best_move_score == MIN_FLOAT32_VAL: 158 | board_struct['next_move_index'] = NO_MORE_MOVES_VALUE 159 | else: 160 | board_struct['unexplored_move_scores'][board_struct['next_move_index']] = MIN_FLOAT32_VAL 161 | return best_move_score 162 | 163 | 164 | def start_move_scoring(children, not_children, child_score_mask, not_child_score_mask, move_eval_fn): 165 | num_children_to_score = np.sum(child_score_mask) 166 | num_not_child_to_score = np.sum(not_child_score_mask) 167 | 168 | result_getter = [None] 169 | def set_move_scores(): 170 | result_getter[0] = move_eval_fn( 171 | *struct_array_to_ann_inputs( 172 | children, 173 | not_children, 174 | child_score_mask, 175 | not_child_score_mask, 176 | num_children_to_score + num_not_child_to_score)) 177 | 178 | t = threading.Thread(target=set_move_scores) 179 | t.start() 180 | return t, result_getter, num_children_to_score, num_not_child_to_score 181 | 182 | 183 | def start_board_evaluations(struct_array, to_score_mask, board_eval_fn): 184 | """ 185 | Start the evaluation of the depth zero nodes which were not previously terminated. 186 | """ 187 | num_to_score = np.sum(to_score_mask) 188 | evaluation_scores = np.empty(num_to_score, dtype=np.float32) 189 | 190 | def evaluate_and_set(): 191 | evaluation_scores[:] = board_eval_fn( 192 | *struct_array_to_ann_inputs( 193 | struct_array, 194 | np.array([], dtype=numpy_node_info_dtype), 195 | to_score_mask, 196 | np.array([], dtype=np.bool_), 197 | num_to_score)) 198 | 199 | t = threading.Thread(target=evaluate_and_set) 200 | t.start() 201 | 202 | return t, evaluation_scores 203 | 204 | 205 | @njit 206 | def should_terminate_from_tt(board_struct, hash_table): 207 | """ 208 | Checks if the node should be terminated from the information contained in the given hash_table. It also 209 | updates the values in the given node when applicable. 210 | """ 211 | hash_entry = hash_table[board_struct['hash'] & TT_HASH_MASK] 212 | if hash_entry['depth'] != NO_TT_ENTRY_VALUE: 213 | if hash_entry['entry_hash'] == board_struct['hash']: 214 | if hash_entry['depth'] >= board_struct['depth']: 215 | if hash_entry['lower_bound'] >= board_struct['separator']: 216 | board_struct['best_value'] = hash_entry['lower_bound'] 217 | return True 218 | else: 219 | if hash_entry['upper_bound'] < board_struct['separator']: 220 | board_struct['best_value'] = hash_entry['upper_bound'] 221 | return True 222 | if hash_entry['lower_bound'] > board_struct['best_value']: 223 | board_struct['best_value'] = hash_entry['lower_bound'] 224 | return False 225 | 226 | 227 | @njit 228 | def depth_zero_should_terminate_array(struct_array, hash_table, previous_board_map, node_holder): 229 | """ 230 | This function goes through the given struct_array and looks for depth zero nodes which should terminate 231 | for reasons other than scoring by the evaluation function. This is separate from 232 | the child_termination_check_and_move_gen function so that it can give the GPU the boards for evaluation as quickly 233 | as possible. 234 | 235 | 236 | Things being checked: 237 | 1) Draw by the 50-move rule 238 | 2) Draw by insufficient material 239 | 3) Draw by stalemate 240 | 4) Win/loss by checkmate 241 | 5) Termination by information contained in the TT 242 | 6) Draw by threefold repetition 243 | """ 244 | for j in range(len(struct_array)): 245 | if struct_array[j]['depth'] == 0: 246 | if struct_array[j]['halfmove_clock'] >= 50 or has_insufficient_material(struct_array[j]): 247 | struct_array[j]['terminated'] = True 248 | struct_array[j]['best_value'] = TIE_RESULT_SCORE 249 | elif can_draw_from_repetition(struct_array[j], node_holder.held_node, previous_board_map): 250 | # This is just assigning a draw value, though it doesn't necessarily imply a draw, 251 | # just that one can be claimed. Not sure if this needs to be handled, and if yes how to handle it 252 | struct_array[j]['terminated'] = True 253 | struct_array[j]['best_value'] = TIE_RESULT_SCORE 254 | elif should_terminate_from_tt(struct_array[j], hash_table): 255 | struct_array[j]['terminated'] = True 256 | elif not has_legal_move(struct_array[j]): 257 | struct_array[j]['terminated'] = True 258 | 259 | node_holder = node_holder.next_holder 260 | 261 | 262 | @njit 263 | def has_legal_tt_move(board_struct, hash_table): 264 | """ 265 | Checks if a move is being stored in the transposition table for the given board struct, and if there is, that the 266 | move is legal. If it does find a legal move, it stores the move in the struct's first move index, sets the 267 | struct's next move score to a constant value, and sets it's children_left to a specified constant to indicate there 268 | was a legal move found in the tt. 269 | 270 | :return: True if a move is found, or False if not. 271 | """ 272 | node_entry = hash_table[board_struct['hash'] & TT_HASH_MASK] 273 | if node_entry['depth'] != NO_TT_ENTRY_VALUE: 274 | if node_entry['entry_hash'] == board_struct['hash']: 275 | if node_entry['stored_move'][0] != NO_TT_MOVE_VALUE: 276 | if is_legal_move(board_struct, node_entry['stored_move']): 277 | board_struct['unexplored_moves'][0] = node_entry['stored_move'] 278 | board_struct['next_move_index'] = 0 279 | board_struct['children_left'] = NEXT_MOVE_IS_FROM_TT_VAL 280 | return True 281 | return False 282 | 283 | 284 | @njit 285 | def child_termination_check_and_move_gen(struct_array, hash_table, node_holder, previous_board_map): 286 | """ 287 | Things being checked: 288 | 1) Draw by the 50-move rule 289 | 2) Draw by insufficient material 290 | 3) Draw by stalemate 291 | 4) Win/loss by checkmate 292 | 5) Termination by information contained in the TT 293 | 6) Draw by threefold repetition 294 | """ 295 | for j in range(len(struct_array)): 296 | if struct_array[j]['depth'] != 0: 297 | if struct_array[j]["halfmove_clock"] >= 50 or has_insufficient_material(struct_array[j]): 298 | struct_array[j]['best_value'] = TIE_RESULT_SCORE 299 | struct_array[j]['terminated'] = True 300 | elif can_draw_from_repetition(struct_array[j], node_holder.held_node, previous_board_map): 301 | # This is just assigning a draw value, though it doesn't necessarily imply a draw, 302 | # just that one can be claimed. Not sure if this needs to be handled, and if yes how to handle it 303 | struct_array[j]['terminated'] = True 304 | struct_array[j]['best_value'] = TIE_RESULT_SCORE 305 | elif should_terminate_from_tt(struct_array[j], hash_table): 306 | struct_array[j]['terminated'] = True 307 | elif has_legal_tt_move(struct_array[j], hash_table): 308 | pass 309 | else: 310 | set_up_move_array(struct_array[j]) 311 | 312 | node_holder = node_holder.next_holder 313 | 314 | 315 | @njit 316 | def create_child_structs(struct_array): 317 | #This should not copy the entire array, instead only the fields which are not directly written over 318 | #Also this should not be creating full structs for depth zero nodes, a new dtype will likely need to be created 319 | #which has a subset of the current ones fields. 320 | child_array = struct_array.copy() 321 | 322 | new_next_move_values = np.empty_like(struct_array['best_value']) 323 | 324 | #This should be removed, and struct_array['prev_move'] should be used instead. Numba has been very stuborn in resisting this change 325 | moves_to_push = np.empty((len(struct_array), 3), dtype=np.uint8) 326 | 327 | for j in range(len(struct_array)): 328 | child_array[j]['unexplored_moves'][:] = 255 329 | child_array[j]['unexplored_move_scores'][:] = MIN_FLOAT32_VAL 330 | child_array[j]['prev_move'][:] = struct_array[j]['unexplored_moves'][struct_array[j]['next_move_index']] 331 | child_array[j]['depth'] = struct_array[j]['depth'] - 1 332 | 333 | moves_to_push[j] = struct_array[j]['unexplored_moves'][struct_array[j]['next_move_index']] 334 | 335 | if struct_array[j]['children_left'] != NEXT_MOVE_IS_FROM_TT_VAL: 336 | new_next_move_values[j] = set_up_next_best_move(struct_array[j]) 337 | else: 338 | new_next_move_values[j] = TT_MOVE_SCORE_VALUE 339 | 340 | push_moves(child_array, moves_to_push) 341 | 342 | child_array['best_value'][:] = MIN_FLOAT32_VAL 343 | child_array['children_left'][:] = 0 344 | child_array['separator'][:] *= -1 345 | child_array['next_move_index'][:] = 255 346 | 347 | return child_array, new_next_move_values 348 | 349 | 350 | @njit 351 | def generate_moves_for_tt_move_nodes(struct_array, to_check_mask): 352 | """ 353 | Generates the legal moves for the array of board structs when a legal move for the node was found in 354 | the transposition table (TT), and then was expanded in the same iteration as this function is being run. 355 | It generates all of the legal moves except for the move which was already found in the TT. 356 | It then sets each struct's children_left to the actual number of children left, 357 | as opposed to the indicator value NEXT_MOVE_IS_FROM_TT_VAL which it previously was. 358 | """ 359 | for j in range(len(struct_array)): 360 | if to_check_mask[j]: 361 | struct_array[j]['children_left'] = 0 362 | set_up_move_array_except_move(struct_array[j], struct_array[j]['unexplored_moves'][0].copy()) 363 | struct_array[j]['children_left'] += 1 364 | 365 | 366 | @njit 367 | def create_holder_for_structs(struct_array, parent_holder, to_create_mask, starting_holder=None): 368 | found = 0 369 | for j in range(len(struct_array)): 370 | if to_create_mask[j]: 371 | starting_holder = GameNodeHolder(GameNode(struct_array[j:j + 1], parent_holder.held_node), starting_holder) 372 | found += 1 373 | parent_holder = parent_holder.next_holder 374 | 375 | return starting_holder, found 376 | 377 | 378 | @njit 379 | def create_new_holders_and_filter_old(root, node_linked_list, have_children_left_mask, child_struct, create_holder_mask): 380 | """ 381 | Creates new GameNodes and GameNodeHolders for the given new children, and filters the parents which don't need 382 | to be given to the open node holder for re-insertion. Their node holder are connected, and appended to the given root. 383 | """ 384 | new_child_nodes, num_new_children = create_holder_for_structs(child_struct, node_linked_list, create_holder_mask) 385 | 386 | num_not_filtered = filter_holders_then_append(root, node_linked_list, have_children_left_mask, new_child_nodes) 387 | 388 | return num_new_children, num_new_children + num_not_filtered 389 | 390 | @njit 391 | def get_struct_array_from_node_holder(node_holder, length): 392 | to_return = np.empty(length, dtype=numpy_node_info_dtype) 393 | for j in range(length): 394 | to_return[j] = node_holder.struct 395 | node_holder = node_holder.next_holder 396 | return to_return 397 | 398 | 399 | @njit 400 | def update_node_from_value(node, value, following_move, hash_table, new_termination=True): 401 | if not node is None: 402 | if node.struct['terminated']: 403 | if value > node.struct['best_value']: 404 | node.struct['best_value'] = value 405 | 406 | tt.add_board_and_move_to_tt(node.struct, following_move, hash_table) 407 | update_node_from_value(node.parent, - value, node.struct['prev_move'], hash_table, False) 408 | else: 409 | if new_termination: 410 | node.struct['children_left'] -= 1 411 | 412 | node.struct['best_value'] = np.maximum(value, node.struct['best_value']) 413 | 414 | if node.struct['best_value'] >= node.struct['separator'] or node.struct['children_left'] == 0: 415 | node.struct['terminated'] = True 416 | 417 | tt.add_board_and_move_to_tt(node.struct, following_move, hash_table) 418 | 419 | update_node_from_value(node.parent, - node.struct['best_value'], node.struct['prev_move'], hash_table) 420 | 421 | 422 | @njit 423 | def update_tree_from_terminating_nodes(parent_node_holder, struct_array, hash_table, was_evaluated_mask, eval_results): 424 | """ 425 | Updates the search tree from the nodes in the current batch which are terminating, this includes all nodes which 426 | have been marked terminated, or are depth zero. It also updates the transposition table as needed. 427 | """ 428 | should_update_mask = np.logical_or(struct_array['depth'] == 0, struct_array['terminated']) 429 | 430 | if eval_results[0] != MAX_FLOAT32_VAL: #This would be a None parameter but Numba won't let it compile so this is used instead 431 | tt.add_evaluated_boards_to_tt(struct_array, was_evaluated_mask, eval_results, hash_table) 432 | 433 | eval_results_for_parents = - eval_results 434 | 435 | 436 | index_in_evaluations = 0 437 | for j in range(len(struct_array)): 438 | if was_evaluated_mask[j]: 439 | update_node_from_value( 440 | parent_node_holder.held_node, 441 | eval_results_for_parents[index_in_evaluations], 442 | struct_array[j]['prev_move'], 443 | hash_table) 444 | index_in_evaluations += 1 445 | 446 | elif should_update_mask[j]: 447 | update_node_from_value( 448 | parent_node_holder.held_node, 449 | - struct_array[j]['best_value'], 450 | struct_array[j]['prev_move'], 451 | hash_table) 452 | 453 | parent_node_holder = parent_node_holder.next_holder 454 | 455 | 456 | @njit 457 | def set_nodes_to_altered_structs(node_holder, struct_array, to_do_mask): 458 | for j in range(len(struct_array)): 459 | if to_do_mask[j]: 460 | node_holder.struct['unexplored_moves'][:] = struct_array[j]['unexplored_moves'][:] 461 | node_holder.struct['unexplored_move_scores'][:] = struct_array[j]['unexplored_move_scores'][:] 462 | 463 | node_holder.struct['children_left'] = struct_array[j]['children_left'] 464 | node_holder.struct['next_move_index'] = struct_array[j]['next_move_index'] 465 | 466 | node_holder = node_holder.next_holder 467 | 468 | 469 | @njit 470 | def set_child_move_scores(child_structs, scored_child_mask, scores, score_size_array, cum_sum_sizes): 471 | next_move_scores = np.empty(len(score_size_array),dtype=np.float32) 472 | num_completed = 0 473 | for j in range(len(child_structs)): 474 | if scored_child_mask[j]: 475 | cur_score_size = score_size_array[num_completed] 476 | cur_cum_sum_size = cum_sum_sizes[num_completed] 477 | 478 | child_structs[j]['unexplored_move_scores'][:cur_score_size] = scores[cur_cum_sum_size - cur_score_size:cur_cum_sum_size] 479 | 480 | next_move_scores[num_completed] = set_up_next_best_move(child_structs[j]) 481 | num_completed += 1 482 | return next_move_scores 483 | 484 | 485 | @njit 486 | def get_move_from_and_filter_squares_and_sizes(child_structs, not_child_structs, child_mask, not_child_mask, num_scored, num_children): 487 | size_array = np.empty(num_scored, np.uint8) 488 | total_num_children = len(child_structs) 489 | 490 | size_array[:num_children] = child_structs['children_left'][child_mask] 491 | size_array[num_children:] = not_child_structs['children_left'][not_child_mask] - 1 #subtracting 1 here to account for the TT move which doesn't need to be scored 492 | 493 | move_indices = np.empty((np.sum(size_array), 2), dtype=np.uint8) 494 | 495 | cur_start_index = 0 496 | scored_so_far = 0 497 | for j in range(len(child_structs) + len(not_child_structs)): 498 | if j < len(child_structs): 499 | was_scored = child_mask[j] 500 | struct = child_structs[j] 501 | else: 502 | was_scored = not_child_mask[j - total_num_children] 503 | struct = not_child_structs[j - total_num_children] 504 | 505 | if was_scored: 506 | cur_size = size_array[scored_so_far] 507 | 508 | if struct['turn']: 509 | relevant_moves = struct['unexplored_moves'][:cur_size,:2] 510 | else: 511 | relevant_moves = SQUARES_180[struct['unexplored_moves'][:cur_size,:2].ravel()].reshape((-1, 2)) 512 | 513 | move_indices[cur_start_index:cur_start_index + cur_size, 0] = relevant_moves[:, 0] 514 | 515 | #The following loop is needed since Numba can't handle more than 1 advanced index 516 | for i in range(cur_size): 517 | move_indices[cur_start_index + i, 1] = MOVE_FILTER_LOOKUP[relevant_moves[i, 0], relevant_moves[i, 1], struct['unexplored_moves'][i, 2]] 518 | 519 | cur_start_index += cur_size 520 | scored_so_far += 1 521 | 522 | return size_array, move_indices 523 | 524 | 525 | @njit 526 | def prepare_to_finish_move_scoring(child_structs, adult_structs, scored_child_mask, scored_adult_mask, 527 | num_scored_children, num_scored_adults): 528 | size_array, from_to_squares = get_move_from_and_filter_squares_and_sizes( 529 | child_structs, 530 | adult_structs, 531 | scored_child_mask, 532 | scored_adult_mask, 533 | num_scored_children + num_scored_adults, 534 | num_scored_children) 535 | 536 | cum_sum_sizes = np.cumsum(size_array) 537 | 538 | return size_array, from_to_squares, cum_sum_sizes 539 | 540 | 541 | @njit 542 | def complete_move_evaluation(scores, child_structs, adult_nodes, scored_child_mask, scored_adult_mask, 543 | num_children, size_array, cum_sum_sizes): 544 | adult_next_move_scores = np.empty(len(size_array) - num_children, dtype=np.float32) 545 | 546 | child_next_move_scores = set_child_move_scores( 547 | child_structs, 548 | scored_child_mask, 549 | scores, 550 | size_array[:num_children], 551 | cum_sum_sizes[:num_children]) 552 | 553 | cur_adult_index = 0 554 | for j in range(len(child_structs)): 555 | if scored_adult_mask[j]: 556 | cur_index = cur_adult_index + num_children 557 | cur_size = size_array[cur_index] 558 | cur_cum_sum_size = cum_sum_sizes[cur_index] 559 | cur_node = adult_nodes.held_node 560 | 561 | cur_node.struct['unexplored_move_scores'][:cur_size] = scores[ 562 | cur_cum_sum_size - cur_size: cur_cum_sum_size] 563 | adult_next_move_scores[cur_adult_index] = set_up_next_best_move(cur_node.struct) 564 | 565 | cur_adult_index += 1 566 | 567 | adult_nodes = adult_nodes.next_holder 568 | 569 | return child_next_move_scores, adult_next_move_scores 570 | 571 | 572 | def do_iteration(node_linked_list, hash_table, previous_board_map, board_eval_fn, move_eval_fn): 573 | length_of_batch = len_node_holder(node_linked_list) #this can and should be given to this function 574 | struct_batch = get_struct_array_from_node_holder(node_linked_list, length_of_batch) 575 | 576 | child_struct, struct_batch_next_move_scores = create_child_structs(struct_batch) 577 | 578 | child_was_from_tt_move_mask = struct_batch['children_left'] == NEXT_MOVE_IS_FROM_TT_VAL 579 | 580 | depth_zero_children_mask = child_struct['depth'] == 0 581 | depth_not_zero_mask = np.logical_not(depth_zero_children_mask) 582 | 583 | depth_zero_should_terminate_array(child_struct, hash_table, previous_board_map, node_linked_list) 584 | 585 | depth_zero_not_scored_mask = np.logical_and(depth_zero_children_mask, np.logical_not(child_struct['terminated'])) 586 | 587 | if np.any(depth_zero_not_scored_mask): 588 | evaluation_thread, evaluation_scores = start_board_evaluations( 589 | child_struct, 590 | depth_zero_not_scored_mask, 591 | board_eval_fn) 592 | else: 593 | evaluation_thread = None 594 | evaluation_scores = None 595 | 596 | 597 | generate_moves_for_tt_move_nodes(struct_batch, child_was_from_tt_move_mask) 598 | 599 | not_one_child_left_mask = struct_batch['children_left'] != 1 600 | 601 | not_only_move_was_tt_move_mask = np.logical_or(not_one_child_left_mask, np.logical_not(child_was_from_tt_move_mask)) 602 | tt_move_nodes_with_more_kids_mask = np.logical_and(not_one_child_left_mask, child_was_from_tt_move_mask) 603 | 604 | child_termination_check_and_move_gen(child_struct, hash_table, node_linked_list, previous_board_map) 605 | 606 | non_zerod_child_not_term_mask = np.logical_and( 607 | depth_not_zero_mask, 608 | np.logical_not(child_struct['terminated'])) 609 | 610 | non_zerod_kids_for_move_scoring_mask = np.logical_and( 611 | non_zerod_child_not_term_mask, 612 | child_struct['children_left'] != NEXT_MOVE_IS_FROM_TT_VAL) 613 | 614 | # Now that staging has been implemented for move scoring, this must be started as soon as it knows exactly which 615 | # nodes have moves to be scored. This likely involves stopping the move generation when the first move for each 616 | # board is discovered, and resuming after the boards which have moves to score have been given to TensorFlow 617 | # (or after a thread with that task has been started) 618 | if np.any(non_zerod_kids_for_move_scoring_mask) or np.any(tt_move_nodes_with_more_kids_mask): 619 | move_thread, move_score_getter, num_children_move_scoring, num_adult_move_scoring = start_move_scoring( 620 | child_struct, 621 | struct_batch, 622 | non_zerod_kids_for_move_scoring_mask, 623 | tt_move_nodes_with_more_kids_mask, 624 | move_eval_fn) 625 | else: 626 | move_thread = None 627 | child_next_move_scores = None 628 | not_child_next_move_scores = None 629 | 630 | # A mask of the given batch which have more unexplored children left 631 | have_children_left_mask = np.logical_and( 632 | struct_batch["next_move_index"] != NO_MORE_MOVES_VALUE, 633 | not_only_move_was_tt_move_mask) 634 | 635 | 636 | set_nodes_to_altered_structs( 637 | node_linked_list, 638 | struct_batch, 639 | have_children_left_mask) 640 | 641 | if not evaluation_thread is None: 642 | evaluation_thread.join() 643 | 644 | if not move_thread is None: 645 | move_completion_info = prepare_to_finish_move_scoring( 646 | child_struct, 647 | struct_batch, 648 | non_zerod_kids_for_move_scoring_mask, 649 | tt_move_nodes_with_more_kids_mask, 650 | num_children_move_scoring, 651 | num_adult_move_scoring) 652 | 653 | update_tree_from_terminating_nodes( 654 | node_linked_list, 655 | child_struct, 656 | hash_table, 657 | depth_zero_not_scored_mask, 658 | evaluation_scores if not evaluation_scores is None else INT_ARRAY_NONE) 659 | 660 | if not move_thread is None: 661 | move_thread.join() 662 | 663 | move_scores = move_score_getter[0]( 664 | [move_completion_info[1][:, 0], 665 | move_completion_info[1][:, 1], 666 | move_completion_info[0]]) 667 | 668 | child_next_move_scores, not_child_next_move_scores = complete_move_evaluation( 669 | scores=move_scores, 670 | child_structs=child_struct, 671 | adult_nodes=node_linked_list, 672 | scored_child_mask=non_zerod_kids_for_move_scoring_mask, 673 | scored_adult_mask=tt_move_nodes_with_more_kids_mask, 674 | num_children=num_children_move_scoring, 675 | size_array=move_completion_info[0], 676 | cum_sum_sizes=move_completion_info[2]) 677 | 678 | dummy_root = create_dummy_node_holder() 679 | num_new_children, num_returning = create_new_holders_and_filter_old(dummy_root, node_linked_list, have_children_left_mask, child_struct, non_zerod_child_not_term_mask) 680 | to_return = dummy_root.next_holder 681 | 682 | #Set up the array of scores used to place the returned nodes into their proper bins 683 | scores_to_return = np.full(num_returning, TT_MOVE_SCORE_VALUE, dtype=np.float32) 684 | num_not_child_scores = num_returning - num_new_children 685 | if num_not_child_scores != 0: 686 | scores_to_return[:num_not_child_scores] = struct_batch_next_move_scores[have_children_left_mask] 687 | if not not_child_next_move_scores is None and len(not_child_next_move_scores) != 0: 688 | scores_to_return[:num_not_child_scores][scores_to_return[:num_not_child_scores] == TT_MOVE_SCORE_VALUE] = not_child_next_move_scores 689 | if not child_next_move_scores is None and len(child_next_move_scores) != 0: 690 | scores_to_return[num_not_child_scores:][child_struct[non_zerod_child_not_term_mask]['children_left'] != NEXT_MOVE_IS_FROM_TT_VAL] = child_next_move_scores 691 | 692 | 693 | return to_return, scores_to_return 694 | 695 | 696 | def zero_window_negamax_search(root_game_node, open_node_holder, board_eval_fn, move_eval_fn, hash_table, 697 | previous_board_map): 698 | next_batch = GameNodeHolder(root_game_node, None) 699 | while next_batch: 700 | to_insert, to_insert_scores = do_iteration( 701 | next_batch, hash_table, previous_board_map, board_eval_fn, move_eval_fn) 702 | 703 | if root_game_node.struct['terminated']: 704 | open_node_holder.clear_list() 705 | break 706 | 707 | if not to_insert and open_node_holder.is_empty(): 708 | break 709 | 710 | next_batch = open_node_holder.insert_nodes_and_get_next_batch(to_insert, to_insert_scores) 711 | 712 | return root_game_node.struct['best_value'] 713 | 714 | 715 | def set_up_root_node_for_struct(move_eval_fn, hash_table, previous_board_map, root_struct): 716 | if not root_struct['turn']: 717 | root_struct = convert_board_to_whites_perspective(root_struct) 718 | 719 | root_node = GameNode(root_struct, None) 720 | 721 | temp_game_node_holder = GameNodeHolder(root_node, None) 722 | 723 | struct_array = root_node.board_struct 724 | 725 | child_termination_check_and_move_gen( 726 | struct_array, 727 | hash_table, 728 | temp_game_node_holder, 729 | previous_board_map) 730 | 731 | num_moves_to_score = struct_array[0]['children_left'] 732 | num_moves_to_score_as_array = np.array([num_moves_to_score]) 733 | 734 | if struct_array[0]['terminated'] or num_moves_to_score == NEXT_MOVE_IS_FROM_TT_VAL: 735 | return root_node 736 | 737 | move_thread, move_score_getter, _, _ = start_move_scoring( 738 | struct_array, 739 | struct_array, 740 | np.zeros(1, dtype=np.bool_), 741 | np.ones(1, dtype=np.bool_), 742 | move_eval_fn) 743 | 744 | 745 | move_thread.join() 746 | 747 | relevant_moves = struct_array[0]['unexplored_moves'][:num_moves_to_score] 748 | 749 | if not struct_array[0]['turn']: 750 | relevant_moves[:, :2] = SQUARES_180[relevant_moves[:, :2]] 751 | 752 | move_filters = MOVE_FILTER_LOOKUP[relevant_moves[:, 0], relevant_moves[:, 1], relevant_moves[:, 2]] 753 | move_from_squares = relevant_moves[:, 0] 754 | 755 | scores = move_score_getter[0]([move_from_squares, move_filters, num_moves_to_score_as_array]) 756 | 757 | complete_move_evaluation( 758 | scores, 759 | struct_array, 760 | temp_game_node_holder, 761 | np.zeros(1, dtype=np.bool_), 762 | np.ones(1, dtype=np.bool_), 763 | 0, 764 | num_moves_to_score_as_array, 765 | num_moves_to_score_as_array) 766 | 767 | return root_node 768 | 769 | 770 | def set_up_root_node_from_fen(move_eval_fn, hash_table, previous_board_map, fen, depth=255, separator=0): 771 | return set_up_root_node_for_struct( 772 | move_eval_fn, 773 | hash_table, 774 | previous_board_map, 775 | create_node_info_from_fen(fen, depth, separator)) 776 | 777 | 778 | def mtd_f(fen, depth, first_guess, open_node_holder, board_eval_fn, move_eval_fn, hash_table, previous_board_map, 779 | guess_increment=.05, print_info=False): 780 | """ 781 | Does an mtd(f) search modified to a binary search (this is done to address the granularity of the evaluation network). 782 | """ 783 | cur_guess = first_guess 784 | 785 | upper_bound = WIN_RESULT_SCORES[0] 786 | lower_bound = LOSS_RESULT_SCORES[0] 787 | 788 | if print_info: 789 | counter = 0 790 | 791 | while lower_bound < upper_bound: 792 | 793 | if lower_bound == LOSS_RESULT_SCORES[0]: 794 | if upper_bound != WIN_RESULT_SCORES[0]: 795 | beta = np.minimum(upper_bound - guess_increment, np.nextafter(upper_bound, MIN_FLOAT32_VAL)) 796 | else: 797 | beta = cur_guess 798 | elif upper_bound == WIN_RESULT_SCORES[0]: 799 | beta = np.maximum(lower_bound + guess_increment, np.nextafter(lower_bound, MAX_FLOAT32_VAL)) 800 | else: 801 | beta = np.maximum(lower_bound + (upper_bound - lower_bound) / 2, np.nextafter(lower_bound, MAX_FLOAT32_VAL)) 802 | 803 | seperator_to_use = np.nextafter(beta, MIN_FLOAT32_VAL) 804 | 805 | # This would ideally share the same tree, but updated for the new separation value 806 | cur_root_node = set_up_root_node_from_fen(move_eval_fn, hash_table, previous_board_map, fen, depth, seperator_to_use) 807 | 808 | if cur_root_node.struct['terminated']: 809 | cur_guess = cur_root_node.struct['best_value'] 810 | else: 811 | cur_guess = zero_window_negamax_search( 812 | cur_root_node, 813 | open_node_holder, 814 | board_eval_fn, 815 | move_eval_fn, 816 | hash_table=hash_table, 817 | previous_board_map=previous_board_map) 818 | 819 | if cur_guess < beta: 820 | upper_bound = cur_guess 821 | else: 822 | lower_bound = cur_guess 823 | 824 | if print_info: 825 | counter += 1 826 | print("Finished iteration %d with lower and upper bounds (%f,%f) after search returned %f" % (counter, lower_bound, upper_bound, cur_guess)) 827 | 828 | tt_move = tt.choose_move(hash_table, cur_root_node, fen.split()[1]=='b') 829 | 830 | return cur_guess, tt_move, hash_table 831 | 832 | 833 | def iterative_deepening_mtd_f(fen, depths_to_search, open_node_holder, board_eval_fn, move_eval_fn, hash_table, 834 | previous_board_map, first_guess=0, guess_increments=None, print_info=False): 835 | if guess_increments is None: 836 | guess_increments = [.05]*len(depths_to_search) 837 | 838 | if print_info: 839 | start_time = time.time() 840 | 841 | 842 | for depth, increment in zip(depths_to_search, guess_increments): 843 | if print_info: 844 | print("Starting depth %d search, with first guess %f"%(depth, first_guess)) 845 | started_search = time.time() 846 | 847 | first_guess, tt_move, hash_table = mtd_f( 848 | fen, 849 | depth, 850 | first_guess, 851 | open_node_holder, 852 | board_eval_fn, 853 | move_eval_fn, 854 | hash_table=hash_table, 855 | previous_board_map=previous_board_map, 856 | guess_increment=increment, 857 | print_info=print_info) 858 | 859 | 860 | if print_info: 861 | print("Completed depth %d in time %f with value %f\n"%(depth, time.time() - started_search, first_guess)) 862 | 863 | 864 | if print_info: 865 | print("The nodes processed per second (including repeats) is:", open_node_holder.total_out/(time.time() - start_time)) 866 | print("The number of nodes inserted into the node list (including repeats) was %d, and %d were retrieved.\n" % (open_node_holder.total_in, open_node_holder.total_out)) 867 | open_node_holder.reset_logs() 868 | 869 | 870 | return first_guess, tt_move, hash_table 871 | -------------------------------------------------------------------------------- /batch_first/transposition_table.py: -------------------------------------------------------------------------------- 1 | from . import * 2 | 3 | from .numba_board import square_mirror 4 | 5 | 6 | 7 | hash_table_numpy_dtype = np.dtype([("entry_hash", np.uint64), #Total of 160 bits per entry 8 | ("depth", np.uint8), 9 | ("upper_bound", np.float32), 10 | ("lower_bound", np.float32), 11 | ("stored_move", np.uint8, (3))]) 12 | 13 | hash_table_numba_dtype = nb.from_dtype(hash_table_numpy_dtype) 14 | 15 | 16 | blank_tt_entry = np.array([( 17 | 0, 18 | NO_TT_ENTRY_VALUE, 19 | MAX_FLOAT32_VAL, 20 | MIN_FLOAT32_VAL, 21 | np.full(3, NO_TT_MOVE_VALUE, dtype=np.uint8))], dtype=hash_table_numpy_dtype)[0] 22 | 23 | 24 | 25 | def get_empty_hash_table(): 26 | return np.full(2**SIZE_EXPONENT_OF_TWO_FOR_TT_INDICES, blank_tt_entry) 27 | 28 | 29 | @njit 30 | def clear_hash_table(table): 31 | table[table['depth'] != NO_TT_ENTRY_VALUE] = blank_tt_entry 32 | return table 33 | 34 | 35 | def choose_move(hash_table, node, flip_move=False): 36 | """ 37 | Chooses the desired move to be made from the given node. This is done by use of the given hash table. 38 | 39 | :return: A python-chess Move object representing the desired move to be made 40 | """ 41 | root_tt_entry = hash_table[np.uint64(node.struct['hash']) & TT_HASH_MASK] 42 | move_array = root_tt_entry['stored_move'] 43 | 44 | if flip_move: 45 | move_array[:-1] = square_mirror(move_array[:-1]) 46 | 47 | return chess.Move( 48 | move_array[0].view(np.int8), 49 | move_array[1].view(np.int8), 50 | None if move_array[2]==0 else move_array[2].view(np.int8)) 51 | 52 | 53 | @nb.njit 54 | def set_tt_node(hash_entry, board_hash, depth, overwrite_hash=True, overwrite_bounds=False, 55 | upper_bound=MAX_FLOAT32_VAL, lower_bound=MIN_FLOAT32_VAL): 56 | """ 57 | Puts the given information about a node into the hash table. 58 | """ 59 | hash_entry['depth'] = depth 60 | 61 | if overwrite_hash: 62 | hash_entry['entry_hash'] = board_hash 63 | 64 | if upper_bound != MAX_FLOAT32_VAL or overwrite_bounds: 65 | hash_entry['upper_bound'] = upper_bound 66 | if lower_bound != MIN_FLOAT32_VAL or overwrite_bounds: 67 | hash_entry['lower_bound'] = lower_bound 68 | 69 | 70 | @nb.njit 71 | def set_tt_move(hash_entry, following_move): 72 | """ 73 | Write the given move in the given hash table, at the given index. 74 | """ 75 | hash_entry['stored_move'][:] = following_move 76 | 77 | 78 | @nb.njit 79 | def wipe_tt_move(hash_entry): 80 | """ 81 | Writes over the move in the given hash_table at the given index. It sets all the move values to NO_TT_MOVE_VALUE. 82 | """ 83 | hash_entry['stored_move'][:] = NO_TT_MOVE_VALUE 84 | 85 | 86 | @nb.njit 87 | def add_board_and_move_to_tt(board_struct, following_move, hash_table): 88 | """ 89 | Adds the information about a current board and the move which was made previously, to the 90 | transposition table. 91 | 92 | NOTES: 93 | 1) While this currently does work, it represents one of the most crucial components of the negamax search, 94 | and has not been given the thought and effort it needs. This is an extremely high priority 95 | """ 96 | node_entry = hash_table[board_struct['hash'] & TT_HASH_MASK] 97 | if node_entry['depth'] != NO_TT_ENTRY_VALUE: 98 | if node_entry['entry_hash'] == board_struct['hash']: 99 | if node_entry['depth'] == board_struct['depth']: 100 | if board_struct['best_value'] >= board_struct['separator']: 101 | if board_struct['best_value'] > node_entry['lower_bound']: 102 | node_entry['lower_bound'] = board_struct['best_value'] 103 | set_tt_move(node_entry, following_move) 104 | 105 | elif board_struct['best_value'] < node_entry['upper_bound']: 106 | node_entry['upper_bound'] = board_struct['best_value'] 107 | 108 | elif node_entry['depth'] < board_struct['depth']: 109 | # Overwrite the data currently stored in the hash table 110 | if board_struct['best_value'] >= board_struct['separator']: 111 | set_tt_move(node_entry, following_move) 112 | set_tt_node(node_entry, board_struct['hash'], board_struct['depth'], 113 | lower_bound=board_struct['best_value'], overwrite_hash=False, overwrite_bounds=True) 114 | else: 115 | set_tt_node(node_entry, board_struct['hash'], board_struct['depth'], 116 | upper_bound=board_struct['best_value'], overwrite_hash=False, overwrite_bounds=True) 117 | # Don't change anything if it's depth is less than the depth in the TT 118 | else: 119 | # Using the always replace scheme for simplicity and easy implementation (likely only for now) 120 | if board_struct['best_value'] >= board_struct['separator']: 121 | set_tt_move(node_entry, following_move) 122 | set_tt_node(node_entry, board_struct['hash'], board_struct['depth'], 123 | lower_bound=board_struct['best_value'], overwrite_bounds=True) 124 | else: 125 | wipe_tt_move(node_entry) 126 | set_tt_node(node_entry, board_struct['hash'], board_struct['depth'], 127 | upper_bound=board_struct['best_value'], overwrite_bounds=True) 128 | else: 129 | if board_struct['best_value'] >= board_struct['separator']: 130 | set_tt_move(node_entry, following_move) 131 | set_tt_node(node_entry, board_struct['hash'], board_struct['depth'], lower_bound=board_struct['best_value']) 132 | else: 133 | set_tt_node(node_entry, board_struct['hash'], board_struct['depth'], upper_bound=board_struct['best_value']) 134 | 135 | 136 | 137 | 138 | @nb.njit 139 | def add_evaluated_boards_to_tt(struct_array, was_evaluated_mask, eval_results, hash_table): 140 | num_done = 0 141 | for j in range(len(struct_array)): 142 | if was_evaluated_mask[j]: 143 | node_entry = hash_table[struct_array[j]['hash'] & TT_HASH_MASK] 144 | if node_entry['depth'] == NO_TT_ENTRY_VALUE: 145 | cur_result = eval_results[num_done] 146 | set_tt_node(node_entry, struct_array[j]['hash'], 0, lower_bound=cur_result, upper_bound=cur_result) 147 | 148 | num_done += 1 -------------------------------------------------------------------------------- /playing_chess.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | import chess 4 | import chess.uci 5 | import time 6 | 7 | from batch_first.engine import ChessEngine, BatchFirstEngine 8 | from batch_first.chestimator import get_inference_functions 9 | from batch_first.anns.ann_creation_helper import combine_graphdefs, save_trt_graphdef, remap_inputs 10 | 11 | 12 | def play_one_game(engine1, engine2, print_info=False): 13 | """ 14 | Given two objects which inherit the ChessEngine class this function will officiate one game of chess between the 15 | two engines. 16 | """ 17 | the_board = chess.Board() 18 | prev_move_time = time.time() 19 | halfmove_counter = 0 20 | engine1_turn = True 21 | engine1.start_new_game() 22 | engine2.start_new_game() 23 | 24 | if print_info: 25 | print("%s\n%s\n"%(the_board, the_board.fen())) 26 | 27 | while not the_board.is_game_over(): 28 | cur_engine = engine1 if engine1_turn else engine2 29 | 30 | cur_engine.ready_engine() 31 | next_move = cur_engine.pick_move(the_board) 32 | cur_engine.release_resources() 33 | 34 | if not the_board.is_legal(next_move): 35 | print("Exiting game due to player %d trying to push %s for the following board: \n%s"%(1+int(not engine1_turn), next_move, the_board)) 36 | break 37 | 38 | the_board.push(next_move) 39 | engine1_turn = not engine1_turn 40 | halfmove_counter += 1 41 | 42 | if print_info: 43 | print("Player %d made move %s after %f time."%(1+int(not engine1_turn), str(next_move), time.time() - prev_move_time)) 44 | print("Total halfmove count: %d\n%s\n%s\n"%(halfmove_counter, the_board, the_board.fen())) 45 | prev_move_time = time.time() 46 | 47 | if print_info: 48 | print("The game completed in %d halfmoves with result %s."%(halfmove_counter, the_board.result())) 49 | 50 | return the_board 51 | 52 | 53 | class RandomEngine(ChessEngine): 54 | def pick_move(self, board): 55 | return np.random.choice(np.array(list(board.generate_legal_moves()))) 56 | 57 | 58 | class UCIEngine(ChessEngine): 59 | def __init__(self, engine_location, num_threads=1, move_time=15, print_search_info=False): 60 | """ 61 | :param move_time: Either the time in milliseconds given to choose a move, or a size 2 tuple representing the 62 | range of possible time to give. e.g. (100,1000) would randomly choose a time between 100 and 1000 ms 63 | """ 64 | self.engine = chess.uci.popen_engine(engine_location) 65 | self.engine.setoption({"threads" : num_threads}) 66 | 67 | self.info_handler = chess.uci.InfoHandler() 68 | self.engine.info_handlers.append(self.info_handler) 69 | 70 | self.move_time = move_time 71 | 72 | self.print_info = print_search_info 73 | 74 | def pick_move(self, board): 75 | self.engine.position(board) 76 | if isinstance(self.move_time, tuple): 77 | time_to_use = self.move_time[0] + np.random.rand(1)*(self.move_time[1] - self.move_time[0]) 78 | else: 79 | time_to_use = self.move_time 80 | 81 | to_return = self.engine.go(movetime=time_to_use).bestmove 82 | 83 | if self.print_info: 84 | print(self.info_handler.info) 85 | 86 | return to_return 87 | 88 | 89 | def compete(player1, player2, pairs_of_games=1, print_results=True, print_games=False): 90 | outcomes = np.zeros([2,3],dtype=np.int32) 91 | 92 | result_indices = {"1-0": 0, "0-1": 1, "1/2-1/2": 2} 93 | match_info = [(0, player1, player2), 94 | (1, player2, player1)] 95 | 96 | for _ in range(pairs_of_games): 97 | for i, p_white, p_black in match_info: 98 | outcomes[i, result_indices[play_one_game(p_white, p_black, print_games).result()]] += 1 99 | 100 | if print_results: 101 | for j in range(2): 102 | print("When player %d was white there was: %d wins, %d losses, and %d ties"%(j+1, outcomes[j, 0], outcomes[j, 1], outcomes[j, 2])) 103 | 104 | return outcomes 105 | 106 | 107 | if __name__ == "__main__": 108 | MAX_SEARCH_BATCH_SIZE = 2048 109 | 110 | 111 | GRAPHDEF_FILENAMES = [ 112 | "/srv/tmp/encoder_evaluation_helper/no_input_dilations_inception_modules_3/no_input_dilations_inception_modules_3.8/1542731579", 113 | "/srv/tmp/move_scoring_helper_current/no_dilations_for_trt_test_10_inception_diff_input/no_dilations_for_trt_test_10_inception_diff_input.3/1542881177" 114 | ] 115 | OUTPUT_MODEL_PATH = "/srv/tmp/combining_graphs_1" 116 | OUTPUT_MODEL_FILENAME = "COMBINED_OUTPUT_TEST_314.pbtxt" 117 | 118 | OUTPUT_NODE_NAMES = ["Squeeze", "requested_move_scores"] 119 | 120 | PREFIXES = ["value_network", "policy_network"] 121 | 122 | # combine_graphdefs( 123 | # GRAPHDEF_FILENAMES, 124 | # OUTPUT_MODEL_PATH, 125 | # OUTPUT_MODEL_FILENAME, 126 | # OUTPUT_NODE_NAMES, 127 | # name_prefixes=PREFIXES, 128 | # ) 129 | 130 | REMAPPED_INPUT_NAME = "remapped_input_graphdef__314" 131 | # remap_inputs(OUTPUT_MODEL_PATH + "/" + OUTPUT_MODEL_FILENAME, OUTPUT_MODEL_PATH, REMAPPED_INPUT_NAME, int(MAX_SEARCH_BATCH_SIZE*1.25)) 132 | 133 | OUTPUT_NODE_NAMES = ["%s/%s"%(prefix,name) for name, prefix in zip(OUTPUT_NODE_NAMES, PREFIXES)] 134 | TRT_OUTPUT_FILENAME = "COMBINED_TRT_TEST_314.pbtxt" 135 | # save_trt_graphdef( 136 | # OUTPUT_MODEL_PATH + "/" + REMAPPED_INPUT_NAME, 137 | # OUTPUT_MODEL_PATH, 138 | # TRT_OUTPUT_FILENAME, 139 | # OUTPUT_NODE_NAMES, 140 | # trt_memory_fraction=.65, 141 | # max_batch_size=int(1.25*MAX_SEARCH_BATCH_SIZE), 142 | # write_as_text=True) 143 | 144 | 145 | MOVE_SCORING_TEST_FILENAME = "/srv/databases/lichess/lichess_db_standard_rated_2018-07_first_100k_games.npy" 146 | ZERO_VALUE_BOARD_FILENAME = "/srv/databases/has_zero_valued_board/combined_zero_boards.npy" 147 | 148 | BOARD_PREDICTOR, MOVE_PREDICTOR, PREDICTOR_CLOSER = get_inference_functions(OUTPUT_MODEL_PATH + "/" + TRT_OUTPUT_FILENAME, session_gpu_memory=.2) 149 | 150 | search_depth = 4 151 | batch_first_engine = BatchFirstEngine( 152 | search_depth, 153 | BOARD_PREDICTOR, 154 | MOVE_PREDICTOR, 155 | bin_database_file="deeper_network_1.npy", 156 | max_batch_size=MAX_SEARCH_BATCH_SIZE, 157 | saved_zero_shift_file="no_dilations_inception_1.npy", 158 | ) 159 | 160 | 161 | 162 | ethereal_engine = UCIEngine("Ethereal-11.00/src/Ethereal", move_time=10, num_threads=1, print_search_info=True) 163 | 164 | competition_results = compete(batch_first_engine, ethereal_engine, print_games=True) 165 | 166 | PREDICTOR_CLOSER() 167 | --------------------------------------------------------------------------------