UCT Linear Adaptive Dynkomi: Actually update previous value
[pachi.git] / uct / dynkomi.c
blob2190ae499d8bc7c86aed04589b31a63e3a738bb7
1 #define DEBUG
2 #include <assert.h>
3 #include <math.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
8 #include "board.h"
9 #include "debug.h"
10 #include "tactics/util.h"
11 #include "uct/dynkomi.h"
12 #include "uct/internal.h"
13 #include "uct/tree.h"
16 static void
17 generic_done(struct uct_dynkomi *d)
19 if (d->data) free(d->data);
20 free(d);
24 /* NONE dynkomi strategy - never fiddle with komi values. */
26 struct uct_dynkomi *
27 uct_dynkomi_init_none(struct uct *u, char *arg, struct board *b)
29 struct uct_dynkomi *d = calloc2(1, sizeof(*d));
30 d->uct = u;
31 d->permove = NULL;
32 d->persim = NULL;
33 d->done = generic_done;
34 d->data = NULL;
36 if (arg) {
37 fprintf(stderr, "uct: Dynkomi method none accepts no arguments\n");
38 exit(1);
41 return d;
45 /* LINEAR dynkomi strategy - Linearly Decreasing Handicap Compensation. */
46 /* At move 0, we impose extra komi of handicap_count*handicap_value, then
47 * we linearly decrease this extra komi throughout the game down to 0
48 * at @moves moves. Towards the end of the game the linear compensation
49 * becomes zero but we increase the extra komi when winning big. This reduces
50 * the number of point-wasting moves and makes the game more enjoyable for humans. */
52 struct dynkomi_linear {
53 int handicap_value[S_MAX];
54 int moves[S_MAX];
55 bool rootbased;
56 /* Increase the extra komi if my win ratio > green_zone but always
57 * keep extra_komi <= komi_ratchet. komi_ratchet starts infinite but decreases
58 * when we give too much extra komi and this puts us back < orange_zone.
59 * This is meant only to increase the territory margin when playing against
60 * weaker opponents. We never take negative komi when losing. The ratchet helps
61 * avoiding oscillations and keeping us above orange_zone.
62 * To disable the adaptive phase, set green_zone=2. */
63 floating_t komi_ratchet;
64 floating_t green_zone;
65 floating_t orange_zone;
66 floating_t drop_step;
69 static floating_t
70 linear_permove(struct uct_dynkomi *d, struct board *b, struct tree *tree)
72 struct dynkomi_linear *l = d->data;
73 enum stone color = d->uct->pondering ? tree->root_color : stone_other(tree->root_color);
74 int lmoves = l->moves[color];
75 floating_t extra_komi;
77 if (b->moves < lmoves) {
78 floating_t base_komi = board_effective_handicap(b, l->handicap_value[color]);
79 extra_komi = base_komi * (lmoves - b->moves) / lmoves;
80 return extra_komi;
81 } else {
82 extra_komi = floor(tree->extra_komi);
85 /* Do not take decisions on unstable value. */
86 if (tree->root->u.playouts < GJ_MINGAMES) return extra_komi;
88 floating_t my_value = tree_node_get_value(tree, 1, tree->root->u.value);
89 /* We normalize komi as in komi_by_value(), > 0 when winning. */
90 extra_komi = komi_by_color(extra_komi, color);
91 assert(extra_komi >= 0);
93 if (my_value < 0.5 && l->komi_ratchet > 0 && l->komi_ratchet != INFINITY) {
94 if (DEBUGL(0))
95 fprintf(stderr, "losing %f extra %.1f ratchet %.1f -> 0\n",
96 my_value, extra_komi, l->komi_ratchet);
97 /* Disable dynkomi completely, too dangerous in this game. */
98 extra_komi = l->komi_ratchet = 0;
100 } else if (my_value < l->orange_zone && extra_komi > 0) {
101 extra_komi = l->komi_ratchet = fmax(extra_komi - l->drop_step, 0.0);
102 if (DEBUGL(3))
103 fprintf(stderr, "dropping to %f ratchet -> %.1f\n",
104 my_value, extra_komi);
106 } else if (my_value > l->green_zone && extra_komi +1 <= l->komi_ratchet) {
107 extra_komi += 1;
108 if (DEBUGL(3))
109 fprintf(stderr, "winning %f extra_komi -> %.1f, ratchet %.1f\n",
110 my_value, extra_komi, l->komi_ratchet);
112 return komi_by_color(extra_komi, color);
115 static floating_t
116 linear_persim(struct uct_dynkomi *d, struct board *b, struct tree *tree, struct tree_node *node)
118 struct dynkomi_linear *l = d->data;
119 if (l->rootbased)
120 return tree->extra_komi;
121 /* We don't reuse computed value from tree->extra_komi,
122 * since we want to use value correct for this node depth.
123 * This also means the values will stay correct after
124 * node promotion. */
125 return linear_permove(d, b, tree);
128 struct uct_dynkomi *
129 uct_dynkomi_init_linear(struct uct *u, char *arg, struct board *b)
131 struct uct_dynkomi *d = calloc2(1, sizeof(*d));
132 d->uct = u;
133 d->permove = linear_permove;
134 d->persim = linear_persim;
135 d->done = generic_done;
137 struct dynkomi_linear *l = calloc2(1, sizeof(*l));
138 d->data = l;
140 /* Force white to feel behind and try harder, but not to the
141 * point of resigning immediately in high handicap games.
142 * By move 100 white should still be behind but should have
143 * caught up enough to avoid resigning. */
144 if (board_large(b)) {
145 l->moves[S_BLACK] = 100;
146 l->moves[S_WHITE] = 50;
148 /* The real value of one stone is twice the komi so about 15 points.
149 * But use a lower value to avoid being too pessimistic as black
150 * or too optimistic as white. */
151 l->handicap_value[S_BLACK] = 8;
152 l->handicap_value[S_WHITE] = 1;
154 l->komi_ratchet = INFINITY;
155 l->green_zone = 0.85;
156 l->orange_zone = 0.8;
157 l->drop_step = 4.0;
159 if (arg) {
160 char *optspec, *next = arg;
161 while (*next) {
162 optspec = next;
163 next += strcspn(next, ":");
164 if (*next) { *next++ = 0; } else { *next = 0; }
166 char *optname = optspec;
167 char *optval = strchr(optspec, '=');
168 if (optval) *optval++ = 0;
170 if (!strcasecmp(optname, "moves") && optval) {
171 /* Dynamic komi in handicap game; linearly
172 * decreases to basic settings until move
173 * #optval. moves=blackmoves%whitemoves */
174 for (int i = S_BLACK; *optval && i <= S_WHITE; i++) {
175 l->moves[i] = atoi(optval);
176 optval += strcspn(optval, "%");
177 if (*optval) optval++;
179 } else if (!strcasecmp(optname, "handicap_value") && optval) {
180 /* Point value of single handicap stone,
181 * for dynkomi computation. */
182 for (int i = S_BLACK; *optval && i <= S_WHITE; i++) {
183 l->handicap_value[i] = atoi(optval);
184 optval += strcspn(optval, "%");
185 if (*optval) optval++;
187 } else if (!strcasecmp(optname, "rootbased")) {
188 /* If set, the extra komi applied will be
189 * the same for all simulations within a move,
190 * instead of being same for all simulations
191 * within the tree node. */
192 l->rootbased = !optval || atoi(optval);
193 } else if (!strcasecmp(optname, "green_zone") && optval) {
194 /* Increase komi when win ratio is above green_zone */
195 l->green_zone = atof(optval);
196 } else if (!strcasecmp(optname, "orange_zone") && optval) {
197 /* Decrease komi when > 0 and win ratio is below orange_zone */
198 l->orange_zone = atof(optval);
199 } else if (!strcasecmp(optname, "drop_step") && optval) {
200 /* Decrease komi by drop_step points */
201 l->drop_step = atof(optval);
202 } else {
203 fprintf(stderr, "uct: Invalid dynkomi argument %s or missing value\n", optname);
204 exit(1);
209 return d;
213 /* ADAPTIVE dynkomi strategy - Adaptive Situational Compensation */
214 /* We adapt the komi based on current situation:
215 * (i) score-based: We maintain the average score outcome of our
216 * games and adjust the komi by a fractional step towards the expected
217 * score;
218 * (ii) value-based: While winrate is above given threshold, adjust
219 * the komi by a fixed step in the appropriate direction.
220 * These adjustments can be
221 * (a) Move-stepped, new extra komi value is always set only at the
222 * beginning of the tree search for next move;
223 * (b) Continuous, new extra komi value is periodically re-determined
224 * and adjusted throughout a single tree search. */
226 struct dynkomi_adaptive {
227 /* Do not take measured average score into regard for
228 * first @lead_moves - the variance is just too much.
229 * (Instead, we consider the handicap-based komi provided
230 * by linear dynkomi.) */
231 int lead_moves;
232 /* Maximum komi to pretend the opponent to give. */
233 floating_t max_losing_komi;
234 /* Game portion at which losing komi is not allowed anymore. */
235 floating_t losing_komi_stop;
236 /* Alternative game portion determination. */
237 bool adapt_aport;
238 floating_t (*indicator)(struct uct_dynkomi *d, struct board *b, struct tree *tree, enum stone color);
240 /* Value-based adaptation. */
241 floating_t zone_red, zone_green;
242 int score_step;
243 floating_t score_step_byavg; // use portion of average score as increment
244 bool use_komi_ratchet;
245 bool losing_komi_ratchet; // ratchet even losing komi
246 int komi_ratchet_maxage;
247 // runtime, not configuration:
248 int komi_ratchet_age;
249 floating_t komi_ratchet;
251 /* Score-based adaptation. */
252 floating_t (*adapter)(struct uct_dynkomi *d, struct board *b);
253 floating_t adapt_base; // [0,1)
254 /* Sigmoid adaptation rate parameter; see below for details. */
255 floating_t adapt_phase; // [0,1]
256 floating_t adapt_rate; // [1,infty)
257 /* Linear adaptation rate parameter. */
258 int adapt_moves;
259 floating_t adapt_dir; // [-1,1]
261 #define TRUSTWORTHY_KOMI_PLAYOUTS 200
263 static floating_t
264 board_game_portion(struct dynkomi_adaptive *a, struct board *b)
266 if (!a->adapt_aport) {
267 int total_moves = b->moves + 2 * board_estimated_moves_left(b);
268 return (floating_t) b->moves / total_moves;
269 } else {
270 int brsize = board_size(b) - 2;
271 return 1.0 - (floating_t) b->flen / (brsize * brsize);
275 static floating_t
276 adapter_sigmoid(struct uct_dynkomi *d, struct board *b)
278 struct dynkomi_adaptive *a = d->data;
279 /* Figure out how much to adjust the komi based on the game
280 * stage. The adaptation rate is 0 at the beginning,
281 * at game stage a->adapt_phase crosses though 0.5 and
282 * approaches 1 at the game end; the slope is controlled
283 * by a->adapt_rate. */
284 floating_t game_portion = board_game_portion(a, b);
285 floating_t l = game_portion - a->adapt_phase;
286 return 1.0 / (1.0 + exp(-a->adapt_rate * l));
289 static floating_t
290 adapter_linear(struct uct_dynkomi *d, struct board *b)
292 struct dynkomi_adaptive *a = d->data;
293 /* Figure out how much to adjust the komi based on the game
294 * stage. We just linearly increase/decrease the adaptation
295 * rate for first N moves. */
296 if (b->moves > a->adapt_moves)
297 return 0;
298 if (a->adapt_dir < 0)
299 return 1 - (- a->adapt_dir) * b->moves / a->adapt_moves;
300 else
301 return a->adapt_dir * b->moves / a->adapt_moves;
304 static floating_t
305 komi_by_score(struct uct_dynkomi *d, struct board *b, struct tree *tree, enum stone color)
307 struct dynkomi_adaptive *a = d->data;
308 if (d->score.playouts < TRUSTWORTHY_KOMI_PLAYOUTS)
309 return tree->extra_komi;
311 struct move_stats score = d->score;
312 /* Almost-reset tree->score to gather fresh stats. */
313 d->score.playouts = 1;
315 /* Look at average score and push extra_komi in that direction. */
316 floating_t p = a->adapter(d, b);
317 p = a->adapt_base + p * (1 - a->adapt_base);
318 if (p > 0.9) p = 0.9; // don't get too eager!
319 floating_t extra_komi = tree->extra_komi + p * score.value;
320 if (DEBUGL(3))
321 fprintf(stderr, "mC += %f * %f\n", p, score.value);
322 return extra_komi;
325 static floating_t
326 komi_by_value(struct uct_dynkomi *d, struct board *b, struct tree *tree, enum stone color)
328 struct dynkomi_adaptive *a = d->data;
329 if (d->value.playouts < TRUSTWORTHY_KOMI_PLAYOUTS)
330 return tree->extra_komi;
332 struct move_stats value = d->value;
333 /* Almost-reset tree->value to gather fresh stats. */
334 d->value.playouts = 1;
335 /* Correct color POV. */
336 if (color == S_WHITE)
337 value.value = 1 - value.value;
339 /* We have three "value zones":
340 * red zone | yellow zone | green zone
341 * ~45% ~60%
342 * red zone: reduce komi
343 * yellow zone: do not touch komi
344 * green zone: enlage komi.
346 * Also, at some point komi will be tuned in such way
347 * that it will be in green zone but increasing it will
348 * be unfeasible. Thus, we have a _ratchet_ - we will
349 * remember the last komi that has put us into the
350 * red zone, and not use it or go over it. We use the
351 * ratchet only when giving extra komi, we always want
352 * to try to reduce extra komi we take.
354 * TODO: Make the ratchet expire after a while. */
356 /* We use komi_by_color() first to normalize komi
357 * additions/subtractions, then apply it again on
358 * return value to restore original komi parity. */
359 /* Positive extra_komi means that we are _giving_
360 * komi (winning), negative extra_komi is _taking_
361 * komi (losing). */
362 floating_t extra_komi = komi_by_color(tree->extra_komi, color);
363 int score_step_red = -a->score_step;
364 int score_step_green = a->score_step;
366 if (a->score_step_byavg != 0) {
367 struct move_stats score = d->score;
368 /* Almost-reset tree->score to gather fresh stats. */
369 d->score.playouts = 1;
370 /* Correct color POV. */
371 if (color == S_WHITE)
372 score.value = - score.value;
373 if (score.value > 0)
374 score_step_green = round(score.value * a->score_step_byavg);
375 else
376 score_step_red = round(-score.value * a->score_step_byavg);
377 if (score_step_green < 0 || score_step_red > 0) {
378 /* The steps are in bad direction - keep still. */
379 return komi_by_color(extra_komi, color);
383 /* Wear out the ratchet. */
384 if (a->use_komi_ratchet && a->komi_ratchet_maxage > 0) {
385 a->komi_ratchet_age += value.playouts;
386 if (a->komi_ratchet_age > a->komi_ratchet_maxage) {
387 a->komi_ratchet = 1000;
388 a->komi_ratchet_age = 0;
392 if (value.value < a->zone_red) {
393 /* Red zone. Take extra komi. */
394 if (DEBUGL(3))
395 fprintf(stderr, "[red] %f, step %d | komi ratchet %f age %d/%d -> %f\n",
396 value.value, score_step_red, a->komi_ratchet, a->komi_ratchet_age, a->komi_ratchet_maxage, extra_komi);
397 if (a->losing_komi_ratchet || extra_komi > 0) {
398 a->komi_ratchet = extra_komi;
399 a->komi_ratchet_age = 0;
401 extra_komi += score_step_red;
402 return komi_by_color(extra_komi, color);
404 } else if (value.value < a->zone_green) {
405 /* Yellow zone, do nothing. */
406 return komi_by_color(extra_komi, color);
408 } else {
409 /* Green zone. Give extra komi. */
410 if (DEBUGL(3))
411 fprintf(stderr, "[green] %f, step %d | komi ratchet %f age %d/%d\n",
412 value.value, score_step_green, a->komi_ratchet, a->komi_ratchet_age, a->komi_ratchet_maxage);
413 extra_komi += score_step_green;
414 if (a->use_komi_ratchet && extra_komi >= a->komi_ratchet)
415 extra_komi = a->komi_ratchet - 1;
416 return komi_by_color(extra_komi, color);
420 static floating_t
421 bounded_komi(struct dynkomi_adaptive *a, struct board *b,
422 enum stone color, floating_t komi, floating_t max_losing_komi)
424 /* At the end of game, disallow losing komi. */
425 if (komi_by_color(komi, color) < 0
426 && board_game_portion(a, b) > a->losing_komi_stop)
427 return 0;
429 /* Get lower bound on komi we take so that we don't underperform
430 * too much. */
431 floating_t min_komi = komi_by_color(- max_losing_komi, color);
433 if (komi_by_color(komi - min_komi, color) > 0)
434 return komi;
435 else
436 return min_komi;
439 static floating_t
440 adaptive_permove(struct uct_dynkomi *d, struct board *b, struct tree *tree)
442 /* We do not use extra komi at the game end - we are not
443 * to fool ourselves at this point. */
444 if (board_estimated_moves_left(b) <= MIN_MOVES_LEFT) {
445 tree->use_extra_komi = false;
446 return 0;
448 struct dynkomi_adaptive *a = d->data;
449 enum stone color = stone_other(tree->root_color);
450 if (DEBUGL(3))
451 fprintf(stderr, "m %d/%d ekomi %f permove %f/%d\n",
452 b->moves, a->lead_moves, tree->extra_komi,
453 d->score.value, d->score.playouts);
455 if (b->moves <= a->lead_moves)
456 return bounded_komi(a, b, color,
457 board_effective_handicap(b, 7 /* XXX */),
458 a->max_losing_komi);
460 floating_t komi = a->indicator(d, b, tree, color);
461 if (DEBUGL(3))
462 fprintf(stderr, "dynkomi: %f -> %f\n", tree->extra_komi, komi);
463 return bounded_komi(a, b, color, komi, a->max_losing_komi);
466 static floating_t
467 adaptive_persim(struct uct_dynkomi *d, struct board *b, struct tree *tree, struct tree_node *node)
469 return tree->extra_komi;
472 struct uct_dynkomi *
473 uct_dynkomi_init_adaptive(struct uct *u, char *arg, struct board *b)
475 struct uct_dynkomi *d = calloc2(1, sizeof(*d));
476 d->uct = u;
477 d->permove = adaptive_permove;
478 d->persim = adaptive_persim;
479 d->done = generic_done;
481 struct dynkomi_adaptive *a = calloc2(1, sizeof(*a));
482 d->data = a;
484 a->lead_moves = board_large(b) ? 20 : 4; // XXX
485 a->max_losing_komi = 30;
486 a->losing_komi_stop = 1.0f;
487 a->indicator = komi_by_value;
489 a->adapter = adapter_sigmoid;
490 a->adapt_rate = -18;
491 a->adapt_phase = 0.65;
492 a->adapt_moves = 200;
493 a->adapt_dir = -0.5;
495 a->zone_red = 0.45;
496 a->zone_green = 0.50;
497 a->score_step = 1;
498 a->use_komi_ratchet = true;
499 a->komi_ratchet_maxage = 0;
500 a->komi_ratchet = 1000;
502 if (arg) {
503 char *optspec, *next = arg;
504 while (*next) {
505 optspec = next;
506 next += strcspn(next, ":");
507 if (*next) { *next++ = 0; } else { *next = 0; }
509 char *optname = optspec;
510 char *optval = strchr(optspec, '=');
511 if (optval) *optval++ = 0;
513 if (!strcasecmp(optname, "lead_moves") && optval) {
514 /* Do not adjust komi adaptively for first
515 * N moves. */
516 a->lead_moves = atoi(optval);
517 } else if (!strcasecmp(optname, "max_losing_komi") && optval) {
518 a->max_losing_komi = atof(optval);
519 } else if (!strcasecmp(optname, "losing_komi_stop") && optval) {
520 a->losing_komi_stop = atof(optval);
521 } else if (!strcasecmp(optname, "indicator")) {
522 /* Adaptatation indicator - how to decide
523 * the adaptation rate and direction. */
524 if (!strcasecmp(optval, "value")) {
525 /* Winrate w/ komi so far. */
526 a->indicator = komi_by_value;
527 } else if (!strcasecmp(optval, "score")) {
528 /* Expected score w/ current komi. */
529 a->indicator = komi_by_score;
530 } else {
531 fprintf(stderr, "UCT: Invalid indicator %s\n", optval);
532 exit(1);
535 /* value indicator settings */
536 } else if (!strcasecmp(optname, "zone_red") && optval) {
537 a->zone_red = atof(optval);
538 } else if (!strcasecmp(optname, "zone_green") && optval) {
539 a->zone_green = atof(optval);
540 } else if (!strcasecmp(optname, "score_step") && optval) {
541 a->score_step = atoi(optval);
542 } else if (!strcasecmp(optname, "score_step_byavg") && optval) {
543 a->score_step_byavg = atof(optval);
544 } else if (!strcasecmp(optname, "use_komi_ratchet")) {
545 a->use_komi_ratchet = !optval || atoi(optval);
546 } else if (!strcasecmp(optname, "losing_komi_ratchet")) {
547 a->losing_komi_ratchet = !optval || atoi(optval);
548 } else if (!strcasecmp(optname, "komi_ratchet_age") && optval) {
549 a->komi_ratchet_maxage = atoi(optval);
551 /* score indicator settings */
552 } else if (!strcasecmp(optname, "adapter") && optval) {
553 /* Adaptatation method. */
554 if (!strcasecmp(optval, "sigmoid")) {
555 a->adapter = adapter_sigmoid;
556 } else if (!strcasecmp(optval, "linear")) {
557 a->adapter = adapter_linear;
558 } else {
559 fprintf(stderr, "UCT: Invalid adapter %s\n", optval);
560 exit(1);
562 } else if (!strcasecmp(optname, "adapt_base") && optval) {
563 /* Adaptation base rate; see above. */
564 a->adapt_base = atof(optval);
565 } else if (!strcasecmp(optname, "adapt_rate") && optval) {
566 /* Adaptation slope; see above. */
567 a->adapt_rate = atof(optval);
568 } else if (!strcasecmp(optname, "adapt_phase") && optval) {
569 /* Adaptation phase shift; see above. */
570 a->adapt_phase = atof(optval);
571 } else if (!strcasecmp(optname, "adapt_moves") && optval) {
572 /* Adaptation move amount; see above. */
573 a->adapt_moves = atoi(optval);
574 } else if (!strcasecmp(optname, "adapt_aport")) {
575 a->adapt_aport = !optval || atoi(optval);
576 } else if (!strcasecmp(optname, "adapt_dir") && optval) {
577 /* Adaptation direction vector; see above. */
578 a->adapt_dir = atof(optval);
580 } else {
581 fprintf(stderr, "uct: Invalid dynkomi argument %s or missing value\n", optname);
582 exit(1);
587 return d;