15 #include "playout/elo.h"
18 #include "uct/dynkomi.h"
19 #include "uct/internal.h"
20 #include "uct/search.h"
26 uct_progress_status(struct uct
*u
, struct tree
*t
, enum stone color
, int playouts
)
32 struct tree_node
*best
= u
->policy
->choose(u
->policy
, t
->root
, t
->board
, color
, resign
);
34 fprintf(stderr
, "... No moves left\n");
37 fprintf(stderr
, "[%d] ", playouts
);
38 fprintf(stderr
, "best %f ", tree_node_get_value(t
, 1, best
->u
.value
));
41 if (t
->use_extra_komi
)
42 fprintf(stderr
, "komi %.1f ", t
->extra_komi
);
45 fprintf(stderr
, "| seq ");
46 for (int depth
= 0; depth
< 4; depth
++) {
47 if (best
&& best
->u
.playouts
>= 25) {
48 fprintf(stderr
, "%3s ", coord2sstr(best
->coord
, t
->board
));
49 best
= u
->policy
->choose(u
->policy
, best
, t
->board
, color
, resign
);
56 fprintf(stderr
, "| can ");
58 struct tree_node
*can
[cans
];
59 memset(can
, 0, sizeof(can
));
60 best
= t
->root
->children
;
63 while ((!can
[c
] || best
->u
.playouts
> can
[c
]->u
.playouts
) && ++c
< cans
);
64 for (int d
= 0; d
< c
; d
++) can
[d
] = can
[d
+ 1];
65 if (c
> 0) can
[c
- 1] = best
;
70 fprintf(stderr
, "%3s(%.3f) ",
71 coord2sstr(can
[cans
]->coord
, t
->board
),
72 tree_node_get_value(t
, 1, can
[cans
]->u
.value
));
78 fprintf(stderr
, "\n");
83 record_amaf_move(struct playout_amafmap
*amaf
, coord_t coord
, enum stone color
)
85 if (amaf
->map
[coord
] == S_NONE
|| amaf
->map
[coord
] == color
) {
86 amaf
->map
[coord
] = color
;
87 } else { // XXX: Respect amaf->record_nakade
88 amaf_op(amaf
->map
[coord
], +);
90 amaf
->game
[amaf
->gamelen
].coord
= coord
;
91 amaf
->game
[amaf
->gamelen
].color
= color
;
93 assert(amaf
->gamelen
< sizeof(amaf
->game
) / sizeof(amaf
->game
[0]));
97 ltree_node_gamma(struct tree_node
*li
, enum stone color
)
99 /* TODO: How to do this? */
100 #define li_value(color, li) (li->u.playouts * (color == S_BLACK ? li->u.value : (1 - li->u.value)))
101 return 0.5 + li_value(color
, li
);
105 struct uct_playout_callback
{
108 struct tree_node
*lnode
;
110 coord_t
*treepool
[2];
115 uct_playout_probdist(void *data
, struct board
*b
, enum stone to_play
, struct probdist
*pd
)
117 /* Create probability distribution according to found local tree
119 struct uct_playout_callback
*upc
= data
;
120 assert(upc
&& upc
->tree
&& pd
&& b
);
121 coord_t c
= b
->last_move
.coord
;
122 enum stone color
= b
->last_move
.color
;
125 /* Break local sequence. */
127 } else if (upc
->lnode
) {
128 /* Try to follow local sequence. */
129 upc
->lnode
= tree_get_node(upc
->tree
, upc
->lnode
, c
, false);
132 if (!upc
->lnode
|| !upc
->lnode
->children
) {
133 /* There's no local sequence, start new one! */
134 upc
->lnode
= color
== S_BLACK
? upc
->tree
->ltree_black
: upc
->tree
->ltree_white
;
135 upc
->lnode
= tree_get_node(upc
->tree
, upc
->lnode
, c
, false);
138 if (!upc
->lnode
|| !upc
->lnode
->children
) {
139 /* We have no local sequence and we cannot find any starting
140 * by node corresponding to last move. */
141 if (!upc
->uct
->local_tree_pseqroot
) {
142 /* Give up then, we have nothing to contribute. */
145 /* Construct probability distribution from possible first
146 * sequence move. Remember that @color is color of the
148 upc
->lnode
= color
== S_BLACK
? upc
->tree
->ltree_white
: upc
->tree
->ltree_black
;
149 if (!upc
->lnode
->children
) {
150 /* We don't even have anything in our tree yet. */
155 /* The probdist has the right structure only if BOARD_GAMMA is defined. */
160 /* Construct probability distribution from lnode children. */
161 struct tree_node
*li
= upc
->lnode
->children
;
163 if (is_pass(li
->coord
)) {
165 /* TODO: Spread tenuki gamma over all moves we don't touch. */
168 for (; li
; li
= li
->sibling
) {
169 if (board_at(b
, li
->coord
) != S_NONE
)
171 double gamma
= fixp_to_double(pd
->items
[li
->coord
]) * ltree_node_gamma(li
, to_play
);
172 probdist_set(pd
, li
->coord
, double_to_fixp(gamma
));
178 uct_playout_hook(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
, int mode
)
180 struct uct_playout_callback
*upc
= setup
->hook_data
;
181 struct uct
*u
= upc
->uct
;
184 fprintf(stderr
, "treepool check [%d] %d, %p,%p\n", mode
, u
->treepool_chance
[mode
], upc
->treepool
[0], upc
->treepool
[1]);
186 if (u
->treepool_chance
[mode
] > fast_random(100) && upc
->treepool
[color
- 1]) {
187 assert(upc
->treepool_n
[color
- 1] > 0);
189 fprintf(stderr
, "Treepool: ");
190 for (int i
= 0; i
< upc
->treepool_n
[color
- 1]; i
++)
191 fprintf(stderr
, "%s ", coord2sstr(upc
->treepool
[color
- 1][i
], b
));
192 fprintf(stderr
, "\n");
195 coord_t treepool_move
= pass
;
196 if (u
->treepool_pickfactor
) {
197 /* With pickfactor=10, we get uniform distribution. */
198 int prob
= 1000 * u
->treepool_pickfactor
/ (upc
->treepool_n
[color
- 1] * 10);
199 for (int i
= 0; i
< upc
->treepool_n
[color
- 1]; i
++) {
200 treepool_move
= upc
->treepool
[color
- 1][i
];
201 if (prob
> fast_random(1000)) break;
204 treepool_move
= upc
->treepool
[color
- 1][fast_random(upc
->treepool_n
[color
- 1])];
207 fprintf(stderr
, "Treepool pick <%d> %s,%s\n",
208 upc
->treepool_n
[color
- 1],
209 stone2str(color
), coord2sstr(treepool_move
, b
));
211 if (board_is_valid_play(b
, color
, treepool_move
))
212 return treepool_move
;
218 uct_playout_prepolicy(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
)
220 return uct_playout_hook(playout
, setup
, b
, color
, 0);
224 uct_playout_postpolicy(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
)
226 return uct_playout_hook(playout
, setup
, b
, color
, 1);
230 treepool_node_value(struct uct
*u
, struct tree
*tree
, int parity
, struct tree_node
*node
)
232 /* XXX: Playouts get cast to double */
233 switch (u
->treepool_type
) {
234 case UTT_RAVE_PLAYOUTS
:
235 return node
->amaf
.playouts
;
237 return tree_node_get_value(tree
, parity
, node
->amaf
.value
);
238 case UTT_UCT_PLAYOUTS
:
239 return node
->u
.playouts
;
241 return tree_node_get_value(tree
, parity
, node
->u
.value
);
244 struct uct_descent d
= { .node
= node
};
245 assert(u
->policy
->evaluate
);
246 return u
->policy
->evaluate(u
->policy
, tree
, &d
, parity
);
254 treepool_setup(struct uct_playout_callback
*upc
, struct board
*b
, struct tree_node
*node
, int color
)
256 struct uct
*u
= upc
->uct
;
257 int parity
= ((node
->depth
^ upc
->tree
->root
->depth
) & 1) ? -1 : 1;
259 /* XXX: Naive O(N^2) way. */
260 for (int i
= 0; i
< u
->treepool_size
; i
++) {
261 /* For each item, find the highest
262 * node not in the pool yet. */
263 struct tree_node
*best
= NULL
;
264 double best_val
= -1;
266 assert(node
->children
&& is_pass(node
->children
->coord
));
267 for (struct tree_node
*ni
= node
->children
->sibling
; ni
; ni
= ni
->sibling
) {
268 /* Do we already have it? */
270 for (int j
= 0; j
< upc
->treepool_n
[color
]; j
++) {
271 if (upc
->treepool
[color
][j
] == ni
->coord
) {
279 double i_val
= treepool_node_value(u
, upc
->tree
, parity
, ni
);
280 if (i_val
> best_val
) {
287 upc
->treepool
[color
][upc
->treepool_n
[color
]++] = best
->coord
;
293 uct_leaf_node(struct uct
*u
, struct board
*b
, enum stone player_color
,
294 struct playout_amafmap
*amaf
, struct uct_descent
*descent
,
295 struct tree_node
*significant
[2],
296 struct tree
*t
, struct tree_node
*n
, enum stone node_color
,
299 enum stone next_color
= stone_other(node_color
);
300 int parity
= (next_color
== player_color
? 1 : -1);
302 /* We need to make sure only one thread expands the node. If
303 * we are unlucky enough for two threads to meet in the same
304 * node, the latter one will simply do another simulation from
305 * the node itself, no big deal. t->nodes_size may exceed
306 * the maximum in multi-threaded case but not by much so it's ok.
307 * The size test must be before the test&set not after, to allow
308 * expansion of the node later if enough nodes have been freed. */
309 if (n
->u
.playouts
>= u
->expand_p
&& t
->nodes_size
< u
->max_tree_size
310 && !__sync_lock_test_and_set(&n
->is_expanded
, 1)) {
311 tree_expand_node(t
, n
, b
, next_color
, u
, parity
);
314 fprintf(stderr
, "%s*-- UCT playout #%d start [%s] %f\n",
315 spaces
, n
->u
.playouts
, coord2sstr(n
->coord
, t
->board
),
316 tree_node_get_value(t
, parity
, n
->u
.value
));
318 struct uct_playout_callback upc
= {
321 /* TODO: Don't necessarily restart the sequence walk when
322 * entering playout. */
326 if (u
->local_tree_playout
) {
327 /* N.B.: We know this is ELO playout. */
328 playout_elo_callback(u
->playout
, uct_playout_probdist
, &upc
);
331 coord_t pool
[2][u
->treepool_size
];
332 if (u
->treepool_chance
[0] + u
->treepool_chance
[1] > 0) {
333 for (int color
= 0; color
< 2; color
++) {
334 /* Prepare tree-based pool of moves to try forcing
335 * during the playout. */
336 /* We consider the children of the last significant
337 * node, picking top N choices. */
338 struct tree_node
*n
= significant
[color
];
339 if (!n
|| !n
->children
|| !n
->children
->sibling
) {
340 /* No significant node, or it's childless or has
341 * only pass as its child. */
342 upc
.treepool
[color
] = NULL
;
343 upc
.treepool_n
[color
] = 0;
345 upc
.treepool
[color
] = (coord_t
*) &pool
[color
];
346 treepool_setup(&upc
, b
, n
, color
);
351 struct playout_setup ps
= {
352 .gamelen
= u
->gamelen
,
353 .mercymin
= u
->mercymin
,
354 .prepolicy_hook
= uct_playout_prepolicy
,
355 .postpolicy_hook
= uct_playout_postpolicy
,
358 int result
= play_random_game(&ps
, b
, next_color
,
359 u
->playout_amaf
? amaf
: NULL
,
360 &u
->ownermap
, u
->playout
);
361 if (next_color
== S_WHITE
) {
362 /* We need the result from black's perspective. */
366 fprintf(stderr
, "%s -- [%d..%d] %s random playout result %d\n",
367 spaces
, player_color
, next_color
, coord2sstr(n
->coord
, t
->board
), result
);
373 scale_value(struct uct
*u
, struct board
*b
, int result
)
375 floating_t rval
= result
> 0;
377 int vp
= u
->val_points
;
379 vp
= board_size(b
) - 1; vp
*= vp
; vp
*= 2;
382 floating_t sval
= (floating_t
) abs(result
) / vp
;
383 sval
= sval
> 1 ? 1 : sval
;
384 if (result
< 0) sval
= 1 - sval
;
386 rval
+= u
->val_scale
* sval
;
388 rval
= (1 - u
->val_scale
) * rval
+ u
->val_scale
* sval
;
389 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
395 record_local_sequence(struct uct
*u
, struct tree
*t
,
396 struct uct_descent
*descent
, int dlen
, int di
,
397 enum stone seq_color
, floating_t rval
)
399 /* Ignore pass sequences. */
400 if (is_pass(descent
[di
].node
->coord
))
403 #define LTREE_DEBUG if (UDEBUGL(6))
404 LTREE_DEBUG
fprintf(stderr
, "recording result %f in local %s sequence: ",
405 rval
, stone2str(seq_color
));
408 /* Pick the right local tree root... */
409 struct tree_node
*lnode
= seq_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
412 /* ...and record the sequence. */
413 while (di
< dlen
&& (di
== di0
|| descent
[di
].node
->d
< u
->tenuki_d
)) {
414 LTREE_DEBUG
fprintf(stderr
, "%s[%d] ",
415 coord2sstr(descent
[di
].node
->coord
, t
->board
),
416 descent
[di
].node
->d
);
417 lnode
= tree_get_node(t
, lnode
, descent
[di
++].node
->coord
, true);
419 stats_add_result(&lnode
->u
, rval
, 1);
422 /* Add lnode for tenuki (pass) if we descended further. */
424 LTREE_DEBUG
fprintf(stderr
, "pass ");
425 lnode
= tree_get_node(t
, lnode
, pass
, true);
427 stats_add_result(&lnode
->u
, rval
, 1);
430 LTREE_DEBUG
fprintf(stderr
, "\n");
435 uct_playout(struct uct
*u
, struct board
*b
, enum stone player_color
, struct tree
*t
)
440 struct playout_amafmap
*amaf
= NULL
;
441 if (u
->policy
->wants_amaf
) {
442 amaf
= calloc2(1, sizeof(*amaf
));
443 amaf
->map
= calloc2(board_size2(&b2
) + 1, sizeof(*amaf
->map
));
444 amaf
->map
++; // -1 is pass
447 /* Walk the tree until we find a leaf, then expand it and do
448 * a random playout. */
449 struct tree_node
*n
= t
->root
;
450 enum stone node_color
= stone_other(player_color
);
451 assert(node_color
== t
->root_color
);
453 /* Tree descent history. */
454 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
457 struct uct_descent descent
[DLEN
];
458 descent
[0].node
= n
; descent
[0].lnode
= NULL
;
460 /* Total value of the sequence. */
461 struct move_stats seq_value
= { .playouts
= 0 };
462 /* The last "significant" node along the descent (i.e. node
463 * with higher than configured number of playouts). For black
465 struct tree_node
*significant
[2] = { NULL
, NULL
};
466 if (n
->u
.playouts
>= u
->significant_threshold
)
467 significant
[node_color
- 1] = n
;
470 int pass_limit
= (board_size(&b2
) - 2) * (board_size(&b2
) - 2) / 2;
471 int passes
= is_pass(b
->last_move
.coord
) && b
->moves
> 0;
475 static char spaces
[] = "\0 ";
478 fprintf(stderr
, "--- UCT walk with color %d\n", player_color
);
480 while (!tree_leaf_node(n
) && passes
< 2) {
481 spaces
[depth
++] = ' '; spaces
[depth
] = 0;
484 /*** Choose a node to descend to: */
486 /* Parity is chosen already according to the child color, since
487 * it is applied to children. */
488 node_color
= stone_other(node_color
);
489 int parity
= (node_color
== player_color
? 1 : -1);
492 descent
[dlen
] = descent
[dlen
- 1];
493 if (u
->local_tree
&& (!descent
[dlen
].lnode
|| descent
[dlen
].node
->d
>= u
->tenuki_d
)) {
494 /* Start new local sequence. */
495 /* Remember that node_color already holds color of the
496 * to-be-found child. */
497 descent
[dlen
].lnode
= node_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
500 if (!u
->random_policy_chance
|| fast_random(u
->random_policy_chance
))
501 u
->policy
->descend(u
->policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
503 u
->random_policy
->descend(u
->random_policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
506 /*** Perform the descent: */
508 if (descent
[dlen
].node
->u
.playouts
>= u
->significant_threshold
) {
509 significant
[node_color
- 1] = descent
[dlen
].node
;
512 seq_value
.playouts
+= descent
[dlen
].value
.playouts
;
513 seq_value
.value
+= descent
[dlen
].value
.value
* descent
[dlen
].value
.playouts
;
514 n
= descent
[dlen
++].node
;
515 assert(n
== t
->root
|| n
->parent
);
517 fprintf(stderr
, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
518 spaces
, coord2sstr(n
->coord
, t
->board
),
519 n
->coord
, n
->u
.playouts
,
520 tree_node_get_value(t
, parity
, n
->u
.value
));
522 /* Add virtual loss if we need to; this is used to discourage
523 * other threads from visiting this node in case of multiple
524 * threads doing the tree search. */
526 stats_add_result(&n
->u
, tree_parity(t
, parity
) > 0 ? 0 : 1, 1);
528 assert(n
->coord
>= -1);
529 if (amaf
&& !is_pass(n
->coord
))
530 record_amaf_move(amaf
, n
->coord
, node_color
);
532 struct move m
= { n
->coord
, node_color
};
533 int res
= board_play(&b2
, &m
);
535 if (res
< 0 || (!is_pass(m
.coord
) && !group_at(&b2
, m
.coord
)) /* suicide */
536 || b2
.superko_violation
) {
538 for (struct tree_node
*ni
= n
; ni
; ni
= ni
->parent
)
539 fprintf(stderr
, "%s<%"PRIhash
"> ", coord2sstr(ni
->coord
, t
->board
), ni
->hash
);
540 fprintf(stderr
, "marking invalid %s node %d,%d res %d group %d spk %d\n",
541 stone2str(node_color
), coord_x(n
->coord
,b
), coord_y(n
->coord
,b
),
542 res
, group_at(&b2
, m
.coord
), b2
.superko_violation
);
544 n
->hints
|= TREE_HINT_INVALID
;
549 if (is_pass(n
->coord
))
556 amaf
->game_baselen
= amaf
->gamelen
;
557 amaf
->record_nakade
= u
->playout_amaf_nakade
;
560 if (t
->use_extra_komi
&& u
->dynkomi
->persim
) {
561 b2
.komi
+= round(u
->dynkomi
->persim(u
->dynkomi
, &b2
, t
, n
));
565 /* XXX: No dead groups support. */
566 floating_t score
= board_official_score(&b2
, NULL
);
567 /* Result from black's perspective (no matter who
568 * the player; black's perspective is always
569 * what the tree stores. */
570 result
= - (score
* 2);
573 fprintf(stderr
, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
574 player_color
, node_color
, coord2sstr(n
->coord
, t
->board
), result
, score
);
576 board_print(&b2
, stderr
);
578 board_ownermap_fill(&u
->ownermap
, &b2
);
580 } else { // assert(tree_leaf_node(n));
581 /* In case of parallel tree search, the assertion might
582 * not hold if two threads chew on the same node. */
583 result
= uct_leaf_node(u
, &b2
, player_color
, amaf
, &descent
[dlen
- 1], significant
, t
, n
, node_color
, spaces
);
586 if (amaf
&& u
->playout_amaf_cutoff
) {
587 unsigned int cutoff
= amaf
->game_baselen
;
588 cutoff
+= (amaf
->gamelen
- amaf
->game_baselen
) * u
->playout_amaf_cutoff
/ 100;
589 /* Now, reconstruct the amaf map. */
590 memset(amaf
->map
, 0, board_size2(&b2
) * sizeof(*amaf
->map
));
591 for (unsigned int i
= 0; i
< cutoff
; i
++) {
592 coord_t coord
= amaf
->game
[i
].coord
;
593 enum stone color
= amaf
->game
[i
].color
;
594 if (amaf
->map
[coord
] == S_NONE
|| amaf
->map
[coord
] == color
) {
595 amaf
->map
[coord
] = color
;
596 /* Nakade always recorded for in-tree part */
597 } else if (amaf
->record_nakade
|| i
<= amaf
->game_baselen
) {
598 amaf_op(amaf
->map
[n
->coord
], +);
603 assert(n
== t
->root
|| n
->parent
);
605 floating_t rval
= scale_value(u
, b
, result
);
606 u
->policy
->update(u
->policy
, t
, n
, node_color
, player_color
, amaf
, rval
);
608 if (t
->use_extra_komi
) {
609 stats_add_result(&u
->dynkomi
->score
, result
/ 2, 1);
610 stats_add_result(&u
->dynkomi
->value
, rval
, 1);
613 if (u
->local_tree
&& n
->parent
&& !is_pass(n
->coord
) && dlen
> 0) {
614 /* Possibly transform the rval appropriately. */
615 floating_t expval
= seq_value
.value
/ seq_value
.playouts
;
616 rval
= stats_temper_value(rval
, expval
, u
->local_tree
);
618 /* Get the local sequences and record them in ltree. */
619 /* We will look for sequence starts in our descent
620 * history, then run record_local_sequence() for each
621 * found sequence start; record_local_sequence() may
622 * pick longer sequences from descent history then,
623 * which is expected as it will create new lnodes. */
624 enum stone seq_color
= player_color
;
625 /* First move always starts a sequence. */
626 record_local_sequence(u
, t
, descent
, dlen
, 1, seq_color
, rval
);
627 seq_color
= stone_other(seq_color
);
628 for (int dseqi
= 2; dseqi
< dlen
; dseqi
++, seq_color
= stone_other(seq_color
)) {
629 if (u
->local_tree_allseq
) {
630 /* We are configured to record all subsequences. */
631 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
634 if (descent
[dseqi
].node
->d
>= u
->tenuki_d
) {
635 /* Tenuki! Record the fresh sequence. */
636 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
639 if (descent
[dseqi
].lnode
&& !descent
[dseqi
].lnode
) {
640 /* Record result for in-descent picked sequence. */
641 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
649 /* We need to undo the virtual loss we added during descend. */
650 if (u
->virtual_loss
) {
651 int parity
= (node_color
== player_color
? 1 : -1);
652 for (; n
->parent
; n
= n
->parent
) {
653 stats_rm_result(&n
->u
, tree_parity(t
, parity
) > 0 ? 0 : 1, 1);
662 board_done_noalloc(&b2
);
667 uct_playouts(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, struct time_info
*ti
)
670 if (ti
&& ti
->dim
== TD_GAMES
) {
671 for (i
= 0; t
->root
->u
.playouts
<= ti
->len
.games
; i
++)
672 uct_playout(u
, b
, color
, t
);
674 for (i
= 0; !uct_halt
; i
++)
675 uct_playout(u
, b
, color
, t
);