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
;
183 if (u
->treepool_chance
[mode
] > fast_random(100) && upc
->treepool
[color
- 1]) {
184 assert(upc
->treepool_n
[color
- 1] > 0);
185 coord_t treepool_move
= upc
->treepool
[color
- 1][fast_random(upc
->treepool_n
[color
- 1])];
186 if (board_is_valid_play(b
, color
, treepool_move
))
187 return treepool_move
;
193 uct_playout_prepolicy(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
)
195 return uct_playout_hook(playout
, setup
, b
, color
, 0);
199 uct_playout_postpolicy(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
)
201 return uct_playout_hook(playout
, setup
, b
, color
, 1);
205 treepool_node_value(struct uct
*u
, struct tree
*tree
, int parity
, struct tree_node
*node
)
207 /* XXX: Playouts get cast to double */
208 switch (u
->treepool_type
) {
209 case UTT_RAVE_PLAYOUTS
:
210 return node
->amaf
.playouts
;
212 return tree_node_get_value(tree
, parity
, node
->amaf
.value
);
213 case UTT_UCT_PLAYOUTS
:
214 return node
->u
.playouts
;
216 return tree_node_get_value(tree
, parity
, node
->u
.value
);
219 struct uct_descent d
= { .node
= node
};
220 assert(u
->policy
->evaluate
);
221 return u
->policy
->evaluate(u
->policy
, tree
, &d
, parity
);
229 treepool_setup(struct uct_playout_callback
*upc
, struct tree_node
*node
, int color
)
231 struct uct
*u
= upc
->uct
;
232 int parity
= ((node
->depth
^ upc
->tree
->root
->depth
) & 1) ? -1 : 1;
234 /* XXX: Naive O(N^2) way. */
235 for (int i
= 0; i
< u
->treepool_size
; i
++) {
236 /* For each item, find the highest
237 * node not in the pool yet. */
238 struct tree_node
*best
= NULL
;
239 double best_val
= -1;
241 // first comes pass which we skip
242 for (struct tree_node
*ni
= node
->children
->sibling
; ni
; ni
= ni
->sibling
) {
243 /* Do we already have it? */
245 for (int j
= 0; j
< upc
->treepool_n
[color
]; j
++)
246 if (upc
->treepool
[color
][j
] == ni
->coord
) {
253 double i_val
= treepool_node_value(u
, upc
->tree
, parity
, ni
);
254 if (i_val
> best_val
) {
261 upc
->treepool
[color
][upc
->treepool_n
[color
]++] = best
->coord
;
267 uct_leaf_node(struct uct
*u
, struct board
*b
, enum stone player_color
,
268 struct playout_amafmap
*amaf
, struct uct_descent
*descent
,
269 struct tree
*t
, struct tree_node
*n
, enum stone node_color
,
272 enum stone next_color
= stone_other(node_color
);
273 int parity
= (next_color
== player_color
? 1 : -1);
275 /* We need to make sure only one thread expands the node. If
276 * we are unlucky enough for two threads to meet in the same
277 * node, the latter one will simply do another simulation from
278 * the node itself, no big deal. t->nodes_size may exceed
279 * the maximum in multi-threaded case but not by much so it's ok.
280 * The size test must be before the test&set not after, to allow
281 * expansion of the node later if enough nodes have been freed. */
282 if (n
->u
.playouts
>= u
->expand_p
&& t
->nodes_size
< u
->max_tree_size
283 && !__sync_lock_test_and_set(&n
->is_expanded
, 1)) {
284 tree_expand_node(t
, n
, b
, next_color
, u
, parity
);
287 fprintf(stderr
, "%s*-- UCT playout #%d start [%s] %f\n",
288 spaces
, n
->u
.playouts
, coord2sstr(n
->coord
, t
->board
),
289 tree_node_get_value(t
, parity
, n
->u
.value
));
291 struct uct_playout_callback upc
= {
294 /* TODO: Don't necessarily restart the sequence walk when
295 * entering playout. */
299 if (u
->local_tree_playout
) {
300 /* N.B.: We know this is ELO playout. */
301 playout_elo_callback(u
->playout
, uct_playout_probdist
, &upc
);
304 coord_t pool
[2][u
->treepool_size
];
305 if (u
->treepool_chance
[0] + u
->treepool_chance
[1] > 0) {
306 for (int color
= 0; color
< 2; color
++) {
307 /* Prepare tree-based pool of moves to try forcing
308 * during the playout. */
309 /* We consider the children of the last significant
310 * node, picking top N choices. */
311 struct tree_node
*n
= descent
->significant
[color
];
312 if (!n
|| !n
->children
|| !n
->children
->sibling
) {
313 /* No significant node, or it's childless or has
314 * only pass as its child. */
315 upc
.treepool
[color
] = NULL
;
316 upc
.treepool_n
[color
] = 0;
318 upc
.treepool
[color
] = (coord_t
*) &pool
[color
];
319 treepool_setup(&upc
, n
, color
);
324 struct playout_setup ps
= {
325 .gamelen
= u
->gamelen
,
326 .mercymin
= u
->mercymin
,
327 .prepolicy_hook
= uct_playout_prepolicy
,
328 .postpolicy_hook
= uct_playout_postpolicy
,
331 int result
= play_random_game(&ps
, b
, next_color
,
332 u
->playout_amaf
? amaf
: NULL
,
333 &u
->ownermap
, u
->playout
);
334 if (next_color
== S_WHITE
) {
335 /* We need the result from black's perspective. */
339 fprintf(stderr
, "%s -- [%d..%d] %s random playout result %d\n",
340 spaces
, player_color
, next_color
, coord2sstr(n
->coord
, t
->board
), result
);
346 scale_value(struct uct
*u
, struct board
*b
, int result
)
348 float rval
= result
> 0;
350 int vp
= u
->val_points
;
352 vp
= board_size(b
) - 1; vp
*= vp
; vp
*= 2;
355 float sval
= (float) abs(result
) / vp
;
356 sval
= sval
> 1 ? 1 : sval
;
357 if (result
< 0) sval
= 1 - sval
;
359 rval
+= u
->val_scale
* sval
;
361 rval
= (1 - u
->val_scale
) * rval
+ u
->val_scale
* sval
;
362 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
368 record_local_sequence(struct uct
*u
, struct tree
*t
,
369 struct uct_descent
*descent
, int dlen
, int di
,
370 enum stone seq_color
, float rval
)
372 /* Ignore pass sequences. */
373 if (is_pass(descent
[di
].node
->coord
))
376 #define LTREE_DEBUG if (UDEBUGL(6))
377 LTREE_DEBUG
fprintf(stderr
, "recording result %f in local %s sequence: ",
378 rval
, stone2str(seq_color
));
381 /* Pick the right local tree root... */
382 struct tree_node
*lnode
= seq_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
385 /* ...and record the sequence. */
386 while (di
< dlen
&& (di
== di0
|| descent
[di
].node
->d
< u
->tenuki_d
)) {
387 LTREE_DEBUG
fprintf(stderr
, "%s[%d] ",
388 coord2sstr(descent
[di
].node
->coord
, t
->board
),
389 descent
[di
].node
->d
);
390 lnode
= tree_get_node(t
, lnode
, descent
[di
++].node
->coord
, true);
392 stats_add_result(&lnode
->u
, rval
, 1);
395 /* Add lnode for tenuki (pass) if we descended further. */
397 LTREE_DEBUG
fprintf(stderr
, "pass ");
398 lnode
= tree_get_node(t
, lnode
, pass
, true);
400 stats_add_result(&lnode
->u
, rval
, 1);
403 LTREE_DEBUG
fprintf(stderr
, "\n");
408 uct_playout(struct uct
*u
, struct board
*b
, enum stone player_color
, struct tree
*t
)
413 struct playout_amafmap
*amaf
= NULL
;
414 if (u
->policy
->wants_amaf
) {
415 amaf
= calloc2(1, sizeof(*amaf
));
416 amaf
->map
= calloc2(board_size2(&b2
) + 1, sizeof(*amaf
->map
));
417 amaf
->map
++; // -1 is pass
420 /* Walk the tree until we find a leaf, then expand it and do
421 * a random playout. */
422 struct tree_node
*n
= t
->root
;
423 enum stone node_color
= stone_other(player_color
);
424 assert(node_color
== t
->root_color
);
426 /* Tree descent history. */
427 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
430 struct uct_descent descent
[DLEN
];
431 descent
[0].node
= n
; descent
[0].lnode
= NULL
;
432 descent
[0].significant
[0] = descent
[0].significant
[1] = NULL
;
434 /* Total value of the sequence. */
435 struct move_stats seq_value
= { .playouts
= 0 };
438 int pass_limit
= (board_size(&b2
) - 2) * (board_size(&b2
) - 2) / 2;
439 int passes
= is_pass(b
->last_move
.coord
) && b
->moves
> 0;
443 static char spaces
[] = "\0 ";
446 fprintf(stderr
, "--- UCT walk with color %d\n", player_color
);
448 while (!tree_leaf_node(n
) && passes
< 2) {
449 spaces
[depth
++] = ' '; spaces
[depth
] = 0;
452 /*** Choose a node to descend to: */
454 /* Parity is chosen already according to the child color, since
455 * it is applied to children. */
456 node_color
= stone_other(node_color
);
457 int parity
= (node_color
== player_color
? 1 : -1);
460 descent
[dlen
] = descent
[dlen
- 1];
461 if (u
->local_tree
&& (!descent
[dlen
].lnode
|| descent
[dlen
].node
->d
>= u
->tenuki_d
)) {
462 /* Start new local sequence. */
463 /* Remember that node_color already holds color of the
464 * to-be-found child. */
465 descent
[dlen
].lnode
= node_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
468 if (!u
->random_policy_chance
|| fast_random(u
->random_policy_chance
))
469 u
->policy
->descend(u
->policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
471 u
->random_policy
->descend(u
->random_policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
474 /*** Perform the descent: */
476 if (descent
[dlen
].node
->u
.playouts
>= u
->significant_threshold
) {
477 descent
[dlen
].significant
[node_color
- 1] = n
;
480 seq_value
.playouts
+= descent
[dlen
].value
.playouts
;
481 seq_value
.value
+= descent
[dlen
].value
.value
* descent
[dlen
].value
.playouts
;
482 n
= descent
[dlen
++].node
;
483 assert(n
== t
->root
|| n
->parent
);
485 fprintf(stderr
, "%s+-- UCT sent us to [%s:%d] %f\n",
486 spaces
, coord2sstr(n
->coord
, t
->board
), n
->coord
,
487 tree_node_get_value(t
, parity
, n
->u
.value
));
489 /* Add virtual loss if we need to; this is used to discourage
490 * other threads from visiting this node in case of multiple
491 * threads doing the tree search. */
493 stats_add_result(&n
->u
, tree_parity(t
, parity
) > 0 ? 0 : 1, 1);
495 assert(n
->coord
>= -1);
496 if (amaf
&& !is_pass(n
->coord
))
497 record_amaf_move(amaf
, n
->coord
, node_color
);
499 struct move m
= { n
->coord
, node_color
};
500 int res
= board_play(&b2
, &m
);
502 if (res
< 0 || (!is_pass(m
.coord
) && !group_at(&b2
, m
.coord
)) /* suicide */
503 || b2
.superko_violation
) {
505 for (struct tree_node
*ni
= n
; ni
; ni
= ni
->parent
)
506 fprintf(stderr
, "%s<%"PRIhash
"> ", coord2sstr(ni
->coord
, t
->board
), ni
->hash
);
507 fprintf(stderr
, "marking invalid %s node %d,%d res %d group %d spk %d\n",
508 stone2str(node_color
), coord_x(n
->coord
,b
), coord_y(n
->coord
,b
),
509 res
, group_at(&b2
, m
.coord
), b2
.superko_violation
);
511 n
->hints
|= TREE_HINT_INVALID
;
516 if (is_pass(n
->coord
))
523 amaf
->game_baselen
= amaf
->gamelen
;
524 amaf
->record_nakade
= u
->playout_amaf_nakade
;
527 if (t
->use_extra_komi
&& u
->dynkomi
->persim
) {
528 b2
.komi
+= round(u
->dynkomi
->persim(u
->dynkomi
, &b2
, t
, n
));
532 /* XXX: No dead groups support. */
533 float score
= board_official_score(&b2
, NULL
);
534 /* Result from black's perspective (no matter who
535 * the player; black's perspective is always
536 * what the tree stores. */
537 result
= - (score
* 2);
540 fprintf(stderr
, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
541 player_color
, node_color
, coord2sstr(n
->coord
, t
->board
), result
, score
);
543 board_print(&b2
, stderr
);
545 board_ownermap_fill(&u
->ownermap
, &b2
);
547 } else { // assert(tree_leaf_node(n));
548 /* In case of parallel tree search, the assertion might
549 * not hold if two threads chew on the same node. */
550 result
= uct_leaf_node(u
, &b2
, player_color
, amaf
, &descent
[dlen
- 1], t
, n
, node_color
, spaces
);
553 if (amaf
&& u
->playout_amaf_cutoff
) {
554 unsigned int cutoff
= amaf
->game_baselen
;
555 cutoff
+= (amaf
->gamelen
- amaf
->game_baselen
) * u
->playout_amaf_cutoff
/ 100;
556 /* Now, reconstruct the amaf map. */
557 memset(amaf
->map
, 0, board_size2(&b2
) * sizeof(*amaf
->map
));
558 for (unsigned int i
= 0; i
< cutoff
; i
++) {
559 coord_t coord
= amaf
->game
[i
].coord
;
560 enum stone color
= amaf
->game
[i
].color
;
561 if (amaf
->map
[coord
] == S_NONE
|| amaf
->map
[coord
] == color
) {
562 amaf
->map
[coord
] = color
;
563 /* Nakade always recorded for in-tree part */
564 } else if (amaf
->record_nakade
|| i
<= amaf
->game_baselen
) {
565 amaf_op(amaf
->map
[n
->coord
], +);
570 assert(n
== t
->root
|| n
->parent
);
572 float rval
= scale_value(u
, b
, result
);
573 u
->policy
->update(u
->policy
, t
, n
, node_color
, player_color
, amaf
, rval
);
575 if (t
->use_extra_komi
) {
576 stats_add_result(&u
->dynkomi
->score
, result
/ 2, 1);
577 stats_add_result(&u
->dynkomi
->value
, rval
, 1);
580 if (u
->local_tree
&& n
->parent
&& !is_pass(n
->coord
) && dlen
> 0) {
581 /* Possibly transform the rval appropriately. */
582 float expval
= seq_value
.value
/ seq_value
.playouts
;
583 rval
= stats_temper_value(rval
, expval
, u
->local_tree
);
585 /* Get the local sequences and record them in ltree. */
586 /* We will look for sequence starts in our descent
587 * history, then run record_local_sequence() for each
588 * found sequence start; record_local_sequence() may
589 * pick longer sequences from descent history then,
590 * which is expected as it will create new lnodes. */
591 enum stone seq_color
= player_color
;
592 /* First move always starts a sequence. */
593 record_local_sequence(u
, t
, descent
, dlen
, 1, seq_color
, rval
);
594 seq_color
= stone_other(seq_color
);
595 for (int dseqi
= 2; dseqi
< dlen
; dseqi
++, seq_color
= stone_other(seq_color
)) {
596 if (u
->local_tree_allseq
) {
597 /* We are configured to record all subsequences. */
598 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
601 if (descent
[dseqi
].node
->d
>= u
->tenuki_d
) {
602 /* Tenuki! Record the fresh sequence. */
603 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
606 if (descent
[dseqi
].lnode
&& !descent
[dseqi
].lnode
) {
607 /* Record result for in-descent picked sequence. */
608 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
616 /* We need to undo the virtual loss we added during descend. */
617 if (u
->virtual_loss
) {
618 int parity
= (node_color
== player_color
? 1 : -1);
619 for (; n
->parent
; n
= n
->parent
) {
620 stats_rm_result(&n
->u
, tree_parity(t
, parity
) > 0 ? 0 : 1, 1);
629 board_done_noalloc(&b2
);
634 uct_playouts(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, struct time_info
*ti
)
637 if (ti
&& ti
->dim
== TD_GAMES
) {
638 for (i
= 0; t
->root
->u
.playouts
<= ti
->len
.games
; i
++)
639 uct_playout(u
, b
, color
, t
);
641 for (i
= 0; !uct_halt
; i
++)
642 uct_playout(u
, b
, color
, t
);