14 #include "playout/elo.h"
17 #include "uct/dynkomi.h"
18 #include "uct/internal.h"
19 #include "uct/search.h"
25 uct_progress_status(struct uct
*u
, struct tree
*t
, enum stone color
, int playouts
)
31 struct tree_node
*best
= u
->policy
->choose(u
->policy
, t
->root
, t
->board
, color
, resign
);
33 fprintf(stderr
, "... No moves left\n");
36 fprintf(stderr
, "[%d] ", playouts
);
37 fprintf(stderr
, "best %f ", tree_node_get_value(t
, 1, best
->u
.value
));
40 if (t
->use_extra_komi
)
41 fprintf(stderr
, "komi %.1f ", t
->extra_komi
);
44 fprintf(stderr
, "deepest % 2d ", t
->max_depth
- t
->root
->depth
);
47 fprintf(stderr
, "| seq ");
48 for (int depth
= 0; depth
< 6; depth
++) {
49 if (best
&& best
->u
.playouts
>= 25) {
50 fprintf(stderr
, "%3s ", coord2sstr(best
->coord
, t
->board
));
51 best
= u
->policy
->choose(u
->policy
, best
, t
->board
, color
, resign
);
58 fprintf(stderr
, "| can ");
60 struct tree_node
*can
[cans
];
61 memset(can
, 0, sizeof(can
));
62 best
= t
->root
->children
;
65 while ((!can
[c
] || best
->u
.playouts
> can
[c
]->u
.playouts
) && ++c
< cans
);
66 for (int d
= 0; d
< c
; d
++) can
[d
] = can
[d
+ 1];
67 if (c
> 0) can
[c
- 1] = best
;
72 fprintf(stderr
, "%3s(%.3f) ",
73 coord2sstr(can
[cans
]->coord
, t
->board
),
74 tree_node_get_value(t
, 1, can
[cans
]->u
.value
));
80 fprintf(stderr
, "\n");
84 struct uct_playout_callback
{
87 struct tree_node
*lnode
;
91 uct_playout_probdist(void *data
, struct board
*b
, enum stone to_play
, struct probdist
*pd
)
93 /* Create probability distribution according to found local tree
95 struct uct_playout_callback
*upc
= data
;
96 assert(upc
&& upc
->tree
&& pd
&& b
);
97 coord_t c
= b
->last_move
.coord
;
98 enum stone color
= b
->last_move
.color
;
101 /* Break local sequence. */
103 } else if (upc
->lnode
) {
104 /* Try to follow local sequence. */
105 upc
->lnode
= tree_get_node(upc
->tree
, upc
->lnode
, c
, false);
108 if (!upc
->lnode
|| !upc
->lnode
->children
) {
109 /* There's no local sequence, start new one! */
110 upc
->lnode
= color
== S_BLACK
? upc
->tree
->ltree_black
: upc
->tree
->ltree_white
;
111 upc
->lnode
= tree_get_node(upc
->tree
, upc
->lnode
, c
, false);
114 if (!upc
->lnode
|| !upc
->lnode
->children
) {
115 /* We have no local sequence and we cannot find any starting
116 * by node corresponding to last move. */
117 if (!upc
->uct
->local_tree_pseqroot
) {
118 /* Give up then, we have nothing to contribute. */
121 /* Construct probability distribution from possible first
122 * sequence move. Remember that @color is color of the
124 upc
->lnode
= color
== S_BLACK
? upc
->tree
->ltree_white
: upc
->tree
->ltree_black
;
125 if (!upc
->lnode
->children
) {
126 /* We don't even have anything in our tree yet. */
131 /* The probdist has the right structure only if BOARD_GAMMA is defined. */
136 /* Construct probability distribution from lnode children. */
137 /* XXX: How to derive the appropriate gamma? */
138 #define li_value(color, li) (li->u.playouts * (color == S_BLACK ? li->u.value : (1 - li->u.value)))
139 #define li_gamma(color, li) (0.5 + li_value(color, li))
140 struct tree_node
*li
= upc
->lnode
->children
;
142 if (is_pass(li
->coord
)) {
144 /* TODO: Spread tenuki gamma over all moves we don't touch. */
147 for (; li
; li
= li
->sibling
) {
148 if (board_at(b
, li
->coord
) != S_NONE
)
150 probdist_set(pd
, li
->coord
, pd
->items
[li
->coord
] * li_gamma(to_play
, li
));
156 uct_leaf_node(struct uct
*u
, struct board
*b
, enum stone player_color
,
157 struct playout_amafmap
*amaf
,
158 struct tree
*t
, struct tree_node
*n
, enum stone node_color
,
161 enum stone next_color
= stone_other(node_color
);
162 int parity
= (next_color
== player_color
? 1 : -1);
164 /* If we don't anticipate well the opponent move during pondering
165 * (the played move has few playouts) we still need more memory
166 * during genmove to explore the tree actually played.
167 * For fast_alloc, the tree compaction will free enough memory
169 unsigned long max_tree_size
= u
->max_tree_size
;
170 if (u
->pondering
&& !u
->fast_alloc
)
171 max_tree_size
= (max_tree_size
* (100 - MIN_FREE_MEM_PERCENT
)) / 100;
173 /* We need to make sure only one thread expands the node. If
174 * we are unlucky enough for two threads to meet in the same
175 * node, the latter one will simply do another simulation from
176 * the node itself, no big deal. t->nodes_size may exceed
177 * the maximum in multi-threaded case but not by much so it's ok.
178 * The size test must be before the test&set not after, to allow
179 * expansion of the node later if enough nodes have been freed. */
180 if (n
->u
.playouts
>= u
->expand_p
&& t
->nodes_size
< max_tree_size
181 && !__sync_lock_test_and_set(&n
->is_expanded
, 1)) {
182 tree_expand_node(t
, n
, b
, next_color
, u
, parity
);
185 fprintf(stderr
, "%s*-- UCT playout #%d start [%s] %f\n",
186 spaces
, n
->u
.playouts
, coord2sstr(n
->coord
, t
->board
),
187 tree_node_get_value(t
, parity
, n
->u
.value
));
189 /* TODO: Don't necessarily restart the sequence walk when entering
191 struct uct_playout_callback upc
= { .uct
= u
, .tree
= t
, .lnode
= NULL
};
192 if (u
->local_tree_playout
) {
193 /* N.B.: We know this is ELO playout. */
194 playout_elo_callback(u
->playout
, uct_playout_probdist
, &upc
);
197 struct playout_setup ps
= { .gamelen
= u
->gamelen
, .mercymin
= u
->mercymin
};
198 int result
= play_random_game(&ps
, b
, next_color
,
199 u
->playout_amaf
? amaf
: NULL
,
200 &u
->ownermap
, u
->playout
);
201 if (next_color
== S_WHITE
) {
202 /* We need the result from black's perspective. */
206 fprintf(stderr
, "%s -- [%d..%d] %s random playout result %d\n",
207 spaces
, player_color
, next_color
, coord2sstr(n
->coord
, t
->board
), result
);
213 scale_value(struct uct
*u
, struct board
*b
, int result
)
215 float rval
= result
> 0;
217 int vp
= u
->val_points
;
219 vp
= board_size(b
) - 1; vp
*= vp
; vp
*= 2;
222 float sval
= (float) abs(result
) / vp
;
223 sval
= sval
> 1 ? 1 : sval
;
224 if (result
< 0) sval
= 1 - sval
;
226 rval
+= u
->val_scale
* sval
;
228 rval
= (1 - u
->val_scale
) * rval
+ u
->val_scale
* sval
;
229 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
235 record_local_sequence(struct uct
*u
, struct tree
*t
,
236 struct uct_descent
*descent
, int dlen
, int di
,
237 enum stone seq_color
, float rval
)
239 /* Ignore pass sequences. */
240 if (is_pass(descent
[di
].node
->coord
))
243 #define LTREE_DEBUG if (UDEBUGL(6))
244 LTREE_DEBUG
fprintf(stderr
, "recording result %f in local %s sequence: ",
245 rval
, stone2str(seq_color
));
248 /* Pick the right local tree root... */
249 struct tree_node
*lnode
= seq_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
252 /* ...and record the sequence. */
253 while (di
< dlen
&& (di
== di0
|| descent
[di
].node
->d
< u
->tenuki_d
)) {
254 LTREE_DEBUG
fprintf(stderr
, "%s[%d] ",
255 coord2sstr(descent
[di
].node
->coord
, t
->board
),
256 descent
[di
].node
->d
);
257 lnode
= tree_get_node(t
, lnode
, descent
[di
++].node
->coord
, true);
259 stats_add_result(&lnode
->u
, rval
, 1);
262 /* Add lnode for tenuki (pass) if we descended further. */
264 LTREE_DEBUG
fprintf(stderr
, "pass ");
265 lnode
= tree_get_node(t
, lnode
, pass
, true);
267 stats_add_result(&lnode
->u
, rval
, 1);
270 LTREE_DEBUG
fprintf(stderr
, "\n");
275 uct_playout(struct uct
*u
, struct board
*b
, enum stone player_color
, struct tree
*t
)
280 struct playout_amafmap
*amaf
= NULL
;
281 if (u
->policy
->wants_amaf
) {
282 amaf
= calloc2(1, sizeof(*amaf
));
283 amaf
->map
= calloc2(board_size2(&b2
) + 1, sizeof(*amaf
->map
));
284 amaf
->map
++; // -1 is pass
287 /* Walk the tree until we find a leaf, then expand it and do
288 * a random playout. */
289 struct tree_node
*n
= t
->root
;
290 enum stone node_color
= stone_other(player_color
);
291 assert(node_color
== t
->root_color
);
293 /* Tree descent history. */
294 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
297 struct uct_descent descent
[DLEN
];
298 descent
[0].node
= n
; descent
[0].lnode
= NULL
;
300 /* Total value of the sequence. */
301 struct move_stats seq_value
= { .playouts
= 0 };
304 int pass_limit
= (board_size(&b2
) - 2) * (board_size(&b2
) - 2) / 2;
305 int passes
= is_pass(b
->last_move
.coord
) && b
->moves
> 0;
309 static char spaces
[] = "\0 ";
312 fprintf(stderr
, "--- UCT walk with color %d\n", player_color
);
314 while (!tree_leaf_node(n
) && passes
< 2) {
315 spaces
[depth
++] = ' '; spaces
[depth
] = 0;
318 /*** Choose a node to descend to: */
320 /* Parity is chosen already according to the child color, since
321 * it is applied to children. */
322 node_color
= stone_other(node_color
);
323 int parity
= (node_color
== player_color
? 1 : -1);
326 descent
[dlen
] = descent
[dlen
- 1];
327 if (u
->local_tree
&& (!descent
[dlen
].lnode
|| descent
[dlen
].node
->d
>= u
->tenuki_d
)) {
328 /* Start new local sequence. */
329 /* Remember that node_color already holds color of the
330 * to-be-found child. */
331 descent
[dlen
].lnode
= node_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
334 if (!u
->random_policy_chance
|| fast_random(u
->random_policy_chance
))
335 u
->policy
->descend(u
->policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
337 u
->random_policy
->descend(u
->random_policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
340 /*** Perform the descent: */
342 seq_value
.playouts
+= descent
[dlen
].value
.playouts
;
343 seq_value
.value
+= descent
[dlen
].value
.value
* descent
[dlen
].value
.playouts
;
344 n
= descent
[dlen
++].node
;
345 assert(n
== t
->root
|| n
->parent
);
347 fprintf(stderr
, "%s+-- UCT sent us to [%s:%d] %f\n",
348 spaces
, coord2sstr(n
->coord
, t
->board
), n
->coord
,
349 tree_node_get_value(t
, parity
, n
->u
.value
));
351 /* Add virtual loss if we need to; this is used to discourage
352 * other threads from visiting this node in case of multiple
353 * threads doing the tree search. */
355 stats_add_result(&n
->u
, tree_parity(t
, parity
) > 0 ? 0 : 1, 1);
357 assert(n
->coord
>= -1);
358 if (amaf
&& !is_pass(n
->coord
)) {
359 if (amaf
->map
[n
->coord
] == S_NONE
|| amaf
->map
[n
->coord
] == node_color
) {
360 amaf
->map
[n
->coord
] = node_color
;
361 } else { // XXX: Respect amaf->record_nakade
362 amaf_op(amaf
->map
[n
->coord
], +);
364 amaf
->game
[amaf
->gamelen
].coord
= n
->coord
;
365 amaf
->game
[amaf
->gamelen
].color
= node_color
;
367 assert(amaf
->gamelen
< sizeof(amaf
->game
) / sizeof(amaf
->game
[0]));
370 struct move m
= { n
->coord
, node_color
};
371 int res
= board_play(&b2
, &m
);
373 if (res
< 0 || (!is_pass(m
.coord
) && !group_at(&b2
, m
.coord
)) /* suicide */
374 || b2
.superko_violation
) {
376 for (struct tree_node
*ni
= n
; ni
; ni
= ni
->parent
)
377 fprintf(stderr
, "%s<%"PRIhash
"> ", coord2sstr(ni
->coord
, t
->board
), ni
->hash
);
378 fprintf(stderr
, "marking invalid %s node %d,%d res %d group %d spk %d\n",
379 stone2str(node_color
), coord_x(n
->coord
,b
), coord_y(n
->coord
,b
),
380 res
, group_at(&b2
, m
.coord
), b2
.superko_violation
);
382 n
->hints
|= TREE_HINT_INVALID
;
387 if (is_pass(n
->coord
))
394 amaf
->game_baselen
= amaf
->gamelen
;
395 amaf
->record_nakade
= u
->playout_amaf_nakade
;
398 if (t
->use_extra_komi
&& u
->dynkomi
->persim
) {
399 b2
.komi
+= round(u
->dynkomi
->persim(u
->dynkomi
, &b2
, t
, n
));
403 /* XXX: No dead groups support. */
404 float score
= board_official_score(&b2
, NULL
);
405 /* Result from black's perspective (no matter who
406 * the player; black's perspective is always
407 * what the tree stores. */
408 result
= - (score
* 2);
411 fprintf(stderr
, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
412 player_color
, node_color
, coord2sstr(n
->coord
, t
->board
), result
, score
);
414 board_print(&b2
, stderr
);
416 board_ownermap_fill(&u
->ownermap
, &b2
);
418 } else { assert(u
->parallel_tree
|| tree_leaf_node(n
));
419 /* In case of parallel tree search, the assertion might
420 * not hold if two threads chew on the same node. */
421 result
= uct_leaf_node(u
, &b2
, player_color
, amaf
, t
, n
, node_color
, spaces
);
424 if (amaf
&& u
->playout_amaf_cutoff
) {
425 int cutoff
= amaf
->game_baselen
;
426 cutoff
+= (amaf
->gamelen
- amaf
->game_baselen
) * u
->playout_amaf_cutoff
/ 100;
427 /* Now, reconstruct the amaf map. */
428 memset(amaf
->map
, 0, board_size2(&b2
) * sizeof(*amaf
->map
));
429 for (int i
= 0; i
< cutoff
; i
++) {
430 coord_t coord
= amaf
->game
[i
].coord
;
431 enum stone color
= amaf
->game
[i
].color
;
432 if (amaf
->map
[coord
] == S_NONE
|| amaf
->map
[coord
] == color
) {
433 amaf
->map
[coord
] = color
;
434 /* Nakade always recorded for in-tree part */
435 } else if (amaf
->record_nakade
|| i
<= amaf
->game_baselen
) {
436 amaf_op(amaf
->map
[n
->coord
], +);
441 assert(n
== t
->root
|| n
->parent
);
443 float rval
= scale_value(u
, b
, result
);
444 u
->policy
->update(u
->policy
, t
, n
, node_color
, player_color
, amaf
, rval
);
446 if (t
->use_extra_komi
) {
447 stats_add_result(&u
->dynkomi
->score
, result
/ 2, 1);
448 stats_add_result(&u
->dynkomi
->value
, rval
, 1);
451 if (u
->local_tree
&& n
->parent
&& !is_pass(n
->coord
) && dlen
> 0) {
452 /* Possibly transform the rval appropriately. */
453 float expval
= seq_value
.value
/ seq_value
.playouts
;
454 rval
= stats_temper_value(rval
, expval
, u
->local_tree
);
456 /* Get the local sequences and record them in ltree. */
457 /* We will look for sequence starts in our descent
458 * history, then run record_local_sequence() for each
459 * found sequence start; record_local_sequence() may
460 * pick longer sequences from descent history then,
461 * which is expected as it will create new lnodes. */
462 enum stone seq_color
= player_color
;
463 /* First move always starts a sequence. */
464 record_local_sequence(u
, t
, descent
, dlen
, 1, seq_color
, rval
);
465 seq_color
= stone_other(seq_color
);
466 for (int dseqi
= 2; dseqi
< dlen
; dseqi
++, seq_color
= stone_other(seq_color
)) {
467 if (u
->local_tree_allseq
) {
468 /* We are configured to record all subsequences. */
469 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
472 if (descent
[dseqi
].node
->d
>= u
->tenuki_d
) {
473 /* Tenuki! Record the fresh sequence. */
474 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
477 if (descent
[dseqi
].lnode
&& !descent
[dseqi
].lnode
) {
478 /* Record result for in-descent picked sequence. */
479 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
487 /* We need to undo the virtual loss we added during descend. */
488 if (u
->virtual_loss
) {
489 int parity
= (node_color
== player_color
? 1 : -1);
490 for (; n
->parent
; n
= n
->parent
) {
491 stats_rm_result(&n
->u
, tree_parity(t
, parity
) > 0 ? 0 : 1, 1);
500 board_done_noalloc(&b2
);
505 uct_playouts(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
)
508 for (i
= 0; !uct_halt
; i
++)
509 uct_playout(u
, b
, color
, t
);