├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── README.md ├── marlinformat ├── .gitignore ├── Cargo.toml └── src │ └── lib.rs ├── parse ├── .cargo │ └── config.toml ├── Cargo.toml └── src │ ├── batch.rs │ ├── data_loader.rs │ ├── input_features │ ├── board_768.rs │ ├── half_ka.rs │ ├── half_kp.rs │ └── mod.rs │ └── lib.rs ├── trainer ├── LICENSE ├── cudasparse.py ├── dataloader.py ├── main.py ├── model.py ├── requirements.txt ├── trainlog.py └── visualize.py └── utils ├── Cargo.toml └── src ├── convert ├── halfkp.rs ├── mod.rs └── utils.rs ├── interleave.rs ├── main.rs ├── shuffle.rs └── txt_to_data.rs /.gitignore: -------------------------------------------------------------------------------- 1 | data 2 | trainer/nn 3 | trainer/runs 4 | /target 5 | libparse.dylib 6 | libparse.dll 7 | libparse.so 8 | __pycache__ 9 | venv -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 4 4 | 5 | [[package]] 6 | name = "aliasable" 7 | version = "0.1.3" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "250f629c0161ad8107cf89319e990051fae62832fd343083bea452d93e2205fd" 10 | 11 | [[package]] 12 | name = "ansi_term" 13 | version = "0.12.1" 14 | source = "registry+https://github.com/rust-lang/crates.io-index" 15 | checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" 16 | dependencies = [ 17 | "winapi", 18 | ] 19 | 20 | [[package]] 21 | name = "atty" 22 | version = "0.2.14" 23 | source = "registry+https://github.com/rust-lang/crates.io-index" 24 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 25 | dependencies = [ 26 | "hermit-abi", 27 | "libc", 28 | "winapi", 29 | ] 30 | 31 | [[package]] 32 | name = "bitflags" 33 | version = "1.3.2" 34 | source = "registry+https://github.com/rust-lang/crates.io-index" 35 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 36 | 37 | [[package]] 38 | name = "bitflags" 39 | version = "2.9.0" 40 | source = "registry+https://github.com/rust-lang/crates.io-index" 41 | checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" 42 | 43 | [[package]] 44 | name = "bytemuck" 45 | version = "1.22.0" 46 | source = "registry+https://github.com/rust-lang/crates.io-index" 47 | checksum = "b6b1fc10dbac614ebc03540c9dbd60e83887fda27794998c6528f1782047d540" 48 | dependencies = [ 49 | "bytemuck_derive", 50 | ] 51 | 52 | [[package]] 53 | name = "bytemuck_derive" 54 | version = "1.9.3" 55 | source = "registry+https://github.com/rust-lang/crates.io-index" 56 | checksum = "7ecc273b49b3205b83d648f0690daa588925572cc5063745bfe547fe7ec8e1a1" 57 | dependencies = [ 58 | "proc-macro2", 59 | "quote", 60 | "syn 2.0.100", 61 | ] 62 | 63 | [[package]] 64 | name = "cfg-if" 65 | version = "1.0.0" 66 | source = "registry+https://github.com/rust-lang/crates.io-index" 67 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 68 | 69 | [[package]] 70 | name = "clap" 71 | version = "2.34.0" 72 | source = "registry+https://github.com/rust-lang/crates.io-index" 73 | checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" 74 | dependencies = [ 75 | "ansi_term", 76 | "atty", 77 | "bitflags 1.3.2", 78 | "strsim", 79 | "textwrap", 80 | "unicode-width", 81 | "vec_map", 82 | ] 83 | 84 | [[package]] 85 | name = "cozy-chess" 86 | version = "0.3.4" 87 | source = "registry+https://github.com/rust-lang/crates.io-index" 88 | checksum = "27029a361056fc4f85ee27c02c8b3d219be061cb5ee95392541d4d5fc8aaff68" 89 | dependencies = [ 90 | "cozy-chess-types", 91 | ] 92 | 93 | [[package]] 94 | name = "cozy-chess-types" 95 | version = "0.2.2" 96 | source = "registry+https://github.com/rust-lang/crates.io-index" 97 | checksum = "276b4804775347af35852c80665ad23d62a9ee742a14656e7da6a7b1cee74ee9" 98 | 99 | [[package]] 100 | name = "cozy-syzygy" 101 | version = "0.1.0" 102 | source = "git+https://github.com/MinusKelvin/cozy-syzygy#72e2344443983fb7f7144431ea0593529fae52bb" 103 | dependencies = [ 104 | "cozy-chess", 105 | "memmap", 106 | "ouroboros", 107 | ] 108 | 109 | [[package]] 110 | name = "crossbeam-deque" 111 | version = "0.8.6" 112 | source = "registry+https://github.com/rust-lang/crates.io-index" 113 | checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" 114 | dependencies = [ 115 | "crossbeam-epoch", 116 | "crossbeam-utils", 117 | ] 118 | 119 | [[package]] 120 | name = "crossbeam-epoch" 121 | version = "0.9.18" 122 | source = "registry+https://github.com/rust-lang/crates.io-index" 123 | checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" 124 | dependencies = [ 125 | "crossbeam-utils", 126 | ] 127 | 128 | [[package]] 129 | name = "crossbeam-utils" 130 | version = "0.8.21" 131 | source = "registry+https://github.com/rust-lang/crates.io-index" 132 | checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" 133 | 134 | [[package]] 135 | name = "either" 136 | version = "1.15.0" 137 | source = "registry+https://github.com/rust-lang/crates.io-index" 138 | checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" 139 | 140 | [[package]] 141 | name = "errno" 142 | version = "0.3.11" 143 | source = "registry+https://github.com/rust-lang/crates.io-index" 144 | checksum = "976dd42dc7e85965fe702eb8164f21f450704bdde31faefd6471dba214cb594e" 145 | dependencies = [ 146 | "libc", 147 | "windows-sys", 148 | ] 149 | 150 | [[package]] 151 | name = "fastrand" 152 | version = "2.3.0" 153 | source = "registry+https://github.com/rust-lang/crates.io-index" 154 | checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" 155 | 156 | [[package]] 157 | name = "getrandom" 158 | version = "0.2.15" 159 | source = "registry+https://github.com/rust-lang/crates.io-index" 160 | checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" 161 | dependencies = [ 162 | "cfg-if", 163 | "libc", 164 | "wasi 0.11.0+wasi-snapshot-preview1", 165 | ] 166 | 167 | [[package]] 168 | name = "getrandom" 169 | version = "0.3.2" 170 | source = "registry+https://github.com/rust-lang/crates.io-index" 171 | checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0" 172 | dependencies = [ 173 | "cfg-if", 174 | "libc", 175 | "r-efi", 176 | "wasi 0.14.2+wasi-0.2.4", 177 | ] 178 | 179 | [[package]] 180 | name = "heck" 181 | version = "0.3.3" 182 | source = "registry+https://github.com/rust-lang/crates.io-index" 183 | checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" 184 | dependencies = [ 185 | "unicode-segmentation", 186 | ] 187 | 188 | [[package]] 189 | name = "heck" 190 | version = "0.4.1" 191 | source = "registry+https://github.com/rust-lang/crates.io-index" 192 | checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" 193 | 194 | [[package]] 195 | name = "hermit-abi" 196 | version = "0.1.19" 197 | source = "registry+https://github.com/rust-lang/crates.io-index" 198 | checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" 199 | dependencies = [ 200 | "libc", 201 | ] 202 | 203 | [[package]] 204 | name = "itoa" 205 | version = "1.0.15" 206 | source = "registry+https://github.com/rust-lang/crates.io-index" 207 | checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" 208 | 209 | [[package]] 210 | name = "lazy_static" 211 | version = "1.5.0" 212 | source = "registry+https://github.com/rust-lang/crates.io-index" 213 | checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" 214 | 215 | [[package]] 216 | name = "libc" 217 | version = "0.2.171" 218 | source = "registry+https://github.com/rust-lang/crates.io-index" 219 | checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" 220 | 221 | [[package]] 222 | name = "linux-raw-sys" 223 | version = "0.9.4" 224 | source = "registry+https://github.com/rust-lang/crates.io-index" 225 | checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" 226 | 227 | [[package]] 228 | name = "marlinflow-utils" 229 | version = "0.1.0" 230 | dependencies = [ 231 | "bytemuck", 232 | "cozy-chess", 233 | "marlinformat", 234 | "rand", 235 | "serde", 236 | "serde_json", 237 | "structopt", 238 | "tempfile", 239 | ] 240 | 241 | [[package]] 242 | name = "marlinformat" 243 | version = "0.1.0" 244 | dependencies = [ 245 | "bytemuck", 246 | "cozy-chess", 247 | ] 248 | 249 | [[package]] 250 | name = "memchr" 251 | version = "2.7.4" 252 | source = "registry+https://github.com/rust-lang/crates.io-index" 253 | checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" 254 | 255 | [[package]] 256 | name = "memmap" 257 | version = "0.7.0" 258 | source = "registry+https://github.com/rust-lang/crates.io-index" 259 | checksum = "6585fd95e7bb50d6cc31e20d4cf9afb4e2ba16c5846fc76793f11218da9c475b" 260 | dependencies = [ 261 | "libc", 262 | "winapi", 263 | ] 264 | 265 | [[package]] 266 | name = "once_cell" 267 | version = "1.21.3" 268 | source = "registry+https://github.com/rust-lang/crates.io-index" 269 | checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" 270 | 271 | [[package]] 272 | name = "ouroboros" 273 | version = "0.18.5" 274 | source = "registry+https://github.com/rust-lang/crates.io-index" 275 | checksum = "1e0f050db9c44b97a94723127e6be766ac5c340c48f2c4bb3ffa11713744be59" 276 | dependencies = [ 277 | "aliasable", 278 | "ouroboros_macro", 279 | "static_assertions", 280 | ] 281 | 282 | [[package]] 283 | name = "ouroboros_macro" 284 | version = "0.18.5" 285 | source = "registry+https://github.com/rust-lang/crates.io-index" 286 | checksum = "3c7028bdd3d43083f6d8d4d5187680d0d3560d54df4cc9d752005268b41e64d0" 287 | dependencies = [ 288 | "heck 0.4.1", 289 | "proc-macro2", 290 | "proc-macro2-diagnostics", 291 | "quote", 292 | "syn 2.0.100", 293 | ] 294 | 295 | [[package]] 296 | name = "parse" 297 | version = "0.1.0" 298 | dependencies = [ 299 | "bytemuck", 300 | "cozy-chess", 301 | "cozy-syzygy", 302 | "marlinformat", 303 | "rayon", 304 | ] 305 | 306 | [[package]] 307 | name = "ppv-lite86" 308 | version = "0.2.21" 309 | source = "registry+https://github.com/rust-lang/crates.io-index" 310 | checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" 311 | dependencies = [ 312 | "zerocopy", 313 | ] 314 | 315 | [[package]] 316 | name = "proc-macro-error" 317 | version = "1.0.4" 318 | source = "registry+https://github.com/rust-lang/crates.io-index" 319 | checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" 320 | dependencies = [ 321 | "proc-macro-error-attr", 322 | "proc-macro2", 323 | "quote", 324 | "syn 1.0.109", 325 | "version_check", 326 | ] 327 | 328 | [[package]] 329 | name = "proc-macro-error-attr" 330 | version = "1.0.4" 331 | source = "registry+https://github.com/rust-lang/crates.io-index" 332 | checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" 333 | dependencies = [ 334 | "proc-macro2", 335 | "quote", 336 | "version_check", 337 | ] 338 | 339 | [[package]] 340 | name = "proc-macro2" 341 | version = "1.0.94" 342 | source = "registry+https://github.com/rust-lang/crates.io-index" 343 | checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" 344 | dependencies = [ 345 | "unicode-ident", 346 | ] 347 | 348 | [[package]] 349 | name = "proc-macro2-diagnostics" 350 | version = "0.10.1" 351 | source = "registry+https://github.com/rust-lang/crates.io-index" 352 | checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" 353 | dependencies = [ 354 | "proc-macro2", 355 | "quote", 356 | "syn 2.0.100", 357 | "version_check", 358 | "yansi", 359 | ] 360 | 361 | [[package]] 362 | name = "quote" 363 | version = "1.0.40" 364 | source = "registry+https://github.com/rust-lang/crates.io-index" 365 | checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" 366 | dependencies = [ 367 | "proc-macro2", 368 | ] 369 | 370 | [[package]] 371 | name = "r-efi" 372 | version = "5.2.0" 373 | source = "registry+https://github.com/rust-lang/crates.io-index" 374 | checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" 375 | 376 | [[package]] 377 | name = "rand" 378 | version = "0.8.5" 379 | source = "registry+https://github.com/rust-lang/crates.io-index" 380 | checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" 381 | dependencies = [ 382 | "libc", 383 | "rand_chacha", 384 | "rand_core", 385 | ] 386 | 387 | [[package]] 388 | name = "rand_chacha" 389 | version = "0.3.1" 390 | source = "registry+https://github.com/rust-lang/crates.io-index" 391 | checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" 392 | dependencies = [ 393 | "ppv-lite86", 394 | "rand_core", 395 | ] 396 | 397 | [[package]] 398 | name = "rand_core" 399 | version = "0.6.4" 400 | source = "registry+https://github.com/rust-lang/crates.io-index" 401 | checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" 402 | dependencies = [ 403 | "getrandom 0.2.15", 404 | ] 405 | 406 | [[package]] 407 | name = "rayon" 408 | version = "1.10.0" 409 | source = "registry+https://github.com/rust-lang/crates.io-index" 410 | checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa" 411 | dependencies = [ 412 | "either", 413 | "rayon-core", 414 | ] 415 | 416 | [[package]] 417 | name = "rayon-core" 418 | version = "1.12.1" 419 | source = "registry+https://github.com/rust-lang/crates.io-index" 420 | checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" 421 | dependencies = [ 422 | "crossbeam-deque", 423 | "crossbeam-utils", 424 | ] 425 | 426 | [[package]] 427 | name = "rustix" 428 | version = "1.0.5" 429 | source = "registry+https://github.com/rust-lang/crates.io-index" 430 | checksum = "d97817398dd4bb2e6da002002db259209759911da105da92bec29ccb12cf58bf" 431 | dependencies = [ 432 | "bitflags 2.9.0", 433 | "errno", 434 | "libc", 435 | "linux-raw-sys", 436 | "windows-sys", 437 | ] 438 | 439 | [[package]] 440 | name = "ryu" 441 | version = "1.0.20" 442 | source = "registry+https://github.com/rust-lang/crates.io-index" 443 | checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" 444 | 445 | [[package]] 446 | name = "serde" 447 | version = "1.0.219" 448 | source = "registry+https://github.com/rust-lang/crates.io-index" 449 | checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" 450 | dependencies = [ 451 | "serde_derive", 452 | ] 453 | 454 | [[package]] 455 | name = "serde_derive" 456 | version = "1.0.219" 457 | source = "registry+https://github.com/rust-lang/crates.io-index" 458 | checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" 459 | dependencies = [ 460 | "proc-macro2", 461 | "quote", 462 | "syn 2.0.100", 463 | ] 464 | 465 | [[package]] 466 | name = "serde_json" 467 | version = "1.0.140" 468 | source = "registry+https://github.com/rust-lang/crates.io-index" 469 | checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" 470 | dependencies = [ 471 | "itoa", 472 | "memchr", 473 | "ryu", 474 | "serde", 475 | ] 476 | 477 | [[package]] 478 | name = "static_assertions" 479 | version = "1.1.0" 480 | source = "registry+https://github.com/rust-lang/crates.io-index" 481 | checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" 482 | 483 | [[package]] 484 | name = "strsim" 485 | version = "0.8.0" 486 | source = "registry+https://github.com/rust-lang/crates.io-index" 487 | checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" 488 | 489 | [[package]] 490 | name = "structopt" 491 | version = "0.3.26" 492 | source = "registry+https://github.com/rust-lang/crates.io-index" 493 | checksum = "0c6b5c64445ba8094a6ab0c3cd2ad323e07171012d9c98b0b15651daf1787a10" 494 | dependencies = [ 495 | "clap", 496 | "lazy_static", 497 | "structopt-derive", 498 | ] 499 | 500 | [[package]] 501 | name = "structopt-derive" 502 | version = "0.4.18" 503 | source = "registry+https://github.com/rust-lang/crates.io-index" 504 | checksum = "dcb5ae327f9cc13b68763b5749770cb9e048a99bd9dfdfa58d0cf05d5f64afe0" 505 | dependencies = [ 506 | "heck 0.3.3", 507 | "proc-macro-error", 508 | "proc-macro2", 509 | "quote", 510 | "syn 1.0.109", 511 | ] 512 | 513 | [[package]] 514 | name = "syn" 515 | version = "1.0.109" 516 | source = "registry+https://github.com/rust-lang/crates.io-index" 517 | checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" 518 | dependencies = [ 519 | "proc-macro2", 520 | "quote", 521 | "unicode-ident", 522 | ] 523 | 524 | [[package]] 525 | name = "syn" 526 | version = "2.0.100" 527 | source = "registry+https://github.com/rust-lang/crates.io-index" 528 | checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" 529 | dependencies = [ 530 | "proc-macro2", 531 | "quote", 532 | "unicode-ident", 533 | ] 534 | 535 | [[package]] 536 | name = "tempfile" 537 | version = "3.19.1" 538 | source = "registry+https://github.com/rust-lang/crates.io-index" 539 | checksum = "7437ac7763b9b123ccf33c338a5cc1bac6f69b45a136c19bdd8a65e3916435bf" 540 | dependencies = [ 541 | "fastrand", 542 | "getrandom 0.3.2", 543 | "once_cell", 544 | "rustix", 545 | "windows-sys", 546 | ] 547 | 548 | [[package]] 549 | name = "textwrap" 550 | version = "0.11.0" 551 | source = "registry+https://github.com/rust-lang/crates.io-index" 552 | checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" 553 | dependencies = [ 554 | "unicode-width", 555 | ] 556 | 557 | [[package]] 558 | name = "unicode-ident" 559 | version = "1.0.18" 560 | source = "registry+https://github.com/rust-lang/crates.io-index" 561 | checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" 562 | 563 | [[package]] 564 | name = "unicode-segmentation" 565 | version = "1.12.0" 566 | source = "registry+https://github.com/rust-lang/crates.io-index" 567 | checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" 568 | 569 | [[package]] 570 | name = "unicode-width" 571 | version = "0.1.14" 572 | source = "registry+https://github.com/rust-lang/crates.io-index" 573 | checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" 574 | 575 | [[package]] 576 | name = "vec_map" 577 | version = "0.8.2" 578 | source = "registry+https://github.com/rust-lang/crates.io-index" 579 | checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" 580 | 581 | [[package]] 582 | name = "version_check" 583 | version = "0.9.5" 584 | source = "registry+https://github.com/rust-lang/crates.io-index" 585 | checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" 586 | 587 | [[package]] 588 | name = "wasi" 589 | version = "0.11.0+wasi-snapshot-preview1" 590 | source = "registry+https://github.com/rust-lang/crates.io-index" 591 | checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" 592 | 593 | [[package]] 594 | name = "wasi" 595 | version = "0.14.2+wasi-0.2.4" 596 | source = "registry+https://github.com/rust-lang/crates.io-index" 597 | checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" 598 | dependencies = [ 599 | "wit-bindgen-rt", 600 | ] 601 | 602 | [[package]] 603 | name = "winapi" 604 | version = "0.3.9" 605 | source = "registry+https://github.com/rust-lang/crates.io-index" 606 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 607 | dependencies = [ 608 | "winapi-i686-pc-windows-gnu", 609 | "winapi-x86_64-pc-windows-gnu", 610 | ] 611 | 612 | [[package]] 613 | name = "winapi-i686-pc-windows-gnu" 614 | version = "0.4.0" 615 | source = "registry+https://github.com/rust-lang/crates.io-index" 616 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 617 | 618 | [[package]] 619 | name = "winapi-x86_64-pc-windows-gnu" 620 | version = "0.4.0" 621 | source = "registry+https://github.com/rust-lang/crates.io-index" 622 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 623 | 624 | [[package]] 625 | name = "windows-sys" 626 | version = "0.59.0" 627 | source = "registry+https://github.com/rust-lang/crates.io-index" 628 | checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" 629 | dependencies = [ 630 | "windows-targets", 631 | ] 632 | 633 | [[package]] 634 | name = "windows-targets" 635 | version = "0.52.6" 636 | source = "registry+https://github.com/rust-lang/crates.io-index" 637 | checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" 638 | dependencies = [ 639 | "windows_aarch64_gnullvm", 640 | "windows_aarch64_msvc", 641 | "windows_i686_gnu", 642 | "windows_i686_gnullvm", 643 | "windows_i686_msvc", 644 | "windows_x86_64_gnu", 645 | "windows_x86_64_gnullvm", 646 | "windows_x86_64_msvc", 647 | ] 648 | 649 | [[package]] 650 | name = "windows_aarch64_gnullvm" 651 | version = "0.52.6" 652 | source = "registry+https://github.com/rust-lang/crates.io-index" 653 | checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" 654 | 655 | [[package]] 656 | name = "windows_aarch64_msvc" 657 | version = "0.52.6" 658 | source = "registry+https://github.com/rust-lang/crates.io-index" 659 | checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" 660 | 661 | [[package]] 662 | name = "windows_i686_gnu" 663 | version = "0.52.6" 664 | source = "registry+https://github.com/rust-lang/crates.io-index" 665 | checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" 666 | 667 | [[package]] 668 | name = "windows_i686_gnullvm" 669 | version = "0.52.6" 670 | source = "registry+https://github.com/rust-lang/crates.io-index" 671 | checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" 672 | 673 | [[package]] 674 | name = "windows_i686_msvc" 675 | version = "0.52.6" 676 | source = "registry+https://github.com/rust-lang/crates.io-index" 677 | checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" 678 | 679 | [[package]] 680 | name = "windows_x86_64_gnu" 681 | version = "0.52.6" 682 | source = "registry+https://github.com/rust-lang/crates.io-index" 683 | checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" 684 | 685 | [[package]] 686 | name = "windows_x86_64_gnullvm" 687 | version = "0.52.6" 688 | source = "registry+https://github.com/rust-lang/crates.io-index" 689 | checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" 690 | 691 | [[package]] 692 | name = "windows_x86_64_msvc" 693 | version = "0.52.6" 694 | source = "registry+https://github.com/rust-lang/crates.io-index" 695 | checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" 696 | 697 | [[package]] 698 | name = "wit-bindgen-rt" 699 | version = "0.39.0" 700 | source = "registry+https://github.com/rust-lang/crates.io-index" 701 | checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" 702 | dependencies = [ 703 | "bitflags 2.9.0", 704 | ] 705 | 706 | [[package]] 707 | name = "yansi" 708 | version = "1.0.1" 709 | source = "registry+https://github.com/rust-lang/crates.io-index" 710 | checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" 711 | 712 | [[package]] 713 | name = "zerocopy" 714 | version = "0.8.24" 715 | source = "registry+https://github.com/rust-lang/crates.io-index" 716 | checksum = "2586fea28e186957ef732a5f8b3be2da217d65c5969d4b1e17f973ebbe876879" 717 | dependencies = [ 718 | "zerocopy-derive", 719 | ] 720 | 721 | [[package]] 722 | name = "zerocopy-derive" 723 | version = "0.8.24" 724 | source = "registry+https://github.com/rust-lang/crates.io-index" 725 | checksum = "a996a8f63c5c4448cd959ac1bab0aaa3306ccfd060472f85943ee0750f0169be" 726 | dependencies = [ 727 | "proc-macro2", 728 | "quote", 729 | "syn 2.0.100", 730 | ] 731 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | 3 | members = [ 4 | "parse", 5 | "utils", 6 | "marlinformat", 7 | ] 8 | 9 | [profile.release] 10 | lto = true 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Marlinflow 2 | ### Neural Network training repository for the [Black Marlin](https://github.com/dsekercioglu/blackmarlin) chess engine. 3 | 4 | This repo is or was relied upon by a number of other engines, including but not limited to [Viridithas](https://github.com/cosmobobak/viridithas), [Svart](https://github.com/crippa1337/svart), and [Carp](https://github.com/dede1751/carp). 5 | 6 | # Requirements 7 | - Python 3 8 | - Cargo (Rust) 9 | - Numpy 10 | - PyTorch 11 | 12 | # Usage 13 | 1. Clone the repo with `git clone https://github.com/dsekercioglu/marlinflow` 14 | 2. Build the data parser, using native CPU optimisations for your system: 15 | 16 | ```bash 17 | cd parse 18 | cargo rustc --release -- -C target-cpu=native 19 | ``` 20 | 21 | 3. Locate the resulting `.so`/`.dll` in the `target/release/` directory and move it to the `trainer/` directory, renamed as libparse.so/libparse.dll. 22 | 4. Create some directories for training output in the `trainer/` directory: 23 | 24 | In `trainer/`, do 25 | ```bash 26 | mkdir nn 27 | mkdir runs 28 | ``` 29 | 30 | 5. Decide upon the directory in which you want to store your training data. (simply making a `data/` directory inside `trainer/` is a solid option) 31 | 6. Place your data file in the directory created in step 5. (if you don't have one, consult [Getting Data](#getting-data)) 32 | 7. In `trainer/`, run `main.py` with the proper command line arguments: 33 | 34 | A typical invocation for training a network looks like this: 35 | ```bash 36 | python main.py \ 37 | --data-root data \ 38 | --train-id net0001 \ 39 | --lr 0.001 \ 40 | --epochs 45 \ 41 | --lr-drop 30 \ 42 | --batch-size 16384 \ 43 | --wdl 0.3 \ 44 | --scale 400 \ 45 | --save-epochs 5 46 | ``` 47 | 48 | - `--data-root` is the directory created in step 5. 49 | - `--train-id` is the name of the training run. 50 | - `--lr` is the learning rate. 51 | - `--epochs` is the number of epochs to train for. 52 | - `--lr-drop` is the number of epochs after which the learning rate is dropped by a factor of 10. 53 | - `--batch-size` is the batch size. 54 | - `--wdl` is the weight of the WDL loss. (1.0 would train the network to only predict game outcome, while 0.0 would aim to predict only eval, and other values interpolate between the two) 55 | - `--scale` is the multiplier for the sigmoid output of the final neuron. 56 | - `--save-epochs n` tells the trainer to save the network every `n` epochs. 57 | 58 | 8. Convert the resulting JSON network file into a format usable by your engine: 59 | 60 | The trainer will output a number of files in the `nn/` directory - files of the form `net0001_X` are saved state_dict files, which you can ignore (unless you're aiming to resume a half-completed training run) - `net0001.json` is what you're interested in: a JSON file containing the final weights of the network. 61 | 62 | In order to use the network, you will need to convert the JSON file into a more usable format, and you will almost certainly want to quantise it. For simple perspective networks, this can be done with [nnue-jsontobin](https://github.com/cosmobobak/nnue-jsontobin), while for more complex networks like HalfKP and HalfKA (or ones you have designed yourself!) you will need to employ some elbow grease. 63 | 64 | # Getting Data 65 | To train a network, you will need a large amount of training data. There are a number of possible sources for this data, the most common of which is that you will generate it using your own chess engine, which requires that you write some datagen code. It is recommended that your data generator produce data directly in the marlinflow data format, and not in the legacy text format (see [Legacy Text Format](#legacy-text-format)), as it is a significantly more compact format, and skips the required conversion step. 66 | 67 | To convert a file in the legacy text format into a data file, use marlinflow-utils, which is built in much the same way as the parser: 68 | ```bash 69 | cd utils 70 | cargo rustc --release -- -C target-cpu=native 71 | ``` 72 | The resulting binary will be in `target/release/`, and can be invoked as follows: 73 | ```bash 74 | target/release/marlinflow-utils txt-to-data INPUT.txt --output OUTPUT.bin 75 | ``` 76 | 77 | # Legacy Text Format 78 | Marlinflow accepts a specific text format for conversion into data files, with lines set out as following: 79 | ``` 80 | | | 81 | | | 82 | ``` 83 | Here, `` is a [FEN string](https://www.chessprogramming.org/Forsyth-Edwards_Notation), `` is a evaluation in centipawns from white's point of view, and `` is 1.0, 0.5, or 0.0, representing a win for white, a draw, or a win for black, respectively. 84 | 85 | # Marlinflow-Utils 86 | `marlinflow-utils` is a program that provides a number of utilities for working with marlinflow. These are as follows: 87 | - `txt-to-data` converts a legacy text file into a data file. 88 | - `shuffle` shuffles a data file. It is extremely important to shuffle your data before training, to prevent overfitting. 89 | - `interleave` randomly interleaves data files. This allows you to cleanly combine data from multiple sources without requiring a re-shuffle, provided that the source files have already been shuffled. 90 | - `convert` will convert an NNUE JSON file into the BlackMarlin NNUE format. (currently only supports HalfKP) -------------------------------------------------------------------------------- /marlinformat/.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | -------------------------------------------------------------------------------- /marlinformat/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "marlinformat" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | bytemuck = { version = "1.10.0", features = ["derive"] } 10 | cozy-chess = "0.3.4" 11 | -------------------------------------------------------------------------------- /marlinformat/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | use bytemuck::{Pod, Zeroable}; 4 | use cozy_chess::{BitBoard, Board, BoardBuilder, Color, Piece, Rank, Square}; 5 | 6 | const UNMOVED_ROOK: u8 = Piece::NUM as u8; 7 | 8 | #[derive(Copy, Clone, Debug, Pod, Zeroable)] 9 | #[repr(C)] 10 | pub struct PackedBoard { 11 | occupancy: util::U64Le, 12 | pieces: util::U4Array32, 13 | stm_ep_square: u8, 14 | halfmove_clock: u8, 15 | fullmove_number: util::U16Le, 16 | eval: util::I16Le, 17 | wdl: u8, 18 | extra: u8, 19 | } 20 | 21 | impl PackedBoard { 22 | pub fn pack(board: &Board, eval: i16, wdl: u8, extra: u8) -> Self { 23 | let occupancy = board.occupied(); 24 | 25 | let mut pieces = util::U4Array32::default(); 26 | for (i, sq) in occupancy.into_iter().enumerate() { 27 | let piece = board.piece_on(sq).unwrap(); 28 | let color = board.color_on(sq).unwrap(); 29 | 30 | let mut piece_code = piece as u8; 31 | if piece == Piece::Rook && sq.rank() == Rank::First.relative_to(color) { 32 | let castling_file = match board.king(color) < sq { 33 | true => board.castle_rights(color).short, 34 | false => board.castle_rights(color).long, 35 | }; 36 | if Some(sq.file()) == castling_file { 37 | piece_code = UNMOVED_ROOK; 38 | } 39 | } 40 | 41 | pieces.set(i, piece_code | (color as u8) << 3); 42 | } 43 | 44 | PackedBoard { 45 | occupancy: util::U64Le::new(occupancy.0), 46 | pieces, 47 | stm_ep_square: (board.side_to_move() as u8) << 7 48 | | board.en_passant().map_or(Square::NUM as u8, |f| { 49 | Square::new(f, Rank::Sixth.relative_to(board.side_to_move())) as u8 50 | }), 51 | halfmove_clock: board.halfmove_clock(), 52 | fullmove_number: util::U16Le::new(board.fullmove_number()), 53 | wdl, 54 | eval: util::I16Le::new(eval), 55 | extra, 56 | } 57 | } 58 | 59 | pub fn unpack(&self) -> Option<(Board, i16, u8, u8)> { 60 | let mut builder = BoardBuilder::empty(); 61 | 62 | let mut seen_king = [false; 2]; 63 | for (i, sq) in BitBoard(self.occupancy.get()).into_iter().enumerate() { 64 | let color = Color::try_index(self.pieces.get(i) as usize >> 3)?; 65 | let piece_code = self.pieces.get(i) & 0b0111; 66 | let piece = match piece_code { 67 | UNMOVED_ROOK => { 68 | if seen_king[color as usize] { 69 | builder.castle_rights_mut(color).short = Some(sq.file()); 70 | } else { 71 | builder.castle_rights_mut(color).long = Some(sq.file()); 72 | } 73 | Piece::Rook 74 | } 75 | _ => Piece::try_index(piece_code as usize)?, 76 | }; 77 | if piece == Piece::King { 78 | seen_king[color as usize] = true; 79 | } 80 | builder.board[sq as usize] = Some((piece, color)); 81 | } 82 | 83 | builder.en_passant = Square::try_index(self.stm_ep_square as usize & 0b01111111); 84 | builder.side_to_move = Color::try_index(self.stm_ep_square as usize >> 7)?; 85 | builder.halfmove_clock = self.halfmove_clock; 86 | builder.fullmove_number = self.fullmove_number.get(); 87 | 88 | Some((builder.build().ok()?, self.eval.get(), self.wdl, self.extra)) 89 | } 90 | } 91 | 92 | mod util { 93 | use bytemuck::{Pod, Zeroable}; 94 | 95 | #[derive(Copy, Clone, Debug, Default, Pod, Zeroable)] 96 | #[repr(transparent)] 97 | pub struct U64Le(u64); 98 | 99 | impl U64Le { 100 | pub fn new(v: u64) -> Self { 101 | U64Le(v.to_le()) 102 | } 103 | 104 | pub fn get(self) -> u64 { 105 | u64::from_le(self.0) 106 | } 107 | } 108 | 109 | #[derive(Copy, Clone, Debug, Default, Pod, Zeroable)] 110 | #[repr(transparent)] 111 | pub struct U16Le(u16); 112 | 113 | impl U16Le { 114 | pub fn new(v: u16) -> Self { 115 | U16Le(v.to_le()) 116 | } 117 | 118 | pub fn get(self) -> u16 { 119 | u16::from_le(self.0) 120 | } 121 | } 122 | 123 | #[derive(Copy, Clone, Debug, Default, Pod, Zeroable)] 124 | #[repr(transparent)] 125 | pub struct I16Le(i16); 126 | 127 | impl I16Le { 128 | pub fn new(v: i16) -> Self { 129 | I16Le(v.to_le()) 130 | } 131 | 132 | pub fn get(self) -> i16 { 133 | i16::from_le(self.0) 134 | } 135 | } 136 | 137 | #[derive(Copy, Clone, Debug, Default, Pod, Zeroable)] 138 | #[repr(transparent)] 139 | pub struct U4Array32([u8; 16]); 140 | 141 | impl U4Array32 { 142 | pub fn get(&self, i: usize) -> u8 { 143 | (self.0[i / 2] >> (i % 2) * 4) & 0xF 144 | } 145 | 146 | pub fn set(&mut self, i: usize, v: u8) { 147 | debug_assert!(v < 0x10); 148 | self.0[i / 2] |= v << (i % 2) * 4; 149 | } 150 | } 151 | } 152 | 153 | #[cfg(test)] 154 | mod tests { 155 | use super::*; 156 | 157 | #[test] 158 | #[ignore] 159 | fn roundtrip() { 160 | // Grab `valid.sfens` from `cozy-chess` to run test 161 | for sfen in include_str!("valid.sfens").lines() { 162 | let board = Board::from_fen(sfen, true).unwrap(); 163 | let packed = PackedBoard::pack(&board, 0, 0, 0); 164 | let (unpacked, _, _, _) = packed 165 | .unpack() 166 | .unwrap_or_else(|| panic!("Failed to unpack {}. {:#X?}", sfen, packed)); 167 | assert_eq!(board, unpacked, "{}", sfen); 168 | } 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /parse/.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [build] 2 | rustflags = ["-C", "target-cpu=native"] 3 | -------------------------------------------------------------------------------- /parse/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "parse" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | [lib] 8 | crate-type = ["cdylib"] 9 | 10 | [dependencies] 11 | cozy-chess = "0.3.4" 12 | cozy-syzygy = { git = "https://github.com/MinusKelvin/cozy-syzygy" } 13 | rayon = "1.5.0" 14 | marlinformat = { path = "../marlinformat" } 15 | bytemuck = "1.10.0" 16 | -------------------------------------------------------------------------------- /parse/src/batch.rs: -------------------------------------------------------------------------------- 1 | pub struct Batch { 2 | // The maximum number of entries 3 | capacity: usize, 4 | 5 | max_features: usize, 6 | 7 | stm_feature_buffer: Box<[i64]>, 8 | nstm_feature_buffer: Box<[i64]>, 9 | values: Box<[f32]>, 10 | total_features: usize, 11 | indices_per_feature: usize, 12 | 13 | cp: Box<[f32]>, 14 | wdl: Box<[f32]>, 15 | 16 | // The number of entries actually written 17 | entries: usize, 18 | } 19 | 20 | impl Batch { 21 | pub fn new(capacity: usize, max_features: usize, indices_per_feature: usize) -> Self { 22 | Self { 23 | capacity, 24 | max_features, 25 | stm_feature_buffer: vec![0; capacity * max_features * indices_per_feature] 26 | .into_boxed_slice(), 27 | nstm_feature_buffer: vec![0; capacity * max_features * indices_per_feature] 28 | .into_boxed_slice(), 29 | total_features: 0, 30 | indices_per_feature, 31 | values: vec![1.0; capacity * max_features].into_boxed_slice(), 32 | cp: vec![0_f32; capacity].into_boxed_slice(), 33 | wdl: vec![0_f32; capacity].into_boxed_slice(), 34 | entries: 0, 35 | } 36 | } 37 | 38 | pub fn make_entry(&mut self, cp: f32, wdl: f32) -> EntryFeatureWriter { 39 | let index_in_batch = self.entries; 40 | self.entries += 1; 41 | self.cp[index_in_batch] = cp; 42 | self.wdl[index_in_batch] = wdl; 43 | EntryFeatureWriter { 44 | batch: self, 45 | index_in_batch, 46 | } 47 | } 48 | 49 | pub fn clear(&mut self) { 50 | self.entries = 0; 51 | self.total_features = 0; 52 | } 53 | 54 | pub fn capacity(&self) -> usize { 55 | self.capacity 56 | } 57 | 58 | pub fn len(&self) -> usize { 59 | self.entries 60 | } 61 | 62 | pub fn stm_feature_buffer_ptr(&self) -> *const i64 { 63 | &self.stm_feature_buffer[0] 64 | } 65 | 66 | pub fn nstm_feature_buffer_ptr(&self) -> *const i64 { 67 | &self.nstm_feature_buffer[0] 68 | } 69 | 70 | pub fn values_ptr(&self) -> *const f32 { 71 | &self.values[0] 72 | } 73 | 74 | pub fn total_features(&self) -> usize { 75 | self.total_features 76 | } 77 | 78 | pub fn indices_per_feature(&self) -> usize { 79 | self.indices_per_feature 80 | } 81 | 82 | pub fn cp_ptr(&self) -> *const f32 { 83 | &self.cp[0] 84 | } 85 | 86 | pub fn wdl_ptr(&self) -> *const f32 { 87 | &self.wdl[0] 88 | } 89 | } 90 | 91 | pub struct SparseBatchWriter<'b> { 92 | entry_feature_writer: EntryFeatureWriter<'b>, 93 | } 94 | 95 | impl SparseBatchWriter<'_> { 96 | pub fn add_feature(&mut self, stm_feature: i64, nstm_feature: i64) { 97 | self.entry_feature_writer 98 | .add_feature_sparse(stm_feature, nstm_feature); 99 | } 100 | } 101 | 102 | pub struct CudaBatchWriter<'b> { 103 | entry_feature_writer: EntryFeatureWriter<'b>, 104 | count: usize, 105 | } 106 | 107 | impl CudaBatchWriter<'_> { 108 | pub fn add_feature(&mut self, stm_feature: i64, nstm_feature: i64) { 109 | self.entry_feature_writer 110 | .add_feature_cuda(stm_feature, nstm_feature); 111 | self.count += 1; 112 | } 113 | } 114 | 115 | impl<'b> Drop for CudaBatchWriter<'b> { 116 | fn drop(&mut self) { 117 | self.entry_feature_writer.complete_cuda(self.count); 118 | } 119 | } 120 | 121 | pub struct EntryFeatureWriter<'b> { 122 | batch: &'b mut Batch, 123 | index_in_batch: usize, 124 | } 125 | 126 | impl<'b> EntryFeatureWriter<'b> { 127 | pub fn sparse(self) -> SparseBatchWriter<'b> { 128 | SparseBatchWriter { 129 | entry_feature_writer: self, 130 | } 131 | } 132 | 133 | pub fn cuda(self) -> CudaBatchWriter<'b> { 134 | CudaBatchWriter { 135 | entry_feature_writer: self, 136 | count: 0, 137 | } 138 | } 139 | 140 | fn add_feature_sparse(&mut self, stm_feature: i64, nstm_feature: i64) { 141 | let index = self.batch.total_features; 142 | self.batch.stm_feature_buffer[index * 2] = self.index_in_batch as i64; 143 | self.batch.nstm_feature_buffer[index * 2] = self.index_in_batch as i64; 144 | self.batch.stm_feature_buffer[index * 2 + 1] = stm_feature; 145 | self.batch.nstm_feature_buffer[index * 2 + 1] = nstm_feature; 146 | self.batch.total_features += 1; 147 | } 148 | 149 | fn add_feature_cuda(&mut self, stm_feature: i64, nstm_feature: i64) { 150 | self.batch.stm_feature_buffer[self.batch.total_features] = stm_feature; 151 | self.batch.nstm_feature_buffer[self.batch.total_features] = nstm_feature; 152 | self.batch.total_features += 1; 153 | } 154 | 155 | fn complete_cuda(&mut self, count: usize) { 156 | let left_to_fill = self.batch.max_features - count; 157 | for _ in 0..left_to_fill { 158 | self.batch.stm_feature_buffer[self.batch.total_features] = -1; 159 | self.batch.nstm_feature_buffer[self.batch.total_features] = -1; 160 | self.batch.total_features += 1; 161 | } 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /parse/src/data_loader.rs: -------------------------------------------------------------------------------- 1 | use std::{fs::File, io::Read, path::Path}; 2 | 3 | use bytemuck::Zeroable; 4 | use cozy_chess::{Board, Color}; 5 | use marlinformat::PackedBoard; 6 | use rayon::iter::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator}; 7 | 8 | use crate::batch::Batch; 9 | use crate::input_features::InputFeatureSet; 10 | 11 | #[derive(Debug)] 12 | pub struct AnnotatedBoard { 13 | board: Board, 14 | cp: f32, 15 | wdl: f32, 16 | } 17 | 18 | impl AnnotatedBoard { 19 | pub fn relative_value(&self) -> (f32, f32) { 20 | match self.board.side_to_move() { 21 | Color::White => (self.cp, self.wdl), 22 | Color::Black => (-self.cp, 1.0 - self.wdl), 23 | } 24 | } 25 | } 26 | 27 | pub struct FileReader { 28 | file: File, 29 | packed_buffer: Vec, 30 | board_buffer: Vec>, 31 | } 32 | 33 | impl FileReader { 34 | pub fn new(path: impl AsRef) -> std::io::Result { 35 | let file = File::open(path)?; 36 | Ok(Self { 37 | file, 38 | packed_buffer: vec![], 39 | board_buffer: vec![], 40 | }) 41 | } 42 | 43 | fn try_fill_buffer(&mut self, chunk_size: usize) -> bool { 44 | self.packed_buffer.resize(chunk_size, PackedBoard::zeroed()); 45 | let buffer = bytemuck::cast_slice_mut(&mut self.packed_buffer); 46 | let mut bytes_read = 0; 47 | loop { 48 | match self.file.read(&mut buffer[bytes_read..]) { 49 | Ok(0) => break, 50 | Ok(some) => bytes_read += some, 51 | Err(_) => break, 52 | } 53 | } 54 | let elems = bytes_read / std::mem::size_of::(); 55 | self.packed_buffer.truncate(elems); 56 | 57 | self.packed_buffer 58 | .par_iter() 59 | .map(|packed| { 60 | let (board, cp, wdl, _) = packed.unpack()?; 61 | let cp = cp as f32; 62 | let wdl = wdl as f32 / 2.0; 63 | 64 | if cp.abs() > 3000.0 { 65 | return None; 66 | } 67 | 68 | Some(AnnotatedBoard { board, cp, wdl }) 69 | }) 70 | .rev() 71 | .collect_into_vec(&mut self.board_buffer); 72 | !self.board_buffer.is_empty() 73 | } 74 | 75 | fn next_from_buffer(&mut self) -> Option { 76 | while let Some(maybe_board) = self.board_buffer.pop() { 77 | if let Some(board) = maybe_board { 78 | return Some(board); 79 | } 80 | } 81 | None 82 | } 83 | } 84 | 85 | impl Iterator for FileReader { 86 | type Item = AnnotatedBoard; 87 | 88 | fn next(&mut self) -> Option { 89 | loop { 90 | if let Some(board) = self.next_from_buffer() { 91 | return Some(board); 92 | } 93 | if !self.try_fill_buffer(32_000) { 94 | return None; 95 | } 96 | } 97 | } 98 | } 99 | 100 | pub fn read_batch_into(reader: &mut FileReader, batch: &mut Batch) -> bool { 101 | batch.clear(); 102 | for annotated in reader.take(batch.capacity()) { 103 | let (cp, wdl) = annotated.relative_value(); 104 | let entry = batch.make_entry(cp, wdl); 105 | F::add_features(annotated.board, entry); 106 | } 107 | batch.capacity() == batch.len() 108 | } 109 | -------------------------------------------------------------------------------- /parse/src/input_features/board_768.rs: -------------------------------------------------------------------------------- 1 | use cozy_chess::{Board, Color, Piece, Square}; 2 | 3 | use crate::batch::EntryFeatureWriter; 4 | 5 | use super::InputFeatureSet; 6 | 7 | pub struct Board768; 8 | 9 | pub struct Board768Cuda; 10 | 11 | impl InputFeatureSet for Board768 { 12 | const MAX_FEATURES: usize = 32; 13 | const INDICES_PER_FEATURE: usize = 2; 14 | 15 | fn add_features(board: Board, entry: EntryFeatureWriter) { 16 | let mut sparse_entry = entry.sparse(); 17 | let stm = board.side_to_move(); 18 | 19 | for &color in &Color::ALL { 20 | for &piece in &Piece::ALL { 21 | for square in board.pieces(piece) & board.colors(color) { 22 | let stm_feature = feature(stm, color, piece, square); 23 | let nstm_feature = feature(!stm, color, piece, square); 24 | sparse_entry.add_feature(stm_feature as i64, nstm_feature as i64); 25 | } 26 | } 27 | } 28 | } 29 | } 30 | 31 | impl InputFeatureSet for Board768Cuda { 32 | const MAX_FEATURES: usize = 32; 33 | const INDICES_PER_FEATURE: usize = 1; 34 | 35 | fn add_features(board: Board, entry: EntryFeatureWriter) { 36 | let mut cuda_entry = entry.cuda(); 37 | let stm = board.side_to_move(); 38 | 39 | for &color in &Color::ALL { 40 | for &piece in &Piece::ALL { 41 | for square in board.pieces(piece) & board.colors(color) { 42 | let stm_feature = feature(stm, color, piece, square); 43 | let nstm_feature = feature(!stm, color, piece, square); 44 | cuda_entry.add_feature(stm_feature as i64, nstm_feature as i64); 45 | } 46 | } 47 | } 48 | } 49 | } 50 | 51 | fn feature(perspective: Color, color: Color, piece: Piece, square: Square) -> usize { 52 | let (square, color) = match perspective { 53 | Color::White => (square, color), 54 | Color::Black => (square.flip_rank(), !color), 55 | }; 56 | let mut index = 0; 57 | index = index * Color::NUM + color as usize; 58 | index = index * Piece::NUM + piece as usize; 59 | index = index * Square::NUM + square as usize; 60 | index 61 | } 62 | -------------------------------------------------------------------------------- /parse/src/input_features/half_ka.rs: -------------------------------------------------------------------------------- 1 | use cozy_chess::{Board, Color, Piece, Square}; 2 | 3 | use crate::batch::EntryFeatureWriter; 4 | 5 | use super::InputFeatureSet; 6 | 7 | pub struct HalfKa; 8 | pub struct HalfKaCuda; 9 | 10 | impl InputFeatureSet for HalfKa { 11 | const MAX_FEATURES: usize = 32; 12 | const INDICES_PER_FEATURE: usize = 2; 13 | 14 | fn add_features(board: Board, entry: EntryFeatureWriter) { 15 | let mut sparse_entry = entry.sparse(); 16 | let stm = board.side_to_move(); 17 | 18 | let stm_king = board.king(stm); 19 | let nstm_king = board.king(!stm); 20 | 21 | for &color in &Color::ALL { 22 | for &piece in &Piece::ALL { 23 | for square in board.pieces(piece) & board.colors(color) { 24 | let stm_feature = feature(stm, stm_king, color, piece, square); 25 | let nstm_feature = feature(!stm, nstm_king, color, piece, square); 26 | sparse_entry.add_feature(stm_feature as i64, nstm_feature as i64); 27 | } 28 | } 29 | } 30 | } 31 | } 32 | 33 | impl InputFeatureSet for HalfKaCuda { 34 | const MAX_FEATURES: usize = 32; 35 | const INDICES_PER_FEATURE: usize = 1; 36 | 37 | fn add_features(board: Board, entry: EntryFeatureWriter) { 38 | let mut cuda_entry = entry.cuda(); 39 | let stm = board.side_to_move(); 40 | 41 | let stm_king = board.king(stm); 42 | let nstm_king = board.king(!stm); 43 | 44 | for &color in &Color::ALL { 45 | for &piece in &Piece::ALL { 46 | for square in board.pieces(piece) & board.colors(color) { 47 | let stm_feature = feature(stm, stm_king, color, piece, square); 48 | let nstm_feature = feature(!stm, nstm_king, color, piece, square); 49 | cuda_entry.add_feature(stm_feature as i64, nstm_feature as i64); 50 | } 51 | } 52 | } 53 | } 54 | } 55 | 56 | fn feature(perspective: Color, king: Square, color: Color, piece: Piece, square: Square) -> usize { 57 | let (king, square, color) = match perspective { 58 | Color::White => (king, square, color), 59 | Color::Black => (king.flip_rank(), square.flip_rank(), !color), 60 | }; 61 | let mut index = 0; 62 | index = index * Square::NUM + king as usize; 63 | index = index * Color::NUM + color as usize; 64 | index = index * Piece::NUM + piece as usize; 65 | index = index * Square::NUM + square as usize; 66 | index 67 | } 68 | -------------------------------------------------------------------------------- /parse/src/input_features/half_kp.rs: -------------------------------------------------------------------------------- 1 | use cozy_chess::{Board, Color, Piece, Square}; 2 | 3 | use crate::batch::EntryFeatureWriter; 4 | 5 | use super::InputFeatureSet; 6 | 7 | pub struct HalfKp; 8 | 9 | pub struct HalfKpCuda; 10 | 11 | impl InputFeatureSet for HalfKp { 12 | const MAX_FEATURES: usize = 30; 13 | const INDICES_PER_FEATURE: usize = 2; 14 | 15 | fn add_features(board: Board, entry: EntryFeatureWriter) { 16 | let mut sparse_entry = entry.sparse(); 17 | let stm = board.side_to_move(); 18 | 19 | let stm_king = board.king(stm); 20 | let nstm_king = board.king(!stm); 21 | 22 | for &color in &Color::ALL { 23 | for &piece in &Piece::ALL { 24 | if piece == Piece::King { 25 | continue; 26 | } 27 | for square in board.pieces(piece) & board.colors(color) { 28 | let stm_feature = feature(stm, stm_king, color, piece, square); 29 | let nstm_feature = feature(!stm, nstm_king, color, piece, square); 30 | sparse_entry.add_feature(stm_feature as i64, nstm_feature as i64); 31 | } 32 | } 33 | } 34 | } 35 | } 36 | 37 | impl InputFeatureSet for HalfKpCuda { 38 | const MAX_FEATURES: usize = 30; 39 | const INDICES_PER_FEATURE: usize = 1; 40 | 41 | fn add_features(board: Board, entry: EntryFeatureWriter) { 42 | let mut cuda_entry = entry.cuda(); 43 | let stm = board.side_to_move(); 44 | 45 | let stm_king = board.king(stm); 46 | let nstm_king = board.king(!stm); 47 | 48 | for &color in &Color::ALL { 49 | for &piece in &Piece::ALL { 50 | if piece == Piece::King { 51 | continue; 52 | } 53 | for square in board.pieces(piece) & board.colors(color) { 54 | let stm_feature = feature(stm, stm_king, color, piece, square); 55 | let nstm_feature = feature(!stm, nstm_king, color, piece, square); 56 | cuda_entry.add_feature(stm_feature as i64, nstm_feature as i64); 57 | } 58 | } 59 | } 60 | } 61 | } 62 | 63 | fn feature(perspective: Color, king: Square, color: Color, piece: Piece, square: Square) -> usize { 64 | let (king, square, color) = match perspective { 65 | Color::White => (king, square, color), 66 | Color::Black => (king.flip_rank(), square.flip_rank(), !color), 67 | }; 68 | let mut index = 0; 69 | index = index * Square::NUM + king as usize; 70 | index = index * Color::NUM + color as usize; 71 | index = index * (Piece::NUM - 1) + piece as usize; // sub 1 since no king 72 | index = index * Square::NUM + square as usize; 73 | index 74 | } 75 | -------------------------------------------------------------------------------- /parse/src/input_features/mod.rs: -------------------------------------------------------------------------------- 1 | use cozy_chess::Board; 2 | 3 | use crate::batch::EntryFeatureWriter; 4 | 5 | mod board_768; 6 | mod half_ka; 7 | mod half_kp; 8 | 9 | pub use board_768::Board768; 10 | pub use board_768::Board768Cuda; 11 | pub use half_ka::HalfKa; 12 | pub use half_ka::HalfKaCuda; 13 | pub use half_kp::HalfKp; 14 | pub use half_kp::HalfKpCuda; 15 | 16 | pub trait InputFeatureSet { 17 | const INDICES_PER_FEATURE: usize; 18 | const MAX_FEATURES: usize; 19 | 20 | fn add_features(board: Board, entry: EntryFeatureWriter); 21 | } 22 | -------------------------------------------------------------------------------- /parse/src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::CStr; 2 | use std::os::raw::c_char; 3 | 4 | use batch::Batch; 5 | use data_loader::FileReader; 6 | use input_features::{ 7 | Board768, Board768Cuda, HalfKa, HalfKaCuda, HalfKp, HalfKpCuda, InputFeatureSet, 8 | }; 9 | 10 | mod batch; 11 | mod data_loader; 12 | mod input_features; 13 | 14 | #[no_mangle] 15 | pub unsafe extern "C" fn batch_new( 16 | batch_size: u32, 17 | max_features: u32, 18 | indices_per_feature: u32, 19 | ) -> *mut Batch { 20 | let batch = Batch::new( 21 | batch_size as usize, 22 | max_features as usize, 23 | indices_per_feature as usize, 24 | ); 25 | Box::into_raw(Box::new(batch)) 26 | } 27 | 28 | #[no_mangle] 29 | pub unsafe extern "C" fn batch_drop(batch: *mut Batch) { 30 | drop(Box::from_raw(batch)); 31 | } 32 | 33 | #[no_mangle] 34 | pub unsafe extern "C" fn batch_clear(batch: *mut Batch) { 35 | batch.as_mut().unwrap().clear(); 36 | } 37 | 38 | macro_rules! export_batch_getters { 39 | ($($getter:ident $(as $cast_type:ty)?: $exported:ident -> $type:ty,)*) => {$( 40 | #[no_mangle] 41 | pub unsafe extern "C" fn $exported(batch: *mut Batch) -> $type { 42 | batch.as_mut().unwrap().$getter() $(as $cast_type)* 43 | } 44 | )*} 45 | } 46 | export_batch_getters! { 47 | capacity as u32 : batch_get_capacity -> u32, 48 | len as u32 : batch_get_len -> u32, 49 | stm_feature_buffer_ptr : batch_get_stm_feature_buffer_ptr -> *const i64, 50 | nstm_feature_buffer_ptr : batch_get_nstm_feature_buffer_ptr -> *const i64, 51 | values_ptr : batch_get_values_ptr -> *const f32, 52 | total_features as u32 : batch_get_total_features -> u32, 53 | indices_per_feature as u32 : batch_get_indices_per_feature -> u32, 54 | cp_ptr : batch_get_cp_ptr -> *const f32, 55 | wdl_ptr : batch_get_wdl_ptr -> *const f32, 56 | } 57 | 58 | #[no_mangle] 59 | pub unsafe extern "C" fn file_reader_new(path: *const c_char) -> *mut FileReader { 60 | pub unsafe fn try_new_file_reader(path: *const c_char) -> Option { 61 | let path = CStr::from_ptr(path).to_str().ok()?; 62 | let reader = FileReader::new(path).ok()?; 63 | Some(reader) 64 | } 65 | if let Some(reader) = try_new_file_reader(path) { 66 | Box::into_raw(Box::new(reader)) 67 | } else { 68 | std::ptr::null_mut() 69 | } 70 | } 71 | 72 | #[no_mangle] 73 | pub unsafe extern "C" fn file_reader_drop(reader: *mut FileReader) { 74 | drop(Box::from_raw(reader)); 75 | } 76 | 77 | #[repr(C)] 78 | pub enum InputFeatureSetType { 79 | Board768, 80 | HalfKp, 81 | HalfKa, 82 | Board768Cuda, 83 | HalfKpCuda, 84 | HalfKaCuda, 85 | } 86 | 87 | #[no_mangle] 88 | pub unsafe extern "C" fn input_feature_set_get_max_features( 89 | feature_set: InputFeatureSetType, 90 | ) -> u32 { 91 | let max_features = match feature_set { 92 | InputFeatureSetType::Board768 => Board768::MAX_FEATURES, 93 | InputFeatureSetType::HalfKp => HalfKp::MAX_FEATURES, 94 | InputFeatureSetType::HalfKa => HalfKa::MAX_FEATURES, 95 | InputFeatureSetType::Board768Cuda => Board768Cuda::MAX_FEATURES, 96 | InputFeatureSetType::HalfKpCuda => HalfKpCuda::MAX_FEATURES, 97 | InputFeatureSetType::HalfKaCuda => HalfKaCuda::MAX_FEATURES, 98 | }; 99 | max_features as u32 100 | } 101 | 102 | #[no_mangle] 103 | pub unsafe extern "C" fn input_feature_set_get_indices_per_feature( 104 | feature_set: InputFeatureSetType, 105 | ) -> u32 { 106 | let indices_per_feature = match feature_set { 107 | InputFeatureSetType::Board768 => Board768::INDICES_PER_FEATURE, 108 | InputFeatureSetType::HalfKp => HalfKp::INDICES_PER_FEATURE, 109 | InputFeatureSetType::HalfKa => HalfKa::INDICES_PER_FEATURE, 110 | InputFeatureSetType::Board768Cuda => Board768Cuda::INDICES_PER_FEATURE, 111 | InputFeatureSetType::HalfKpCuda => HalfKpCuda::INDICES_PER_FEATURE, 112 | InputFeatureSetType::HalfKaCuda => HalfKaCuda::INDICES_PER_FEATURE, 113 | }; 114 | indices_per_feature as u32 115 | } 116 | 117 | #[no_mangle] 118 | pub unsafe extern "C" fn read_batch_into( 119 | reader: *mut FileReader, 120 | feature_set: InputFeatureSetType, 121 | batch: *mut Batch, 122 | ) -> bool { 123 | let reader = reader.as_mut().unwrap(); 124 | let batch = batch.as_mut().unwrap(); 125 | match feature_set { 126 | InputFeatureSetType::Board768 => data_loader::read_batch_into::(reader, batch), 127 | InputFeatureSetType::HalfKp => data_loader::read_batch_into::(reader, batch), 128 | InputFeatureSetType::HalfKa => data_loader::read_batch_into::(reader, batch), 129 | InputFeatureSetType::Board768Cuda => { 130 | data_loader::read_batch_into::(reader, batch) 131 | } 132 | InputFeatureSetType::HalfKpCuda => { 133 | data_loader::read_batch_into::(reader, batch) 134 | } 135 | InputFeatureSetType::HalfKaCuda => { 136 | data_loader::read_batch_into::(reader, batch) 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /trainer/LICENSE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /trainer/cudasparse.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch import autograd 4 | import cupy as cp 5 | import math 6 | 7 | 8 | def _find_nearest_divisor(value, target): 9 | divisors = [] 10 | for i in range(1, value + 1): 11 | if value % i == 0: 12 | divisors.append((i, abs(target - i))) 13 | divisors.sort(key=lambda x: x[1]) 14 | return divisors[0][0] 15 | 16 | 17 | _num_threads_forward_cache = dict() 18 | 19 | 20 | def _get_num_threads_for_forward(output_size): 21 | optimal_num_threads = 512 22 | if output_size not in _num_threads_forward_cache: 23 | _num_threads_forward_cache[output_size] = _find_nearest_divisor( 24 | output_size, optimal_num_threads 25 | ) 26 | 27 | return _num_threads_forward_cache[output_size] 28 | 29 | 30 | _num_threads_backward_cache = dict() 31 | 32 | 33 | def _get_num_threads_for_backward(output_size): 34 | optimal_num_threads = 512 35 | if output_size not in _num_threads_backward_cache: 36 | _num_threads_backward_cache[output_size] = _find_nearest_divisor( 37 | output_size, optimal_num_threads 38 | ) 39 | 40 | return _num_threads_backward_cache[output_size] 41 | 42 | 43 | def _kernel_with_threads(kernel, threads): 44 | def f(grid, args): 45 | kernel(grid=grid, block=threads, args=args) 46 | 47 | return f 48 | 49 | 50 | _feature_transformer_slice_forward_kernel_cache = dict() 51 | 52 | 53 | def make_feature_transformer_slice_forward_kernel(max_active_features, output_size): 54 | """ 55 | @param: max_active_features 56 | The maximum number of features that are active 57 | (non-zero) for a single position. This value determines 58 | the shape of the inputs. 59 | This value is of type uint32_t. 60 | @param: output_size 61 | The number of outputs. Must match the shape of weights 62 | and biases. 63 | This value is of type uint32. 64 | """ 65 | num_threads = _get_num_threads_for_forward(output_size) 66 | output_thread_slice_size = output_size // num_threads 67 | key = (max_active_features, output_size, num_threads) 68 | if key not in _feature_transformer_slice_forward_kernel_cache: 69 | kernel = cp.RawKernel( 70 | r""" 71 | typedef unsigned int uint32_t; 72 | typedef int int32_t; 73 | extern "C" __global__ 74 | /* 75 | @assumptions: 76 | The blocks must have dimensionality (BATCH_SIZE,) 77 | The threads must have dimensionality (N,), where 78 | N * output_thread_slice_size == output_size. 79 | @param: feature_indices 80 | A matrix of shape (BATCH_SIZE, max_active_features) 81 | containing indices of active features for each position 82 | in a batch. Feature index of -1 means that the slot is empty 83 | and the weights will not be accumulated for it. Moreover 84 | no further indices from this block will be considered. 85 | The indices form an implicit matrix of shape 86 | (BATCH_SIZE, NUM_INPUTS), where the first dimension index is 87 | inferred from the memory location (BATCH_SIZE), and the 88 | second dimension index is stored in the feature_indices matrix. 89 | The type for feature indices is int32_t. 90 | @param: feature_values 91 | A matrix of shape (BATCH_SIZE, max_active_features) 92 | containing the values (arity) of the corresponding 93 | feature index in feature_indices. 94 | The type for the feature value (arity) is float32. 95 | @param: weight 96 | The weight matrix of shape (NUM_INPUTS, output_size). 97 | Weights must be of type float32. 98 | @param: bias 99 | The bias vector of shape (output_size,). 100 | Bias values must be of type float32. 101 | @param: output 102 | An output matrix of shape (BATCH_SIZE, output_size). 103 | It may not be initialized, bias is always copied 104 | to the output first. 105 | Output values must have type float32. 106 | */ 107 | void feature_transformer_slice_forward( 108 | const int32_t* const feature_indices, 109 | const float* const feature_values, 110 | const float* const weight, 111 | const float* const bias, 112 | float* const output 113 | ) {{ 114 | __shared__ 115 | float shared_output[{output_size}]; 116 | const uint32_t block_idx = blockIdx.x; 117 | const uint32_t slice_offset = threadIdx.x * {output_thread_slice_size}; 118 | float* const output_slice = output + block_idx * {output_size} + slice_offset; 119 | const float* const bias_slice = bias + slice_offset; 120 | float* shared_output_slice = shared_output + slice_offset; 121 | const int32_t* const feature_index_row = feature_indices + block_idx * {max_active_features}; 122 | const float* const feature_value_row = feature_values + block_idx * {max_active_features}; 123 | #pragma unroll 124 | for (uint32_t s = 0; s < {output_thread_slice_size}; ++s) 125 | {{ 126 | shared_output_slice[s] = bias_slice[s]; 127 | }} 128 | for (uint32_t k = 0; k < {max_active_features}; ++k) 129 | {{ 130 | const int32_t feature_index = feature_index_row[k]; 131 | const float feature_value = feature_value_row[k]; 132 | if (feature_index != -1) 133 | {{ 134 | const float* const weight_slice = weight + feature_index * {output_size} + slice_offset; 135 | #pragma unroll 136 | for (uint32_t s = 0; s < {output_thread_slice_size}; ++s) 137 | {{ 138 | shared_output_slice[s] += weight_slice[s] * feature_value; 139 | }} 140 | }} else break; 141 | }} 142 | #pragma unroll 143 | for (uint32_t s = 0; s < {output_thread_slice_size}; ++s) 144 | {{ 145 | output_slice[s] = shared_output_slice[s]; 146 | }} 147 | }} 148 | """.format( 149 | max_active_features=max_active_features, 150 | output_thread_slice_size=output_thread_slice_size, 151 | output_size=output_size, 152 | ), 153 | "feature_transformer_slice_forward", 154 | ) 155 | kernel.compile() 156 | _feature_transformer_slice_forward_kernel_cache[key] = _kernel_with_threads( 157 | kernel, (num_threads,) 158 | ) 159 | return _feature_transformer_slice_forward_kernel_cache[key] 160 | 161 | 162 | _feature_transformer_slice_backward_kernel_cache = dict() 163 | 164 | 165 | def make_feature_transformer_slice_backward_kernel(max_active_features, output_size): 166 | """' 167 | @param: max_active_features 168 | The maximum number of features that are active 169 | (non-zero) for a single position. This value determines 170 | the shape of the inputs. 171 | This value is of type uint32_t. 172 | @param: output_size 173 | The number of outputs. Must match the shape of weights 174 | and biases. 175 | This value is of type uint32. 176 | """ 177 | num_threads = _get_num_threads_for_backward(output_size) 178 | output_thread_slice_size = output_size // num_threads 179 | key = (max_active_features, output_size, num_threads) 180 | if key not in _feature_transformer_slice_backward_kernel_cache: 181 | kernel = cp.RawKernel( 182 | r""" 183 | typedef unsigned int uint32_t; 184 | typedef int int32_t; 185 | extern "C" __global__ 186 | /* 187 | @assumptions: 188 | The blocks must have dimensionality (BATCH_SIZE,) 189 | The threads must have dimensionality (N,), where 190 | N * output_thread_slice_size == output_size. 191 | @param: feature_indices 192 | A matrix of shape (BATCH_SIZE, max_active_features) 193 | containing indices of active features for each position 194 | in a batch. Feature index of -1 means that the slot is empty 195 | and the weights will not be accumulated for it. Moreover 196 | no further indices from this block will be considered. 197 | The indices form an implicit matrix of shape 198 | (BATCH_SIZE, NUM_INPUTS), where the first dimension index is 199 | inferred from the memory location (BATCH_SIZE), and the 200 | second dimension index is stored in the feature_indices matrix. 201 | The type for feature indices is int32_t. 202 | @param: feature_values 203 | A matrix of shape (BATCH_SIZE, max_active_features) 204 | containing the values (arity) of the corresponding 205 | feature index in feature_indices. 206 | The type for the feature value (arity) is float32. 207 | @param: weight_grad 208 | The weight gradient matrix of shape (NUM_INPUTS, output_size). 209 | The gradient is accumulated, i.e. it must be zero initialized 210 | on the first call. 211 | Weights must be of type float32. 212 | @param: bias_grad 213 | The bias gradient vector of shape (output_size,). 214 | The gradient is accumulated, i.e. it must be zero initialized 215 | on the first call. 216 | Bias values must be of type float32. 217 | @param: output_grad 218 | An output gradient matrix of shape (BATCH_SIZE, output_size). 219 | Output values must have type float32. 220 | */ 221 | void feature_transformer_slice_backward( 222 | const int32_t* const feature_indices, 223 | const float* const feature_values, 224 | float* const weight_grad, 225 | float* const bias_grad, 226 | const float* const output_grad 227 | ) {{ 228 | __shared__ 229 | float shared_output_grad[{output_size}]; 230 | const uint32_t block_idx = blockIdx.x; 231 | const uint32_t slice_offset = threadIdx.x * {output_thread_slice_size}; 232 | const float* const output_grad_slice = output_grad + block_idx * {output_size} + slice_offset; 233 | float* const bias_grad_slice = bias_grad + slice_offset; 234 | float* shared_output_grad_slice = shared_output_grad + slice_offset; 235 | const int32_t* const feature_index_row = feature_indices + block_idx * {max_active_features}; 236 | const float* const feature_value_row = feature_values + block_idx * {max_active_features}; 237 | #pragma unroll 238 | for (uint32_t s = 0; s < {output_thread_slice_size}; ++s) 239 | {{ 240 | shared_output_grad_slice[s] = output_grad_slice[s]; 241 | }} 242 | #pragma unroll 243 | for (uint32_t s = 0; s < {output_thread_slice_size}; ++s) 244 | {{ 245 | const float sog = shared_output_grad_slice[s]; 246 | if (sog != 0.0f) 247 | {{ 248 | atomicAdd(&bias_grad_slice[s], sog); 249 | }} 250 | }} 251 | for (uint32_t k = 0; k < {max_active_features}; ++k) 252 | {{ 253 | const int32_t feature_index = feature_index_row[k]; 254 | const float feature_value = feature_value_row[k]; 255 | if (feature_index != -1) 256 | {{ 257 | float* const weight_grad_slice = weight_grad + feature_index * {output_size} + slice_offset; 258 | #pragma unroll 259 | for (int s = 0; s < {output_thread_slice_size}; ++s) 260 | {{ 261 | const float sog = shared_output_grad_slice[s]; 262 | if (sog != 0.0f) 263 | {{ 264 | atomicAdd(&weight_grad_slice[s], sog * feature_value); 265 | }} 266 | }} 267 | }} else break; 268 | }} 269 | }} 270 | """.format( 271 | max_active_features=max_active_features, 272 | output_thread_slice_size=output_thread_slice_size, 273 | output_size=output_size, 274 | ), 275 | "feature_transformer_slice_backward", 276 | ) 277 | kernel.compile() 278 | _feature_transformer_slice_backward_kernel_cache[key] = _kernel_with_threads( 279 | kernel, (num_threads,) 280 | ) 281 | return _feature_transformer_slice_backward_kernel_cache[key] 282 | 283 | 284 | class FeatureTransformerSliceFunction(autograd.Function): 285 | @staticmethod 286 | def forward(ctx, feature_indices, feature_values, weight, bias): 287 | ctx.save_for_backward(feature_indices, feature_values, weight, bias) 288 | 289 | assert len(feature_indices.shape) == 2 290 | assert len(feature_values.shape) == 2 291 | assert feature_indices.shape[0] == feature_values.shape[0] 292 | assert feature_indices.shape[1] == feature_values.shape[1] 293 | assert feature_indices.dtype == torch.int32 294 | assert feature_values.dtype == torch.float32 295 | 296 | assert len(weight.shape) == 2 297 | assert weight.dtype == torch.float32 298 | 299 | assert len(bias.shape) == 1 300 | assert bias.dtype == torch.float32 301 | 302 | assert feature_indices.is_cuda 303 | assert feature_values.is_cuda 304 | assert weight.is_cuda 305 | assert bias.is_cuda 306 | 307 | assert feature_values.device == feature_indices.device 308 | assert weight.device == feature_indices.device 309 | assert bias.device == feature_indices.device 310 | 311 | assert feature_indices.is_contiguous() 312 | assert feature_values.is_contiguous() 313 | assert weight.is_contiguous() 314 | assert bias.is_contiguous() 315 | 316 | device = feature_indices.device 317 | batch_size = feature_indices.shape[0] 318 | max_active_features = feature_indices.shape[1] 319 | output_size = weight.shape[1] 320 | 321 | output = torch.empty( 322 | batch_size, 323 | output_size, 324 | dtype=torch.float32, 325 | device=device, 326 | requires_grad=True, 327 | ) 328 | 329 | kernel = make_feature_transformer_slice_forward_kernel( 330 | max_active_features, output_size 331 | ) 332 | kernel( 333 | grid=(batch_size,), 334 | args=( 335 | feature_indices.data_ptr(), 336 | feature_values.data_ptr(), 337 | weight.data_ptr(), 338 | bias.data_ptr(), 339 | output.data_ptr(), 340 | ), 341 | ) 342 | 343 | return output 344 | 345 | @staticmethod 346 | def backward(ctx, grad_output): 347 | assert not ctx.needs_input_grad[0] 348 | assert not ctx.needs_input_grad[1] 349 | 350 | grad_output = grad_output.contiguous() 351 | 352 | feature_indices, feature_values, weight, bias = ctx.saved_tensors 353 | 354 | device = feature_indices.device 355 | batch_size = feature_indices.shape[0] 356 | max_active_features = feature_indices.shape[1] 357 | output_size = weight.shape[1] 358 | 359 | weight_grad = torch.zeros( 360 | weight.shape[0], weight.shape[1], dtype=torch.float32, device=device 361 | ) 362 | bias_grad = torch.zeros(output_size, dtype=torch.float32, device=device) 363 | 364 | kernel = make_feature_transformer_slice_backward_kernel( 365 | max_active_features, output_size 366 | ) 367 | kernel( 368 | grid=(batch_size,), 369 | args=( 370 | feature_indices.data_ptr(), 371 | feature_values.data_ptr(), 372 | weight_grad.data_ptr(), 373 | bias_grad.data_ptr(), 374 | grad_output.data_ptr(), 375 | ), 376 | ) 377 | 378 | return None, None, weight_grad, bias_grad 379 | 380 | 381 | class DoubleFeatureTransformerSliceFunction(autograd.Function): 382 | @staticmethod 383 | def forward( 384 | ctx, 385 | feature_indices_0, 386 | feature_values_0, 387 | feature_indices_1, 388 | feature_values_1, 389 | weight, 390 | bias, 391 | ): 392 | ctx.save_for_backward( 393 | feature_indices_0, 394 | feature_values_0, 395 | feature_indices_1, 396 | feature_values_1, 397 | weight, 398 | bias, 399 | ) 400 | 401 | assert len(feature_indices_0.shape) == 2 402 | assert len(feature_values_0.shape) == 2 403 | assert feature_indices_0.shape[0] == feature_values_0.shape[0] 404 | assert feature_indices_0.shape[1] == feature_values_0.shape[1] 405 | assert feature_indices_0.dtype == torch.int32 406 | assert feature_values_0.dtype == torch.float32 407 | 408 | assert len(feature_indices_1.shape) == 2 409 | assert len(feature_values_1.shape) == 2 410 | assert feature_indices_1.shape[0] == feature_values_1.shape[0] 411 | assert feature_indices_1.shape[1] == feature_values_1.shape[1] 412 | assert feature_indices_1.dtype == torch.int32 413 | assert feature_values_1.dtype == torch.float32 414 | 415 | assert len(weight.shape) == 2 416 | assert weight.dtype == torch.float32 417 | 418 | assert len(bias.shape) == 1 419 | assert bias.dtype == torch.float32 420 | 421 | assert feature_indices_0.is_cuda 422 | assert feature_values_0.is_cuda 423 | assert feature_indices_1.is_cuda 424 | assert feature_values_1.is_cuda 425 | assert weight.is_cuda 426 | assert bias.is_cuda 427 | 428 | assert feature_values_0.device == feature_indices_0.device 429 | assert feature_values_1.device == feature_indices_1.device 430 | assert feature_indices_0.device == feature_indices_1.device 431 | assert weight.device == feature_indices_0.device 432 | assert bias.device == feature_indices_0.device 433 | 434 | assert feature_indices_0.is_contiguous() 435 | assert feature_values_0.is_contiguous() 436 | assert feature_indices_1.is_contiguous() 437 | assert feature_values_1.is_contiguous() 438 | assert weight.is_contiguous() 439 | assert bias.is_contiguous() 440 | 441 | device = feature_indices_0.device 442 | batch_size = feature_indices_0.shape[0] 443 | max_active_features = feature_indices_0.shape[1] 444 | output_size = weight.shape[1] 445 | 446 | output0 = torch.empty( 447 | batch_size, 448 | output_size, 449 | dtype=torch.float32, 450 | device=device, 451 | requires_grad=True, 452 | ) 453 | output1 = torch.empty( 454 | batch_size, 455 | output_size, 456 | dtype=torch.float32, 457 | device=device, 458 | requires_grad=True, 459 | ) 460 | 461 | kernel = make_feature_transformer_slice_forward_kernel( 462 | max_active_features, output_size 463 | ) 464 | kernel( 465 | grid=(batch_size,), 466 | args=( 467 | feature_indices_0.data_ptr(), 468 | feature_values_0.data_ptr(), 469 | weight.data_ptr(), 470 | bias.data_ptr(), 471 | output0.data_ptr(), 472 | ), 473 | ) 474 | 475 | kernel( 476 | grid=(batch_size,), 477 | args=( 478 | feature_indices_1.data_ptr(), 479 | feature_values_1.data_ptr(), 480 | weight.data_ptr(), 481 | bias.data_ptr(), 482 | output1.data_ptr(), 483 | ), 484 | ) 485 | 486 | return output0, output1 487 | 488 | @staticmethod 489 | def backward(ctx, grad_output_0, grad_output_1): 490 | assert not ctx.needs_input_grad[0] 491 | assert not ctx.needs_input_grad[1] 492 | 493 | grad_output_0 = grad_output_0.contiguous() 494 | grad_output_1 = grad_output_1.contiguous() 495 | 496 | ( 497 | feature_indices_0, 498 | feature_values_0, 499 | feature_indices_1, 500 | feature_values_1, 501 | weight, 502 | bias, 503 | ) = ctx.saved_tensors 504 | 505 | device = feature_indices_0.device 506 | batch_size = feature_indices_0.shape[0] 507 | max_active_features = feature_indices_0.shape[1] 508 | output_size = weight.shape[1] 509 | 510 | weight_grad = torch.zeros( 511 | weight.shape[0], weight.shape[1], dtype=torch.float32, device=device 512 | ) 513 | bias_grad = torch.zeros(output_size, dtype=torch.float32, device=device) 514 | 515 | kernel = make_feature_transformer_slice_backward_kernel( 516 | max_active_features, output_size 517 | ) 518 | kernel( 519 | grid=(batch_size,), 520 | args=( 521 | feature_indices_0.data_ptr(), 522 | feature_values_0.data_ptr(), 523 | weight_grad.data_ptr(), 524 | bias_grad.data_ptr(), 525 | grad_output_0.data_ptr(), 526 | ), 527 | ) 528 | 529 | kernel( 530 | grid=(batch_size,), 531 | args=( 532 | feature_indices_1.data_ptr(), 533 | feature_values_1.data_ptr(), 534 | weight_grad.data_ptr(), 535 | bias_grad.data_ptr(), 536 | grad_output_1.data_ptr(), 537 | ), 538 | ) 539 | 540 | return None, None, None, None, weight_grad, bias_grad 541 | 542 | 543 | class FeatureTransformerSlice(nn.Module): 544 | def __init__(self, num_inputs, num_outputs): 545 | super(FeatureTransformerSlice, self).__init__() 546 | self.num_inputs = num_inputs 547 | self.num_outputs = num_outputs 548 | 549 | sigma = math.sqrt(1 / num_inputs) 550 | self.weight = nn.Parameter( 551 | torch.rand(num_inputs, num_outputs, dtype=torch.float32) * (2 * sigma) 552 | - sigma 553 | ) 554 | self.bias = nn.Parameter( 555 | torch.rand(num_outputs, dtype=torch.float32) * (2 * sigma) - sigma 556 | ) 557 | 558 | def forward(self, feature_indices, feature_values): 559 | return FeatureTransformerSliceFunction.apply( 560 | feature_indices, feature_values, self.weight, self.bias 561 | ) 562 | 563 | 564 | class DoubleFeatureTransformerSlice(nn.Module): 565 | def __init__(self, num_inputs, num_outputs): 566 | super(DoubleFeatureTransformerSlice, self).__init__() 567 | self.num_inputs = num_inputs 568 | self.num_outputs = num_outputs 569 | 570 | sigma = math.sqrt(1 / num_inputs) 571 | self.weight = nn.Parameter( 572 | torch.rand(num_inputs, num_outputs, dtype=torch.float32) * (2 * sigma) 573 | - sigma 574 | ) 575 | self.bias = nn.Parameter( 576 | torch.rand(num_outputs, dtype=torch.float32) * (2 * sigma) - sigma 577 | ) 578 | 579 | def forward( 580 | self, feature_indices_0, feature_values_0, feature_indices_1, feature_values_1 581 | ): 582 | return DoubleFeatureTransformerSliceFunction.apply( 583 | feature_indices_0, 584 | feature_values_0, 585 | feature_indices_1, 586 | feature_values_1, 587 | self.weight, 588 | self.bias, 589 | ) 590 | 591 | 592 | if __name__ == "__main__": 593 | import time 594 | import sys 595 | import os 596 | 597 | def FeatureTransformerSliceFunctionEmulate( 598 | feature_indices, feature_values, weight, bias 599 | ): 600 | batch_size = feature_indices.shape[0] 601 | num_inputs = weight.shape[0] 602 | max_active_features = feature_indices.shape[1] 603 | inputs = torch.zeros( 604 | batch_size, num_inputs, dtype=torch.float32, device=weight.device 605 | ) 606 | for i in range(batch_size): 607 | for j in range(max_active_features): 608 | feature = feature_indices[i, j] 609 | value = feature_values[i, j] 610 | inputs[i, feature] += value 611 | 612 | return torch.mm(inputs, weight) + bias 613 | 614 | def test(): 615 | BATCH_SIZE = 16 616 | INPUT_SIZE = 10 617 | MAX_ACTIVE_FEATURES = 32 618 | STRIDE = 128 619 | MAX_ERROR = 1e-4 620 | 621 | torch.manual_seed(0) 622 | weight0 = torch.rand( 623 | INPUT_SIZE, STRIDE, dtype=torch.float32, requires_grad=True 624 | ) 625 | bias0 = torch.rand(STRIDE, dtype=torch.float32, requires_grad=True) 626 | torch.manual_seed(0) 627 | weight1 = torch.rand( 628 | INPUT_SIZE, STRIDE, dtype=torch.float32, requires_grad=True 629 | ) 630 | bias1 = torch.rand(STRIDE, dtype=torch.float32, requires_grad=True) 631 | indices0 = (torch.rand(BATCH_SIZE, MAX_ACTIVE_FEATURES) * INPUT_SIZE).to( 632 | dtype=torch.int32 633 | ) 634 | indices1 = (torch.rand(BATCH_SIZE, MAX_ACTIVE_FEATURES) * INPUT_SIZE).to( 635 | dtype=torch.int32 636 | ) 637 | values0 = torch.rand(BATCH_SIZE, MAX_ACTIVE_FEATURES, dtype=torch.float32) 638 | values1 = torch.rand(BATCH_SIZE, MAX_ACTIVE_FEATURES, dtype=torch.float32) 639 | 640 | output00 = FeatureTransformerSliceFunctionEmulate( 641 | indices0.clone(), values0.clone(), weight0, bias0 642 | ) 643 | output01 = FeatureTransformerSliceFunctionEmulate( 644 | indices1.clone(), values1.clone(), weight0, bias0 645 | ) 646 | # output10 = FeatureTransformerSliceFunction.apply(indices0.clone().cuda(), values0.clone().cuda(), weight1.cuda(), bias1.cuda()) 647 | # output11 = FeatureTransformerSliceFunction.apply(indices1.clone().cuda(), values1.clone().cuda(), weight1.cuda(), bias1.cuda()) 648 | output10, output11 = DoubleFeatureTransformerSliceFunction.apply( 649 | indices0.clone().cuda(), 650 | values0.clone().cuda(), 651 | indices1.clone().cuda(), 652 | values1.clone().cuda(), 653 | weight1.cuda(), 654 | bias1.cuda(), 655 | ) 656 | 657 | assert torch.max(output00.cpu() - output10.cpu()) < MAX_ERROR 658 | assert torch.max(output01.cpu() - output11.cpu()) < MAX_ERROR 659 | (output00 - output01).sum().backward() 660 | (output10 - output11).sum().backward() 661 | assert torch.max(weight0.grad.cpu() - weight1.grad.cpu()) < MAX_ERROR 662 | assert torch.max(bias0.grad.cpu() - bias1.grad.cpu()) < MAX_ERROR 663 | print("Tests passed.") 664 | 665 | def bench(): 666 | INPUT_SIZE = 40960 667 | BATCH_SIZE = 8192 668 | ITERS = 64 669 | STRIDE = 264 670 | MAX_ACTIVE_FEATURES = 64 671 | 672 | layer = DoubleFeatureTransformerSlice(INPUT_SIZE, STRIDE).cuda() 673 | indices0 = torch.cat( 674 | [ 675 | torch.sort( 676 | (torch.rand(BATCH_SIZE, MAX_ACTIVE_FEATURES * 3 // 4) * INPUT_SIZE), 677 | dim=1, 678 | )[0].to(dtype=torch.int32), 679 | torch.full( 680 | (BATCH_SIZE, MAX_ACTIVE_FEATURES // 4), -1, dtype=torch.int32 681 | ), 682 | ], 683 | dim=1, 684 | ).cuda() 685 | values0 = torch.rand( 686 | BATCH_SIZE, MAX_ACTIVE_FEATURES, dtype=torch.float32 687 | ).cuda() 688 | indices1 = torch.cat( 689 | [ 690 | torch.sort( 691 | (torch.rand(BATCH_SIZE, MAX_ACTIVE_FEATURES * 3 // 4)) * INPUT_SIZE, 692 | dim=1, 693 | )[0].to(dtype=torch.int32), 694 | torch.full( 695 | (BATCH_SIZE, MAX_ACTIVE_FEATURES // 4), -1, dtype=torch.int32 696 | ), 697 | ], 698 | dim=1, 699 | ).cuda() 700 | values1 = torch.rand( 701 | BATCH_SIZE, MAX_ACTIVE_FEATURES, dtype=torch.float32 702 | ).cuda() 703 | 704 | output0, output1 = layer(indices0, values0, indices1, values1) 705 | 706 | device = indices0.device 707 | 708 | start = time.time() 709 | 710 | for i in range(ITERS): 711 | output0, output1 = layer(indices0, values0, indices1, values1) 712 | output0 = torch.clamp(output0, 0.0, 1.0) 713 | output1 = torch.clamp(output1, 0.0, 1.0) 714 | 715 | g = ((output0 - output1) ** 2).mean() 716 | g.backward() 717 | 718 | torch.cuda.synchronize() 719 | 720 | end = time.time() 721 | 722 | # for param in layer.parameters(): 723 | # print(param.grad) 724 | 725 | print("{} pos/s".format((ITERS * BATCH_SIZE) / (end - start))) 726 | 727 | test() 728 | bench() 729 | -------------------------------------------------------------------------------- /trainer/dataloader.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from dataclasses import dataclass 4 | from enum import IntEnum 5 | 6 | import ctypes 7 | import os 8 | 9 | import numpy as np 10 | import torch 11 | 12 | 13 | def _load_parse_lib(): 14 | path = "./libparse.dll" if os.name == "nt" else "./libparse.so" 15 | lib = ctypes.cdll.LoadLibrary(path) 16 | 17 | lib.batch_new.restype = ctypes.c_void_p 18 | lib.batch_drop.restype = None 19 | lib.batch_get_capacity.restype = ctypes.c_uint32 20 | lib.batch_get_len.restype = ctypes.c_uint32 21 | lib.batch_get_stm_feature_buffer_ptr.restype = ctypes.POINTER(ctypes.c_int64) 22 | lib.batch_get_nstm_feature_buffer_ptr.restype = ctypes.POINTER(ctypes.c_int64) 23 | lib.batch_get_values_ptr.restype = ctypes.POINTER(ctypes.c_float) 24 | lib.batch_get_total_features.restype = ctypes.c_uint32 25 | lib.batch_get_cp_ptr.restype = ctypes.POINTER(ctypes.c_float) 26 | lib.batch_get_wdl_ptr.restype = ctypes.POINTER(ctypes.c_float) 27 | 28 | lib.file_reader_new.restype = ctypes.c_void_p 29 | lib.file_reader_drop.restype = None 30 | 31 | lib.input_feature_set_get_max_features.restype = ctypes.c_uint32 32 | lib.input_feature_set_get_indices_per_feature.restype = ctypes.c_uint32 33 | 34 | lib.read_batch_into.restype = ctypes.c_bool 35 | 36 | return lib 37 | 38 | 39 | PARSE_LIB = _load_parse_lib() 40 | 41 | 42 | class InputFeatureSet(IntEnum): 43 | BOARD_768 = 0 44 | HALF_KP = 1 45 | HALF_KA = 2 46 | BOARD_768_CUDA = 3 47 | HALF_KP_CUDA = 4 48 | HALF_KA_CUDA = 5 49 | 50 | def max_features(self) -> int: 51 | return PARSE_LIB.input_feature_set_get_max_features(self) 52 | 53 | def indices_per_feature(self) -> int: 54 | return PARSE_LIB.input_feature_set_get_indices_per_feature(self) 55 | 56 | 57 | @dataclass 58 | class Batch: 59 | stm_indices: torch.Tensor 60 | nstm_indices: torch.Tensor 61 | values: torch.Tensor 62 | cp: torch.Tensor 63 | wdl: torch.Tensor 64 | size: int 65 | 66 | 67 | class ParserBatch: 68 | def __init__( 69 | self, batch_size: int, max_features: int, indices_per_feature: int 70 | ) -> None: 71 | self._ptr = ctypes.c_void_p( 72 | PARSE_LIB.batch_new( 73 | ctypes.c_uint32(batch_size), 74 | ctypes.c_uint32(max_features), 75 | ctypes.c_uint32(indices_per_feature), 76 | ) 77 | ) 78 | if self._ptr.value is None: 79 | raise Exception("Failed to create batch") 80 | 81 | def drop(self) -> None: 82 | if self._ptr.value is not None: 83 | PARSE_LIB.batch_drop(self._ptr) 84 | self._ptr.value = None 85 | 86 | def __enter__(self) -> ParserBatch: 87 | return self 88 | 89 | def __exit__(self) -> None: 90 | self.drop() 91 | 92 | def get_capacity(self) -> int: 93 | return PARSE_LIB.batch_get_capacity(self._ptr) 94 | 95 | def get_len(self) -> int: 96 | return PARSE_LIB.batch_get_len(self._ptr) 97 | 98 | def get_stm_feature_buffer_ptr(self) -> ctypes.pointer[ctypes.c_float]: 99 | return PARSE_LIB.batch_get_stm_feature_buffer_ptr(self._ptr) 100 | 101 | def get_nstm_feature_buffer_ptr(self) -> ctypes.pointer[ctypes.c_float]: 102 | return PARSE_LIB.batch_get_nstm_feature_buffer_ptr(self._ptr) 103 | 104 | def get_values_ptr(self) -> ctypes.pointer[ctypes.c_float]: 105 | return PARSE_LIB.batch_get_values_ptr(self._ptr) 106 | 107 | def get_total_features(self) -> int: 108 | return PARSE_LIB.batch_get_total_features(self._ptr) 109 | 110 | def get_indices_per_feature(self) -> int: 111 | return PARSE_LIB.batch_get_indices_per_feature(self._ptr) 112 | 113 | def get_cp_ptr(self) -> ctypes.pointer[ctypes.c_float]: 114 | return PARSE_LIB.batch_get_cp_ptr(self._ptr) 115 | 116 | def get_wdl_ptr(self) -> ctypes.pointer[ctypes.c_float]: 117 | return PARSE_LIB.batch_get_wdl_ptr(self._ptr) 118 | 119 | def to_pytorch_batch(self, device: torch.device) -> Batch: 120 | def to_pytorch(array: np.ndarray) -> torch.Tensor: 121 | tch_array = torch.from_numpy(array) 122 | if torch.cuda.is_available(): 123 | tch_array = tch_array.pin_memory() 124 | return tch_array.to(device, non_blocking=True) 125 | 126 | total_features = self.get_total_features() 127 | indices_per_feature = self.get_indices_per_feature() 128 | boards_stm = to_pytorch( 129 | np.ctypeslib.as_array( 130 | self.get_stm_feature_buffer_ptr(), 131 | shape=(total_features * indices_per_feature,), 132 | ) 133 | ) 134 | boards_nstm = to_pytorch( 135 | np.ctypeslib.as_array( 136 | self.get_nstm_feature_buffer_ptr(), 137 | shape=(total_features * indices_per_feature,), 138 | ) 139 | ) 140 | values = to_pytorch( 141 | np.ctypeslib.as_array(self.get_values_ptr(), shape=(total_features,)) 142 | ) 143 | 144 | batch_len = self.get_len() 145 | cp = to_pytorch(np.ctypeslib.as_array(self.get_cp_ptr(), shape=(batch_len, 1))) 146 | wdl = to_pytorch( 147 | np.ctypeslib.as_array(self.get_wdl_ptr(), shape=(batch_len, 1)) 148 | ) 149 | 150 | return Batch(boards_stm, boards_nstm, values, cp, wdl, batch_len) 151 | 152 | 153 | class ParserFileReader: 154 | def __init__(self, path: str) -> None: 155 | self._ptr = ctypes.c_void_p( 156 | PARSE_LIB.file_reader_new(ctypes.create_string_buffer(bytes(path, "ascii"))) 157 | ) 158 | if self._ptr.value is None: 159 | raise Exception("Failed to create file reader") 160 | 161 | def drop(self) -> None: 162 | if self._ptr.value is not None: 163 | PARSE_LIB.file_reader_drop(self._ptr) 164 | self._ptr.value = None 165 | 166 | def __enter__(self) -> ParserFileReader: 167 | return self 168 | 169 | def __exit__(self) -> None: 170 | self.drop() 171 | 172 | 173 | def read_batch_into( 174 | reader: ParserFileReader, feature_set: InputFeatureSet, parser_batch: ParserBatch 175 | ) -> bool: 176 | return PARSE_LIB.read_batch_into(reader._ptr, feature_set, parser_batch._ptr) 177 | 178 | 179 | class BatchLoader: 180 | def __init__( 181 | self, files: list[str], feature_set: InputFeatureSet, batch_size: int 182 | ) -> None: 183 | assert files 184 | self._feature_set = feature_set 185 | self._files = files 186 | self._file_index = 0 187 | self._reader = ParserFileReader(self._files[self._file_index]) 188 | self._batch = ParserBatch( 189 | batch_size, feature_set.max_features(), feature_set.indices_per_feature() 190 | ) 191 | 192 | def read_batch(self, device: torch.device) -> tuple[bool, Batch]: 193 | new_epoch = False 194 | while not read_batch_into(self._reader, self._feature_set, self._batch): 195 | self._reader.drop() 196 | self._file_index = (self._file_index + 1) % len(self._files) 197 | self._reader = ParserFileReader(self._files[self._file_index]) 198 | new_epoch = self._file_index == 0 199 | return new_epoch, self._batch.to_pytorch_batch(device) 200 | 201 | def drop(self) -> None: 202 | self._reader.drop() 203 | self._batch.drop() 204 | 205 | def __enter__(self) -> BatchLoader: 206 | return self 207 | 208 | def __exit__(self) -> None: 209 | self.drop() 210 | -------------------------------------------------------------------------------- /trainer/main.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import argparse 4 | import json 5 | import os 6 | import pathlib 7 | 8 | from dataloader import BatchLoader 9 | from model import ( 10 | NnBoard768Cuda, 11 | NnBoard768, 12 | NnHalfKA, 13 | NnHalfKACuda, 14 | NnHalfKP, 15 | NnHalfKPCuda, 16 | ) 17 | from time import time 18 | 19 | import torch 20 | from trainlog import TrainLog 21 | 22 | DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") 23 | 24 | LOG_ITERS = 10_000_000 25 | 26 | 27 | class WeightClipper: 28 | def __init__(self, frequency=1): 29 | self.frequency = frequency 30 | 31 | def __call__(self, module): 32 | if hasattr(module, "weight"): 33 | w = module.weight.data 34 | w = w.clamp(-1.98, 1.98) 35 | module.weight.data = w 36 | 37 | 38 | def train( 39 | model: torch.nn.Module, 40 | optimizer: torch.optim.Optimizer, 41 | dataloader: BatchLoader, 42 | wdl: float, 43 | scale: float, 44 | epochs: int, 45 | save_epochs: int, 46 | train_id: str, 47 | lr_drop: int | None = None, 48 | train_log: TrainLog | None = None, 49 | ) -> None: 50 | clipper = WeightClipper() 51 | running_loss = torch.zeros((1,), device=DEVICE) 52 | start_time = time() 53 | iterations = 0 54 | 55 | loss_since_log = torch.zeros((1,), device=DEVICE) 56 | iter_since_log = 0 57 | 58 | fens = 0 59 | epoch = 0 60 | 61 | while epoch < epochs: 62 | new_epoch, batch = dataloader.read_batch(DEVICE) 63 | if new_epoch: 64 | epoch += 1 65 | if epoch == lr_drop: 66 | optimizer.param_groups[0]["lr"] *= 0.1 67 | print( 68 | f"epoch {epoch}", 69 | f"epoch train loss: {running_loss.item() / iterations}", 70 | f"epoch pos/s: {fens / (time() - start_time)}", 71 | sep=os.linesep, 72 | ) 73 | 74 | running_loss = torch.zeros((1,), device=DEVICE) 75 | start_time = time() 76 | iterations = 0 77 | fens = 0 78 | 79 | if epoch % save_epochs == 0: 80 | torch.save(model.state_dict(), f"nn/{train_id}_{epoch}") 81 | param_map = { 82 | name: param.detach().cpu().numpy().tolist() 83 | for name, param in model.named_parameters() 84 | } 85 | with open(f"nn/{train_id}.json", "w") as json_file: 86 | json.dump(param_map, json_file) 87 | 88 | 89 | optimizer.zero_grad() 90 | prediction = model(batch) 91 | expected = torch.sigmoid(batch.cp / scale) * (1 - wdl) + batch.wdl * wdl 92 | 93 | loss = torch.mean((prediction - expected) ** 2) 94 | loss.backward() 95 | optimizer.step() 96 | model.apply(clipper) 97 | 98 | with torch.no_grad(): 99 | running_loss += loss 100 | loss_since_log += loss 101 | iterations += 1 102 | iter_since_log += 1 103 | fens += batch.size 104 | 105 | if iter_since_log * batch.size > LOG_ITERS: 106 | loss = loss_since_log.item() / iter_since_log 107 | print( 108 | f"At {iterations * batch.size} positions", 109 | f"Running Loss: {loss}", 110 | sep=os.linesep, 111 | ) 112 | if train_log is not None: 113 | train_log.update(loss) 114 | train_log.save() 115 | iter_since_log = 0 116 | loss_since_log = torch.zeros((1,), device=DEVICE) 117 | 118 | 119 | def main(): 120 | 121 | parser = argparse.ArgumentParser(description="") 122 | 123 | parser.add_argument( 124 | "--data-root", type=str, help="Root directory of the data files" 125 | ) 126 | parser.add_argument("--train-id", type=str, help="ID to save train logs with") 127 | parser.add_argument("--lr", type=float, help="Initial learning rate") 128 | parser.add_argument("--epochs", type=int, help="Epochs to train for") 129 | parser.add_argument("--batch-size", type=int, default=16384, help="Batch size") 130 | parser.add_argument("--wdl", type=float, default=0.0, help="WDL weight to be used") 131 | parser.add_argument("--scale", type=float, help="WDL weight to be used") 132 | parser.add_argument( 133 | "--save-epochs", 134 | type=int, 135 | default=100, 136 | help="How often the program will save the network", 137 | ) 138 | parser.add_argument( 139 | "--lr-drop", 140 | type=int, 141 | default=None, 142 | help="The epoch learning rate will be dropped", 143 | ) 144 | args = parser.parse_args() 145 | 146 | assert args.train_id is not None 147 | assert args.scale is not None 148 | 149 | train_log = TrainLog(args.train_id) 150 | 151 | model = NnHalfKPCuda(128).to(DEVICE) 152 | 153 | data_path = pathlib.Path(args.data_root) 154 | paths = list(map(str, data_path.glob("*.bin"))) 155 | dataloader = BatchLoader(paths, model.input_feature_set(), args.batch_size) 156 | 157 | optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) 158 | 159 | train( 160 | model, 161 | optimizer, 162 | dataloader, 163 | args.wdl, 164 | args.scale, 165 | args.epochs, 166 | args.save_epochs, 167 | args.train_id, 168 | lr_drop=args.lr_drop, 169 | train_log=train_log, 170 | ) 171 | 172 | 173 | if __name__ == "__main__": 174 | main() 175 | -------------------------------------------------------------------------------- /trainer/model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | from dataloader import Batch, InputFeatureSet 4 | 5 | 6 | class NnBoard768(torch.nn.Module): 7 | def __init__(self, ft_out: int): 8 | super().__init__() 9 | self.ft = torch.nn.Linear(768, ft_out) 10 | self.out = torch.nn.Linear(ft_out * 2, 1) 11 | 12 | def forward(self, batch: Batch): 13 | stm_indices = batch.stm_indices.reshape(-1, 2).T 14 | nstm_indices = batch.nstm_indices.reshape(-1, 2).T 15 | board_stm_sparse = torch.sparse_coo_tensor( 16 | stm_indices, batch.values, (batch.size, 768) 17 | ).to_dense() 18 | board_nstm_sparse = torch.sparse_coo_tensor( 19 | nstm_indices, batch.values, (batch.size, 768) 20 | ).to_dense() 21 | 22 | stm_ft = self.ft(board_stm_sparse) 23 | nstm_ft = self.ft(board_nstm_sparse) 24 | 25 | hidden = torch.clamp(torch.cat((stm_ft, nstm_ft), dim=1), 0, 1) 26 | 27 | return torch.sigmoid(self.out(hidden)) 28 | 29 | def input_feature_set(self) -> InputFeatureSet: 30 | return InputFeatureSet.BOARD_768 31 | 32 | 33 | class NnHalfKP(torch.nn.Module): 34 | def __init__(self, ft_out: int): 35 | super().__init__() 36 | self.ft = torch.nn.Linear(40960, ft_out) 37 | self.fft = torch.nn.Linear(640, ft_out) 38 | self.out = torch.nn.Linear(ft_out * 2, 1) 39 | 40 | def forward(self, batch: Batch): 41 | 42 | stm_indices = batch.stm_indices.reshape(-1, 2).T 43 | nstm_indices = batch.nstm_indices.reshape(-1, 2).T 44 | board_stm_sparse = torch.sparse_coo_tensor( 45 | stm_indices, batch.values, (batch.size, 40960) 46 | ) 47 | board_nstm_sparse = torch.sparse_coo_tensor( 48 | nstm_indices, batch.values, (batch.size, 40960) 49 | ) 50 | 51 | v_stm_indices = torch.clone(stm_indices) 52 | v_nstm_indices = torch.clone(nstm_indices) 53 | v_stm_indices[1][:] %= 640 54 | v_nstm_indices[1][:] %= 640 55 | v_board_stm_sparse = torch.sparse_coo_tensor( 56 | v_stm_indices, batch.values, (batch.size, 640) 57 | ).to_dense() 58 | v_board_nstm_sparse = torch.sparse_coo_tensor( 59 | v_nstm_indices, batch.values, (batch.size, 640) 60 | ).to_dense() 61 | 62 | stm_ft = self.ft(board_stm_sparse) + self.fft(v_board_stm_sparse) 63 | nstm_ft = self.ft(board_nstm_sparse) + self.fft(v_board_nstm_sparse) 64 | 65 | hidden = torch.clamp(torch.cat((stm_ft, nstm_ft), dim=1), 0, 1) 66 | 67 | return torch.sigmoid(self.out(hidden)) 68 | 69 | def input_feature_set(self) -> InputFeatureSet: 70 | return InputFeatureSet.HALF_KP 71 | 72 | 73 | class NnHalfKA(torch.nn.Module): 74 | def __init__(self, ft_out: int): 75 | super().__init__() 76 | self.ft = torch.nn.Linear(49152, ft_out) 77 | self.fft = torch.nn.Linear(768, ft_out) 78 | self.out = torch.nn.Linear(ft_out * 2, 1) 79 | 80 | def forward(self, batch: Batch): 81 | stm_indices = batch.stm_indices.reshape(-1, 2).T 82 | nstm_indices = batch.nstm_indices.reshape(-1, 2).T 83 | board_stm_sparse = torch.sparse_coo_tensor( 84 | stm_indices, batch.values, (batch.size, 49152) 85 | ) 86 | board_nstm_sparse = torch.sparse_coo_tensor( 87 | nstm_indices, batch.values, (batch.size, 49152) 88 | ) 89 | 90 | v_stm_indices = torch.clone(stm_indices) 91 | v_nstm_indices = torch.clone(nstm_indices) 92 | v_stm_indices[1][:] %= 768 93 | v_nstm_indices[1][:] %= 768 94 | v_board_stm_sparse = torch.sparse_coo_tensor( 95 | v_stm_indices, batch.values, (batch.size, 768) 96 | ).to_dense() 97 | v_board_nstm_sparse = torch.sparse_coo_tensor( 98 | v_nstm_indices, batch.values, (batch.size, 768) 99 | ).to_dense() 100 | 101 | stm_ft = self.ft(board_stm_sparse) + self.fft(v_board_stm_sparse) 102 | nstm_ft = self.ft(board_nstm_sparse) + self.fft(v_board_nstm_sparse) 103 | 104 | hidden = torch.clamp(torch.cat((stm_ft, nstm_ft), dim=1), 0, 1) 105 | 106 | return torch.sigmoid(self.out(hidden)) 107 | 108 | def input_feature_set(self) -> InputFeatureSet: 109 | return InputFeatureSet.HALF_KA 110 | 111 | 112 | class NnBoard768Cuda(torch.nn.Module): 113 | def __init__(self, ft_out: int): 114 | from cudasparse import DoubleFeatureTransformerSlice 115 | 116 | super().__init__() 117 | self.max_features = InputFeatureSet.BOARD_768_CUDA.max_features() 118 | self.ft = DoubleFeatureTransformerSlice(768, ft_out) 119 | self.out = torch.nn.Linear(ft_out * 2, 1) 120 | 121 | def forward(self, batch: Batch): 122 | values = batch.values.reshape(-1, self.max_features) 123 | stm_indices = batch.stm_indices.reshape(-1, self.max_features).type( 124 | dtype=torch.int32 125 | ) 126 | nstm_indices = batch.nstm_indices.reshape(-1, self.max_features).type( 127 | dtype=torch.int32 128 | ) 129 | stm_ft, nstm_ft = self.ft( 130 | stm_indices, 131 | values, 132 | nstm_indices, 133 | values, 134 | ) 135 | 136 | hidden = torch.clamp(torch.cat((stm_ft, nstm_ft), dim=1), 0, 1) 137 | 138 | return torch.sigmoid(self.out(hidden)) 139 | 140 | def input_feature_set(self) -> InputFeatureSet: 141 | return InputFeatureSet.BOARD_768_CUDA 142 | 143 | 144 | class NnHalfKPCuda(torch.nn.Module): 145 | def __init__(self, ft_out: int): 146 | super().__init__() 147 | from cudasparse import DoubleFeatureTransformerSlice 148 | 149 | self.max_features = InputFeatureSet.HALF_KP_CUDA.max_features() 150 | self.ft = DoubleFeatureTransformerSlice(40960, ft_out) 151 | self.fft = DoubleFeatureTransformerSlice(640, ft_out) 152 | self.out = torch.nn.Linear(ft_out * 2, 1) 153 | 154 | def forward(self, batch: Batch): 155 | values = batch.values.reshape(-1, self.max_features) 156 | stm_indices = batch.stm_indices.reshape(-1, self.max_features).type( 157 | dtype=torch.int32 158 | ) 159 | nstm_indices = batch.nstm_indices.reshape(-1, self.max_features).type( 160 | dtype=torch.int32 161 | ) 162 | stm_ft, nstm_ft = self.ft( 163 | stm_indices, 164 | values, 165 | nstm_indices, 166 | values, 167 | ) 168 | v_stm_ft, v_nstm_ft = self.fft( 169 | stm_indices.fmod(640), values, nstm_indices.fmod(640), values 170 | ) 171 | 172 | hidden = torch.clamp( 173 | torch.cat((stm_ft + v_stm_ft, nstm_ft + v_nstm_ft), dim=1), 0, 1 174 | ) 175 | 176 | return torch.sigmoid(self.out(hidden)) 177 | 178 | def input_feature_set(self) -> InputFeatureSet: 179 | return InputFeatureSet.HALF_KP_CUDA 180 | 181 | 182 | class NnHalfKACuda(torch.nn.Module): 183 | def __init__(self, ft_out: int): 184 | super().__init__() 185 | from cudasparse import DoubleFeatureTransformerSlice 186 | 187 | self.max_features = InputFeatureSet.HALF_KA_CUDA.max_features() 188 | self.ft = DoubleFeatureTransformerSlice(49152, ft_out) 189 | self.fft = DoubleFeatureTransformerSlice(768, ft_out) 190 | self.out = torch.nn.Linear(ft_out * 2, 1) 191 | 192 | def forward(self, batch: Batch): 193 | values = batch.values.reshape(-1, self.max_features) 194 | stm_indices = batch.stm_indices.reshape(-1, self.max_features).type( 195 | dtype=torch.int32 196 | ) 197 | nstm_indices = batch.nstm_indices.reshape(-1, self.max_features).type( 198 | dtype=torch.int32 199 | ) 200 | stm_ft, nstm_ft = self.ft( 201 | stm_indices, 202 | values, 203 | nstm_indices, 204 | values, 205 | ) 206 | v_stm_ft, v_nstm_ft = self.fft( 207 | stm_indices.fmod(768), values, nstm_indices.fmod(768), values 208 | ) 209 | 210 | hidden = torch.clamp( 211 | torch.cat((stm_ft + v_stm_ft, nstm_ft + v_nstm_ft), dim=1), 0, 1 212 | ) 213 | 214 | return torch.sigmoid(self.out(hidden)) 215 | 216 | def input_feature_set(self) -> InputFeatureSet: 217 | return InputFeatureSet.HALF_KA_CUDA 218 | -------------------------------------------------------------------------------- /trainer/requirements.txt: -------------------------------------------------------------------------------- 1 | black==22.6.0 2 | click==8.1.3 3 | cycler==0.11.0 4 | fonttools==4.34.4 5 | kiwisolver==1.4.3 6 | matplotlib==3.5.2 7 | mypy-extensions==0.4.3 8 | numpy==1.23.1 9 | packaging==21.3 10 | pathspec==0.9.0 11 | Pillow==9.2.0 12 | platformdirs==2.5.2 13 | pyparsing==3.0.9 14 | python-dateutil==2.8.2 15 | six==1.16.0 16 | tomli==2.0.1 17 | torch==1.12.0 18 | typing_extensions==4.3.0 19 | -------------------------------------------------------------------------------- /trainer/trainlog.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | 4 | class TrainLog: 5 | def __init__(self, train_id: str): 6 | self.train_id = train_id 7 | self.losses: list[float] = [] 8 | 9 | def update(self, loss: float) -> None: 10 | self.losses.append(loss) 11 | 12 | def save(self) -> None: 13 | logs = "" 14 | for epoch, loss in enumerate(self.losses): 15 | logs += f"epoch {epoch}: {loss}\n" 16 | with open(f"runs/{self.train_id}.txt", "w") as log: 17 | log.write(logs) 18 | -------------------------------------------------------------------------------- /trainer/visualize.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | import pathlib 3 | 4 | import re 5 | import sys 6 | 7 | from matplotlib import pyplot as plt 8 | 9 | MATCH = re.compile(r"epoch\s([0-9]+):\s([0-9]+.[0-9]+)") 10 | 11 | 12 | def _read_file(path: str) -> tuple[list[int], list[float]]: 13 | epochs: list[int] = [] 14 | losses: list[float] = [] 15 | with open(path) as train_log: 16 | for line in train_log: 17 | match = re.search(MATCH, line) 18 | if match is None: 19 | continue 20 | epochs.append(int(match.group(1))) 21 | losses.append(float(match.group(2))) 22 | return epochs, losses 23 | 24 | 25 | def main(): 26 | files = [arg for arg in sys.argv if arg.endswith(".txt")] 27 | for f in files: 28 | epochs, losses = _read_file(f) 29 | name = pathlib.Path(f).name.split(".")[-2] 30 | plt.plot(epochs, losses, label=name) 31 | plt.legend() 32 | plt.show() 33 | 34 | 35 | if __name__ == "__main__": 36 | main() 37 | -------------------------------------------------------------------------------- /utils/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "marlinflow-utils" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | serde = { version = "1.0.136", features = ["derive"] } 10 | serde_json = "1.0.79" 11 | structopt = "0.3.26" 12 | marlinformat = { path = "../marlinformat" } 13 | rand = "0.8.5" 14 | bytemuck = "1.10.0" 15 | cozy-chess = "0.3.4" 16 | tempfile = "3.3.0" 17 | -------------------------------------------------------------------------------- /utils/src/convert/halfkp.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | use super::utils; 4 | 5 | #[derive(Serialize, Deserialize)] 6 | pub struct HalfKp { 7 | #[serde(rename = "ft.weight")] 8 | feature_weights: Box<[Box<[f32]>]>, 9 | #[serde(rename = "ft.bias")] 10 | feature_bias: Box<[f32]>, 11 | #[serde(rename = "fft.weight")] 12 | v_weights: Box<[Box<[f32]>]>, 13 | #[serde(rename = "fft.bias")] 14 | v_bias: Box<[f32]>, 15 | #[serde(rename = "out.weight")] 16 | out_weights: Box<[Box<[f32]>]>, 17 | #[serde(rename = "out.bias")] 18 | out_bias: Box<[f32]>, 19 | } 20 | 21 | impl HalfKp { 22 | pub fn from(bytes: &[u8]) -> Self { 23 | serde_json::from_slice(bytes).unwrap() 24 | } 25 | 26 | pub fn to_bin(&self, ft_scale: f32, scale: f32) -> Vec { 27 | let mut bin = vec![]; 28 | bin.extend((self.feature_weights.len() as u32).to_le_bytes()); 29 | bin.extend((self.feature_weights[0].len() as u32).to_le_bytes()); 30 | bin.extend((self.out_weights.len() as u32).to_le_bytes()); 31 | 32 | let mut summed_weights = self.feature_weights.clone(); 33 | let mut summed_bias = self.feature_bias.clone(); 34 | 35 | let planes = summed_weights.len() / self.v_weights.len(); 36 | assert_eq!(planes, 64); 37 | for i in 0..planes { 38 | for j in 0..self.v_weights.len() { 39 | assert_eq!(self.v_weights[0].len(), summed_weights[0].len()); 40 | for k in 0..self.v_weights[0].len() { 41 | summed_weights[self.v_weights.len() * i + j][k] += self.v_weights[j][k]; 42 | } 43 | } 44 | } 45 | for (bias, v_bias) in summed_bias.iter_mut().zip(self.v_bias.iter()) { 46 | *bias += *v_bias 47 | } 48 | 49 | utils::serialize_dense_i16(&summed_weights, &mut bin, ft_scale); 50 | utils::serialize_flat_i16(&summed_bias, &mut bin, ft_scale); 51 | utils::serialize_dense_i8(&self.out_weights, &mut bin, scale); 52 | utils::serialize_flat_i16(&self.out_bias, &mut bin, ft_scale * scale); 53 | 54 | bin 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /utils/src/convert/mod.rs: -------------------------------------------------------------------------------- 1 | mod halfkp; 2 | mod utils; 3 | 4 | use std::path::PathBuf; 5 | 6 | use halfkp::HalfKp; 7 | use structopt::StructOpt; 8 | 9 | #[derive(StructOpt)] 10 | /// Convert JSON neural network file into BlackMarlin NNUE format 11 | pub struct Options { 12 | /// Path to the JSON file cont 13 | path: PathBuf, 14 | #[structopt(long, short = "o", default_value = "nnue.bin")] 15 | output: PathBuf, 16 | } 17 | 18 | pub fn run(options: Options) { 19 | let content = std::fs::read(options.path).unwrap(); 20 | 21 | let arch = HalfKp::from(&content); 22 | let bin = arch.to_bin(255.0, 64.0); 23 | std::fs::write(options.output, bin).unwrap(); 24 | } 25 | -------------------------------------------------------------------------------- /utils/src/convert/utils.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused)] // utils module 2 | 3 | pub fn serialize_dense_i8(weights: &[Box<[f32]>], bin: &mut Vec, scale: f32) { 4 | for weights in weights { 5 | for &weight in weights.iter() { 6 | bin.extend(i8::try_from((weight * scale) as i64).unwrap().to_le_bytes()) 7 | } 8 | } 9 | } 10 | 11 | pub fn serialize_flat_i8(weights: &[f32], bin: &mut Vec, scale: f32) { 12 | for &weight in weights { 13 | bin.extend(i8::try_from((weight * scale) as i64).unwrap().to_le_bytes()) 14 | } 15 | } 16 | 17 | pub fn serialize_dense_i16(weights: &[Box<[f32]>], bin: &mut Vec, scale: f32) { 18 | for weights in weights { 19 | for &weight in weights.iter() { 20 | bin.extend( 21 | i16::try_from((weight * scale) as i64) 22 | .unwrap() 23 | .to_le_bytes(), 24 | ) 25 | } 26 | } 27 | } 28 | 29 | pub fn serialize_flat_i16(weights: &[f32], bin: &mut Vec, scale: f32) { 30 | for &weight in weights { 31 | bin.extend( 32 | i16::try_from((weight * scale) as i64) 33 | .unwrap() 34 | .to_le_bytes(), 35 | ) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /utils/src/interleave.rs: -------------------------------------------------------------------------------- 1 | use std::fs::File; 2 | use std::io::{BufReader, BufWriter, Read, Result, Seek, SeekFrom, Write}; 3 | use std::path::PathBuf; 4 | use std::time::Instant; 5 | 6 | use bytemuck::Zeroable; 7 | use marlinformat::PackedBoard; 8 | use rand::{thread_rng, Rng}; 9 | use structopt::StructOpt; 10 | 11 | /// Randomly interleave two or more datasets. 12 | #[derive(StructOpt)] 13 | pub struct Options { 14 | #[structopt(short, long)] 15 | output: PathBuf, 16 | 17 | #[structopt(required = true, min_values = 2)] 18 | files: Vec, 19 | } 20 | 21 | pub fn run(options: Options) -> Result<()> { 22 | let mut files: Vec<_> = options 23 | .files 24 | .iter() 25 | .map(|path| File::open(path)) 26 | .collect::>()?; 27 | 28 | let mut into = File::create(options.output)?; 29 | 30 | let start = Instant::now(); 31 | 32 | interleave(&mut into, &mut files, |progress, total| { 33 | if progress & 0xFFFFF == 0 { 34 | let proportion = progress as f64 / total as f64; 35 | print!("\r\x1B[K{progress:12}/{total} ({:4.1}%)", proportion * 100.0); 36 | let _ = std::io::stdout().flush(); 37 | } 38 | })?; 39 | println!(); 40 | println!("Done ({:.1?}).", start.elapsed()); 41 | 42 | Ok(()) 43 | } 44 | 45 | pub fn interleave( 46 | into: &mut File, 47 | files: &mut [File], 48 | mut progress: impl FnMut(u64, u64), 49 | ) -> Result<()> { 50 | let mut into = BufWriter::new(into); 51 | let mut streams = Vec::with_capacity(files.len()); 52 | let mut total = 0; 53 | for file in files { 54 | let size_bytes = file.seek(SeekFrom::End(0))?; 55 | file.seek(SeekFrom::Start(0))?; 56 | let count = size_bytes / std::mem::size_of::() as u64; 57 | if count > 0 { 58 | streams.push((count, BufReader::new(file))); 59 | total += count; 60 | } 61 | } 62 | 63 | let mut written = 0; 64 | 65 | while total > 0 { 66 | let mut spot = thread_rng().gen_range(0..total); 67 | let mut index = 0; 68 | while streams[index].0 < spot { 69 | spot -= streams[index].0; 70 | index += 1; 71 | } 72 | let (count, reader) = &mut streams[index]; 73 | 74 | let mut value = PackedBoard::zeroed(); 75 | reader.read_exact(bytemuck::bytes_of_mut(&mut value))?; 76 | into.write_all(bytemuck::bytes_of(&value))?; 77 | 78 | total -= 1; 79 | *count -= 1; 80 | if *count == 0 { 81 | streams.swap_remove(index); 82 | } 83 | 84 | written += 1; 85 | progress(written, total); 86 | } 87 | 88 | Ok(()) 89 | } 90 | -------------------------------------------------------------------------------- /utils/src/main.rs: -------------------------------------------------------------------------------- 1 | use structopt::StructOpt; 2 | 3 | mod convert; 4 | mod interleave; 5 | mod shuffle; 6 | mod txt_to_data; 7 | 8 | #[derive(StructOpt)] 9 | pub enum Options { 10 | Convert(convert::Options), 11 | Shuffle(shuffle::Options), 12 | Interleave(interleave::Options), 13 | TxtToData(txt_to_data::Options), 14 | } 15 | 16 | fn main() { 17 | match Options::from_args() { 18 | Options::Convert(options) => convert::run(options), 19 | Options::Shuffle(options) => shuffle::run(options).unwrap(), 20 | Options::Interleave(options) => interleave::run(options).unwrap(), 21 | Options::TxtToData(options) => txt_to_data::run(options).unwrap(), 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /utils/src/shuffle.rs: -------------------------------------------------------------------------------- 1 | use std::fs::File; 2 | use std::io::{Read, Result, Seek, SeekFrom, Write}; 3 | use std::path::PathBuf; 4 | 5 | use bytemuck::Zeroable; 6 | use marlinformat::PackedBoard; 7 | use rand::prelude::*; 8 | use structopt::StructOpt; 9 | 10 | use crate::interleave::interleave; 11 | 12 | #[derive(StructOpt)] 13 | /// Shuffle a dataset 14 | pub struct Options { 15 | dataset: PathBuf, 16 | 17 | /// Overwrite the input file. 18 | #[structopt(long, short)] 19 | _in_place: bool, 20 | 21 | /// Output file 22 | #[structopt(long, short, required_unless("in-place"))] 23 | output: Option, 24 | 25 | #[structopt(long, default_value = "134217728")] 26 | block_size: u64, 27 | #[structopt(long, default_value = "256")] 28 | group_size: u64, 29 | } 30 | 31 | pub fn run(options: Options) -> Result<()> { 32 | let output = options.output.unwrap_or_else(|| options.dataset.clone()); 33 | let output_dir = output 34 | .parent() 35 | .expect("Could not get nominal parent directory of the oiutput file"); 36 | 37 | let mut dataset = File::open(options.dataset)?; 38 | let positions = dataset.seek(SeekFrom::End(0))? / std::mem::size_of::() as u64; 39 | dataset.rewind()?; 40 | 41 | if positions <= options.block_size { 42 | println!("in-memory shuffle"); 43 | let mut data = read(&mut dataset, positions)?; 44 | drop(dataset); 45 | data.shuffle(&mut thread_rng()); 46 | let mut target = tempfile::NamedTempFile::new_in(output_dir)?; 47 | target.write_all(bytemuck::cast_slice(&data))?; 48 | target.persist(output)?; 49 | return Ok(()); 50 | } 51 | 52 | let block_count = (positions + options.block_size - 1) / options.block_size; 53 | 54 | let (send, mut recv) = std::sync::mpsc::sync_channel(options.group_size as usize); 55 | 56 | let mut remaining = positions; 57 | let mut blocks_shuffled = 0; 58 | std::thread::spawn({ 59 | let output_dir = output_dir.to_owned(); 60 | move || loop { 61 | if remaining == 0 { 62 | break; 63 | } 64 | let count = remaining.min(options.block_size); 65 | remaining -= count; 66 | let mut data = read(&mut dataset, count).unwrap(); 67 | data.shuffle(&mut thread_rng()); 68 | let mut f = tempfile::tempfile_in(&output_dir).unwrap(); 69 | f.write_all(bytemuck::cast_slice(&data)).unwrap(); 70 | send.send(f).unwrap(); 71 | blocks_shuffled += 1; 72 | println!("blocks: {blocks_shuffled}/{block_count}"); 73 | } 74 | }); 75 | 76 | let mut items = block_count; 77 | let mut level = 0; 78 | loop { 79 | level += 1; 80 | items = (items + options.group_size - 1) / options.group_size; 81 | if items == 1 { 82 | break; 83 | } 84 | 85 | let (nsend, nrecv) = std::sync::mpsc::sync_channel(options.group_size as usize); 86 | let mut iter = recv.into_iter(); 87 | let mut progress = 0; 88 | std::thread::spawn({ 89 | let output_dir = output_dir.to_owned(); 90 | move || loop { 91 | let mut files: Vec<_> = (&mut iter).take(options.group_size as usize).collect(); 92 | if files.is_empty() { 93 | break; 94 | } 95 | let mut to = tempfile::tempfile_in(&output_dir).unwrap(); 96 | interleave(&mut to, &mut files, |_, _| {}).unwrap(); 97 | nsend.send(to).unwrap(); 98 | progress += 1; 99 | println!("lvl. {level}: {progress}/{items}"); 100 | } 101 | }); 102 | 103 | recv = nrecv; 104 | } 105 | 106 | let mut files: Vec<_> = recv.into_iter().collect(); 107 | let mut target = tempfile::NamedTempFile::new_in(output_dir)?; 108 | interleave(target.as_file_mut(), &mut files, |_, _| {})?; 109 | target.persist(output)?; 110 | 111 | Ok(()) 112 | } 113 | 114 | fn read(dataset: &mut File, count: u64) -> Result> { 115 | let mut boards = vec![PackedBoard::zeroed(); count as usize]; 116 | dataset.read_exact(bytemuck::cast_slice_mut(&mut boards))?; 117 | Ok(boards) 118 | } 119 | -------------------------------------------------------------------------------- /utils/src/txt_to_data.rs: -------------------------------------------------------------------------------- 1 | use std::fs::File; 2 | use std::io::{BufRead, BufReader, BufWriter, Result, Write}; 3 | use std::path::PathBuf; 4 | 5 | use cozy_chess::Board; 6 | use marlinformat::PackedBoard; 7 | use structopt::StructOpt; 8 | 9 | /// Convert legacy text data format to marlinformat. 10 | #[derive(StructOpt)] 11 | pub struct Options { 12 | #[structopt(short, long)] 13 | output: PathBuf, 14 | 15 | txt_file: PathBuf, 16 | } 17 | 18 | pub fn run(options: Options) -> Result<()> { 19 | let input = BufReader::new(File::open(options.txt_file)?); 20 | let mut output = BufWriter::new(File::create(options.output)?); 21 | 22 | let mut had_non_integer_cp = false; 23 | let mut had_out_of_range_cp = false; 24 | 25 | for line in input.lines() { 26 | let line = line?; 27 | let _ = (|| { 28 | let (board, annotation) = line.split_once(" | ")?; 29 | let (cp, wdl) = annotation.split_once(" | ")?; 30 | 31 | let board: Board = board.parse().ok()?; 32 | let cp: f32 = cp.parse().ok()?; 33 | let wdl: f32 = wdl.parse().ok()?; 34 | 35 | if !had_non_integer_cp && cp.floor() != cp { 36 | println!("Warning: dataset contains non-integer centipawn values. These will be truncated."); 37 | had_non_integer_cp = true; 38 | } 39 | 40 | let cp = match (cp as i64).try_into() { 41 | Ok(v) => v, 42 | Err(_) => { 43 | if !had_out_of_range_cp { 44 | println!("Warning: dataset contains centipawn values outside the range representable by an i16. These will be saturated."); 45 | had_out_of_range_cp = true; 46 | } 47 | match cp.is_sign_positive() { 48 | true => i16::MAX, 49 | false => i16::MIN, 50 | } 51 | }, 52 | }; 53 | 54 | let wdl = match () { 55 | _ if wdl < 0.25 => 0, 56 | _ if wdl < 0.75 => 1, 57 | _ => 2 58 | }; 59 | 60 | let packed = PackedBoard::pack(&board, cp, wdl, 0); 61 | Some(output.write_all(bytemuck::bytes_of(&packed))) 62 | })().transpose()?; 63 | } 64 | 65 | Ok(()) 66 | } 67 | --------------------------------------------------------------------------------