Saturday, January 18, 2014

Material signatures and std::map


iCE uses material signatures to classify material combination where it has special knowledge for. It uses a simple enumeration as id for certain material combinations

// ENDGAME IDENTIFIER FOR KNOWN ENDGAMES WITH SPECIAL MODULES
enum EEndGameId { EG_UNKNOWN, EG_KK,
                  EG_KNK, EG_KBK, EG_KRK, EG_KQK, EG_KPK, ...,  EG_MAXCOUNT };


Simple stuff so far. The interesting part is the code that assigns the correct id to a position. So far iCE was using the trivial approach. It just performed a long list of comparisons.

switch (bb.pcsCount)
{
case 2:    return EG_KK; break;
case 3: 

if (bb.pcsTypeCnt[W_KNIGHT] == 1 || bb.pcsTypeCnt[B_KNIGHT] == 1)  return EG_KNK;
if (bb.pcsTypeCnt[W_BISHOP] == 1 || bb.pcsTypeCnt[B_BISHOP] == 1)  return EG_KBK;
if (bb.pcsTypeCnt[W_ROOK] == 1   || bb.pcsTypeCnt[B_ROOK] == 1)    return EG_KRK;
if (bb.pcsTypeCnt[W_QUEEN] == 1  || bb.pcsTypeCnt[B_QUEEN] == 1)   return EG_KQK;
if (bb.pcsTypeCnt[W_PAWN] == 1   || bb.pcsTypeCnt[B_PAWN] == 1)    return EG_KPK;
break;  



This was ok as long as the number of modules was rather small, but over time I added more and more knowledge to iCE and this list grew. Currently iCE has special code for 40 endgames. So the above list was already rather long. It was not really a performance problem. The code is executed only when the material on the board changes and often it just stays as it is. But such a long list is not really elegant.

I considered three alternatives.

1.)
Using a table where I store the endgame ids which is indexed by the lower part of the material hash key. This should be very fast as it is just a look-up. I determined that for my kind of material hash keys I need a table of 8192 slots to allow a collision free perfect hash as long as I restrict the signatures  to 5 men or less positions.  This is currently the case but might change in the future. When adding 6 men positions the size of the required table for a perfect hash will be much bigger.

2.)
Storing the material hash keys of the interesting positions along with the id in a sorted list and then do a binary search in the list. This is a very compact data structure, search will take a bit longer.

3.)
Use the material hash key directly as underlying value in the enumeration. But this is ugly.

The implementation for 1 is straight forward. For the the second I used a std::map container. This is pretty cool. You just store pairs and the map gives you easy access to your values. It is a bit more expensive than the lookup table but should not make a practical difference. If it turns out to be a problem in profiling later I can still change it but I doubt it.

At program start I calculate the material hashes of the combinations that I'm interested in and store them in the map. During search whenever the material on the board changes I have a look there

EEndGameId TBoard::calculateEndGameId()
{
    if (bb.pcsCount > 5 || endgames.count(getMaterialHash()) == 0) return EG_UNKNOWN;
    return endgames[getMaterialHash()];
}


Very elegant and I was able to get rid of an ugly module.

Sunday, January 5, 2014

1659









The Battle of the Lines of Elvas was fought on 14 January 1659, in Elvas, between Portugal and Spain. It ended in a decisive Portuguese victory.

By coincidence 1659 is the exact lines of code that I removed from the iCE source code while reworking its move generators. The move generation code belongs to the oldest modules in iCE. It was created for version 0.1 several years ago. I was not slow or buggy but my coding style changed over time and it did not fit really in anymore. 

iCE has several move generators for quiet moves, tactical moves and check evasions. The all followed the scheme

if (sideToMove == WHITE)
{
    // generate white moves
} else
{
    // do something similar for black
}

This is not really elegant.

Fortunately C++ provides function templates that solve that really nice. It required some code rework including the definition of some new data types. But overall the code now looks much nicer.

As far as I could measure there was no impact on speed and of course the new move generators pass the perft unit test again.

iCE 2.0 v1352 x32 [2014.1.5]
perft        Nodes    Time
  1             20    0 sec
  2            400    0 sec
  3          8.902    0 sec
  4        197.281    0.015 sec
  5      4.865.609    0.109 sec
  6    119.060.324    2.699 sec
 

Perft 1 - 6 executed in 2.823 sec  (43.96 Mnps)

position fen 8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - -
perft        Nodes    Time
  1             14    0 sec
  2            191    0 sec
  3          2.812    0.015 sec
  4         43.238    0 sec
  5        674.624    0.047 sec
  6     11.030.083    0.312 sec
  7    178.633.661    4.867 sec


