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]);
185 if (u
->treepool_chance
[mode
] > fast_random(100) && upc
->treepool
[color
- 1]) {
186 assert(upc
->treepool_n
[color
- 1] > 0);
187 coord_t treepool_move
= upc
->treepool
[color
- 1][fast_random(upc
->treepool_n
[color
- 1])];
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 fprintf(stderr
, "Treepool pick <%d> %s,%s\n", upc
->treepool_n
[color
- 1], stone2str(color
), coord2sstr(treepool_move
, b
));
196 if (board_is_valid_play(b
, color
, treepool_move
))
197 return treepool_move
;
203 uct_playout_prepolicy(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
)
205 return uct_playout_hook(playout
, setup
, b
, color
, 0);
209 uct_playout_postpolicy(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
)
211 return uct_playout_hook(playout
, setup
, b
, color
, 1);
215 treepool_node_value(struct uct
*u
, struct tree
*tree
, int parity
, struct tree_node
*node
)
217 /* XXX: Playouts get cast to double */
218 switch (u
->treepool_type
) {
219 case UTT_RAVE_PLAYOUTS
:
220 return node
->amaf
.playouts
;
222 return tree_node_get_value(tree
, parity
, node
->amaf
.value
);
223 case UTT_UCT_PLAYOUTS
:
224 return node
->u
.playouts
;
226 return tree_node_get_value(tree
, parity
, node
->u
.value
);
229 struct uct_descent d
= { .node
= node
};
230 assert(u
->policy
->evaluate
);
231 return u
->policy
->evaluate(u
->policy
, tree
, &d
, parity
);
239 treepool_setup(struct uct_playout_callback
*upc
, struct board
*b
, struct tree_node
*node
, int color
)
241 struct uct
*u
= upc
->uct
;
242 int parity
= ((node
->depth
^ upc
->tree
->root
->depth
) & 1) ? -1 : 1;
244 /* XXX: Naive O(N^2) way. */
245 for (int i
= 0; i
< u
->treepool_size
; i
++) {
246 /* For each item, find the highest
247 * node not in the pool yet. */
248 struct tree_node
*best
= NULL
;
249 double best_val
= -1;
251 assert(node
->children
&& is_pass(node
->children
->coord
));
252 for (struct tree_node
*ni
= node
->children
->sibling
; ni
; ni
= ni
->sibling
) {
253 /* Do we already have it? */
255 for (int j
= 0; j
< upc
->treepool_n
[color
]; j
++) {
256 if (upc
->treepool
[color
][j
] == ni
->coord
) {
264 double i_val
= treepool_node_value(u
, upc
->tree
, parity
, ni
);
265 if (i_val
> best_val
) {
272 upc
->treepool
[color
][upc
->treepool_n
[color
]++] = best
->coord
;
278 uct_leaf_node(struct uct
*u
, struct board
*b
, enum stone player_color
,
279 struct playout_amafmap
*amaf
, struct uct_descent
*descent
,
280 struct tree_node
*significant
[2],
281 struct tree
*t
, struct tree_node
*n
, enum stone node_color
,
284 enum stone next_color
= stone_other(node_color
);
285 int parity
= (next_color
== player_color
? 1 : -1);
287 /* We need to make sure only one thread expands the node. If
288 * we are unlucky enough for two threads to meet in the same
289 * node, the latter one will simply do another simulation from
290 * the node itself, no big deal. t->nodes_size may exceed
291 * the maximum in multi-threaded case but not by much so it's ok.
292 * The size test must be before the test&set not after, to allow
293 * expansion of the node later if enough nodes have been freed. */
294 if (n
->u
.playouts
>= u
->expand_p
&& t
->nodes_size
< u
->max_tree_size
295 && !__sync_lock_test_and_set(&n
->is_expanded
, 1)) {
296 tree_expand_node(t
, n
, b
, next_color
, u
, parity
);
299 fprintf(stderr
, "%s*-- UCT playout #%d start [%s] %f\n",
300 spaces
, n
->u
.playouts
, coord2sstr(n
->coord
, t
->board
),
301 tree_node_get_value(t
, parity
, n
->u
.value
));
303 struct uct_playout_callback upc
= {
306 /* TODO: Don't necessarily restart the sequence walk when
307 * entering playout. */
311 if (u
->local_tree_playout
) {
312 /* N.B.: We know this is ELO playout. */
313 playout_elo_callback(u
->playout
, uct_playout_probdist
, &upc
);
316 coord_t pool
[2][u
->treepool_size
];
317 if (u
->treepool_chance
[0] + u
->treepool_chance
[1] > 0) {
318 for (int color
= 0; color
< 2; color
++) {
319 /* Prepare tree-based pool of moves to try forcing
320 * during the playout. */
321 /* We consider the children of the last significant
322 * node, picking top N choices. */
323 struct tree_node
*n
= significant
[color
];
324 if (!n
|| !n
->children
|| !n
->children
->sibling
) {
325 /* No significant node, or it's childless or has
326 * only pass as its child. */
327 upc
.treepool
[color
] = NULL
;
328 upc
.treepool_n
[color
] = 0;
330 upc
.treepool
[color
] = (coord_t
*) &pool
[color
];
331 treepool_setup(&upc
, b
, n
, color
);
336 struct playout_setup ps
= {
337 .gamelen
= u
->gamelen
,
338 .mercymin
= u
->mercymin
,
339 .prepolicy_hook
= uct_playout_prepolicy
,
340 .postpolicy_hook
= uct_playout_postpolicy
,
343 int result
= play_random_game(&ps
, b
, next_color
,
344 u
->playout_amaf
? amaf
: NULL
,
345 &u
->ownermap
, u
->playout
);
346 if (next_color
== S_WHITE
) {
347 /* We need the result from black's perspective. */
351 fprintf(stderr
, "%s -- [%d..%d] %s random playout result %d\n",
352 spaces
, player_color
, next_color
, coord2sstr(n
->coord
, t
->board
), result
);
358 scale_value(struct uct
*u
, struct board
*b
, int result
)
360 float rval
= result
> 0;
362 int vp
= u
->val_points
;
364 vp
= board_size(b
) - 1; vp
*= vp
; vp
*= 2;
367 float sval
= (float) abs(result
) / vp
;
368 sval
= sval
> 1 ? 1 : sval
;
369 if (result
< 0) sval
= 1 - sval
;
371 rval
+= u
->val_scale
* sval
;
373 rval
= (1 - u
->val_scale
) * rval
+ u
->val_scale
* sval
;
374 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
380 record_local_sequence(struct uct
*u
, struct tree
*t
,
381 struct uct_descent
*descent
, int dlen
, int di
,
382 enum stone seq_color
, float rval
)
384 /* Ignore pass sequences. */
385 if (is_pass(descent
[di
].node
->coord
))
388 #define LTREE_DEBUG if (UDEBUGL(6))
389 LTREE_DEBUG
fprintf(stderr
, "recording result %f in local %s sequence: ",
390 rval
, stone2str(seq_color
));
393 /* Pick the right local tree root... */
394 struct tree_node
*lnode
= seq_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
397 /* ...and record the sequence. */
398 while (di
< dlen
&& (di
== di0
|| descent
[di
].node
->d
< u
->tenuki_d
)) {
399 LTREE_DEBUG
fprintf(stderr
, "%s[%d] ",
400 coord2sstr(descent
[di
].node
->coord
, t
->board
),
401 descent
[di
].node
->d
);
402 lnode
= tree_get_node(t
, lnode
, descent
[di
++].node
->coord
, true);
404 stats_add_result(&lnode
->u
, rval
, 1);
407 /* Add lnode for tenuki (pass) if we descended further. */
409 LTREE_DEBUG
fprintf(stderr
, "pass ");
410 lnode
= tree_get_node(t
, lnode
, pass
, true);
412 stats_add_result(&lnode
->u
, rval
, 1);
415 LTREE_DEBUG
fprintf(stderr
, "\n");
420 uct_playout(struct uct
*u
, struct board
*b
, enum stone player_color
, struct tree
*t
)
425 struct playout_amafmap
*amaf
= NULL
;
426 if (u
->policy
->wants_amaf
) {
427 amaf
= calloc2(1, sizeof(*amaf
));
428 amaf
->map
= calloc2(board_size2(&b2
) + 1, sizeof(*amaf
->map
));
429 amaf
->map
++; // -1 is pass
432 /* Walk the tree until we find a leaf, then expand it and do
433 * a random playout. */
434 struct tree_node
*n
= t
->root
;
435 enum stone node_color
= stone_other(player_color
);
436 assert(node_color
== t
->root_color
);
438 /* Tree descent history. */
439 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
442 struct uct_descent descent
[DLEN
];
443 descent
[0].node
= n
; descent
[0].lnode
= NULL
;
445 /* Total value of the sequence. */
446 struct move_stats seq_value
= { .playouts
= 0 };
447 /* The last "significant" node along the descent (i.e. node
448 * with higher than configured number of playouts). For black
450 struct tree_node
*significant
[2] = { NULL
, NULL
};
451 if (n
->u
.playouts
>= u
->significant_threshold
)
452 significant
[node_color
- 1] = n
;
455 int pass_limit
= (board_size(&b2
) - 2) * (board_size(&b2
) - 2) / 2;
456 int passes
= is_pass(b
->last_move
.coord
) && b
->moves
> 0;
460 static char spaces
[] = "\0 ";
463 fprintf(stderr
, "--- UCT walk with color %d\n", player_color
);
465 while (!tree_leaf_node(n
) && passes
< 2) {
466 spaces
[depth
++] = ' '; spaces
[depth
] = 0;
469 /*** Choose a node to descend to: */
471 /* Parity is chosen already according to the child color, since
472 * it is applied to children. */
473 node_color
= stone_other(node_color
);
474 int parity
= (node_color
== player_color
? 1 : -1);
477 descent
[dlen
] = descent
[dlen
- 1];
478 if (u
->local_tree
&& (!descent
[dlen
].lnode
|| descent
[dlen
].node
->d
>= u
->tenuki_d
)) {
479 /* Start new local sequence. */
480 /* Remember that node_color already holds color of the
481 * to-be-found child. */
482 descent
[dlen
].lnode
= node_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
485 if (!u
->random_policy_chance
|| fast_random(u
->random_policy_chance
))
486 u
->policy
->descend(u
->policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
488 u
->random_policy
->descend(u
->random_policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
491 /*** Perform the descent: */
493 if (descent
[dlen
].node
->u
.playouts
>= u
->significant_threshold
) {
494 significant
[node_color
- 1] = descent
[dlen
].node
;
497 seq_value
.playouts
+= descent
[dlen
].value
.playouts
;
498 seq_value
.value
+= descent
[dlen
].value
.value
* descent
[dlen
].value
.playouts
;
499 n
= descent
[dlen
++].node
;
500 assert(n
== t
->root
|| n
->parent
);
502 fprintf(stderr
, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
503 spaces
, coord2sstr(n
->coord
, t
->board
),
504 n
->coord
, n
->u
.playouts
,
505 tree_node_get_value(t
, parity
, n
->u
.value
));
507 /* Add virtual loss if we need to; this is used to discourage
508 * other threads from visiting this node in case of multiple
509 * threads doing the tree search. */
511 stats_add_result(&n
->u
, tree_parity(t
, parity
) > 0 ? 0 : 1, 1);
513 assert(n
->coord
>= -1);
514 if (amaf
&& !is_pass(n
->coord
))
515 record_amaf_move(amaf
, n
->coord
, node_color
);
517 struct move m
= { n
->coord
, node_color
};
518 int res
= board_play(&b2
, &m
);
520 if (res
< 0 || (!is_pass(m
.coord
) && !group_at(&b2
, m
.coord
)) /* suicide */
521 || b2
.superko_violation
) {
523 for (struct tree_node
*ni
= n
; ni
; ni
= ni
->parent
)
524 fprintf(stderr
, "%s<%"PRIhash
"> ", coord2sstr(ni
->coord
, t
->board
), ni
->hash
);
525 fprintf(stderr
, "marking invalid %s node %d,%d res %d group %d spk %d\n",
526 stone2str(node_color
), coord_x(n
->coord
,b
), coord_y(n
->coord
,b
),
527 res
, group_at(&b2
, m
.coord
), b2
.superko_violation
);
529 n
->hints
|= TREE_HINT_INVALID
;
534 if (is_pass(n
->coord
))
541 amaf
->game_baselen
= amaf
->gamelen
;
542 amaf
->record_nakade
= u
->playout_amaf_nakade
;
545 if (t
->use_extra_komi
&& u
->dynkomi
->persim
) {
546 b2
.komi
+= round(u
->dynkomi
->persim(u
->dynkomi
, &b2
, t
, n
));
550 /* XXX: No dead groups support. */
551 float score
= board_official_score(&b2
, NULL
);
552 /* Result from black's perspective (no matter who
553 * the player; black's perspective is always
554 * what the tree stores. */
555 result
= - (score
* 2);
558 fprintf(stderr
, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
559 player_color
, node_color
, coord2sstr(n
->coord
, t
->board
), result
, score
);
561 board_print(&b2
, stderr
);
563 board_ownermap_fill(&u
->ownermap
, &b2
);
565 } else { // assert(tree_leaf_node(n));
566 /* In case of parallel tree search, the assertion might
567 * not hold if two threads chew on the same node. */
568 result
= uct_leaf_node(u
, &b2
, player_color
, amaf
, &descent
[dlen
- 1], significant
, t
, n
, node_color
, spaces
);
571 if (amaf
&& u
->playout_amaf_cutoff
) {
572 unsigned int cutoff
= amaf
->game_baselen
;
573 cutoff
+= (amaf
->gamelen
- amaf
->game_baselen
) * u
->playout_amaf_cutoff
/ 100;
574 /* Now, reconstruct the amaf map. */
575 memset(amaf
->map
, 0, board_size2(&b2
) * sizeof(*amaf
->map
));
576 for (unsigned int i
= 0; i
< cutoff
; i
++) {
577 coord_t coord
= amaf
->game
[i
].coord
;
578 enum stone color
= amaf
->game
[i
].color
;
579 if (amaf
->map
[coord
] == S_NONE
|| amaf
->map
[coord
] == color
) {
580 amaf
->map
[coord
] = color
;
581 /* Nakade always recorded for in-tree part */
582 } else if (amaf
->record_nakade
|| i
<= amaf
->game_baselen
) {
583 amaf_op(amaf
->map
[n
->coord
], +);
588 assert(n
== t
->root
|| n
->parent
);
590 float rval
= scale_value(u
, b
, result
);
591 u
->policy
->update(u
->policy
, t
, n
, node_color
, player_color
, amaf
, rval
);
593 if (t
->use_extra_komi
) {
594 stats_add_result(&u
->dynkomi
->score
, result
/ 2, 1);
595 stats_add_result(&u
->dynkomi
->value
, rval
, 1);
598 if (u
->local_tree
&& n
->parent
&& !is_pass(n
->coord
) && dlen
> 0) {
599 /* Possibly transform the rval appropriately. */
600 float expval
= seq_value
.value
/ seq_value
.playouts
;
601 rval
= stats_temper_value(rval
, expval
, u
->local_tree
);
603 /* Get the local sequences and record them in ltree. */
604 /* We will look for sequence starts in our descent
605 * history, then run record_local_sequence() for each
606 * found sequence start; record_local_sequence() may
607 * pick longer sequences from descent history then,
608 * which is expected as it will create new lnodes. */
609 enum stone seq_color
= player_color
;
610 /* First move always starts a sequence. */
611 record_local_sequence(u
, t
, descent
, dlen
, 1, seq_color
, rval
);
612 seq_color
= stone_other(seq_color
);
613 for (int dseqi
= 2; dseqi
< dlen
; dseqi
++, seq_color
= stone_other(seq_color
)) {
614 if (u
->local_tree_allseq
) {
615 /* We are configured to record all subsequences. */
616 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
619 if (descent
[dseqi
].node
->d
>= u
->tenuki_d
) {
620 /* Tenuki! Record the fresh sequence. */
621 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
624 if (descent
[dseqi
].lnode
&& !descent
[dseqi
].lnode
) {
625 /* Record result for in-descent picked sequence. */
626 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
634 /* We need to undo the virtual loss we added during descend. */
635 if (u
->virtual_loss
) {
636 int parity
= (node_color
== player_color
? 1 : -1);
637 for (; n
->parent
; n
= n
->parent
) {
638 stats_rm_result(&n
->u
, tree_parity(t
, parity
) > 0 ? 0 : 1, 1);
647 board_done_noalloc(&b2
);
652 uct_playouts(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, struct time_info
*ti
)
655 if (ti
&& ti
->dim
== TD_GAMES
) {
656 for (i
= 0; t
->root
->u
.playouts
<= ti
->len
.games
; i
++)
657 uct_playout(u
, b
, color
, t
);
659 for (i
= 0; !uct_halt
; i
++)
660 uct_playout(u
, b
, color
, t
);