Changes

Jump to: navigation, search

Magic Bitboards

2,355 bytes added, 13:58, 8 July 2021
no edit summary
'''[[Main Page|Home]] * [[Board Representation]] * [[Bitboards]] * [[Sliding Piece Attacks]] * Magic Bitboards'''
[[FILE:GUGG Magic Garden.jpg|border|right|thumb| [[Arts#:Category:Paul Klee|Paul Klee]] - Magic Garden, 1926
<ref>[https://commons.wikimedia.org/wiki/File:GUGG_Magic_Garden.jpg Paul Klee - Magic Garden, 1926], [https://en.wikipedia.org/wiki/Solomon_R._Guggenheim_Museum Solomon R. Guggenheim Museum]</ref> ]]
'''Magic bitboardsBitboards''',<br/>
a multiply-right-shift [[Hash Table#PerfectHashing|perfect hashing]] algorithm to index an attack bitboard database - which leaves both line-attacks of bishop or rook in one run. Thanks to the fast 64-bit [[General Setwise Operations#Multiplication|multiplication]] and fast and huge [https://en.wikipedia.org/wiki/Cache caches] of recent processors, Magic Bitboards has become a [https://en.wikipedia.org/wiki/De_facto_standard de facto standard] of modern bitboard engines, as used for instance in [[Crafty]], [[Arasan]], [[Stockfish]] and [[Houdini]]. While [[Robert Hyatt]] reported no immediate speed gain over [[Rotated Bitboards]] in Crafty <ref>[http://www.talkchess.com/forum/viewtopic.php?topic_view=threads&p=140141&t=16002 Re: BitBoard Tests Magic v Non-Rotated 32 Bits v 64 Bits] by [[Robert Hyatt]], [[CCC]], August 25, 2007</ref> , [[Jon Dart]] mentioned a 20-25% speedup <ref>[http://www.arasanchess.org/blogs/aug08.html Arasan Blog - Aug 26, 2008] by [[Jon Dart]]</ref> in Arasan over rotated.
=History=
The magic bitboard approach was motivated by [[Gerd Isenberg|Gerd Isenberg's]] multi-direction hashing technique [[Kindergarten Bitboards|kindergarten bitboards]] and probably by Gerd's and [[Tony van Roon-Werten|Tony van Roon-Werten's]] early trials to map line-wise [[Occupancy|occupancies]] by [[De Bruijn sequenceSequence|De Bruijn]]- or random number multiplication <ref>[https://www.stmintz.com/ccc/index.php?id=489834 rotated bitboards obsolete?] by [[Gerd Isenberg]], [[CCC]], February 26, 2006</ref> . [[Lasse Hansen]] had the idea to hash the up to twelve relevant occupied bits of '''both directions''' of a rook- or bishop movement simultaneously <ref>[http://www.open-aurec.com/wbforum/viewtopic.php?t=5015 Fast(er) bitboard move generator] by [[Lasse Hansen]], [[Computer Chess Forums|Winboard Forum]], June 14, [[Timeline#2006|2006]], Initial idea</ref> .
[[Pradu Kannan|Pradu Kannan's]] improvements to Lasse Hansen's initial approach was to introduce a [[Java]]-like, two-dimensional [[Array|array]] with individual size for each square and all it's relevant occupancies <ref>[[Pradu Kannan]] ('''2007'''). ''Magic Move-Bitboard Generation in Computer Chess'', as [http://www.pradu.us/old/Nov27_2008/Buzz/research/magic/Bitboards.pdf pdf]</ref> . Big savings in table-size - since many squares on either orthogonal or diagonal lines require less bits than others, especially considering the [[First Rank Attacks#TheOuterSquares|inner six bits]]. While center squares are more dense for rooks, it is the opposite for bishops <ref>[http://www.open-aurec.com/wbforum/viewtopic.php?t=5441 List of magics for bitboard move generation] by [[Pradu Kannan]], [[Computer Chess Forums|Winboard Forum]], August 23, [[Timeline#2006|2006]]</ref> .
Recently, [[Robert Purves]] coined the names Plain and Fancy Magics <ref>[http://www.talkchess.com/forum/viewtopic.php?t=35858 Plain and fancy magic on modern hardware] by [[Robert Purves]], [[CCC]], August 22, 2010</ref> , and found Hansen's initial Plain Magics with 2 MiB table for rooks and 256 KiB for bishops nearly indistinguishable from Fancy (about 800 KiB and 38 KiB) on his [https://en.wikipedia.org/wiki/Intel_Core_i5 Intel i5] with huge L3 smart cache, see [[Magic Bitboards#Plain|plain]] versus [[Magic Bitboards#Fancy|fancy]] source code. In the same [[CCC]] forum thread, [[Robert Houdart]] proposed a [[Magic Bitboards#ByteLookup|byte lookup]] per square for further table reductions.
=How it works=
The above illustration is correct for the b1 bishop, since it has only one ray and one bit per file and works [[Kindergarten Bitboards|kindergarten]] like. In general a one to one mapping of N scattered occupied bits to N consecutive bits is not always possible due to overflows. A perfect mapping of N scattered bits to N consecutive bits is likely not minimal for most squares. It requires one or two gaps inside the consecutive N bits, to avoid collisions, blowing up the table size.
But the purpose is to perfectly hash attack-sets rather than consecutive occupied bits. The number of distinct attack-sets is much smaller than the relevant occupancies. Thus, with the help of constructive collisions, some initial guess how to map the bits, and/or [[Trial and Error|trial and error]], using exactly N bits is always possible. If one tries hard enough to maximize constructive collisions - even less. There are some N-1 ones reported at [[Best Magics so far]], which will half the individual table size for some squares in the widespread [[Magic Bitboards#Fancy|Fancy Magic Bitboards]] approach.
=Perfect Hashing=
</pre>
But the idea seems like a wishing dream. Can we find ONE of the '''magic group''' of magics? Does it exist in theory? If not, can we use more bits to reach the condition? If yes, can we find a good magic group? A good magic group means that all the hash value <=n, so we can reduce the table size to n, until it reach to 1428/4900. Enough? If all hash values are grouped by square, can we think about using the [[Magic Bitboards#PostMask|Sharing Attacks]] method?
=Implementations=
<span id="FixedShiftFancy"></span>
==Fixed shift Fancy==
A fancy fixed shift variation was introduced by [[Onno Garms]], looking for magics producing factors with appropriate reduced value ranges. That is, leave 12 bit rook indices for all squares, but with upper bit(s) clear for all possible occupancies for all the squares with less than 12 relevant bits, so that it efficiently becomes a less 12 bit index. Onno believes that it is possible to find magic factors with that property for most of those squares, to come close to the fancy table size with the advantage of a fixed shift <ref>[http://www.open-aurec.com/wbforum/viewtopic.php?f=4&t=50043 Magic with fixed shift] by [[Onno Garms]], [[Computer Chess Forums|Winboard Forum]], March 18, 2009</ref> . Even an "overlapping" of square arrays is feasible, if they contain accordant unused slot gaps on both ends. [[Volker Annuss]] came up with a fixed shift solution of only 800 KiB and below <ref>[http://www.open-aurec.com/wbforum/viewtopic.php?f=4&t=51162 Fixed shift magics with 800KB lookup table] by [[Volker Annuss]], [[Computer Chess Forums|Winboard Forum]], September, 05, 2010</ref> <ref>[http://www.talkchess.com/forum/viewtopic.php?t=60065&start=14 Re: understanding fixed shift fancy magic bitboard generation] by [[Volker Annuss]], [[CCC]], May 06, 2016</ref>, and more recently even innovated with [[Magic Bitboards#BlackMagics|Black Magic Bitboards]].
<pre>
U64 attack_table[...]; // > 800 KiB - 1.x MiB - depending on the effort on looking for magics
<span id="BlackMagics"></span>
==Black Magic Bitboards==
[[Volker Annuss|Volker Annuss']] most recent innovation and further improvement of his already dense 700 KiB [[Magic Bitboards#FixedShiftFancy|fixed shift fancy]] reference implementation is called '''Black Magic Bitboards''', introduced in [[CCC]] in August 2017 <ref>[http://www.talkchess.com/forum/viewtopic.php?t=64790 Black magic bitboards] by [[Volker Annuss]], [[CCC]], August 03, 2017</ref>. Instead of [[General Setwise Operations#Intersection|intersection]] with a mask to clear the not relevant occupancy bits, he used the [[General Setwise Operations#Union|union]] with the [[General Setwise Operations#ComplementSet|complement]] of mask to set all not relevant occupancy bits.
<pre>
</pre>
This trick, which basically adds a huge constant to the occupancy factor, enables to find '''Black Magics''' yielding in even smaller array sizes per square, determined by maximum and minimum index - the latter no longer zero for the empty occupancy! Unfortunately so far, the individual savings with denser square arrays don't completely advance to the size of the combined overlapping table, since overlapping became harder due to smaller gaps <ref>[http://www.talkchess.com/forum/viewtopic.php?t=64790&start=11 Re: Black magic bitboards] by [[Volker Annuss]], [[CCC]], August 04, 2017</ref> . However, 692 KiB for the complete rook and bishop attack table is the new fixed shift reference. Black Magic Bitboards are now used in Volker's engine [[Arminius]] <ref>[http://www.talkchess.com/forum/viewtopic.php?t=64790&start=14 Re: Black magic bitboards] by [[Volker Annuss]], [[CCC]], August 04, 2017</ref> <ref>source code according to the [[Magic Bitboards#FixedShiftFancy|fixed shift fancy]] sample - array size from Volker's posting, also containing black magics and arrayoffsets, see [http://www.talkchess.com/forum/viewtopic.php?t=64790 Black magic bitboards] by [[Volker Annuss]], [[CCC]], August 03, 2017</ref>:
<pre>
U64 attack_table[88507]; // 692 KiB for published black magics by Volker Annuss (new size 88316 aka 690 KiB)
<span id="PostMask"></span>
==Sharing Attacks==
The development has not finished. [[Lasse Hansen]] came up with another stunning idea <ref>[[Lasse Hansen|Lasse Hansen's]] [http://www.open-aurec.com/wbforum/viewtopic.php?topic_view=threads&p=185506&t=5441 postmask trick], [[Computer Chess Forums|Winboard Forum]], May 09, 2008</ref> , to use a final [[General Setwise Operations#Intersection|intersection]] by attacks [[On an empty Board|attacks on an empty board]], to share tables by two (rooks) or even four (bishops) squares. Bishop sharing is simple to understand, since there are light and dark colored bishops with disjoint attacks-sets, able to share the pre-calculated union of two square-attacks.
The trick is to share even equal colored bishops and rooks where both attack-sets are not disjoint - but all members of the intersection are always set, since they are direct neighbors of both sliders. This is how rooks and bishops may share union-attack-sets by two resp. four squares:
<span id="IncorporatingOffset"></span>
==Incorporating Offset==
A similar idea as in [[Magic Bitboards#IncorporatingtheShift|Incorporating the Shift]] in the domain [[Magic Bitboards#FixedShiftFancy|fixed shift magics]] was proposed by [[Eugene Kotlov]] concerning the indirection to the stored attack array, using the 16 lower bits of the magic factor as offset <ref>[http://www.talkchess.com/forum/viewtopic.php?t=66538 magic number comprising offset] by [[Eugene Kotlov]], [[CCC]], February 07, 2018</ref>, later even combined with incorporating the shift in the domain of Fancy <ref>[http://www.talkchess.com/forum3/viewtopic.php?f=7&t=69947 Shift and Address included into Magic number] by [[Eugene Kotlov]], [[CCC]], February 18, 2019</ref>.
==Initalization==
===Magic Records===
You may try to find your own magics - to possibly contribute to the record table for most dense fancy or plain tables. So far, there were no magics found for the expensive rook squares a1 and h1 (0, 7) with less than 12 bits, which would allow to half the plain table size. Is there any prove they don't exist - even with [[Magic Bitboards#BlackMagics|Black Magic]]?
* [[Best Magics so far]]
* [[Pradu Kannan]] ('''2007'''). ''Magic Move-Bitboard Generation in Computer Chess'', as [http://www.pradu.us/old/Nov27_2008/Buzz/research/magic/Bitboards.pdf pdf]
* [[Fritz Reul]] ('''2009'''). ''New Architectures in Computer Chess'', Ph.D. Thesis, Chapter 3, Magic Hash Functions for Bitboards, [https://pure.uvt.nl/ws/files/1098572/Proefschrift_Fritz_Reul_170609.pdf pdf]
* [[Maurizio Monge]] ('''20112010'''). ''[http://scholar.google.com/citations?view_op=view_citation&hl=en&user=gpgb4LgAAAAJ&citation_for_view=gpgb4LgAAAAJ:UeHWp8X0CEIC On perfect hashing of numbers with sparse digit representation via multiplication by a constant]''. [httphttps://wwwarxiv.sciencedirectorg/abs/1003.3196 arXiv:1003.3196]* [[Niklas Fiekas]] ('''2020''').com''[https:/science/articlebackscattering.de/piichess/S0166218X11000837 Discrete Applied Mathematics, Volhashtable-packing/ The Hashtable Packing Problem]''. 159, No. 11](Draft)
=Forum Posts=
==2009==
* [http://www.talkchess.com/forum/viewtopic.php?t=25810 Magics revisited] by [[Richard Pijl]], [[CCC]], January 04, 2009
* [http://www.open-aurec.com/wbforum/viewtopic.php?f=4&t=49948 Java & Magic Bitboards] by [[Laurens Winkelhagen]], [[Computer Chess Forums|Winboard Forum]], February 03, 2009 » [[Java]]
* [http://www.open-aurec.com/wbforum/viewtopic.php?f=4&t=50043 Magic with fixed shift] by [[Onno Garms]], [[Computer Chess Forums|Winboard Forum]], March 18, 2009
* [http://www.talkchess.com/forum/viewtopic.php?t=30612 Paradigm shifts] by [[Gian-Carlo Pascutto]], [[CCC]], November 14, 2009
* [http://www.talkchess.com/forum/viewtopic.php?t=55712 question about magic keys generation time] by [[Fermin Serrano]], [[CCC]], March 19, 2015 » [[Looking for Magics]]
* [http://www.talkchess.com/forum/viewtopic.php?t=57722 Fancy magic bitboards question] by Eric VanderHelm, [[CCC]], September 22, 2015
'''2016'''
* [http://www.talkchess.com/forum/viewtopic.php?t=60007 M42 - A C++ library for Bitboard attack mask generation] by [[Syed Fahad]], [[CCC]], April 30, 2016 <ref>[https://sites.google.com/site/sydfhd/projects/m42 M42] by [[Syed Fahad]]</ref>
* [http://www.talkchess.com/forum/viewtopic.php?t=60065 understanding fixed shift fancy magic bitboard generation] by [[Kalyankumar Ramaseshan]], [[CCC]], May 05, 2016
: [http://www.talkchess.com/forum/viewtopic.php?t=60065&start=14 Re: understanding fixed shift fancy magic bitboard generation] by [[Volker Annuss]], [[CCC]], May 06, 2016
* [http://www.talkchess.com/forum/viewtopic.php?t=62561 Why should magic bitboards be sparse?] by Alessandro Power, [[CCC]], December 21, 2016
'''2017'''
* [http://www.talkchess.com/forum/viewtopic.php?t=64578 Looking for dense magics] by Lucas Braesch, [[CCC]], July 11, 2017
* [http://www.talkchess.com/forum/viewtopic.php?t=64790 Black magic bitboards] by [[Volker Annuss]], [[CCC]], August 03, 2017 » [[Magic Bitboards#BlackMagics|Black Magic Bitboards]]
* [http://www.talkchess.com/forum/viewtopic.php?t=65187 Disproving the existence of some magics] by [[Niklas Fiekas]], [[CCC]], September 16, 2017 » [[Looking for Magics]]
* [http://www.talkchess.com/forum3/viewtopic.php?f=7&t=65448 Magic BitBoards Magic numbers] by [[Tamás Kuzmics]], [[CCC]], October 14, 2017
'''2018'''
* [http://www.talkchess.com/forum/viewtopic.php?t=66538 magic number comprising offset] by [[Eugene Kotlov]], [[CCC]], February 07, 2018
* [http://www.talkchess.com/forum/viewtopic.php?t=67051 No bishop magics with fixed shift 8] by [[Niklas Fiekas]], [[CCC]], April 09, 2018 » [[Looking for Magics]]
'''2019'''
* [http://www.talkchess.com/forum3/viewtopic.php?f=7&t=69947 Shift and Address included into Magic number] by [[Eugene Kotlov]], [[CCC]], February 18, 2019
* [http://www.talkchess.com/forum3/viewtopic.php?f=7&t=70341 On the establishment of domains wherein magic numbers can and cannot exist] by [[Bruce Newman]], [[CCC]], March 28, 2019
==2020 ...==
* [http://www.talkchess.com/forum3/viewtopic.php?f=7&t=73071 Hashtable packing (e.g. to optimize magic bitboards) is strongly NP-complete] by [[Niklas Fiekas]], [[CCC]], February 13, 2020 <ref>[https://en.wikipedia.org/wiki/Strong_NP-completeness Strong NP-completeness from Wikipedia]</ref>
* [http://www.talkchess.com/forum3/viewtopic.php?f=7&t=73593 Looking for Magics, with ternary field types] by [[Fabian von der Warth]], [[CCC]], April 07, 2020 » [https://en.wikipedia.org/wiki/Hive_(game) Hive]
* [http://www.talkchess.com/forum3/viewtopic.php?f=7&t=73625 magic bitboard perft] by [[Richard Delorme]], [[CCC]], April 11, 2020 » [[Perft]]
* [http://www.talkchess.com/forum3/viewtopic.php?f=7&t=77648 What is the point of magic hashing over simply using masked occupancy as index ?] by Gautier Blandin, [[CCC]], July 06, 2021 » [[Hashing Dictionaries]]
=External Links=
* [http://www.pradu.us/old/Nov27_2008/Buzz/ Buzz - A Winboard Chess Playing Program by Pradu Kannan] - Source of [[Pradu Kannan|Pradu Kannan's]] [[Magic Bitboards|magic]] Move Generator
* [http://web.archive.org/web/20160304114223/http://www.rivalchess.com/magic-bitboards/ Rival Chess Engine - Magic Bitboards] ([https://en.wikipedia.org/wiki/Wayback_Machine Wayback Machine]) by [[Russell Newman]] and [[Chris Moreton]] » [[Rival]]* [http://web.archive.org/web/20160314001240/http://www.afewmorelines.com/understanding-magic-bitboards-in-chess-programming/ Understanding magic bitboards in chess programming] ([https://en.wikipedia.org/wiki/Wayback_Machine Wayback Machine]) by [[Chris Moreton]] in his programming blog, August 07, 2013
* [http://www.chessprogramming.net/generating-magic-multipliers/ Chess Programming | Generating Magic Multipliers] by [[Steve Maughan]] » [[Looking for Magics]]
* [http://stackoverflow.com/questions/16925204/sliding-move-generation-using-magic-bitboard chess - Sliding move generation using magic bitboard] - [https://en.wikipedia.org/wiki/Stack_Overflow Stack Overflow], June 4, 2013
* [https://sites.google.com/site/sydfhd/projects/m42 M42] by [[Syed Fahad]] <ref>[http://www.talkchess.com/forum/viewtopic.php?t=60007 M42 - A C++ library for Bitboard attack mask generation] by [[Syed Fahad]], [[CCC]], April 30, 2016</ref>
* [https://github.com/goutham/magic-bits GitHub - goutham/magic-bits: Magic-bitboards for Chess] by [[Goutham Bhat]]
* [https://rhysre.net/fast-chess-move-generation-with-magic-bitboards.html Fast Chess Move Generation With Magic Bitboards] by [[Rhys Rustad-Elliott]], January 15, 2019
=Other Magic Stuff=
* [https://en.wikipedia.org/wiki/Magic_hypercube Magic hypercube from Wikipedia]
* Five Senses - Magic Constant, [http://www.kalevatravel.ee/index.aw/tallinn2011_culture_capital_europe Christmas Jazz Festival], [https://en.wikipedia.org/wiki/Tallinn Tallinn], December 10, 2011, [https://en.wikipedia.org/wiki/YouTube YouTube] Video
: line-up: [[Videos#NguyenLe:Category:Nguyên Lê|Nguyên Lê]], [https://de.wikipedia.org/wiki/Claudio_Puntin Claudio Puntin], [https://de.wikipedia.org/wiki/Steffen_Schorn Steffen Schorn], [https://de.wikipedia.org/wiki/Kristjan_Randalu Kristjan Randalu], [http://www.bodekjanke.de/english/home.php Bodek Janke]
: {{#evu:https://www.youtube.com/watch?v=oUDnf2fSIRQ|alignment=left|valignment=top}}
* [[Videos#YounSunNah:Category:Youn Sun Nah|Youn Sun Nah]] - [http://www.allaboutjazz.com/lento-youn-sun-nah-act-music-review-by-ian-patterson.php Momento Magico] (2013), [https://en.wikipedia.org/wiki/YouTube YouTube] Video: [[Videos#YounSunNah:Category:Youn Sun Nah|Youn Sun Nah]], [[Videos#UlfWakenius:Category:Ulf Wakenius|Ulf Wakenius]], [[Videos#LarsDanielsson:Category:Lars Danielsson|Lars Danielsson]], [[Videos#VincentPeirani:Category:Vincent Peirani|Vincent Peirani]]
: {{#evu:https://www.youtube.com/watch?v=bOvB6gUpsuk|alignment=left|valignment=top}}
'''[[Sliding Piece Attacks|Up one Level]]'''
[[Category:Paul Klee]]
[[Category:Lars Danielsson]]
[[Category:Nguyên Lê]]
[[Category:Youn Sun Nah]]
[[Category:Vincent Peirani]]
[[Category:Ulf Wakenius]]

Navigation menu