Perft 1 - 7 executed in 5.241 sec  (36.32 Mnps)


Thursday, January 2, 2014

A bit of New Years cleanup

I'm planning to do spend some time on my move ordering schema, again. So far iCE is not using  a history heuristic scheme. It only relies on the hash table move and the killer moves.


 
For this I have to change my internal move representation a bit so I get a few more bits to store the history score. So far I have 7 bits to hold a move ordering score, which allows values from 0 to 127.




My TMove looks like this

/**********************************************************************
*  A Move is stored as a compact 32bit integer
*     off    bits   name           description
*      0      4     movedPiece     the id of the moved Piece
*      4      6     fromSq         the start square of the move   
*     10      6     toSq           the target square of the move
*     16      4     capturedPiece  which piece is captured
*     20      4     promoteTo      which piece do we promote To
*     24      1     enPassent      this move is an en Passent Capture
*                                  this influences the square where the
*                                  piece is captured
*     25      7     order          an ordering score for move ordering
*                                  range 0 .. 127
***********************************************************************/  


This includes some redundancy. The piece we promote to is stored in 4 bits because the actual piece type is directly stored here. In reality I can only promote to a knight, bishop, rook or queen. The color of the promoted piece is the same a from the moved pawn.  So I only need to code 4 states which require 2 bits

This means with some conversion work I can save 2 bits here, which I can reassign to the ordering value.

I changed and debugged my code and now I'm ready for some more move ordering exercises.  


Saturday, December 21, 2013

Queen vs 3 Minors part 2

I did some more research in the case of a material imbalance of 3 minors vs a queen. In my previous post I determined the imbalance to be worth 0,82 pawns.

Unfortunately this seems to be too simple. The above imbalance figure includes the bonus for the bishop pair which the side with the minors usually enjoys. To remove this effect I repeated the test with positions where the 3 minors did not include the bishop pair.

An additional factor not covered so far is the effect coming from the number of rooks still on the board. In my previous test all starting positions included 2 rook pairs. The theory says that the bonus for the minors should be bigger if the rooks are still on the board. The bonus might be different if some rooks are removed. So I performed several tests to test this hypothesis. 

Here are my results

QRR vs RRBNN
In those positions all rooks were still on the board

Queen side scores 43,0% with equal number of pawns
Queen side scores 23,8% with Minors having an extra pawn

Value of Imbalance for Queen side: -0,37 pawns






QRvsRBNN
In those positions 1 rook for each side was removed

Queen side scores 50,5% with equal number of pawns
Queen side scores 28,9% with Minors having an extra pawn

Value of Imbalance for Queen side: +0,02 pawns






QvsBNN
 In those positions all rooks are removed

Queen side scores 70,8% with equal number of pawns
Queen side scores 44,5% with Minors having an extra pawn

Value of Imbalance for Queen side: +0,79 pawns






It seems the number of rooks has huge impact on the value of the imbalance. Its value changes by more than a pawn. 

 Probably the imbalances of queen and pawns vs a rook and two minors are to hard to be calculated or require a bigger effort. The missing pawns give the side with the minors some development compensation and also half open files, so the value of the imbalance gets polluted with other stuff. So this remains maybe as a future but not immediate exercise.

Wednesday, December 18, 2013

Queen vs 3 minors

Recently there was an interesting "Lonely queen" discussion at Talkchess where it was claimed that stockfish seems to have trouble to understand positions where a queen is exchanged vs 3 pieces.

iCE also does not have special code to handle this imbalance. I relied here on the mobility (3 pieces have more mobility than a queen, whose mobility in iCE is cut at 14 squares). This imbalance is difficult to tune as it appears in less than 1% of the games.






H.G. Muller suggested a cool method to not tune but to measure the value of the imbalance by playing games that enforce the imbalance and measure the winning chances for both sides. This is what I did.

I created a set of starting positions where the imbalance is present. To make it simpler to count I always gave the 3 minors to Black, but awarded the first move in halve of the starting positions to Black.

I then played a iCE vs iCE tournament. After 1000 games, Black scored 63,75%. So the imbalance has a significant influence. I now have to translate this winning percentage into centipawns as this is the score unit in iCE.

Here I removed for Black also the f7 pawn in the starting positions and played again. Black now scored 46,96%. This made the pawn worth 16,79%.


Now I could calculate the value of the imbalance as 13,75% / 16,79% * 1 pawn = 0,82 pawns.

At Talkchess the value of the imbalance was guessed to be 0,70 pawns. It seems this was an excellent guess.

Next step is to include a material imbalance term in the evaluation. It can go with the material signature and material hash, so it provides almost no additional computational costs. The impact on the playing strength will be tiny as it occurs so seldom.

