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 /* Ownership statistics. Value (0..1000) for each possible
142 * point describes likelihood of this point becoming black.
143 * Normally, white rate is 1000-value; exception are possible
144 * seki points, but these should be rare. */
145 fprintf(stderr
, ", \"boards\": {\"territory\": [");
147 foreach_point(t
->board
) {
148 if (board_at(t
->board
, c
) == S_OFFBOARD
) continue;
149 int rate
= u
->ownermap
.map
[c
][S_BLACK
] * 1000 / u
->ownermap
.playouts
;
150 fprintf(stderr
, "%s%d", f
++ > 0 ? "," : "", rate
);
152 fprintf(stderr
, "]}");
156 fprintf(stderr
, "}}\n");
160 uct_progress_status(struct uct
*u
, struct tree
*t
, enum stone color
, int playouts
, bool final
)
162 switch (u
->reporting
) {
164 uct_progress_text(u
, t
, color
, playouts
, final
);
168 uct_progress_json(u
, t
, color
, playouts
, final
,
169 u
->reporting
== UR_JSON_BIG
);
177 record_amaf_move(struct playout_amafmap
*amaf
, coord_t coord
)
179 assert(amaf
->gamelen
< MAX_GAMELEN
);
180 amaf
->game
[amaf
->gamelen
++] = coord
;
184 struct uct_playout_callback
{
187 struct tree_node
*lnode
;
192 uct_playout_hook(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
, int mode
)
194 /* XXX: This is used in some non-master branches. */
199 uct_playout_prepolicy(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
)
201 return uct_playout_hook(playout
, setup
, b
, color
, 0);
205 uct_playout_postpolicy(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
)
207 return uct_playout_hook(playout
, setup
, b
, color
, 1);
212 uct_leaf_node(struct uct
*u
, struct board
*b
, enum stone player_color
,
213 struct playout_amafmap
*amaf
,
214 struct uct_descent
*descent
, int *dlen
,
215 struct tree_node
*significant
[2],
216 struct tree
*t
, struct tree_node
*n
, enum stone node_color
,
219 enum stone next_color
= stone_other(node_color
);
220 int parity
= (next_color
== player_color
? 1 : -1);
223 fprintf(stderr
, "%s*-- UCT playout #%d start [%s] %f\n",
224 spaces
, n
->u
.playouts
, coord2sstr(node_coord(n
), t
->board
),
225 tree_node_get_value(t
, parity
, n
->u
.value
));
227 struct uct_playout_callback upc
= {
230 /* TODO: Don't necessarily restart the sequence walk when
231 * entering playout. */
235 struct playout_setup ps
= {
236 .gamelen
= u
->gamelen
,
237 .mercymin
= u
->mercymin
,
238 .prepolicy_hook
= uct_playout_prepolicy
,
239 .postpolicy_hook
= uct_playout_postpolicy
,
242 int result
= play_random_game(&ps
, b
, next_color
,
243 u
->playout_amaf
? amaf
: NULL
,
244 &u
->ownermap
, u
->playout
);
245 if (next_color
== S_WHITE
) {
246 /* We need the result from black's perspective. */
250 fprintf(stderr
, "%s -- [%d..%d] %s random playout result %d\n",
251 spaces
, player_color
, next_color
, coord2sstr(node_coord(n
), t
->board
), result
);
257 scale_value(struct uct
*u
, struct board
*b
, int result
)
259 floating_t rval
= result
> 0 ? 1.0 : result
< 0 ? 0.0 : 0.5;
260 if (u
->val_scale
&& result
!= 0) {
261 int vp
= u
->val_points
;
263 vp
= board_size(b
) - 1; vp
*= vp
; vp
*= 2;
266 floating_t sval
= (floating_t
) abs(result
) / vp
;
267 sval
= sval
> 1 ? 1 : sval
;
268 if (result
< 0) sval
= 1 - sval
;
270 rval
+= u
->val_scale
* sval
;
272 rval
= (1 - u
->val_scale
) * rval
+ u
->val_scale
* sval
;
273 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
279 local_value(struct uct
*u
, struct board
*b
, coord_t coord
, enum stone color
)
281 /* Tactical evaluation of move @coord by color @color, given
282 * simulation end position @b. I.e., a move is tactically good
283 * if the resulting group stays on board until the game end. */
284 /* We can also take into account surrounding stones, e.g. to
285 * encourage taking off external liberties during a semeai. */
286 double val
= board_local_value(u
->local_tree_neival
, b
, coord
, color
);
287 return (color
== S_WHITE
) ? 1.f
- val
: val
;
291 record_local_sequence(struct uct
*u
, struct tree
*t
, struct board
*endb
,
292 struct uct_descent
*descent
, int dlen
, int di
,
293 enum stone seq_color
)
295 #define LTREE_DEBUG if (UDEBUGL(6))
297 /* Ignore pass sequences. */
298 if (is_pass(node_coord(descent
[di
].node
)))
301 LTREE_DEBUG
board_print(endb
, stderr
);
302 LTREE_DEBUG
fprintf(stderr
, "recording local %s sequence: ",
303 stone2str(seq_color
));
305 /* Sequences starting deeper are less relevant in general. */
306 int pval
= LTREE_PLAYOUTS_MULTIPLIER
;
307 if (u
->local_tree
&& u
->local_tree_depth_decay
> 0)
308 pval
= ((floating_t
) pval
) / pow(u
->local_tree_depth_decay
, di
- 1);
310 LTREE_DEBUG
fprintf(stderr
, "too deep @%d\n", di
);
314 /* Pick the right local tree root... */
315 struct tree_node
*lnode
= seq_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
318 /* ...determine the sequence value... */
320 if (u
->local_tree_eval
!= LTE_EACH
) {
321 sval
= local_value(u
, endb
, node_coord(descent
[di
].node
), seq_color
);
322 LTREE_DEBUG
fprintf(stderr
, "(goal %s[%s %1.3f][%d]) ",
323 coord2sstr(node_coord(descent
[di
].node
), t
->board
),
324 stone2str(seq_color
), sval
, descent
[di
].node
->d
);
326 if (u
->local_tree_eval
== LTE_TOTAL
) {
328 while (di
< dlen
&& (di
== di0
|| descent
[di
].node
->d
< u
->tenuki_d
)) {
329 enum stone color
= (di
- di0
) % 2 ? stone_other(seq_color
) : seq_color
;
330 double rval
= local_value(u
, endb
, node_coord(descent
[di
].node
), color
);
336 sval
/= (di
- di0
+ 1);
341 /* ...and record the sequence. */
343 while (di
< dlen
&& !is_pass(node_coord(descent
[di
].node
))
344 && (di
== di0
|| descent
[di
].node
->d
< u
->tenuki_d
)) {
345 enum stone color
= (di
- di0
) % 2 ? stone_other(seq_color
) : seq_color
;
347 if (u
->local_tree_eval
!= LTE_EACH
)
350 rval
= local_value(u
, endb
, node_coord(descent
[di
].node
), color
);
351 LTREE_DEBUG
fprintf(stderr
, "%s[%s %1.3f][%d] ",
352 coord2sstr(node_coord(descent
[di
].node
), t
->board
),
353 stone2str(color
), rval
, descent
[di
].node
->d
);
354 lnode
= tree_get_node(t
, lnode
, node_coord(descent
[di
++].node
), true);
356 stats_add_result(&lnode
->u
, rval
, pval
);
359 /* Add lnode for tenuki (pass) if we descended further. */
361 double rval
= u
->local_tree_eval
!= LTE_EACH
? sval
: 0.5;
362 LTREE_DEBUG
fprintf(stderr
, "pass ");
363 lnode
= tree_get_node(t
, lnode
, pass
, true);
365 stats_add_result(&lnode
->u
, rval
, pval
);
368 LTREE_DEBUG
fprintf(stderr
, "\n");
373 uct_playout(struct uct
*u
, struct board
*b
, enum stone player_color
, struct tree
*t
)
378 struct playout_amafmap amaf
;
379 amaf
.gamelen
= amaf
.game_baselen
= 0;
381 /* Walk the tree until we find a leaf, then expand it and do
382 * a random playout. */
383 struct tree_node
*n
= t
->root
;
384 enum stone node_color
= stone_other(player_color
);
385 assert(node_color
== t
->root_color
);
387 /* Make sure the root node is expanded. */
388 if (tree_leaf_node(n
) && !__sync_lock_test_and_set(&n
->is_expanded
, 1))
389 tree_expand_node(t
, n
, &b2
, player_color
, u
, 1);
391 /* Tree descent history. */
392 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
394 struct uct_descent descent
[DESCENT_DLEN
];
395 descent
[0].node
= n
; descent
[0].lnode
= NULL
;
397 /* Total value of the sequence. */
398 struct move_stats seq_value
= { .playouts
= 0 };
399 /* The last "significant" node along the descent (i.e. node
400 * with higher than configured number of playouts). For black
402 struct tree_node
*significant
[2] = { NULL
, NULL
};
403 if (n
->u
.playouts
>= u
->significant_threshold
)
404 significant
[node_color
- 1] = n
;
407 int pass_limit
= (board_size(&b2
) - 2) * (board_size(&b2
) - 2) / 2;
408 int passes
= is_pass(b
->last_move
.coord
) && b
->moves
> 0;
411 static char spaces
[] = "\0 ";
414 fprintf(stderr
, "--- UCT walk with color %d\n", player_color
);
416 while (!tree_leaf_node(n
) && passes
< 2) {
417 spaces
[dlen
- 1] = ' '; spaces
[dlen
] = 0;
420 /*** Choose a node to descend to: */
422 /* Parity is chosen already according to the child color, since
423 * it is applied to children. */
424 node_color
= stone_other(node_color
);
425 int parity
= (node_color
== player_color
? 1 : -1);
427 assert(dlen
< DESCENT_DLEN
);
428 descent
[dlen
] = descent
[dlen
- 1];
429 if (u
->local_tree
&& (!descent
[dlen
].lnode
|| descent
[dlen
].node
->d
>= u
->tenuki_d
)) {
430 /* Start new local sequence. */
431 /* Remember that node_color already holds color of the
432 * to-be-found child. */
433 descent
[dlen
].lnode
= node_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
436 if (!u
->random_policy_chance
|| fast_random(u
->random_policy_chance
))
437 u
->policy
->descend(u
->policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
439 u
->random_policy
->descend(u
->random_policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
442 /*** Perform the descent: */
444 if (descent
[dlen
].node
->u
.playouts
>= u
->significant_threshold
) {
445 significant
[node_color
- 1] = descent
[dlen
].node
;
448 seq_value
.playouts
+= descent
[dlen
].value
.playouts
;
449 seq_value
.value
+= descent
[dlen
].value
.value
* descent
[dlen
].value
.playouts
;
450 n
= descent
[dlen
++].node
;
451 assert(n
== t
->root
|| n
->parent
);
453 fprintf(stderr
, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
454 spaces
, coord2sstr(node_coord(n
), t
->board
),
455 node_coord(n
), n
->u
.playouts
,
456 tree_node_get_value(t
, parity
, n
->u
.value
));
458 /* Add virtual loss if we need to; this is used to discourage
459 * other threads from visiting this node in case of multiple
460 * threads doing the tree search. */
462 stats_add_result(&n
->u
, node_color
== S_BLACK
? 0.0 : 1.0, u
->virtual_loss
);
464 assert(node_coord(n
) >= -1);
465 record_amaf_move(&amaf
, node_coord(n
));
467 struct move m
= { node_coord(n
), node_color
};
468 int res
= board_play(&b2
, &m
);
470 if (res
< 0 || (!is_pass(m
.coord
) && !group_at(&b2
, m
.coord
)) /* suicide */
471 || b2
.superko_violation
) {
473 for (struct tree_node
*ni
= n
; ni
; ni
= ni
->parent
)
474 fprintf(stderr
, "%s<%"PRIhash
"> ", coord2sstr(node_coord(ni
), t
->board
), ni
->hash
);
475 fprintf(stderr
, "marking invalid %s node %d,%d res %d group %d spk %d\n",
476 stone2str(node_color
), coord_x(node_coord(n
),b
), coord_y(node_coord(n
),b
),
477 res
, group_at(&b2
, m
.coord
), b2
.superko_violation
);
479 n
->hints
|= TREE_HINT_INVALID
;
484 if (is_pass(node_coord(n
)))
489 enum stone next_color
= stone_other(node_color
);
490 /* We need to make sure only one thread expands the node. If
491 * we are unlucky enough for two threads to meet in the same
492 * node, the latter one will simply do another simulation from
493 * the node itself, no big deal. t->nodes_size may exceed
494 * the maximum in multi-threaded case but not by much so it's ok.
495 * The size test must be before the test&set not after, to allow
496 * expansion of the node later if enough nodes have been freed. */
497 if (tree_leaf_node(n
)
498 && n
->u
.playouts
- u
->virtual_loss
>= u
->expand_p
&& t
->nodes_size
< u
->max_tree_size
499 && !__sync_lock_test_and_set(&n
->is_expanded
, 1))
500 tree_expand_node(t
, n
, &b2
, next_color
, u
, -parity
);
503 amaf
.game_baselen
= amaf
.gamelen
;
505 if (t
->use_extra_komi
&& u
->dynkomi
->persim
) {
506 b2
.komi
+= round(u
->dynkomi
->persim(u
->dynkomi
, &b2
, t
, n
));
510 /* XXX: No dead groups support. */
511 floating_t score
= board_official_score(&b2
, NULL
);
512 /* Result from black's perspective (no matter who
513 * the player; black's perspective is always
514 * what the tree stores. */
515 result
= - (score
* 2);
518 fprintf(stderr
, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
519 player_color
, node_color
, coord2sstr(node_coord(n
), t
->board
), result
, score
);
521 board_print(&b2
, stderr
);
523 board_ownermap_fill(&u
->ownermap
, &b2
);
525 } else { // assert(tree_leaf_node(n));
526 /* In case of parallel tree search, the assertion might
527 * not hold if two threads chew on the same node. */
528 result
= uct_leaf_node(u
, &b2
, player_color
, &amaf
, descent
, &dlen
, significant
, t
, n
, node_color
, spaces
);
531 if (u
->policy
->wants_amaf
&& u
->playout_amaf_cutoff
) {
532 unsigned int cutoff
= amaf
.game_baselen
;
533 cutoff
+= (amaf
.gamelen
- amaf
.game_baselen
) * u
->playout_amaf_cutoff
/ 100;
534 amaf
.gamelen
= cutoff
;
537 /* Record the result. */
539 assert(n
== t
->root
|| n
->parent
);
540 floating_t rval
= scale_value(u
, b
, result
);
541 u
->policy
->update(u
->policy
, t
, n
, node_color
, player_color
, &amaf
, &b2
, rval
);
543 stats_add_result(&t
->avg_score
, result
/ 2, 1);
544 if (t
->use_extra_komi
) {
545 stats_add_result(&u
->dynkomi
->score
, result
/ 2, 1);
546 stats_add_result(&u
->dynkomi
->value
, rval
, 1);
549 if (u
->local_tree
&& n
->parent
&& !is_pass(node_coord(n
)) && dlen
> 0) {
550 /* Get the local sequences and record them in ltree. */
551 /* We will look for sequence starts in our descent
552 * history, then run record_local_sequence() for each
553 * found sequence start; record_local_sequence() may
554 * pick longer sequences from descent history then,
555 * which is expected as it will create new lnodes. */
556 enum stone seq_color
= player_color
;
557 /* First move always starts a sequence. */
558 record_local_sequence(u
, t
, &b2
, descent
, dlen
, 1, seq_color
);
559 seq_color
= stone_other(seq_color
);
560 for (int dseqi
= 2; dseqi
< dlen
; dseqi
++, seq_color
= stone_other(seq_color
)) {
561 if (u
->local_tree_allseq
) {
562 /* We are configured to record all subsequences. */
563 record_local_sequence(u
, t
, &b2
, descent
, dlen
, dseqi
, seq_color
);
566 if (descent
[dseqi
].node
->d
>= u
->tenuki_d
) {
567 /* Tenuki! Record the fresh sequence. */
568 record_local_sequence(u
, t
, &b2
, descent
, dlen
, dseqi
, seq_color
);
571 if (descent
[dseqi
].lnode
&& !descent
[dseqi
].lnode
) {
572 /* Record result for in-descent picked sequence. */
573 record_local_sequence(u
, t
, &b2
, descent
, dlen
, dseqi
, seq_color
);
580 /* We need to undo the virtual loss we added during descend. */
581 if (u
->virtual_loss
) {
582 floating_t loss
= node_color
== S_BLACK
? 0.0 : 1.0;
583 for (; n
->parent
; n
= n
->parent
) {
584 stats_rm_result(&n
->u
, loss
, u
->virtual_loss
);
589 board_done_noalloc(&b2
);
594 uct_playouts(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, struct time_info
*ti
)
597 if (ti
&& ti
->dim
== TD_GAMES
) {
598 for (i
= 0; t
->root
->u
.playouts
<= ti
->len
.games
&& !uct_halt
; i
++)
599 uct_playout(u
, b
, color
, t
);
601 for (i
= 0; !uct_halt
; i
++)
602 uct_playout(u
, b
, color
, t
);