Back up a playout value through an MCTS path with alternating players
After a Monte Carlo tree search playout, the result is pushed back up the path from the leaf to the root. In a two-player game a win for one player is a loss for the other, so the sign flips at every level.
Write backup(stats, path, value). stats is a dict node -> [visits, value_sum]. path is the list of nodes from root to leaf. value is the playout result from the point of view of the player who made the move INTO the leaf (the last node in path).
- Walk the path from the leaf back to the root.
- The leaf gets +value, its parent -value, the next one up +value again, and so on.
- Each node on the path gets visits += 1 and value_sum += its signed value.
- Nodes missing from stats start at [0, 0.0].
Return a new dict (do not change the input) with every node's [visits, value_sum].
def backup(stats, path, value)Example
backup({}, ["r", "a"], 1.0) returns {"r": [1, -1.0], "a": [1, 1.0]}.
Understand the idea
After a Monte Carlo tree search playout, the result travels back up the path from the leaf to the root, and every node on the way gets one more visit and a share of the value. In a two-player game a good result for one player is bad for the other, so the sign flips at each level, like a scoreboard that reads plus for one side and minus for the other. Worked example: stats {'r': [3, 1.0]}, path ['r', 'a', 'b'], value 1.0 from the view of the player who moved into b. b gets +1: [1, 1.0]. a gets -1: [1, -1.0]. r gets +1 again: [3 + 1, 1.0 + 1.0] = [4, 2.0]. Rule: walk the path from the last node to the first; the leaf gets +value, its parent -value, then +value, alternating; each node adds 1 to visits and its signed value to value_sum; missing nodes start at [0, 0.0]; return a new dict, leaving the input unchanged (copy the lists, not just the dict). Adding the same sign everywhere makes both players chase the same outcome. This backup step is part of every MCTS engine, including AlphaZero-style search.