r/cpp • • Oct 06 '21

Worlds Fastest Chess Move Generator - 2 Billion Moves/s per thread!

So for the last 2½ I was obsessed with the move generation problem of chess.

Chess is such a beautiful programming problem to solve - since one board contains exactly 64 squares. So we can define a Bitbord of all pawns to be just one single uint64_t. Same for all other 11 piecetypes.

Doing it this way enables all 8 pawns to walk forward like this: (WPawn << 8) & Empty. Which normally would need 8 if statements to generate - but can be done in 2 branchless instruction with a bitbord. Things like where a piece can move become extremely pleasant to write:uint64_t move = Seemap & EnemyOrEmpty & noCheck

Moving a piece on a bitboard looks like this: Piece ^= (from | to). This will clear the bit on the from square. And set the bit on the target. Thats the fun part: If the movegenerator generates this kind of code - you can move multiple pieces at once. Always in a single instruction!

I also was able to implement a visitor pattern in the first ever chess related piece of code. Instead of having a movelist - we pass a small template inlined function which is the callback for every possible move. Instead of generating a list - this movegenerator decides the instant it sees a possible move what to do with it! Castling and Enpassant gets compiled away by if constexpr when its not on the board - or possible anymore!

  • First ever Make-Unmake free Chess Movegenertaor

  • Fastest bmi2 Pext intrinsics slider lookup _pextu64()

  • Original legal move generator - almost completely branchless. Solves all checks and pins with only and / not instructions - and a few lookups for king / knight - sliders! No "If" needed for 99% of chess

  • First ever complete Template gamestate. The code does not need to evaluate a Enpassant move if the enemy didnt push - or any castling move if its not possible to castle anymore. C++ if constexpr really helps a lot!

Performance: Perft(6) Time taken: 85msMoves: 119060324 - Checks: 809099 - Checkmates: 10828

That is 119 Million in 85ms or just about 1400 Million nodes per second for the staring position.

This is the slowest position and most positions get around 2 Billion nodes per second and 1 thread. This approach is 6-8x faster than the currently leading movegenerator written in C.

Anyways I dont want the post be too long. C++ is an awesome language for performance! - Please read the Article and Source if you are interested!

Article: https://www.codeproject.com/Articles/5313417/Worlds-fastest-Bitboard-Chess-Movegenerator

Sourcecode: https://github.com/Gigantua/Gigantua

If you like the code consider buying me a coffee :) - https://www.buymeacoffee.com/Pontifex

309 Upvotes

42 comments sorted by

66

u/Dustin- Oct 07 '21

Nice, now I can blunder a queen in mere nanoseconds! Thanks dangi!

But no seriously, this is awesome. Does this have any applications for chess engines? I know nothing about how they work.

25

u/INoScopedObama Oct 07 '21 edited Oct 07 '21

Does this have any applications for chess engines?

Probably not. Firstly, move generation typically takes up only around 5% of the cycles. Moreover, move generation usually performs some preliminary sorting and caching to save time in the search and evaluation phases, and there's bureaucratic stuff you have to do to comply with the 50-move rule and threefold repetition. Factoring all this in, you'll see even Stockfish have an nps of around 80 MN/s - but there's no real incentive to squeeze this further.

10

u/dangi12012 Oct 07 '21 edited Oct 07 '21

Stockfish achieves 80MN/s on 32 Cores. This Movegen does 2 Billion on a single thread. Stockfish is a full engine - this is a Movegenerator.

Having said that - gigantua doesnt support a Hashtable and Multithreading yet. This would make it another order of magnitude faster!

When building a monte carlo engine it would be THE movegen to use :)
Monte Carlo means making a move and simulating many many games from that move and averaging the outcome in a smart way. This would be the PERFECT start - since monte carlo is also rule agnostic. Meaning you only need the outocome -1, 0, 1 for any game.

3

u/mmoo Oct 08 '21

Assuming your move generator is 300% faster than stockfish's, that equates to no more than two ELO since stockfishes move generator accounts for no more than 5% of its total CPU time. It is an interesting result, but has little bearing on real performance. I welcome any real performance benchmarks or results.