But if your engine plays in 1% of its games really awkward people will notice. The stockfish case is a good example for that.

Next steps will be the measurement of some more imbalances that also involve a rook.

Saturday, December 14, 2013

iCE and the "wrong" bishop

iCE vs Gaviota    55. Rxe7   1/2 : 1/2
After my failed pawn structure experiment I was looking for a small task that has a high chance of success in making my engine better ... just to overcome my disappointment.

I remembered that one of the nice folks that tested my engine after release wrote iCE doesn't know about the wrong bishop. iCE is reporting large winning scores in dead drawn games.

I got a reference of a game against gaviota 0.86. Where iCE exchanged into a endgame with the wrong bishop (diagram).

After the exchange 55. Rxe7 Kxe7 56. Kxe5 iCE found itself in this position and evaluated it with +7. So it thought it is winning,
Draw (wrong bishop)

Of course it is not.

56. ...     Kf8
57. Kf6  Kg8

and the black king controls the corner.






So this is a sign of missing chess knowledge. Humans will see the draw rather easily and if an engine scores such a position as winning it makes a bit a fool out of himself (and its author). The funny thing is, that iCE actually knows about the wrong bishop in king, bishop and pawn vs. king endgames. It did not apply this knowledge because black still owns a pawn. So the endgame module did not kick in (this requires a bare king).

In the above position iCE would not have captured the pawn at f7 (although it could). Its knowledge tells him that without the black pawn the position is a draw. So it tried to keep the black pawn alive and made silly looking moves instead.

To overcome that I coded a few lines to teach iCE about the wrong bishop in a KBPKP endgame. It is a bit more difficult than the original KBPK endgame. In some positions black can still win and in some positions having still a pawn is the losing fact for black. But finally I came up with a good set of positions that are recognized as drawn.

Now this knowledge helps in the above position

iCE 2.0 v1001 x32 [2013.12.2]
position fen 8/3Rbp2/5k2/4n3/2B1K2P/8/8/8 w - - 3 55
go depth 8
info depth 7 seldepth 10 time 0 nodes 2448 pv d7e7 e5c4 e7c7 c4d2 e4d5 f6g6 d5e5  nps 2447999 score cp 586

info depth 8 seldepth 11 time 15 nodes 17773 pv d7c7 e5c4 c7c4 f6g6 e4f3 g6h5 f3g3 f7f5 nps 1184866 score cp 477

At depth 8 iCE realizes that the exchange leads to a wrong bishop endgame and selects a different move.

Probably this not worth a single ELO point, but as I'm not belonging to the only ELO matters fraction it is worth keeping.

Saturday, November 30, 2013

Drawish pawn structures

Many moves later the games ends 1/2 : 1/2
One of the things I had on my todo list was related to pawn structures. I thought that some pawn structures have a more drawish character than others.

Especially blocked or symmetrical positions tend to be more drawish than open ones. 

My idea was to build up a statistics over a lot of games and calculate the probability that a game ends as draw depending on the pawn structure that's on the board. If my engine later encounters a pawn structure with a high probability for a draw the score is pulled towards 0.

So if my engine is ahead it tries to avoid such structures (e.g. not lock its pawns) and if behind it tries to play towards them.

The first step was to collect a lot of positions from games and categorize them depending on the game outcome of the game they were taken from. I assembled a collection of games that lasted at least 60 moves as a base.
  • I saved the position at move number 50 into either a WIN or DRAW file.
  • I then processed the positions from the WIN and DRAW files. 
  • In all positions I only considered the specific pawn structure for the files B - G
Index: 111101 111011 = 3.963
  • For a white pawn at the file I recorded a 1 in the lower 6 bits and for a black pawn a 1 in the higher 6 bits. This number served as a index where I stored the number of games that ended as DRAW or as WIN when this structure was present.
Example: In my statistics the above pawn structure was found in 2.286 games. 857 were drawn and 1.429 were won. This resulted in a draw probability of 37% pct. The overall draw probability over all games and structures was 36%. So this pawn structure is a tiny bit more drawish than the average.

I did this for every possible combination. If there is no white and black pawn present on the B - G files the structure is very drawish (62%), symmetrical combinations had values of about 45%.

Finally I modified my evaluation function to scale the score up or down depending on the pawn structure. It used a lookup table where it stored all the 4096 possible scaling values.

Unfortunately it did not work. The tests showed the modified engine as equal or even slightly weaker then the original engine. I used also different indexing schemes like only counting files with blocked pawns etc... Nothing worked. So the patch was removed from the code again.

It was worth a try.

Hopefully I have more luck with the next idea.