17 #include "uct/dynkomi.h"
18 #include "uct/internal.h"
19 #include "uct/search.h"
24 #define DESCENT_DLEN 512
28 uct_progress_text(struct uct
*u
, struct tree
*t
, enum stone color
, int playouts
, bool final
)
34 struct tree_node
*best
= u
->policy
->choose(u
->policy
, t
->root
, t
->board
, color
, resign
);
36 fprintf(stderr
, "... No moves left\n");
39 fprintf(stderr
, "[%d] ", playouts
);
40 fprintf(stderr
, "best %f ", tree_node_get_value(t
, 1, best
->u
.value
));
43 if (t
->use_extra_komi
)
44 fprintf(stderr
, "komi %.1f ", t
->extra_komi
);
47 fprintf(stderr
, "| seq ");
48 for (int depth
= 0; depth
< 4; 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 uct_progress_json(struct uct
*u
, struct tree
*t
, enum stone color
, int playouts
, bool final
, bool big
)
86 /* Prefix indicating JSON line. */
87 fprintf(stderr
, "{\"%s\": {", final
? "move" : "frame");
90 fprintf(stderr
, "\"playouts\": %d", playouts
);
93 if (t
->use_extra_komi
)
94 fprintf(stderr
, ", \"extrakomi\": %.1f", t
->extra_komi
);
96 struct tree_node
*best
= u
->policy
->choose(u
->policy
, t
->root
, t
->board
, color
, resign
);
99 fprintf(stderr
, ", \"best\": {\"%s\": %f}",
100 coord2sstr(best
->coord
, t
->board
),
101 tree_node_get_value(t
, 1, best
->u
.value
));
104 fprintf(stderr
, ", \"seq\": [");
105 for (int depth
= 0; depth
< 4; depth
++) {
106 if (!best
|| best
->u
.playouts
< 25) break;
107 fprintf(stderr
, "%s\"%s\"", depth
> 0 ? "," : "",
108 coord2sstr(best
->coord
, t
->board
));
109 best
= u
->policy
->choose(u
->policy
, best
, t
->board
, color
, resign
);
111 fprintf(stderr
, "]");
114 /* Best candidates */
116 struct tree_node
*can
[cans
];
117 memset(can
, 0, sizeof(can
));
118 best
= t
->root
->children
;
121 while ((!can
[c
] || best
->u
.playouts
> can
[c
]->u
.playouts
) && ++c
< cans
);
122 for (int d
= 0; d
< c
; d
++) can
[d
] = can
[d
+ 1];
123 if (c
> 0) can
[c
- 1] = best
;
124 best
= best
->sibling
;
126 fprintf(stderr
, ", \"can\": [");
127 while (--cans
>= 0) {
128 if (!can
[cans
]) break;
129 fprintf(stderr
, "%s{\"%s\":%.3f}",
131 coord2sstr(can
[cans
]->coord
, t
->board
),
132 tree_node_get_value(t
, 1, can
[cans
]->u
.value
));
134 fprintf(stderr
, "]");
137 /* Ownership statistics. {"b":val,"w":val,"d":val}
138 * where each val is in range [0,1] describes likelihood
139 * of this point becoming black, white and dame.
140 * If dame rate would be 0, only black rate is sent and
141 * white rate can be computed as 1-blackrate. */
142 fprintf(stderr
, ", \"territstatus\": [");
144 foreach_point(t
->board
) {
145 if (board_at(t
->board
, c
) != S_NONE
) continue;
146 int rate
= u
->ownermap
.map
[c
][S_BLACK
] * 1000 / u
->ownermap
.playouts
;
147 int drate
= u
->ownermap
.map
[c
][S_NONE
] * 1000 / u
->ownermap
.playouts
;
148 fprintf(stderr
, "%s[%d,%d]", f
++ > 0 ? "," : "", rate
, drate
);
150 fprintf(stderr
, "]");
152 /* Chain status statistics. Each chain is identified
153 * by some stone within, and bound to a value in range
154 * [0,1] describing likelihood of survival. */
155 fprintf(stderr
, ", \"chainstatus\": [");
157 foreach_point(t
->board
) {
158 group_t g
= group_at(t
->board
, c
);
159 if (!g
|| groupnext_at(t
->board
, c
)) continue;
160 /* Last stone in some group. */
161 fprintf(stderr
, "%s{\"%s\":%.3f}",
163 coord2sstr(c
, t
->board
),
164 (floating_t
) u
->ownermap
.map
[c
][board_at(t
->board
, c
)] / u
->ownermap
.playouts
);
166 fprintf(stderr
, "]");
169 fprintf(stderr
, "}}\n");
173 uct_progress_status(struct uct
*u
, struct tree
*t
, enum stone color
, int playouts
, bool final
)
175 switch (u
->reporting
) {
177 uct_progress_text(u
, t
, color
, playouts
, final
);
181 uct_progress_json(u
, t
, color
, playouts
, final
,
182 u
->reporting
== UR_JSON_BIG
);
190 record_amaf_move(struct playout_amafmap
*amaf
, coord_t coord
, enum stone color
)
192 if (amaf
->map
[coord
] == S_NONE
|| amaf
->map
[coord
] == color
) {
193 amaf
->map
[coord
] = color
;
194 } else { // XXX: Respect amaf->record_nakade
195 amaf_op(amaf
->map
[coord
], +);
197 amaf
->game
[amaf
->gamelen
].coord
= coord
;
198 amaf
->game
[amaf
->gamelen
].color
= color
;
200 assert(amaf
->gamelen
< sizeof(amaf
->game
) / sizeof(amaf
->game
[0]));
204 struct uct_playout_callback
{
207 struct tree_node
*lnode
;
212 uct_playout_hook(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
, int mode
)
214 /* XXX: This is used in some non-master branches. */
219 uct_playout_prepolicy(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
)
221 return uct_playout_hook(playout
, setup
, b
, color
, 0);
225 uct_playout_postpolicy(struct playout_policy
*playout
, struct playout_setup
*setup
, struct board
*b
, enum stone color
)
227 return uct_playout_hook(playout
, setup
, b
, color
, 1);
232 uct_leaf_node(struct uct
*u
, struct board
*b
, enum stone player_color
,
233 struct playout_amafmap
*amaf
,
234 struct uct_descent
*descent
, int *dlen
,
235 struct tree_node
*significant
[2],
236 struct tree
*t
, struct tree_node
*n
, enum stone node_color
,
239 enum stone next_color
= stone_other(node_color
);
240 int parity
= (next_color
== player_color
? 1 : -1);
242 /* We need to make sure only one thread expands the node. If
243 * we are unlucky enough for two threads to meet in the same
244 * node, the latter one will simply do another simulation from
245 * the node itself, no big deal. t->nodes_size may exceed
246 * the maximum in multi-threaded case but not by much so it's ok.
247 * The size test must be before the test&set not after, to allow
248 * expansion of the node later if enough nodes have been freed. */
249 if (n
->u
.playouts
>= u
->expand_p
&& t
->nodes_size
< u
->max_tree_size
250 && !__sync_lock_test_and_set(&n
->is_expanded
, 1)) {
251 tree_expand_node(t
, n
, b
, next_color
, u
, parity
);
254 fprintf(stderr
, "%s*-- UCT playout #%d start [%s] %f\n",
255 spaces
, n
->u
.playouts
, coord2sstr(n
->coord
, t
->board
),
256 tree_node_get_value(t
, parity
, n
->u
.value
));
258 struct uct_playout_callback upc
= {
261 /* TODO: Don't necessarily restart the sequence walk when
262 * entering playout. */
266 struct playout_setup ps
= {
267 .gamelen
= u
->gamelen
,
268 .mercymin
= u
->mercymin
,
269 .prepolicy_hook
= uct_playout_prepolicy
,
270 .postpolicy_hook
= uct_playout_postpolicy
,
273 int result
= play_random_game(&ps
, b
, next_color
,
274 u
->playout_amaf
? amaf
: NULL
,
275 &u
->ownermap
, u
->playout
);
276 if (next_color
== S_WHITE
) {
277 /* We need the result from black's perspective. */
281 fprintf(stderr
, "%s -- [%d..%d] %s random playout result %d\n",
282 spaces
, player_color
, next_color
, coord2sstr(n
->coord
, t
->board
), result
);
288 scale_value(struct uct
*u
, struct board
*b
, int result
)
290 floating_t rval
= result
> 0 ? 1.0 : result
< 0 ? 0.0 : 0.5;
291 if (u
->val_scale
&& result
!= 0) {
292 int vp
= u
->val_points
;
294 vp
= board_size(b
) - 1; vp
*= vp
; vp
*= 2;
297 floating_t sval
= (floating_t
) abs(result
) / vp
;
298 sval
= sval
> 1 ? 1 : sval
;
299 if (result
< 0) sval
= 1 - sval
;
301 rval
+= u
->val_scale
* sval
;
303 rval
= (1 - u
->val_scale
) * rval
+ u
->val_scale
* sval
;
304 // fprintf(stderr, "score %d => sval %f, rval %f\n", result, sval, rval);
310 record_local_sequence(struct uct
*u
, struct tree
*t
,
311 struct uct_descent
*descent
, int dlen
, int di
,
312 enum stone seq_color
, floating_t rval
)
314 #define LTREE_DEBUG if (UDEBUGL(6))
316 /* Ignore pass sequences. */
317 if (is_pass(descent
[di
].node
->coord
))
320 /* Transform the rval appropriately, based on the expected
321 * result at the root of the sequence. */
322 if (u
->local_tree_rootseqval
) {
323 float expval
= descent
[di
- 1].value
.value
;
324 rval
= stats_temper_value(rval
, expval
, u
->local_tree
);
327 LTREE_DEBUG
fprintf(stderr
, "recording result %f in local %s sequence: ",
328 rval
, stone2str(seq_color
));
330 /* Sequences starting deeper are less relevant in general. */
331 int pval
= LTREE_PLAYOUTS_MULTIPLIER
;
332 if (u
->local_tree
&& u
->local_tree_depth_decay
> 0)
333 pval
= ((floating_t
) pval
) / pow(u
->local_tree_depth_decay
, di
- 1);
335 LTREE_DEBUG
fprintf(stderr
, "too deep @%d\n", di
);
339 /* Pick the right local tree root... */
340 struct tree_node
*lnode
= seq_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
343 /* ...and record the sequence. */
345 while (di
< dlen
&& (di
== di0
|| descent
[di
].node
->d
< u
->tenuki_d
)) {
346 LTREE_DEBUG
fprintf(stderr
, "%s[%d] ",
347 coord2sstr(descent
[di
].node
->coord
, t
->board
),
348 descent
[di
].node
->d
);
349 lnode
= tree_get_node(t
, lnode
, descent
[di
++].node
->coord
, true);
351 stats_add_result(&lnode
->u
, rval
, pval
);
354 /* Add lnode for tenuki (pass) if we descended further. */
356 LTREE_DEBUG
fprintf(stderr
, "pass ");
357 lnode
= tree_get_node(t
, lnode
, pass
, true);
359 stats_add_result(&lnode
->u
, rval
, pval
);
362 LTREE_DEBUG
fprintf(stderr
, "\n");
367 uct_playout(struct uct
*u
, struct board
*b
, enum stone player_color
, struct tree
*t
)
372 struct playout_amafmap
*amaf
= NULL
;
373 if (u
->policy
->wants_amaf
) {
374 amaf
= calloc2(1, sizeof(*amaf
));
375 amaf
->map
= calloc2(board_size2(&b2
) + 1, sizeof(*amaf
->map
));
376 amaf
->map
++; // -1 is pass
379 /* Walk the tree until we find a leaf, then expand it and do
380 * a random playout. */
381 struct tree_node
*n
= t
->root
;
382 enum stone node_color
= stone_other(player_color
);
383 assert(node_color
== t
->root_color
);
385 /* Tree descent history. */
386 /* XXX: This is somewhat messy since @n and descent[dlen-1].node are
388 struct uct_descent descent
[DESCENT_DLEN
];
389 descent
[0].node
= n
; descent
[0].lnode
= NULL
;
391 /* Total value of the sequence. */
392 struct move_stats seq_value
= { .playouts
= 0 };
393 /* The last "significant" node along the descent (i.e. node
394 * with higher than configured number of playouts). For black
396 struct tree_node
*significant
[2] = { NULL
, NULL
};
397 if (n
->u
.playouts
>= u
->significant_threshold
)
398 significant
[node_color
- 1] = n
;
401 int pass_limit
= (board_size(&b2
) - 2) * (board_size(&b2
) - 2) / 2;
402 int passes
= is_pass(b
->last_move
.coord
) && b
->moves
> 0;
405 static char spaces
[] = "\0 ";
408 fprintf(stderr
, "--- UCT walk with color %d\n", player_color
);
410 while (!tree_leaf_node(n
) && passes
< 2) {
411 spaces
[dlen
- 1] = ' '; spaces
[dlen
] = 0;
414 /*** Choose a node to descend to: */
416 /* Parity is chosen already according to the child color, since
417 * it is applied to children. */
418 node_color
= stone_other(node_color
);
419 int parity
= (node_color
== player_color
? 1 : -1);
421 assert(dlen
< DESCENT_DLEN
);
422 descent
[dlen
] = descent
[dlen
- 1];
423 if (u
->local_tree
&& (!descent
[dlen
].lnode
|| descent
[dlen
].node
->d
>= u
->tenuki_d
)) {
424 /* Start new local sequence. */
425 /* Remember that node_color already holds color of the
426 * to-be-found child. */
427 descent
[dlen
].lnode
= node_color
== S_BLACK
? t
->ltree_black
: t
->ltree_white
;
430 if (!u
->random_policy_chance
|| fast_random(u
->random_policy_chance
))
431 u
->policy
->descend(u
->policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
433 u
->random_policy
->descend(u
->random_policy
, t
, &descent
[dlen
], parity
, b2
.moves
> pass_limit
);
436 /*** Perform the descent: */
438 if (descent
[dlen
].node
->u
.playouts
>= u
->significant_threshold
) {
439 significant
[node_color
- 1] = descent
[dlen
].node
;
442 seq_value
.playouts
+= descent
[dlen
].value
.playouts
;
443 seq_value
.value
+= descent
[dlen
].value
.value
* descent
[dlen
].value
.playouts
;
444 n
= descent
[dlen
++].node
;
445 assert(n
== t
->root
|| n
->parent
);
447 fprintf(stderr
, "%s+-- UCT sent us to [%s:%d] %d,%f\n",
448 spaces
, coord2sstr(n
->coord
, t
->board
),
449 n
->coord
, n
->u
.playouts
,
450 tree_node_get_value(t
, parity
, n
->u
.value
));
452 /* Add virtual loss if we need to; this is used to discourage
453 * other threads from visiting this node in case of multiple
454 * threads doing the tree search. */
456 stats_add_result(&n
->u
, node_color
== S_BLACK
? 0.0 : 1.0, u
->virtual_loss
);
458 assert(n
->coord
>= -1);
459 if (amaf
&& !is_pass(n
->coord
))
460 record_amaf_move(amaf
, n
->coord
, node_color
);
462 struct move m
= { n
->coord
, node_color
};
463 int res
= board_play(&b2
, &m
);
465 if (res
< 0 || (!is_pass(m
.coord
) && !group_at(&b2
, m
.coord
)) /* suicide */
466 || b2
.superko_violation
) {
468 for (struct tree_node
*ni
= n
; ni
; ni
= ni
->parent
)
469 fprintf(stderr
, "%s<%"PRIhash
"> ", coord2sstr(ni
->coord
, t
->board
), ni
->hash
);
470 fprintf(stderr
, "marking invalid %s node %d,%d res %d group %d spk %d\n",
471 stone2str(node_color
), coord_x(n
->coord
,b
), coord_y(n
->coord
,b
),
472 res
, group_at(&b2
, m
.coord
), b2
.superko_violation
);
474 n
->hints
|= TREE_HINT_INVALID
;
479 if (is_pass(n
->coord
))
486 amaf
->game_baselen
= amaf
->gamelen
;
487 amaf
->record_nakade
= u
->playout_amaf_nakade
;
490 if (t
->use_extra_komi
&& u
->dynkomi
->persim
) {
491 b2
.komi
+= round(u
->dynkomi
->persim(u
->dynkomi
, &b2
, t
, n
));
495 /* XXX: No dead groups support. */
496 floating_t score
= board_official_score(&b2
, NULL
);
497 /* Result from black's perspective (no matter who
498 * the player; black's perspective is always
499 * what the tree stores. */
500 result
= - (score
* 2);
503 fprintf(stderr
, "[%d..%d] %s p-p scoring playout result %d (W %f)\n",
504 player_color
, node_color
, coord2sstr(n
->coord
, t
->board
), result
, score
);
506 board_print(&b2
, stderr
);
508 board_ownermap_fill(&u
->ownermap
, &b2
);
510 } else { // assert(tree_leaf_node(n));
511 /* In case of parallel tree search, the assertion might
512 * not hold if two threads chew on the same node. */
513 result
= uct_leaf_node(u
, &b2
, player_color
, amaf
, descent
, &dlen
, significant
, t
, n
, node_color
, spaces
);
516 if (amaf
&& u
->playout_amaf_cutoff
) {
517 unsigned int cutoff
= amaf
->game_baselen
;
518 cutoff
+= (amaf
->gamelen
- amaf
->game_baselen
) * u
->playout_amaf_cutoff
/ 100;
519 /* Now, reconstruct the amaf map. */
520 memset(amaf
->map
, 0, board_size2(&b2
) * sizeof(*amaf
->map
));
521 for (unsigned int i
= 0; i
< cutoff
; i
++) {
522 coord_t coord
= amaf
->game
[i
].coord
;
523 enum stone color
= amaf
->game
[i
].color
;
524 if (amaf
->map
[coord
] == S_NONE
|| amaf
->map
[coord
] == color
) {
525 amaf
->map
[coord
] = color
;
526 /* Nakade always recorded for in-tree part */
527 } else if (amaf
->record_nakade
|| i
<= amaf
->game_baselen
) {
528 amaf_op(amaf
->map
[n
->coord
], +);
533 /* Record the result. */
535 assert(n
== t
->root
|| n
->parent
);
536 floating_t rval
= scale_value(u
, b
, result
);
537 u
->policy
->update(u
->policy
, t
, n
, node_color
, player_color
, amaf
, &b2
, rval
);
539 if (t
->use_extra_komi
) {
540 stats_add_result(&u
->dynkomi
->score
, result
/ 2, 1);
541 stats_add_result(&u
->dynkomi
->value
, rval
, 1);
544 if (u
->local_tree
&& n
->parent
&& !is_pass(n
->coord
) && dlen
> 0) {
545 /* Possibly transform the rval appropriately. */
546 if (!u
->local_tree_rootseqval
) {
547 floating_t expval
= seq_value
.value
/ seq_value
.playouts
;
548 rval
= stats_temper_value(rval
, expval
, u
->local_tree
);
551 /* Get the local sequences and record them in ltree. */
552 /* We will look for sequence starts in our descent
553 * history, then run record_local_sequence() for each
554 * found sequence start; record_local_sequence() may
555 * pick longer sequences from descent history then,
556 * which is expected as it will create new lnodes. */
557 enum stone seq_color
= player_color
;
558 /* First move always starts a sequence. */
559 record_local_sequence(u
, t
, descent
, dlen
, 1, seq_color
, rval
);
560 seq_color
= stone_other(seq_color
);
561 for (int dseqi
= 2; dseqi
< dlen
; dseqi
++, seq_color
= stone_other(seq_color
)) {
562 if (u
->local_tree_allseq
) {
563 /* We are configured to record all subsequences. */
564 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
567 if (descent
[dseqi
].node
->d
>= u
->tenuki_d
) {
568 /* Tenuki! Record the fresh sequence. */
569 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
572 if (descent
[dseqi
].lnode
&& !descent
[dseqi
].lnode
) {
573 /* Record result for in-descent picked sequence. */
574 record_local_sequence(u
, t
, descent
, dlen
, dseqi
, seq_color
, rval
);
581 /* We need to undo the virtual loss we added during descend. */
582 if (u
->virtual_loss
) {
583 floating_t loss
= node_color
== S_BLACK
? 0.0 : 1.0;
584 for (; n
->parent
; n
= n
->parent
) {
585 stats_rm_result(&n
->u
, loss
, u
->virtual_loss
);
594 board_done_noalloc(&b2
);
599 uct_playouts(struct uct
*u
, struct board
*b
, enum stone color
, struct tree
*t
, struct time_info
*ti
)
602 if (ti
&& ti
->dim
== TD_GAMES
) {
603 for (i
= 0; t
->root
->u
.playouts
<= ti
->len
.games
; i
++)
604 uct_playout(u
, b
, color
, t
);
606 for (i
= 0; !uct_halt
; i
++)
607 uct_playout(u
, b
, color
, t
);