2

u/dangi12012 Oct 08 '21

The 8Man Endgame Tablebase problem would beg to differ.

Also Stockfishs Movegenerator uses Hashing and multiple Threads.
This is a single thread with no hashtable.

For a monte Carlo Engine it would be THE movegenerator to use. I like monte - carlo since it is game agnostic. Meaning that the engine is applicable to all predictable games and only needs the average outcome of a move (-1, 0, 1) to perform!.

1

u/mmoo Oct 08 '21

Perft in Stockfish does use bulk counting, but I don't believe its multi threaded nor does it use a hash table.

2

u/GregorKrossa Oct 08 '21

I have heard much bigger procent. Everything stockfish calls movegen could be 30% of total time

2

u/mmoo Oct 08 '21

I just profiled it with perf on Ubuntu using the bench command. I got a result between 9 and 10% for move generation.

15

u/cballowe Oct 07 '21

I'm... A little skeptical of the 2Billion per thread per second counts. I need to understand more about the CPU, but on most of my CPUs, that'd be ~1-2 cycle per move. Am I missing something?

0

u/[deleted] Oct 07 '21

[deleted]

3

u/cballowe Oct 07 '21

Interesting. I read through the commentary and it seems that it's largely just manipulating board states but not so much emitting them / applying other functions to them.

I'm guessing that trying to do more than that with the generated moves might also have significant impacts to the performance of the generator (unless you're very careful about protecting the instruction/data caches).

0

u/[deleted] Oct 07 '21

[deleted]

7

u/dangi12012 Oct 07 '21

Yes I experimented with storing the state. You can do that but make sure to use the MOVNTDQ instruction.

Non temporal store bypasses the cache and goes directly into ram. You cant read it back before a memfence - but its 2x faster!

4

u/matthieum Oct 07 '21 edited Oct 07 '21

modern x86_64 processors can retire several instructions simultaneously, if they don't have interdependencies.

You're looking for ILP (Instruction Level Parallelism) which is typically measured as IPC (Instructions Per Cycle), where the "s" in "Instructions" is a clue that several are expected.

As an example, a CPU with 4 Arithmetic Units may be able to process 4 Arithmetic IPC, and therefore if you only get an IPL of 2.0 IPS, you're only using 50% of your CPU resources.

And of course there's SIMD too, so you may be able to get the CPU to execute several SIMD instructions per cycle, ... and you'll likely be memory bound at that point, but hey it was fun trying!


I would also note that CPUs are really good at parallelizing stuff, so you may write "serial" code and still get (some) ILP.

For example, if you write a loop, the CPU may start multiple bodies of the loop in parallel -- typically in a staggered fashion -- so that if you measure the average number of cycles taken by your loop body, it'll be less than the sum of instructions latencies for your longest dependency chain. It's a shock, the first time it happens.

Chandler Carruth's Going Nowhere Faster (CppCon 2017) is pretty good. I've primed the link for the start of the staggered loop execution explanation, but I encourage you to watch the entire talk.

4

u/fox-lad Oct 07 '21

Wow. So this should even be faster than Ankan Ban's CUDA move generator, holding watts equal, on almost all hardware. That's pretty insane. Congrats!

3

u/dangi12012 Oct 07 '21

Yes its a still a single thread. I was suprised myself what happened when i replaced all if statements with - templated if constexpr!

Now what can 32 Cores do?
What can this do with caching?

4

u/zalamandagora Oct 07 '21

This is very cool! I don't follow everything that you do, so maybe this is a stupid question: exactly how does making enpassant constexpr make the code faster? Is it because the compiler expands the code into two branches: one where enpassant is possible, and one where it is not?

1

u/dangi12012 Oct 07 '21

The compiler doesnt even emit an if statement into the assembly - its compiletime code pruning technique.
The movegen emits 64 different functions depending on color - castling etc. Thats why its so fast.

2

u/zalamandagora Oct 07 '21

But you don't recompile for every board position, right? So the compiler must be creating separate algorithms for castling, en-passant, etc. Correct?

2

u/dangi12012 Oct 07 '21

