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
;
182 if (upc
->uct
->treepool_chance
[mode
] > fast_random(100) && upc
->treepool
[color
- 1]) {
183 assert(upc
->treepool_n
[color
- 1] > 0);
184 coord_t treepool_move
= upc
->treepool
[color
- 1][fast_random(upc
->treepool_n
[color
- 1])];
185 if (board_is_valid_play(b
, treepool_move
, color
))
186 return treepool_move
;
192 uct_playout_prepolicy(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
)
194 return uct_playout_hook(playout
, setup
, b
, color
, 0);
198 uct_playout_postpolicy(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
)
200 return uct_playout_hook(playout
, setup
, b
, color
, 1);
204 treepool_node_value(struct uct
*u
, struct tree
*tree
, int parity
, struct tree_node
*node
)
206 /* XXX: Playouts get cast to double */
207 switch (u
->treepool_type
) {
208 case UTT_RAVE_PLAYOUTS
:
209 return node
->amaf
.playouts
;
211 return tree_node_get_value(tree
, parity
, node
->amaf
.value
);
212 case UTT_UCT_PLAYOUTS
:
213 return node
->u
.playouts
;
215 return tree_node_get_value(tree
, parity
, node
->u
.value
);
218 struct uct_descent d
= { .node
= node
};
219 assert(u
->policy
->evaluate
);
220 return u
->policy
->evaluate(u
->policy
, tree
, &d
, parity
);
228 treepool_setup(struct uct_playout_callback
*upc
, struct tree_node
*node
, int color
)
230 struct uct
*u
= upc
->uct
;
231 int parity
= ((node
->depth
^ upc
->tree
->root
->depth
) & 1) ? -1 : 1;
233 /* XXX: Naive O(N^2) way. */
234 for (int i
= 0; i
< u
->treepool_size
; i
++) {
235 /* For each item, find the highest
236 * node not in the pool yet. */
237 struct tree_node
*best
= NULL
;
238 double best_val
= -1;
240 // first comes pass which we skip
241 for (struct tree_node
*ni
= node
->children
->sibling
; ni
; ni
= ni
->sibling
) {
242 /* Do we already have it? */
244 for (int j
= 0; j
< upc
->treepool_n
[color
]; j
++)
245 if (upc
->treepool
[color
][j
] == ni
->coord
) {
252 double i_val
= treepool_node_value(u
, upc
->tree
, parity
, ni
);
253 if (i_val
> best_val
) {
260 upc
->treepool
[color
][upc
->treepool_n
[color
]++] = best
->coord
;
266 uct_leaf_node(struct uct
*u
, struct board
*b
, enum stone player_color
,
267 struct playout_amafmap
*amaf
, struct uct_descent
*descent
,
268 struct tree
*t
, struct tree_node
*n
, enum stone node_color
,
271 enum stone next_color
= stone_other(node_color
);
272 int parity
= (next_color
== player_color
? 1 : -1);
274 /* We need to make sure only one thread expands the node. If
275 * we are unlucky enough for two threads to meet in the same
276 * node, the latter one will simply do another simulation from
277 * the node itself, no big deal. t->nodes_size may exceed
278 * the maximum in multi-threaded case but not by much so it's ok.
279 * The size test must be before the test&set not after, to allow
280 * expansion of the node later if enough nodes have been freed. */
281 if (n
->u
.playouts
>= u
->expand_p
&& t
->nodes_size
< u
->max_tree_size
282 && !__sync_lock_test_and_set(&n
->is_expanded
, 1)) {
283 tree_expand_node(t
, n
, b
, next_color
, u
, parity
);
286 fprintf(stderr
, "%s*-- UCT playout #%d start [%s] %f\n",
287 spaces
, n
->u
.playouts
, coord2sstr(n
->coord
, t
->board
),
288 tree_node_get_value(t
, parity
, n
->u
.value
));
290 struct uct_playout_callback upc
= {
293 /* TODO: Don't necessarily restart the sequence walk when
294 * entering playout. */
298 if (u
->local_tree_playout
) {
299 /* N.B.: We know this is ELO playout. */
300 playout_elo_callback(u
->playout
, uct_playout_probdist
, &upc
);
303 coord_t pool
[2][u
->treepool_size
];
304 if (u
->treepool_chance
[0] + u
->treepool_chance
[1] > 0) {
305 for (int color
= 0; color
< 2; color
++) {
306 /* Prepare tree-based pool of moves to try forcing
307 * during the playout. */
308 /* We consider the children of the last significant
309 * node, picking top N choices. */
310 struct tree_node
*n
= descent
->significant
[color
];
311 if (!n
|| !n
->children
|| !n
->children
->sibling
) {
312 /* No significant node, or it's childless or has
313 * only pass as its child. */
314 upc
.treepool
[color
] = NULL
;
315 upc
.treepool_n
[color
] = 0;
317 upc
.treepool
[color
] = (coord_t
*) &pool
[color
];
318 treepool_setup(&upc
, n
, color
);
323 struct playout_setup ps
= {
324 .gamelen
= u
->gamelen
,
325 .mercymin
= u
->mercymin
,
326 .prepolicy_hook
= uct_playout_prepolicy
,
327 .postpolicy_hook
= uct_playout_postpolicy
,
330 int result
= play_random_game(&ps
, b
, next_color
,
331 u
->playout_amaf
? amaf
: NULL
,
332 &u
->ownermap
, u
->playout
);
333 if (next_color
== S_WHITE
) {
334 /* We need the result from black's perspective. */
338 fprintf(stderr
, "%s -- [%d..%d] %s random playout result %d\n",
339 spaces
, player_color
, next_color
, coord2sstr(n
->coord
, t
->board
), result
);
345 scale_value(struct uct
*u
, struct board
*b
, int result
)
347 float rval
= result
> 0;
349 int vp
= u
->val_points
;
351 vp
= board_size(b
) - 1; vp
*= vp
; vp
*= 2;
354 float sval
= (float) abs(result
) / vp
;
355 sval
= sval
> 1 ? 1 : sval
;
356 if (result
< 0) sval
= 1 - sval
;
358 rval
+= u
->val_scale
* sval
;
360 rval
= (1 - u
->val_scale
) * rval
+ u
->val_scale
* sval
;
361 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
367 record_local_sequence(struct uct
*u
, struct tree
*t
,
368 struct uct_descent
*descent
, int dlen
, int di
,
369 enum stone seq_color
, float rval
)
371 /* Ignore pass sequences. */
372 if (is_pass(descent
[di
].node
->coord
))
375 #define LTREE_DEBUG if (UDEBUGL(6))
376 LTREE_DEBUG
fprintf(stderr
, "recording result %f in local %s sequence: ",
377 rval
, stone2str(seq_color
));
380 /* Pick the right local tree root... */
381 struct tree_node
*lnode
= seq_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
384 /* ...and record the sequence. */
385 while (di
< dlen
&& (di
== di0
|| descent
[di
].node
->d
< u
->tenuki_d
)) {
386 LTREE_DEBUG
fprintf(stderr
, "%s[%d] ",
387 coord2sstr(descent
[di
].node
->coord
, t
->board
),
388 descent
[di
].node
->d
);
389 lnode
= tree_get_node(t
, lnode
, descent
[di
++].node
->coord
, true);
391 stats_add_result(&lnode
->u
, rval
, 1);
394 /* Add lnode for tenuki (pass) if we descended further. */
396 LTREE_DEBUG
fprintf(stderr
, "pass ");
397 lnode
= tree_get_node(t
, lnode
, pass
, true);
399 stats_add_result(&lnode
->u
, rval
, 1);
402 LTREE_DEBUG
fprintf(stderr
, "\n");
407 uct_playout(struct uct
*u
, struct board
*b
, enum stone player_color
, struct tree
*t
)
412 struct playout_amafmap
*amaf
= NULL
;
413 if (u
->policy
->wants_amaf
) {
414 amaf
= calloc2(1, sizeof(*amaf
));
415 amaf
->map
= calloc2(board_size2(&b2
) + 1, sizeof(*amaf
->map
));
416 amaf
->map
++; // -1 is pass
419 /* Walk the tree until we find a leaf, then expand it and do
420 * a random playout. */
421 struct tree_node
*n
= t
->root
;
422 enum stone node_color
= stone_other(player_color
);
423 assert(node_color
== t
->root_color
);
425 /* Tree descent history. */
426 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
429 struct uct_descent descent
[DLEN
];
430 descent
[0].node
= n
; descent
[0].lnode
= NULL
;
431 descent
[0].significant
[0] = descent
[0].significant
[1] = NULL
;
433 /* Total value of the sequence. */
434 struct move_stats seq_value
= { .playouts
= 0 };
437 int pass_limit
= (board_size(&b2
) - 2) * (board_size(&b2
) - 2) / 2;
438 int passes
= is_pass(b
->last_move
.coord
) && b
->moves
> 0;
442 static char spaces
[] = "\0 ";
445 fprintf(stderr
, "--- UCT walk with color %d\n", player_color
);
447 while (!tree_leaf_node(n
) && passes
< 2) {
448 spaces
[depth
++] = ' '; spaces
[depth
] = 0;
451 /*** Choose a node to descend to: */
453 /* Parity is chosen already according to the child color, since
454 * it is applied to children. */
455 node_color
= stone_other(node_color
);
456 int parity
= (node_color
== player_color
? 1 : -1);
459 descent
[dlen
] = descent
[dlen
- 1];
460 if (u
->local_tree
&& (!descent
[dlen
].lnode
|| descent
[dlen
].node
->d
>= u
->tenuki_d
)) {
461 /* Start new local sequence. */
462 /* Remember that node_color already holds color of the
463 * to-be-found child. */
464 descent
[dlen
].lnode
= node_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
467 if (!u
->random_policy_chance
|| fast_random(u
->random_policy_chance
))
468 u
->policy
->descend(u
->policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
470 u
->random_policy
->descend(u
->random_policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
473 /*** Perform the descent: */
475 if (descent
[dlen
].node
->u
.playouts
>= u
->significant_threshold
) {
476 descent
[dlen
].significant
[node_color
- 1] = n
;
479 seq_value
.playouts
+= descent
[dlen
].value
.playouts
;
480 seq_value
.value
+= descent
[dlen
].value
.value
* descent
[dlen
].value
.playouts
;
481 n
= descent
[dlen
++].node
;
482 assert(n
== t
->root
|| n
->parent
);
484 fprintf(stderr
, "%s+-- UCT sent us to [%s:%d] %f\n",
485 spaces
, coord2sstr(n
->coord
, t
->board
), n
->coord
,
486 tree_node_get_value(t
, parity
, n
->u
.value
));
488 /* Add virtual loss if we need to; this is used to discourage
489 * other threads from visiting this node in case of multiple
490 * threads doing the tree search. */
492 stats_add_result(&n
->u
, tree_parity(t
, parity
) > 0 ? 0 : 1, 1);
494 assert(n
->coord
>= -1);
495 if (amaf
&& !is_pass(n
->coord
))
496 record_amaf_move(amaf
, n
->coord
, node_color
);
498 struct move m
= { n
->coord
, node_color
};
499 int res
= board_play(&b2
, &m
);
501 if (res
< 0 || (!is_pass(m
.coord
) && !group_at(&b2
, m
.coord
)) /* suicide */
502 || b2
.superko_violation
) {
504 for (struct tree_node
*ni
= n
; ni
; ni
= ni
->parent
)
505 fprintf(stderr
, "%s<%"PRIhash
"> ", coord2sstr(ni
->coord
, t
->board
), ni
->hash
);
506 fprintf(stderr
, "marking invalid %s node %d,%d res %d group %d spk %d\n",
507 stone2str(node_color
), coord_x(n
->coord
,b
), coord_y(n
->coord
,b
),
508 res
, group_at(&b2
, m
.coord
), b2
.superko_violation
);
510 n
->hints
|= TREE_HINT_INVALID
;
515 if (is_pass(n
->coord
))
522 amaf
->game_baselen
= amaf
->gamelen
;
523 amaf
->record_nakade
= u
->playout_amaf_nakade
;
526 if (t
->use_extra_komi
&& u
->dynkomi
->persim
) {
527 b2
.komi
+= round(u
->dynkomi
->persim(u
->dynkomi
, &b2
, t
, n
));
531 /* XXX: No dead groups support. */
532 float score
= board_official_score(&b2
, NULL
);
533 /* Result from black's perspective (no matter who
534 * the player; black's perspective is always
535 * what the tree stores. */
536 result
= - (score
* 2);
539 fprintf(stderr
, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
540 player_color
, node_color
, coord2sstr(n
->coord
, t
->board
), result
, score
);
542 board_print(&b2
, stderr
);
544 board_ownermap_fill(&u
->ownermap
, &b2
);
546 } else { // assert(tree_leaf_node(n));
547 /* In case of parallel tree search, the assertion might
548 * not hold if two threads chew on the same node. */
549 result
= uct_leaf_node(u
, &b2
, player_color
, amaf
, &descent
[dlen
- 1], t
, n
, node_color
, spaces
);
552 if (amaf
&& u
->playout_amaf_cutoff
) {
553 unsigned int cutoff
= amaf
->game_baselen
;
554 cutoff
+= (amaf
->gamelen
- amaf
->game_baselen
) * u
->playout_amaf_cutoff
/ 100;
555 /* Now, reconstruct the amaf map. */
556 memset(amaf
->map
, 0, board_size2(&b2
) * sizeof(*amaf
->map
));
557 for (unsigned int i
= 0; i
< cutoff
; i
++) {
558 coord_t coord
= amaf
->game
[i
].coord
;
559 enum stone color
= amaf
->game
[i
].color
;
560 if (amaf
->map
[coord
] == S_NONE
|| amaf
->map
[coord
] == color
) {
561 amaf
->map
[coord
] = color
;
562 /* Nakade always recorded for in-tree part */
563 } else if (amaf
->record_nakade
|| i
<= amaf
->game_baselen
) {
564 amaf_op(amaf
->map
[n
->coord
], +);
569 assert(n
== t
->root
|| n
->parent
);
571 float rval
= scale_value(u
, b
, result
);
572 u
->policy
->update(u
->policy
, t
, n
, node_color
, player_color
, amaf
, rval
);
574 if (t
->use_extra_komi
) {
575 stats_add_result(&u
->dynkomi
->score
, result
/ 2, 1);
576 stats_add_result(&u
->dynkomi
->value
, rval
, 1);
579 if (u
->local_tree
&& n
->parent
&& !is_pass(n
->coord
) && dlen
> 0) {
580 /* Possibly transform the rval appropriately. */
581 float expval
= seq_value
.value
/ seq_value
.playouts
;
582 rval
= stats_temper_value(rval
, expval
, u
->local_tree
);
584 /* Get the local sequences and record them in ltree. */
585 /* We will look for sequence starts in our descent
586 * history, then run record_local_sequence() for each
587 * found sequence start; record_local_sequence() may
588 * pick longer sequences from descent history then,
589 * which is expected as it will create new lnodes. */
590 enum stone seq_color
= player_color
;
591 /* First move always starts a sequence. */
592 record_local_sequence(u
, t
, descent
, dlen
, 1, seq_color
, rval
);
593 seq_color
= stone_other(seq_color
);
594 for (int dseqi
= 2; dseqi
< dlen
; dseqi
++, seq_color
= stone_other(seq_color
)) {
595 if (u
->local_tree_allseq
) {
596 /* We are configured to record all subsequences. */
597 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
600 if (descent
[dseqi
].node
->d
>= u
->tenuki_d
) {
601 /* Tenuki! Record the fresh sequence. */
602 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
605 if (descent
[dseqi
].lnode
&& !descent
[dseqi
].lnode
) {
606 /* Record result for in-descent picked sequence. */
607 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
615 /* We need to undo the virtual loss we added during descend. */
616 if (u
->virtual_loss
) {
617 int parity
= (node_color
== player_color
? 1 : -1);
618 for (; n
->parent
; n
= n
->parent
) {
619 stats_rm_result(&n
->u
, tree_parity(t
, parity
) > 0 ? 0 : 1, 1);
628 board_done_noalloc(&b2
);
633 uct_playouts(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, struct time_info
*ti
)
636 if (ti
->dim
== TD_GAMES
) {
637 for (i
= 0; t
->root
->u
.playouts
<= ti
->len
.games
; i
++)
638 uct_playout(u
, b
, color
, t
);
640 for (i
= 0; !uct_halt
; i
++)
641 uct_playout(u
, b
, color
, t
);