|
| 1 | +# tag::alphago_imports[] |
| 2 | +import numpy as np |
| 3 | +from dlgo.agent.base import Agent |
| 4 | +from dlgo.goboard_fast import Move |
| 5 | +from dlgo import kerasutil |
| 6 | +import operator |
| 7 | +# end::alphago_imports[] |
| 8 | + |
| 9 | + |
| 10 | +__all__ = [ |
| 11 | + 'AlphaGoNode', |
| 12 | + 'AlphaGoMCTS' |
| 13 | +] |
| 14 | + |
| 15 | + |
| 16 | +# tag::init_alphago_node[] |
| 17 | +class AlphaGoNode: |
| 18 | + def __init__(self, parent=None, probability=1.0): |
| 19 | + self.parent = parent # <1> |
| 20 | + self.children = {} # <1> |
| 21 | + |
| 22 | + self.visit_count = 0 |
| 23 | + self.q_value = 0 |
| 24 | + self.prior_value = probability # <2> |
| 25 | + self.u_value = probability # <3> |
| 26 | +# <1> Tree nodes have one parent and potentially many children. |
| 27 | +# <2> A node is initialized with a prior probability. |
| 28 | +# <3> The utility function will be updated during search. |
| 29 | +# end::init_alphago_node[] |
| 30 | + |
| 31 | +# tag::select_node[] |
| 32 | + def select_child(self): |
| 33 | + return max(self.children.items(), |
| 34 | + key=lambda child: child[1].q_value + \ |
| 35 | + child[1].u_value) |
| 36 | +# end::select_node[] |
| 37 | + |
| 38 | +# tag::expand_children[] |
| 39 | + def expand_children(self, moves, probabilities): |
| 40 | + for move, prob in zip(moves, probabilities): |
| 41 | + if move not in self.children: |
| 42 | + self.children[move] = AlphaGoNode(probability=prob) |
| 43 | +# end::expand_children[] |
| 44 | + |
| 45 | +# tag::update_values[] |
| 46 | + def update_values(self, leaf_value): |
| 47 | + if self.parent is not None: |
| 48 | + self.parent.update_values(leaf_value) # <1> |
| 49 | + |
| 50 | + self.visit_count += 1 # <2> |
| 51 | + |
| 52 | + self.q_value += leaf_value / self.visit_count # <3> |
| 53 | + |
| 54 | + if self.parent is not None: |
| 55 | + c_u = 5 |
| 56 | + self.u_value = c_u * np.sqrt(self.parent.visit_count) \ |
| 57 | + * self.prior_value / (1 + self.visit_count) # <4> |
| 58 | + |
| 59 | +# <1> We update parents first to ensure we traverse the tree top to bottom. |
| 60 | +# <2> Increment the visit count for this node. |
| 61 | +# <3> Add the specified leaf value to the Q-value, normalized by visit count. |
| 62 | +# <4> Update utility with current visit counts. |
| 63 | +# end::update_values[] |
| 64 | + |
| 65 | + |
| 66 | +# tag::alphago_mcts_init[] |
| 67 | +class AlphaGoMCTS(Agent): |
| 68 | + def __init__(self, policy_agent, fast_policy_agent, value_agent, |
| 69 | + lambda_value=0.5, num_simulations=1000, |
| 70 | + depth=50, rollout_limit=100): |
| 71 | + self.policy = policy_agent |
| 72 | + self.rollout_policy = fast_policy_agent |
| 73 | + self.value = value_agent |
| 74 | + |
| 75 | + self.lambda_value = lambda_value |
| 76 | + self.num_simulations = num_simulations |
| 77 | + self.depth = depth |
| 78 | + self.rollout_limit = rollout_limit |
| 79 | + self.root = AlphaGoNode() |
| 80 | +# end::alphago_mcts_init[] |
| 81 | + |
| 82 | +# tag::alphago_mcts_rollout[] |
| 83 | + def select_move(self, game_state): |
| 84 | + for simulation in range(self.num_simulations): # <1> |
| 85 | + current_state = game_state |
| 86 | + node = self.root |
| 87 | + for depth in range(self.depth): # <2> |
| 88 | + if not node.children: # <3> |
| 89 | + if current_state.is_over(): |
| 90 | + break |
| 91 | + moves, probabilities = self.policy_probabilities(current_state) # <4> |
| 92 | + node.expand_children(moves, probabilities) # <4> |
| 93 | + |
| 94 | + move, node = node.select_child() # <5> |
| 95 | + current_state = current_state.apply_move(move) # <5> |
| 96 | + |
| 97 | + value = self.value.predict(current_state) # <6> |
| 98 | + rollout = self.policy_rollout(current_state) # <6> |
| 99 | + |
| 100 | + weighted_value = (1 - self.lambda_value) * value + \ |
| 101 | + self.lambda_value * rollout # <7> |
| 102 | + |
| 103 | + node.update_values(weighted_value) # <8> |
| 104 | +# <1> From current state play out a number of simulations |
| 105 | +# <2> Play moves until the specified depth is reached. |
| 106 | +# <3> If the current node doesn't have any children... |
| 107 | +# <4> ... expand them with probabilities from the strong policy. |
| 108 | +# <5> If there are children, we can select one and play the corresponding move. |
| 109 | +# <6> Compute output of value network and a rollout by the fast policy. |
| 110 | +# <7> Determine the combined value function. |
| 111 | +# <8> Update values for this node in the backup phase |
| 112 | +# end::alphago_mcts_rollout[] |
| 113 | + |
| 114 | +# tag::alphago_mcts_selection[] |
| 115 | + move = max(self.root.children, key=lambda move: # <1> |
| 116 | + self.root.children.get(move).visit_count) # <1> |
| 117 | + |
| 118 | + self.root = AlphaGoNode() |
| 119 | + if move in self.root.children: # <2> |
| 120 | + self.root = self.root.children[move] |
| 121 | + self.root.parent = None |
| 122 | + |
| 123 | + return move |
| 124 | +# <1> Pick most visited child of the root as next move. |
| 125 | +# <2> If the picked move is a child, set new root to this child node. |
| 126 | +# end::alphago_mcts_selection[] |
| 127 | + |
| 128 | +# tag::alphago_policy_probs[] |
| 129 | + def policy_probabilities(self, game_state): |
| 130 | + encoder = self.policy._encoder |
| 131 | + outputs = self.policy.predict(game_state) |
| 132 | + legal_moves = game_state.legal_moves() |
| 133 | + if not legal_moves: |
| 134 | + return [], [] |
| 135 | + encoded_points = [encoder.encode_point(move.point) for move in legal_moves if move.point] |
| 136 | + legal_outputs = outputs[encoded_points] |
| 137 | + normalized_outputs = legal_outputs / np.sum(legal_outputs) |
| 138 | + return legal_moves, normalized_outputs |
| 139 | +# end::alphago_policy_probs[] |
| 140 | + |
| 141 | +# tag::alphago_policy_rollout[] |
| 142 | + def policy_rollout(self, game_state): |
| 143 | + for step in range(self.rollout_limit): |
| 144 | + if game_state.is_over(): |
| 145 | + break |
| 146 | + move_probabilities = self.rollout_policy.predict(game_state) |
| 147 | + encoder = self.rollout_policy.encoder |
| 148 | + valid_moves = [m for idx, m in enumerate(move_probabilities) |
| 149 | + if Move(encoder.decode_point_index(idx)) in game_state.legal_moves()] |
| 150 | + max_index, max_value = max(enumerate(valid_moves), key=operator.itemgetter(1)) |
| 151 | + max_point = encoder.decode_point_index(max_index) |
| 152 | + greedy_move = Move(max_point) |
| 153 | + if greedy_move in game_state.legal_moves(): |
| 154 | + game_state = game_state.apply_move(greedy_move) |
| 155 | + |
| 156 | + next_player = game_state.next_player |
| 157 | + winner = game_state.winner() |
| 158 | + if winner is not None: |
| 159 | + return 1 if winner == next_player else -1 |
| 160 | + else: |
| 161 | + return 0 |
| 162 | +# end::alphago_policy_rollout[] |
| 163 | + |
| 164 | + |
| 165 | + def serialize(self, h5file): |
| 166 | + raise IOError("AlphaGoMCTS agent can\'t be serialized" + |
| 167 | + "consider serializing the three underlying" + |
| 168 | + "neural networks instad.") |
0 commit comments