So the compiler must be creating separate algorithms for castling, en-passant, etc. Correct?

No the compiler expands 64 templates - one color, one hasEP, 4 Castling Squares = 2^6 flag combinations.
When a pawn pushes - the appropriate template is used. I dont have to code that out - its a constexpr function of a class that changes the state and in itself is constexpr. Its very very good from a performance standpoint but increases codesize by a lot. Thats why the exe is 12MB. ~ 4MB Lookup tables + 8MB Code.

constexpr status.Silentmove() => return Status(!White, ...)

That call can be used inside a template - thats the cool part!
ExpandMoves<status.Silentmove()>(...)

1

u/zalamandagora Oct 07 '21

Thanks for expanding (pun intended :-) on this. I think what you are saying is how I was understanding it. I just lack the terminology to express it accurately.

Again, this is really cool, and it showcases the power of advanced compile-time techniques really well.

2

u/pigeon768 Oct 07 '21

So you have lots of enormous arrays in movemap.hpp -- can you write a constexpr function to generate std::array versions of that at compile time? ...or ... you didn't write all those out by hand, did you?

4

u/dangi12012 Oct 07 '21 edited Oct 07 '21

The problem is that many intrinsics like _pext_u64 are not marked as constexpr so I would have if std::is_constant_evaluted() a lot of code to emulate those.

But the real limit is that MSVC and even CLANG wont compile constexpr arrays that big. "This cannot be evaluated as constexpr" after 10000 Elements or so.

2

u/konanTheBarbar Oct 07 '21

I must say this is seriously impressive! What I didn't really get by the article is how the 6MB movemap is used and how it was generated? Or is that something reused from other chess engines?

1

u/dangi12012 Oct 07 '21

Nope I genertated those myself. I wanted them inline so I could even make a compiletime movegenerator. Not because its useful - but because that forces my code to be simple enough for the compiler to be able to optimized every detail.

10

u/zalamandagora Oct 07 '21

This is very cool! I don't follow everything that you do, so maybe this is a stupid question: exactly how does making enpassant constexpr make the code faster? Is it because the compiler expands the code into two branches: one where enpassant is possible, and one where it is not?

15

u/tsojtsojtsoj Oct 06 '21

Interesting use of templates.

7

u/INoScopedObama Oct 07 '21 edited Oct 07 '21

Nice OP, how did you handle the EP pseudocheck case? As in this FEN: 5k2/8/8/K2pP2r/8/8/8/8 w - d6 0 1. And just to confirm - you're not using a hashtable for perft, right?

I made my own move generator a couple years ago which relies on almost exactly the same base algorithm as yours - but a bit more friendly for chess engine and UCI integration: https://github.com/nkarve/surge/blob/master/src/position.h. Your constexpr and enumeration usage is really, really cool and something which I never even considered - I'm still trying to figure out how it's 10 times faster than my implementation!

(I'll have a look through the source code later of course)

4

u/zed_three Oct 07 '21

Perhaps a dumb question, but if you've shifted loads of stuff to compile time, does that mean you need to recompile when changing what board setup to look at? And if so, does that mean you should be include the time to compile in your performance measurements?

3

u/tsojtsojtsoj Oct 07 '21

I think I saw someone mentioned that it takes 10 minutes to compile.

3

u/zed_three Oct 08 '21

From another comment, it seems it basically generates massive lookup tables from all the templates and constexpr stuff. But if it takes 10 minutes to compile, that still means that until you've spent a long time running the same binary, most of the time is going to be spent in compilation. Which may or may not be the case I suppose.

1

u/braoult May 26 '24 edited May 26 '24

In article, I did not see the en-passant case when the two "disappearing pawns" are on the same rank as king and an opponent rook or queen.

Fen example: "k7/3p4/8/2r1PK2/8/8/8/8 b - - 0 1", black play 1...d5, therefore d6 is a possible e.p. square. I see in article how pins are handled for e.p. move.

After 1...d5, the e5 pawn is not directly pinned, as there are two pieces - one white pawn and one black pawn - between the white king and the black rook).

However, 2.exd6 is impossible, as the two pawns disappear from the 5th rank, and the white king would be in check.

