17 #include "tactics/util.h"
18 #include "uct/dynkomi.h"
19 #include "uct/internal.h"
20 #include "uct/search.h"
25 #define DESCENT_DLEN 512
29 uct_progress_text(struct uct
*u
, struct tree
*t
, enum stone color
, int playouts
, bool final
)
35 struct tree_node
*best
= u
->policy
->choose(u
->policy
, t
->root
, t
->board
, color
, resign
);
37 fprintf(stderr
, "... No moves left\n");
40 fprintf(stderr
, "[%d] ", playouts
);
41 fprintf(stderr
, "best %f ", tree_node_get_value(t
, 1, best
->u
.value
));
44 if (t
->use_extra_komi
)
45 fprintf(stderr
, "komi %.1f ", t
->extra_komi
);
48 fprintf(stderr
, "| seq ");
49 for (int depth
= 0; depth
< 4; depth
++) {
50 if (best
&& best
->u
.playouts
>= 25) {
51 fprintf(stderr
, "%3s ", coord2sstr(node_coord(best
), t
->board
));
52 best
= u
->policy
->choose(u
->policy
, best
, t
->board
, color
, resign
);
59 fprintf(stderr
, "| can ");
61 struct tree_node
*can
[cans
];
62 memset(can
, 0, sizeof(can
));
63 best
= t
->root
->children
;
66 while ((!can
[c
] || best
->u
.playouts
> can
[c
]->u
.playouts
) && ++c
< cans
);
67 for (int d
= 0; d
< c
; d
++) can
[d
] = can
[d
+ 1];
68 if (c
> 0) can
[c
- 1] = best
;
73 fprintf(stderr
, "%3s(%.3f) ",
74 coord2sstr(node_coord(can
[cans
]), t
->board
),
75 tree_node_get_value(t
, 1, can
[cans
]->u
.value
));
81 fprintf(stderr
, "\n");
85 uct_progress_json(struct uct
*u
, struct tree
*t
, enum stone color
, int playouts
, bool final
, bool big
)
87 /* Prefix indicating JSON line. */
88 fprintf(stderr
, "{\"%s\": {", final
? "move" : "frame");
91 fprintf(stderr
, "\"playouts\": %d", playouts
);
94 if (t
->use_extra_komi
)
95 fprintf(stderr
, ", \"extrakomi\": %.1f", t
->extra_komi
);
97 struct tree_node
*best
= u
->policy
->choose(u
->policy
, t
->root
, t
->board
, color
, resign
);
100 fprintf(stderr
, ", \"best\": {\"%s\": %f}",
101 coord2sstr(best
->coord
, t
->board
),
102 tree_node_get_value(t
, 1, best
->u
.value
));
105 fprintf(stderr
, ", \"seq\": [");
106 for (int depth
= 0; depth
< 4; depth
++) {
107 if (!best
|| best
->u
.playouts
< 25) break;
108 fprintf(stderr
, "%s\"%s\"", depth
> 0 ? "," : "",
109 coord2sstr(best
->coord
, t
->board
));
110 best
= u
->policy
->choose(u
->policy
, best
, t
->board
, color
, resign
);
112 fprintf(stderr
, "]");
115 /* Best candidates */
117 struct tree_node
*can
[cans
];
118 memset(can
, 0, sizeof(can
));
119 best
= t
->root
->children
;
122 while ((!can
[c
] || best
->u
.playouts
> can
[c
]->u
.playouts
) && ++c
< cans
);
123 for (int d
= 0; d
< c
; d
++) can
[d
] = can
[d
+ 1];
124 if (c
> 0) can
[c
- 1] = best
;
125 best
= best
->sibling
;
127 fprintf(stderr
, ", \"can\": [");
128 while (--cans
>= 0) {
129 if (!can
[cans
]) break;
130 fprintf(stderr
, "%s{\"%s\":%.3f}",
132 coord2sstr(can
[cans
]->coord
, t
->board
),
133 tree_node_get_value(t
, 1, can
[cans
]->u
.value
));
135 fprintf(stderr
, "]");
139 if (t
->avg_score
.playouts
> 0)
140 fprintf(stderr
, ", \"avg\": {\"score\": %.3f}", t
->avg_score
.value
);
141 /* Per-intersection information. */
142 fprintf(stderr
, ", \"boards\": {");
143 /* Position coloring information. */
144 fprintf(stderr
, "\"colors\": [");
146 foreach_point(t
->board
) {
147 if (board_at(t
->board
, c
) == S_OFFBOARD
) continue;
148 fprintf(stderr
, "%s%d", f
++ > 0 ? "," : "", board_at(t
->board
, c
));
150 fprintf(stderr
, "]");
151 /* Ownership statistics. Value (0..1000) for each possible
152 * point describes likelihood of this point becoming black.
153 * Normally, white rate is 1000-value; exception are possible
154 * seki points, but these should be rare. */
155 fprintf(stderr
, ", \"territory\": [");
157 foreach_point(t
->board
) {
158 if (board_at(t
->board
, c
) == S_OFFBOARD
) continue;
159 int rate
= u
->ownermap
.map
[c
][S_BLACK
] * 1000 / u
->ownermap
.playouts
;
160 fprintf(stderr
, "%s%d", f
++ > 0 ? "," : "", rate
);
162 fprintf(stderr
, "]");
163 fprintf(stderr
, "}");
166 fprintf(stderr
, "}}\n");
170 uct_progress_status(struct uct
*u
, struct tree
*t
, enum stone color
, int playouts
, bool final
)
172 switch (u
->reporting
) {
174 uct_progress_text(u
, t
, color
, playouts
, final
);
178 uct_progress_json(u
, t
, color
, playouts
, final
,
179 u
->reporting
== UR_JSON_BIG
);
187 record_amaf_move(struct playout_amafmap
*amaf
, coord_t coord
)
189 assert(amaf
->gamelen
< MAX_GAMELEN
);
190 amaf
->game
[amaf
->gamelen
++] = coord
;
194 struct uct_playout_callback
{
197 struct tree_node
*lnode
;
202 uct_playout_hook(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
, int mode
)
204 /* XXX: This is used in some non-master branches. */
209 uct_playout_prepolicy(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
)
211 return uct_playout_hook(playout
, setup
, b
, color
, 0);
215 uct_playout_postpolicy(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
)
217 return uct_playout_hook(playout
, setup
, b
, color
, 1);
222 uct_leaf_node(struct uct
*u
, struct board
*b
, enum stone player_color
,
223 struct playout_amafmap
*amaf
,
224 struct uct_descent
*descent
, int *dlen
,
225 struct tree_node
*significant
[2],
226 struct tree
*t
, struct tree_node
*n
, enum stone node_color
,
229 enum stone next_color
= stone_other(node_color
);
230 int parity
= (next_color
== player_color
? 1 : -1);
233 fprintf(stderr
, "%s*-- UCT playout #%d start [%s] %f\n",
234 spaces
, n
->u
.playouts
, coord2sstr(node_coord(n
), t
->board
),
235 tree_node_get_value(t
, parity
, n
->u
.value
));
237 struct uct_playout_callback upc
= {
240 /* TODO: Don't necessarily restart the sequence walk when
241 * entering playout. */
245 struct playout_setup ps
= {
246 .gamelen
= u
->gamelen
,
247 .mercymin
= u
->mercymin
,
248 .prepolicy_hook
= uct_playout_prepolicy
,
249 .postpolicy_hook
= uct_playout_postpolicy
,
252 int result
= play_random_game(&ps
, b
, next_color
,
253 u
->playout_amaf
? amaf
: NULL
,
254 &u
->ownermap
, u
->playout
);
255 if (next_color
== S_WHITE
) {
256 /* We need the result from black's perspective. */
260 fprintf(stderr
, "%s -- [%d..%d] %s random playout result %d\n",
261 spaces
, player_color
, next_color
, coord2sstr(node_coord(n
), t
->board
), result
);
267 scale_value(struct uct
*u
, struct board
*b
, int result
)
269 floating_t rval
= result
> 0 ? 1.0 : result
< 0 ? 0.0 : 0.5;
270 if (u
->val_scale
&& result
!= 0) {
271 int vp
= u
->val_points
;
273 vp
= board_size(b
) - 1; vp
*= vp
; vp
*= 2;
276 floating_t sval
= (floating_t
) abs(result
) / vp
;
277 sval
= sval
> 1 ? 1 : sval
;
278 if (result
< 0) sval
= 1 - sval
;
280 rval
+= u
->val_scale
* sval
;
282 rval
= (1 - u
->val_scale
) * rval
+ u
->val_scale
* sval
;
283 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
289 local_value(struct uct
*u
, struct board
*b
, coord_t coord
, enum stone color
)
291 /* Tactical evaluation of move @coord by color @color, given
292 * simulation end position @b. I.e., a move is tactically good
293 * if the resulting group stays on board until the game end. */
294 /* We can also take into account surrounding stones, e.g. to
295 * encourage taking off external liberties during a semeai. */
296 double val
= board_local_value(u
->local_tree_neival
, b
, coord
, color
);
297 return (color
== S_WHITE
) ? 1.f
- val
: val
;
301 record_local_sequence(struct uct
*u
, struct tree
*t
, struct board
*endb
,
302 struct uct_descent
*descent
, int dlen
, int di
,
303 enum stone seq_color
)
305 #define LTREE_DEBUG if (UDEBUGL(6))
307 /* Ignore pass sequences. */
308 if (is_pass(node_coord(descent
[di
].node
)))
311 LTREE_DEBUG
board_print(endb
, stderr
);
312 LTREE_DEBUG
fprintf(stderr
, "recording local %s sequence: ",
313 stone2str(seq_color
));
315 /* Sequences starting deeper are less relevant in general. */
316 int pval
= LTREE_PLAYOUTS_MULTIPLIER
;
317 if (u
->local_tree
&& u
->local_tree_depth_decay
> 0)
318 pval
= ((floating_t
) pval
) / pow(u
->local_tree_depth_decay
, di
- 1);
320 LTREE_DEBUG
fprintf(stderr
, "too deep @%d\n", di
);
324 /* Pick the right local tree root... */
325 struct tree_node
*lnode
= seq_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
328 /* ...determine the sequence value... */
330 if (u
->local_tree_eval
!= LTE_EACH
) {
331 sval
= local_value(u
, endb
, node_coord(descent
[di
].node
), seq_color
);
332 LTREE_DEBUG
fprintf(stderr
, "(goal %s[%s %1.3f][%d]) ",
333 coord2sstr(node_coord(descent
[di
].node
), t
->board
),
334 stone2str(seq_color
), sval
, descent
[di
].node
->d
);
336 if (u
->local_tree_eval
== LTE_TOTAL
) {
338 while (di
< dlen
&& (di
== di0
|| descent
[di
].node
->d
< u
->tenuki_d
)) {
339 enum stone color
= (di
- di0
) % 2 ? stone_other(seq_color
) : seq_color
;
340 double rval
= local_value(u
, endb
, node_coord(descent
[di
].node
), color
);
346 sval
/= (di
- di0
+ 1);
351 /* ...and record the sequence. */
353 while (di
< dlen
&& !is_pass(node_coord(descent
[di
].node
))
354 && (di
== di0
|| descent
[di
].node
->d
< u
->tenuki_d
)) {
355 enum stone color
= (di
- di0
) % 2 ? stone_other(seq_color
) : seq_color
;
357 if (u
->local_tree_eval
!= LTE_EACH
)
360 rval
= local_value(u
, endb
, node_coord(descent
[di
].node
), color
);
361 LTREE_DEBUG
fprintf(stderr
, "%s[%s %1.3f][%d] ",
362 coord2sstr(node_coord(descent
[di
].node
), t
->board
),
363 stone2str(color
), rval
, descent
[di
].node
->d
);
364 lnode
= tree_get_node(t
, lnode
, node_coord(descent
[di
++].node
), true);
366 stats_add_result(&lnode
->u
, rval
, pval
);
369 /* Add lnode for tenuki (pass) if we descended further. */
371 double rval
= u
->local_tree_eval
!= LTE_EACH
? sval
: 0.5;
372 LTREE_DEBUG
fprintf(stderr
, "pass ");
373 lnode
= tree_get_node(t
, lnode
, pass
, true);
375 stats_add_result(&lnode
->u
, rval
, pval
);
378 LTREE_DEBUG
fprintf(stderr
, "\n");
383 uct_playout(struct uct
*u
, struct board
*b
, enum stone player_color
, struct tree
*t
)
388 struct playout_amafmap amaf
;
389 amaf
.gamelen
= amaf
.game_baselen
= 0;
391 /* Walk the tree until we find a leaf, then expand it and do
392 * a random playout. */
393 struct tree_node
*n
= t
->root
;
394 enum stone node_color
= stone_other(player_color
);
395 assert(node_color
== t
->root_color
);
397 /* Make sure the root node is expanded. */
398 if (tree_leaf_node(n
) && !__sync_lock_test_and_set(&n
->is_expanded
, 1))
399 tree_expand_node(t
, n
, &b2
, player_color
, u
, 1);
401 /* Tree descent history. */
402 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
404 struct uct_descent descent
[DESCENT_DLEN
];
405 descent
[0].node
= n
; descent
[0].lnode
= NULL
;
407 /* Total value of the sequence. */
408 struct move_stats seq_value
= { .playouts
= 0 };
409 /* The last "significant" node along the descent (i.e. node
410 * with higher than configured number of playouts). For black
412 struct tree_node
*significant
[2] = { NULL
, NULL
};
413 if (n
->u
.playouts
>= u
->significant_threshold
)
414 significant
[node_color
- 1] = n
;
417 int pass_limit
= (board_size(&b2
) - 2) * (board_size(&b2
) - 2) / 2;
418 int passes
= is_pass(b
->last_move
.coord
) && b
->moves
> 0;
421 static char spaces
[] = "\0 ";
424 fprintf(stderr
, "--- UCT walk with color %d\n", player_color
);
426 while (!tree_leaf_node(n
) && passes
< 2) {
427 spaces
[dlen
- 1] = ' '; spaces
[dlen
] = 0;
430 /*** Choose a node to descend to: */
432 /* Parity is chosen already according to the child color, since
433 * it is applied to children. */
434 node_color
= stone_other(node_color
);
435 int parity
= (node_color
== player_color
? 1 : -1);
437 assert(dlen
< DESCENT_DLEN
);
438 descent
[dlen
] = descent
[dlen
- 1];
439 if (u
->local_tree
&& (!descent
[dlen
].lnode
|| descent
[dlen
].node
->d
>= u
->tenuki_d
)) {
440 /* Start new local sequence. */
441 /* Remember that node_color already holds color of the
442 * to-be-found child. */
443 descent
[dlen
].lnode
= node_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
446 if (!u
->random_policy_chance
|| fast_random(u
->random_policy_chance
))
447 u
->policy
->descend(u
->policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
449 u
->random_policy
->descend(u
->random_policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
452 /*** Perform the descent: */
454 if (descent
[dlen
].node
->u
.playouts
>= u
->significant_threshold
) {
455 significant
[node_color
- 1] = descent
[dlen
].node
;
458 seq_value
.playouts
+= descent
[dlen
].value
.playouts
;
459 seq_value
.value
+= descent
[dlen
].value
.value
* descent
[dlen
].value
.playouts
;
460 n
= descent
[dlen
++].node
;
461 assert(n
== t
->root
|| n
->parent
);
463 fprintf(stderr
, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
464 spaces
, coord2sstr(node_coord(n
), t
->board
),
465 node_coord(n
), n
->u
.playouts
,
466 tree_node_get_value(t
, parity
, n
->u
.value
));
468 /* Add virtual loss if we need to; this is used to discourage
469 * other threads from visiting this node in case of multiple
470 * threads doing the tree search. */
472 stats_add_result(&n
->u
, node_color
== S_BLACK
? 0.0 : 1.0, u
->virtual_loss
);
474 assert(node_coord(n
) >= -1);
475 record_amaf_move(&amaf
, node_coord(n
));
477 struct move m
= { node_coord(n
), node_color
};
478 int res
= board_play(&b2
, &m
);
480 if (res
< 0 || (!is_pass(m
.coord
) && !group_at(&b2
, m
.coord
)) /* suicide */
481 || b2
.superko_violation
) {
483 for (struct tree_node
*ni
= n
; ni
; ni
= ni
->parent
)
484 fprintf(stderr
, "%s<%"PRIhash
"> ", coord2sstr(node_coord(ni
), t
->board
), ni
->hash
);
485 fprintf(stderr
, "marking invalid %s node %d,%d res %d group %d spk %d\n",
486 stone2str(node_color
), coord_x(node_coord(n
),b
), coord_y(node_coord(n
),b
),
487 res
, group_at(&b2
, m
.coord
), b2
.superko_violation
);
489 n
->hints
|= TREE_HINT_INVALID
;
494 if (is_pass(node_coord(n
)))
499 enum stone next_color
= stone_other(node_color
);
500 /* We need to make sure only one thread expands the node. If
501 * we are unlucky enough for two threads to meet in the same
502 * node, the latter one will simply do another simulation from
503 * the node itself, no big deal. t->nodes_size may exceed
504 * the maximum in multi-threaded case but not by much so it's ok.
505 * The size test must be before the test&set not after, to allow
506 * expansion of the node later if enough nodes have been freed. */
507 if (tree_leaf_node(n
)
508 && n
->u
.playouts
- u
->virtual_loss
>= u
->expand_p
&& t
->nodes_size
< u
->max_tree_size
509 && !__sync_lock_test_and_set(&n
->is_expanded
, 1))
510 tree_expand_node(t
, n
, &b2
, next_color
, u
, -parity
);
513 amaf
.game_baselen
= amaf
.gamelen
;
515 if (t
->use_extra_komi
&& u
->dynkomi
->persim
) {
516 b2
.komi
+= round(u
->dynkomi
->persim(u
->dynkomi
, &b2
, t
, n
));
520 /* XXX: No dead groups support. */
521 floating_t score
= board_official_score(&b2
, NULL
);
522 /* Result from black's perspective (no matter who
523 * the player; black's perspective is always
524 * what the tree stores. */
525 result
= - (score
* 2);
528 fprintf(stderr
, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
529 player_color
, node_color
, coord2sstr(node_coord(n
), t
->board
), result
, score
);
531 board_print(&b2
, stderr
);
533 board_ownermap_fill(&u
->ownermap
, &b2
);
535 } else { // assert(tree_leaf_node(n));
536 /* In case of parallel tree search, the assertion might
537 * not hold if two threads chew on the same node. */
538 result
= uct_leaf_node(u
, &b2
, player_color
, &amaf
, descent
, &dlen
, significant
, t
, n
, node_color
, spaces
);
541 if (u
->policy
->wants_amaf
&& u
->playout_amaf_cutoff
) {
542 unsigned int cutoff
= amaf
.game_baselen
;
543 cutoff
+= (amaf
.gamelen
- amaf
.game_baselen
) * u
->playout_amaf_cutoff
/ 100;
544 amaf
.gamelen
= cutoff
;
547 /* Record the result. */
549 assert(n
== t
->root
|| n
->parent
);
550 floating_t rval
= scale_value(u
, b
, result
);
551 u
->policy
->update(u
->policy
, t
, n
, node_color
, player_color
, &amaf
, &b2
, rval
);
553 stats_add_result(&t
->avg_score
, result
/ 2, 1);
554 if (t
->use_extra_komi
) {
555 stats_add_result(&u
->dynkomi
->score
, result
/ 2, 1);
556 stats_add_result(&u
->dynkomi
->value
, rval
, 1);
559 if (u
->local_tree
&& n
->parent
&& !is_pass(node_coord(n
)) && dlen
> 0) {
560 /* Get the local sequences and record them in ltree. */
561 /* We will look for sequence starts in our descent
562 * history, then run record_local_sequence() for each
563 * found sequence start; record_local_sequence() may
564 * pick longer sequences from descent history then,
565 * which is expected as it will create new lnodes. */
566 enum stone seq_color
= player_color
;
567 /* First move always starts a sequence. */
568 record_local_sequence(u
, t
, &b2
, descent
, dlen
, 1, seq_color
);
569 seq_color
= stone_other(seq_color
);
570 for (int dseqi
= 2; dseqi
< dlen
; dseqi
++, seq_color
= stone_other(seq_color
)) {
571 if (u
->local_tree_allseq
) {
572 /* We are configured to record all subsequences. */
573 record_local_sequence(u
, t
, &b2
, descent
, dlen
, dseqi
, seq_color
);
576 if (descent
[dseqi
].node
->d
>= u
->tenuki_d
) {
577 /* Tenuki! Record the fresh sequence. */
578 record_local_sequence(u
, t
, &b2
, descent
, dlen
, dseqi
, seq_color
);
581 if (descent
[dseqi
].lnode
&& !descent
[dseqi
].lnode
) {
582 /* Record result for in-descent picked sequence. */
583 record_local_sequence(u
, t
, &b2
, descent
, dlen
, dseqi
, seq_color
);
590 /* We need to undo the virtual loss we added during descend. */
591 if (u
->virtual_loss
) {
592 floating_t loss
= node_color
== S_BLACK
? 0.0 : 1.0;
593 for (; n
->parent
; n
= n
->parent
) {
594 stats_rm_result(&n
->u
, loss
, u
->virtual_loss
);
599 board_done_noalloc(&b2
);
604 uct_playouts(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, struct time_info
*ti
)
607 if (ti
&& ti
->dim
== TD_GAMES
) {
608 for (i
= 0; t
->root
->u
.playouts
<= ti
->len
.games
&& !uct_halt
; i
++)
609 uct_playout(u
, b
, color
, t
);
611 for (i
= 0; !uct_halt
; i
++)
612 uct_playout(u
, b
, color
, t
);