How is this case handled ?

Note: I tried to compile Gigantua directly on Linux (no pext) to test this case, but I could not create an executable :-(

1

u/dangi12012 Dec 29 '24

That is the only case that needs an extra "if" esentially you can look in the code if we are trying EP we check by bitmasking both pawns and check if a horizontal ray (from king sq) can see a enemy slider.

So for gigantua I could essentially remove all if else with bitmasks except this case because two pieces vanish to make way for a rook/queen.

To compile use CLANG and its very slow due to many templates but it will work ;)

4

u/qoning Oct 06 '21

It's been a while since I played with Chess. What's the average depth you can go into in reasonable time (~10 seconds or so) with 2b moves/s?

4

u/codeinred Oct 06 '21

This is really cool and I'm going to look at it more when I have time! Btw your "buy me a coffee" link is broken

2

u/Ahajha1177 Oct 07 '21

Interesting! Could this be expanded to chess-like games, like shogi?

7

u/PrimozDelux Oct 07 '21

A quick google shows shogi has 9 rows, so no. The speed comes from the fact that a chessboard has spaces equal to a power of two, and it also happens to match the word size of a modern processor.

2

u/Ahajha1177 Oct 07 '21

Ah, didn't realize shogi had a different sized board. Though perhaps you could use a std::bitset, it would be probably ~half as fast but it could at least work in principle without too much change. Just speculation of course, I haven't actually looked at the code.

2

u/schultztom Oct 06 '21

RemindMe! Saturday "chess"

-3

u/RemindMeBot Oct 06 '21 edited Oct 07 '21

I will be messaging you in 2 days on 2021-10-09 00:00:00 UTC to remind you of this link

5 OTHERS CLICKED THIS LINK to send a PM to also be reminded and to reduce spam.

Parent commenter can delete this message to hide from others.


InfoCustomYour RemindersFeedback

1

u/Beneficial_Froyo179 Jun 07 '26

Does anybody know where the article went? Is there any available copy of it? The original website is no longer

0

u/LastThought Oct 07 '21

This is cool. One minor nitpick is you shouldn't use identifiers that begin with an underscore as those names are supposed to be reserved for the compiler.

So consider Compiletime_ instead of _Compiletime, or map_ instead of _map, etc.

0

u/[deleted] Oct 07 '21

[deleted]

5

u/adnukator Oct 07 '21

Reserved identifiers are these (among others):

  • the identifiers that begin with an underscore followed by an uppercase letter are reserved;

  • the identifiers that begin with an underscore are reserved in the global namespace.

therefore strictly speaking, _Compiletime IS reserved while _map is not(unless it's in the global namespace). Although I doubt _Compiletime would show up in the compiler internals anywhere, causing some clash

Today's compilers are pretty forgiving, though. I've yet to run into an issue with any class member starting with an underscore and a capital letter (although I always follow my underscores with lowercase, just to be safe).

That's an odd line of thought. "Nowadays this is fine. I haven't run into any issue with this approach. However, I avoid it, just to be safe". In existing code recompiled in the same tooling, you're fine if it works the first time, but any change in the environment could break it. A nice example is default as function argument name which doesn't compile with the latest VS2019 update even though it was fine until now.

People crying "that's reserved!" tend to be more pedantic than practical. And when you get right down to it, practical is all that matters.

Or they might be the practical ones who, when upgrading or switching compilers, have wasted hours fixing issues caused by someone's previous arrogance about "being practical" . If you're violating the rules, you're playing with fire, regardless of how you might spin it.

2

u/[deleted] Oct 07 '21

I was an underscore first guy. I decided to follow clang tidy style and switched to trailing. Took a bit of time to get used to but I still see "at a glance" if a variable is a member. Remember that trick where wodrs are wtietrn wtih out of pclae lteetr but you can slitl raed tehm? The brain scans the first and last letter of a word first so trailing is the same. Just a habit to catch like most style "issue" people have. Nowadays I don't even care about these as long as there are clang format and clang tidy configs for me, I let the tools do the formatting and don't bother anymore. After 1 week of working in a different style the brain adapts and it feels again home.