<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by michelangelo on Medium]]></title>
        <description><![CDATA[Stories by michelangelo on Medium]]></description>
        <link>https://medium.com/@_michelangelo_?source=rss-48b1ae1f0df5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CUC5yTjpaF6h7GEiJaCvqg.png</url>
            <title>Stories by michelangelo on Medium</title>
            <link>https://medium.com/@_michelangelo_?source=rss-48b1ae1f0df5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 19:15:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@_michelangelo_/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[MuZero for dummies!]]></title>
            <link>https://medium.com/@_michelangelo_/muzero-for-dummies-28fa076e781e?source=rss-48b1ae1f0df5------2</link>
            <guid isPermaLink="false">https://medium.com/p/28fa076e781e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[muzero]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[monte-carlo-tree-search]]></category>
            <category><![CDATA[alphazero]]></category>
            <dc:creator><![CDATA[michelangelo]]></dc:creator>
            <pubDate>Tue, 06 Sep 2022 05:47:32 GMT</pubDate>
            <atom:updated>2022-09-06T05:50:27.022Z</atom:updated>
            <content:encoded><![CDATA[<p>We will see how to develop a simple but working implementation of <a href="https://arxiv.org/pdf/1911.08265v2.pdf">MuZero</a>, a revolutionary AI algorithm developed by <a href="https://www.deepmind.com/">DeepMind</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_2pfQ-maj1GK7iGQ" /><figcaption>Photo by <a href="https://unsplash.com/es/@agk42?utm_source=medium&amp;utm_medium=referral">Alex Knight</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>MuZero: idea</h3><p>We have already seen what the MCTS algorithm is and how we can empower it with the use of Neural Networks to learn to play (not only) videogames with the AlphaZero algorithm.</p><p>The key idea of AlphaZero is that, in order to avoid the MCTS algorithm to fall short when using it in games with very big state spaces, we can use neural networks to approximate the Value and the Policy of the tree nodes, so that the limits of the MCTS algorithm are overcomed.</p><p>MuZero builds on the same idea of AlphaZero, but goes a step further. In fact, in AlphaZero, we had complete access to game information: for every action we decided to take, we played such move in an exact copy of the actual game, and we could actually see how the environment state changed as a result of that action.<br>This is a luxury that we can’t always have: can we, for example, in real life, see what the results of taking an action really is? Well, no until we have taken it, but we have learned to predict what the results of taking most common actions are, and we play along the “game” of life like this.</p><p>MuZero builds on the idea that with the use of neural networks, we can actually learn the dynamics of the game itself, so that when we have to plan in order to look for a move, we can guess not only how good the move is, but also what will happen as the result of taking it. In the end, we do not need to play along with the game environment, because we will use neural networks to “simulate” it.</p><p>This is the key concept of MuZero, and there is a particular aspect, which I think is the most incredible one, but also the most difficult for my mind to understand and “accept”: in fact, the neural network that will approximate the dynamics of the environment, will NOT be trained to approximate the environment itself, that is, we are not trying to create an approximated version of the environment by training the network with information about it, no, we are trying to reach our objective (i.e. minimize the loss function, that we will see later) but giving no constraints about how the neural network that predicts the dynamics should do so.<br>The neural network is free to represent its internal state as best as it wants to in order to represent the dynamics of the game, but it has no “human” restriction on how to do so.<br>We do not know how internally the neural network represents the dynamics of the environment, and it is free to do so with something that is not correlated with the real environment <strong>at all</strong>.</p><p>This, I think, is the key powerful idea of MuZero, as it gives the neural network the possibility to really flourish by not giving it any “constraint” and letting it “imagine” the dynamics of the environment as it wants, and, in general, I think this is a fundamental idea in order to build algorithms that aims towards build AGIs.</p><p>Thank you DeepMind for opening my mind to such kind of ideas! As a computer scientist, in the beginning, I was very reluctant to understand and accept it, but now I start seeing things differently!</p><h3>MuZero: implementation</h3><p>So we are ready to tackle a simple but working implementation of MuZero. In this case, I have decided to implement the pseudo-code that the authors at DeepMind have kindly <a href="https://arxiv.org/src/1911.08265v1/anc/pseudocode.py">shared</a> along with the<a href="https://arxiv.org/pdf/1911.08265v2.pdf"> academic paper</a> of the algorithm itself.</p><p>The extra effort for understanding it is really worth as the code is very well structured into classes, the flow is clear, easy to read and implement. Also, it is from the authors of the algorithm itself, so who better than them can provide a guide for the actual implementation?</p><p>As usual, I will try to simplify and explain the basic ideas and concepts about the algorithm, and I will not focus on the details of the (many) optimizations that we will encounter along the way: each one of such optimizations and concepts would require an article (and more) on its own!</p><p>In any case, I assume familiarity with both the MCTS and AlphaZero algorithm. If you need a refresher, you can read the previous articles.</p><h4>Helpers</h4><p>Let’s start with defining helper classes that we will use along the way. There are a lot of them, but they are quite simple to understand and will simplify the actual algorithm code later on.</p><h4>MinMaxStats</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74a6f93c69e7b4c5a6ac5bfd51ef7f9f/href">https://medium.com/media/74a6f93c69e7b4c5a6ac5bfd51ef7f9f/href</a></iframe><p>The <strong>MinMaxStats </strong>object contains minimum and maximum values encountered along MCTS search. We will use it to bound the value of the node between 0 and 1, so that the Value of the node is in the same range of the Policy of the node during the search.</p><h4>Config</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/645923e68a946d1fc21746bb870b2650/href">https://medium.com/media/645923e68a946d1fc21746bb870b2650/href</a></iframe><p>The <strong>MuZeroConfig </strong>object stores the configuration of hyperparameters used by the algorithm for search and training. Some of such parameters are common for all the games, some are very specific, and each game has its own specific configuration. The meaning of each hyperparameter will be explained along the way when we will use them in the actual algorithm.</p><h4>CartPole config</h4><p>As usual, our environment of choice is <em>CartPole-v1. </em>It is simple enough to be solved by such simple implementation, but complex enough to check if learning is actually happening.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a431450a9e5b68044bc7d511b389fc1d/href">https://medium.com/media/a431450a9e5b68044bc7d511b389fc1d/href</a></iframe><p>I have found that this implementation of MuZero is quite sensible about chosen hyperparameters, but I have managed to find values working for the CartPole environment. Also, after the MCTS will have completed its search, we can add an extra exploration probability to the choice of the action by using the <em>visit_softmax_temperature </em>function.</p><h4>Action and Player</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0988ea91fa0d3197ba6a4bd023dc8a4b/href">https://medium.com/media/0988ea91fa0d3197ba6a4bd023dc8a4b/href</a></iframe><p>The <strong>Action </strong>and <strong>Player </strong>classes do not have anything special in this implementation, they are just wrapper objects.</p><h4>Node</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee7db330a9cdf734c23d6e5917cf783b/href">https://medium.com/media/ee7db330a9cdf734c23d6e5917cf783b/href</a></iframe><p>The <strong>Node</strong> class represents the usual MCTS node. Nothing that we have not already seen, but notice the <em>to_play</em> attribute that, in two player games, would change every time we change level of the MCTS tree, to take into account that the value of the node for one player, is the opposite for the other one.</p><h4>ActionHistory</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cacad48eac5b49eb15334dff8341b63/href">https://medium.com/media/6cacad48eac5b49eb15334dff8341b63/href</a></iframe><p>The <strong>ActionHistory </strong>is an helper class that stores the history of actions we have taken along a MCTS search.</p><h4>Environment</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea3250c45fdc2afbe7b0ed6a169ce6d1/href">https://medium.com/media/ea3250c45fdc2afbe7b0ed6a169ce6d1/href</a></iframe><p>The <strong>Environment</strong> is a wrapper for the gym environment, <em>CartPole-v1</em> in our case, and defines how to actually act in the environment just by using the <em>step</em> method of the openAI gym interface.</p><h4>Game</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2fb87a7f7a0b6b207f8bd7c7953ac42/href">https://medium.com/media/c2fb87a7f7a0b6b207f8bd7c7953ac42/href</a></iframe><p>The <strong>Game </strong>represents a single episode of interaction with the environment. In particular, the <em>store_search_statistics </em>will collect data about visit counts and node values during the MCTS search, and the and the <em>make_target </em>allows to build the target values for the neural networks to aim for:</p><ul><li>for the target <strong>Value </strong>we will use a technique called <em>bootstrapping </em>so that the target value of a given node is the discounted root value of the MCTS tree N steps into the future (where N is given in our config by the <em>td_steps </em>hyperparameter), plus the (discounted) sum of all rewards until then (notice that in AlphaZero we did not have the rewards taken into account, but now we have). Every time we use an approximated value to estimate another value, like in this case, we say that we are <em>bootstrapping.</em></li><li>for the <strong>Policy </strong>of the node (i.e. the probability of exploring each action) we use the number of visits, so our target is the MCTS exploring policy.</li></ul><p>Also, and this is very important, as we are looking N steps into the future for doing our estimations, it may happen that these states falls after the end of the actual game. It is important that in these cases our target has null or zero target values, such that these states are learned by the neural network and treated as “absorbing states”. In fact, for the neural network, there is no such a concept of “end game”, and it will continue to imagine how its dynamics will expand forever! By training for absorbing states, the value of such nodes will be lower than other states, and this will be enough to avoid them and choose other, better actions, in the actual game.</p><h4>Replay Buffer</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d91f7e4136b4bdbfd5b7ba53a180d54/href">https://medium.com/media/9d91f7e4136b4bdbfd5b7ba53a180d54/href</a></iframe><p>Nothing major to say about the <strong>ReplayBuffer</strong>, only that for this simple implementation we do not need any kind of priority mechanism (such as <a href="https://arxiv.org/abs/1511.05952">PER</a>, Prioritized Experience Replay) for choosing episodes and positions: completely random choices are enough.</p><h4><strong>Network</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2284e28b8cd43b182cf8c6c36bb5dde4/href">https://medium.com/media/2284e28b8cd43b182cf8c6c36bb5dde4/href</a></iframe><p>The <strong>Network </strong>class represents the brain of MuZero, and is worth understanding the underlying ideas correctly. We have different neural networks that approximates different things:</p><ul><li>The <strong>Representation network </strong>allows us to go from an actual observation of the environment, to an internal state of the neural network. <strong>We will call this state an <em>HiddenState</em>.</strong> <em>Note that the output size of the HiddenState is not the same of the actual observation size of the environment, because, as we said, they are completely unrelated!</em></li><li>The <strong>Value network </strong>approximates the actual value of an <em>HiddenState</em> (how good it is) as a single output number.</li><li>The <strong>Policy network </strong>approximates the MCTS exploring policy in the form of probabilities for each action.</li><li>The <strong>Reward</strong> <strong>network </strong>approximates the reward of an <em>HiddenState </em>and <em>Action</em>, it will tell us how good is to take this single action in that state.</li></ul><p>The MuZero algorithms builds on the combined usage of such networks:</p><ul><li><em>initial_inference </em>is used for example at the start of a new game and during the learning process and takes as input the actual environment observation, transforming it into an <em>HiddenState </em>using the <strong>Representation</strong> <strong>network </strong>and then using such output <em>HiddenState </em>to query the other networks for gathering the predicted <strong>Value </strong>and <strong>Policy </strong>(<strong>Reward </strong>is assumed 0 as there is no previous action taken).</li><li><em>recurrent_inference </em>is the function that is used to transition from an <em>HiddenState</em> to the next one, which is what we will do to simulate the game in the “mind” of MuZero: given the current <em>HiddenState</em> and an <em>Action</em>, we use the <strong>Dynamics network </strong>to get the <strong>next</strong> <em>HiddenState, </em>and then we use the other networks to approximate <strong>Value</strong>, <strong>Policy </strong>and <strong>Reward</strong>.</li></ul><p>Using <em>initial_inference</em> at the root of the MCTS search and then <em>recurrent_inference </em>on the intermediate nodes we have a powerful search mechanism to collect statistics about MCTS values, all in MuZero brain. Wow!</p><p>As usual, the better the networks approximates the real<strong> Values,</strong> <strong>Policy </strong>and <strong>Rewards</strong>, the more “expert” our plays will be. We will see later on how to train the networks to correctly approximate such quantities.</p><p>At the end, the <strong>NetworkOuput </strong>is just a structure containing the <strong>Value</strong>, <strong>Reward</strong>, <strong>Policy</strong> and <strong>HiddenState </strong>predicted by the networks. Just a notice about this specific implementation where I have used the <em>softmax </em>activation function for the last layer of the <strong>Policy</strong> <strong>network</strong>, hence its outputs are not really raw logits as the pseudocode suggests, but already actual probabilities.</p><h4><strong>SharedStorage</strong></h4><p>The last helper class that we need before the actual algorithm implementation is the <strong>SharedStorage.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e563d068bb89710895799756765fffb1/href">https://medium.com/media/e563d068bb89710895799756765fffb1/href</a></iframe><p>In theory, this is a shared space where to store <em>Network </em>objects after each training step, so that jobs (i.e. parallel threads) that finish collecting data about a game can pick the last up-to-date version, train it, and store a new version for other jobs to use it.</p><p>In practice, in our implementation, we have a single <em>Network </em>object and there are no threads, games are played one at time and so is network training.</p><h3><strong>Self-Play and Training</strong></h3><p>We are now ready to tackle the main MuZero algorithm. It is basically divided into two parts: the first part plays a game and stores gathered statistics putting them into the shared <em>ReplayBuffer</em>, the second part is about training the neural network sampling the data from the buffer. While these steps can be executed in parallel and by multiple threads, in this simple implementation everything happens sequentially.</p><h3>Part 1: Self-Play</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba43913f3bfda67832167f286ae69604/href">https://medium.com/media/ba43913f3bfda67832167f286ae69604/href</a></iframe><p>So the steps are quite simple: grab the most up-to-date network (remember, we only have one in this implementation), play the game, store the statistics.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06b8580ba23f407a6b8e36e6cb1af957/href">https://medium.com/media/06b8580ba23f407a6b8e36e6cb1af957/href</a></iframe><p>And we already know how we are going to play games, right? We use the MCTS algorithm to select an action at each step. Notice how we create the root node of the MCTS calling the <em>initial_inference </em>function: we pass to it the initial observation of the environment, and the <strong>Representation network </strong>will take care of transforming it into an internal <em>HiddenState. </em>The first observation of the environment is the only thing that we will know about the real game!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0776a8b7e1dcd2473a36f223dae79e5/href">https://medium.com/media/d0776a8b7e1dcd2473a36f223dae79e5/href</a></iframe><p>Not much to say about the core MCTS algorithm, we have dedicated an entire article to it, and this is just a different implementation. Just notice the use of the <em>recurrent_inference</em> function. We use the <strong>Dynamics network</strong>, to go from one state to another of the imaginary game into the “mind” of MuZero.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c79ce82598e0f606c2297eecfc74148f/href">https://medium.com/media/c79ce82598e0f606c2297eecfc74148f/href</a></iframe><p>Action selection is as usual proportional to MCTS visit counts, with a twist: we use a <em>temperature</em> value to encourage exploration, and we reduce such value based on the number of episodes we have trained on, so that in the beginning we favor exploration, and in the end, when we are confident about the moves, we favor exploitation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3fc7e52045f9d4232569deb3ad4dd40/href">https://medium.com/media/c3fc7e52045f9d4232569deb3ad4dd40/href</a></iframe><p>The remaining MCTS accessory functions are almost self-explanatory:</p><ul><li><em>select_child</em>: chooses the child that maximizes the <em>ucb value</em>.</li><li><em>ucb_score</em>: calculates the <em>ucb value</em> for a node. It is slightly different from the one used in the AlphaZero implementation, but the concept is the same: one term comes from the Value of the node (scaled to the range 0 to 1) and the other term is given by the MCTS policy. Objective of the function is to balance exploration and exploitation.</li><li><em>backpropagate</em>: at the end of the search it propagates up to the root the gathered information. Notice how at each level of the tree the Value of the node depends on the current player, so as to consider also 2 player games.</li><li><em>expand_node</em>: expands the current node creating children with the Policy values that comes from the network prediction. As in this implementation we are already using the <em>softmax </em>activation function for the network, we can use such probabilities directly, so I have commented out the logits approach.</li><li><em>add_exploration_noise</em>: last, but not least, when we create the root node for the MCTS we add to it Dirichlet noise again to favor exploration.</li></ul><p>And this concludes the first part of the MuZero algorithm.</p><h3>Part 2: Training</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a6d9dd5d56d3effef8bd4694f81f565/href">https://medium.com/media/0a6d9dd5d56d3effef8bd4694f81f565/href</a></iframe><p>The second part of the algorithm is all about how to train the various neural networks. In particular, we train all of them trying to minimize the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*js4q_ImbGqQgrPb5mUtr7A.png" /><figcaption>Formula for calculating MuZero loss as found in the <a href="https://arxiv.org/pdf/1911.08265v2.pdf">original paper</a>.</figcaption></figure><p>That is, we are trying to minimize the differences between:</p><ul><li>The predicted <strong>Policy</strong> with respect to the MCTS policy.</li><li>The predicted <strong>Values </strong>with respect to the actual values (i.e. the ones we calculated using the <em>bootstrapping</em> technique).</li><li>The predicted <strong>Rewards </strong>with respect to the observed ones.</li><li>Finally, a regularization term is added in order to penalize big network weights.</li></ul><p>All parameters of the model are trained jointly minimizing such loss.</p><h3>Main</h3><p>There is not much to add to the MuZero algorithm, we have only to create some code to actually use it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/263708d50ed19a6562d20420d717ceae/href">https://medium.com/media/263708d50ed19a6562d20420d717ceae/href</a></iframe><p>We use the usual plot functions in order to track progress. This time, we will also track time, as it will take much more time to train the networks compared to previous MCTS and AlphaZero implementations. In fact, if for AlphaZero you could go grab a cup of coffee, get back and enjoy the result, for the training of MuZero I would suggest leave it overnight and get a good night of sleep, in order to wake up with the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*-Cd8qF3Sn4ofVguCQsXrKw.png" /><figcaption>Reward over 225 episodes.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*7GzjOGMySKEzywdtQ-Po0Q.png" /><figcaption>Loss over 225 episodes.</figcaption></figure><p>And that’s it, we just coded a simple but working implementation of MuZero!</p><p>You can write the code on your own (suggested) or find the repository on <a href="https://github.com/ciamic/muzero">GitHub</a>.</p><p>Besides the implementation, what I think its important to understand are the basic concepts and ideas that we discussed about along the way: they for sure gave me a different way about how to see things and about how to code!</p><p><a href="https://medium.com/@_michelangelo_/monte-carlo-tree-search-mcts-alphazero-and-hopefully-muzero-for-dummies-11ad5d95d9d8">Intro: MCTS, AlphaZero and MuZero for dummies!</a></p><p><a href="https://medium.com/@_michelangelo_/monte-carlo-tree-search-mcts-algorithm-for-dummies-74b2bae53bfa">Part 1: Monte Carlo Tree Search (MCTS) algorithm for dummies!</a></p><p><a href="https://medium.com/@_michelangelo_/alphazero-for-dummies-5bcc713fc9c6">Part 2: AlphaZero for dummies!</a></p><p>Part 3: MuZero for dummies!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28fa076e781e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AlphaZero for dummies!]]></title>
            <link>https://medium.com/@_michelangelo_/alphazero-for-dummies-5bcc713fc9c6?source=rss-48b1ae1f0df5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bcc713fc9c6</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[muzero]]></category>
            <category><![CDATA[alphazero]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[michelangelo]]></dc:creator>
            <pubDate>Wed, 10 Aug 2022 16:14:45 GMT</pubDate>
            <atom:updated>2022-09-06T19:33:10.385Z</atom:updated>
            <content:encoded><![CDATA[<p>We will see how to develop a simple but working implementation of <a href="https://arxiv.org/pdf/1712.01815v1.pdf">AlphaZero</a>, a revolutionary AI algorithm developed by <a href="https://www.deepmind.com/">DeepMind</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nYhxxrcw4a6YrgW3" /><figcaption>Photo by <a href="https://unsplash.com/@santesson89?utm_source=medium&amp;utm_medium=referral">Andrea De Santis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you have followed the previous articles, you know that we are now at the most exciting part of the series, and we are going to take the fly: we are going to integrate the previous MCTS implementation with an AI Deep Neural Network, in order to train an expert policy to play video games!</p><p>If you do not think this is a big deal, keep in mind that the AlphaZero algorithm, along with its predecessor AlphaGo, and successor MuZero, “solved” the game of <a href="https://en.wikipedia.org/wiki/Go_(game)">Go</a>, which was at the time considered from the AI research community at least 10 years away to be solved.</p><p>This is incredible, and even more incredible is the elegance and simplicity of such algorithms which yes, in their full implementation have many optimizations that may be difficult to understand at first, but, at the core, have some basic ideas that make such algorithms work, and we will build on such core ideas to create an AlphaZero implementation on a small scale.</p><p>If you need a refresher on the MCTS algorithm, have a look at the <a href="https://medium.com/@_michelangelo_/monte-carlo-tree-search-mcts-algorithm-for-dummies-74b2bae53bfa">previous article</a>. Also, I will assume some familiarity with basic Neural Networks concepts. If you do not have any, I would suggest the <a href="http://introtodeeplearning.com/">MIT introductory course</a>.</p><p>Let’s see more in detail what all of this is about.</p><p>The problem with the MCTS algorithm is that, even if it is better than brute-force search, as its search is guided towards more promising states, still, for complex games, the state space is so big that, in order to gather a statistically valid amount of data, the time required is not feasible, and the algorithm fall short.</p><p>The core idea of the AlphaZero algorithm, is to have a neural network to “guide” the search along the tree, producing values and exploring probabilities for the nodes. In the end, the MCTS algorithm is based on statistics and approximated data, and neural networks do exactly that, they approximate (arbitrarily complex) functions.</p><p>We will need to estimate two things:</p><ul><li>Value estimation: every time we need to do a rollout from the node, instead of doing an actual rollout, we will ask the neural network what is the (estimated) value of the node.</li><li>Policy estimation: the probability to explore each node will not only depend on the number of times that it has been visited, but also on a probability given by the neural network, which will approximate the MCTS probability distribution.</li></ul><p>We will use the combination of the Value and Policy estimations in order to guide our search along the tree to more promising nodes.</p><p>The closer the Value estimation is to real state value, the better the Policy will be and, vice-versa, the better the Policy, the better the Value estimation.</p><p>When the neural networks closely approximate the required values, we can then use them to choose an action at each step of the game, and play it like an expert.</p><p>Let’s see how to code it!</p><p>Here the usual code to import an openAI gym environment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3864a709b2fb3d86bc63eeb18c03508/href">https://medium.com/media/a3864a709b2fb3d86bc63eeb18c03508/href</a></iframe><p>Notice, however, how this time we are using the version 1 of the environment (i.e. <em>CartPole-v1</em>), whose maximum possible sum of rewards is 500.</p><p>Now we have to define the Deep Neural Networks that we will use to approximate the Value and Policy of the tree nodes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58b12524d94dffdca61ce191ba35799f/href">https://medium.com/media/58b12524d94dffdca61ce191ba35799f/href</a></iframe><p>We are using 2 small, fully connected neural networks:</p><ul><li>The first will approximate the value of the node, hence it will have 1 output value.</li><li>The second will approximate the probabilities of choosing each child node, hence it will have as many output values as actions available in the game.</li></ul><p>Here our MCTS implementation, now combined with the use of the neural networks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/718e3719ef8b6dcdf6ccb76715c50592/href">https://medium.com/media/718e3719ef8b6dcdf6ccb76715c50592/href</a></iframe><p>I will not go into the details of the basic MCTS algorithm, as it has been explained in a previous article, but let’s focus on the key differences:</p><ul><li>The <em>rollout </em>function now uses both the Value and Policy neural networks to approximate the values needed for guiding the MCTS node selection.</li><li>The <em>getUCBscore </em>uses such values in order to balance the exploitation (i.e. try to choose a good action) and the exploration (i.e. exploring new actions). The exploitation is represented by the Value score (i.e. the average of all the rollouts started from that node and from its children nodes which then have propagated their values to root nodes) and the exploration is represented by the Policy score but is also affected by how many times the node has already been visited (i.e. nodes that have low visit count have higher values, so as to favor their exploration).</li></ul><p>The rest is the usual MCTS algorithm stuff, we have just changed its selection mechanism using the neural networks to approximate the node values and policy.</p><p>We also need a structure where we can store the information about game episodes that we will use to train our neural networks to predict accurate values. We will call this structure a <em>ReplayBuffer</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4116d7ac70f735bc9b1604daf44ebee1/href">https://medium.com/media/4116d7ac70f735bc9b1604daf44ebee1/href</a></iframe><p>The <em>ReplayBuffer </em>stores, for each step of the game:</p><ul><li>The observation (i.e. state) of the game environment</li><li>The target Value (i.e. the sum of rewards obtained in the the episode)</li><li>The observation (i.e. state) of the game environment at the previous step</li><li>The target Policy according to visit counts</li></ul><p>We will then train our neural networks to accurately predict the target Value and target Policy, given the game state observations.</p><p>The strategy we will use to play the game is as usual to do a certain amount of searches in the tree for collecting reliable statistics and then picking the best action, which will be the one relative to the children node of the current state that has been visited the most (because, as we have seen in the MCTS algorithm, it is related to a good value anyway, given how the value of the node is calculated).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe49f1c8eab8fffd4eb5499e5ce3ddd2/href">https://medium.com/media/fe49f1c8eab8fffd4eb5499e5ce3ddd2/href</a></iframe><p>And here we are, defining the loop that will allow us to train the neural networks and plot the improvements over time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02af02727d511f11c3d8dbffeb0122e4/href">https://medium.com/media/02af02727d511f11c3d8dbffeb0122e4/href</a></iframe><p>Notice how we define some hyperparameters and proceed to play games and train the neural networks incrementally approximate closely the actual Value and Policy of the MCTS nodes.</p><p>And finally these are the plots of the rewards over episodes along with the moving average over the last 20 episodes, the Value loss and the Policy loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*SmmzCV9IHslqFK2TjebNXw.png" /><figcaption>Plot of rewards over 200 episodes in blue, with moving average in orange.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*zDvV8XZDHp0QRw9s5y7SpA.png" /><figcaption>Value loss over episodes.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*8U2PJlVZgsXZt2_QSU2Vyw.png" /><figcaption>Policy loss over episodes.</figcaption></figure><p>We can see that learning is definitely happening and in the final episodes of the training AlphaZero constantly reaches 500 rewards per episode, which is the maximum for this environment!</p><p><em>You can write the code on your own (suggested) or find the repository on </em><a href="https://github.com/ciamic/alphazero"><em>GitHub</em></a><em>.</em></p><p>I hope that this was both instructive and fun. For me, it is astonishing that with such few basic ideas we are able to write algorithms that learns to play by themselves.</p><p>As you have noticed, however, AlphaZero requires to know the “rules” of the game. Everytime we take a step, we are using a copy of the game environment to simulate an action and get all the required information on the evolution of the state of the game.</p><p>Wouldn’t be amazing if we are able to get the same results, but knowing nothing about the game we are playing? If AlphaZero is not enough magic then follow me in the next chapter, where we will implement MuZero, an evolution of AlphaZero with no knowledge at all about the game, and we will see how it is possible to learn everything about the game using neural networks!</p><p><a href="https://medium.com/@_michelangelo_/monte-carlo-tree-search-mcts-alphazero-and-hopefully-muzero-for-dummies-11ad5d95d9d8">Intro: MCTS, AlphaZero and MuZero for dummies!</a></p><p><a href="https://medium.com/@_michelangelo_/monte-carlo-tree-search-mcts-algorithm-for-dummies-74b2bae53bfa">Part 1: Monte Carlo Tree Search (MCTS) algorithm for dummies!</a></p><p>Part 2: AlphaZero for dummies!</p><p><a href="https://medium.com/@_michelangelo_/muzero-for-dummies-28fa076e781e">Part 3: MuZero for dummies!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bcc713fc9c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monte Carlo Tree Search (MCTS), AlphaZero and MuZero for dummies!]]></title>
            <link>https://medium.com/@_michelangelo_/monte-carlo-tree-search-mcts-alphazero-and-hopefully-muzero-for-dummies-11ad5d95d9d8?source=rss-48b1ae1f0df5------2</link>
            <guid isPermaLink="false">https://medium.com/p/11ad5d95d9d8</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[muzero]]></category>
            <category><![CDATA[alphazero]]></category>
            <dc:creator><![CDATA[michelangelo]]></dc:creator>
            <pubDate>Thu, 04 Aug 2022 08:34:14 GMT</pubDate>
            <atom:updated>2022-09-06T05:48:15.244Z</atom:updated>
            <content:encoded><![CDATA[<p>I will try to explain and code a simple but working implementation of the Monte Carlo Tree Search algorithm (MCTS), AlphaZero and MuZero, in order to play video games!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*puZqA7aw__bJG45w" /><figcaption>Photo by <a href="https://unsplash.com/@grstocks?utm_source=medium&amp;utm_medium=referral">GR Stocks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you are a Computer Scientist like me, you likely have stumbled across all the research and results on AI that are happening these days.<br>Chances are, you already know about <a href="https://www.deepmind.com/">DeepMind </a>and similar AI companies, and how they are revolutionizing the AI research and development in pursuit of AGI (Artificial General Intelligence).</p><p>For me, everything changed when I saw the <a href="https://www.youtube.com/watch?v=WXuK6gekU1Y">AlphaGo Documentary</a>, more or less a year ago. This is what I understood at the time: some very smart people from DeepMind managed to create an algorithm that learns to play video games and table games(some of which, like Go, are very difficult given their state space), through self-play, at a super-human level.</p><p><strong>How</strong> did they do it? This is the question that stuck into my mind since then.</p><p>I am a Computer Scientist but I am not specialized in AI, but damn if I wanted to understand how they have done it. In the end, these are the video games that I was playing when I was a kid, and now there is the possibility to write algorithms that are able to learn how to play them.</p><p>I wanted to try to replicate their results on a small scale.</p><p>So this is where my journey started, reading some generic books and looking at videos about AI, and then graduating at <a href="https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893">Udacity Deep Reinforcement Learning</a> course.</p><p>In this series of articles, which assumes you already have some familiarity with basic programming (we will use Python), basic ML (Machine Learning) and RL (Reinforcement Learning) concepts, and the algorithms themselves, I will try to explain how to implement a (very) simple but working version of the MCTS, AlphaZero and MuZero algorithms, and try to explain some of the key concepts behind.</p><p>This is the kind of implementation which I wish I had at the time I started to understand these concepts, because the only ones that I found may be much more better and complete, but are also quite complex in order to understand the basic ideas behind such algorithms.</p><p>So stay tuned and see you in the next articles!</p><p>Intro: MCTS, AlphaZero and MuZero for dummies!</p><p><a href="https://medium.com/@_michelangelo_/monte-carlo-tree-search-mcts-algorithm-for-dummies-74b2bae53bfa">Part 1: Monte Carlo Tree Search (MCTS) algorithm for dummies!</a></p><p><a href="https://medium.com/@_michelangelo_/alphazero-for-dummies-5bcc713fc9c6">Part 2: AlphaZero for dummies!</a></p><p><a href="https://medium.com/@_michelangelo_/muzero-for-dummies-28fa076e781e">Part 3: MuZero for dummies!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11ad5d95d9d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monte Carlo Tree Search (MCTS) algorithm for dummies!]]></title>
            <link>https://medium.com/@_michelangelo_/monte-carlo-tree-search-mcts-algorithm-for-dummies-74b2bae53bfa?source=rss-48b1ae1f0df5------2</link>
            <guid isPermaLink="false">https://medium.com/p/74b2bae53bfa</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[alphazero]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[muzero]]></category>
            <dc:creator><![CDATA[michelangelo]]></dc:creator>
            <pubDate>Thu, 04 Aug 2022 08:33:22 GMT</pubDate>
            <atom:updated>2022-09-06T05:48:27.282Z</atom:updated>
            <content:encoded><![CDATA[<p>If we really want to have a chance at understanding how AlphaZero and MuZero works, then we have to stop first at unfolding the Monte Carlo Tree Search (MCTS) algorithm, which is at the foundation of both.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JeumAeXUD-a_nGuY" /><figcaption>Photo by <a href="https://unsplash.com/@deepmind?utm_source=medium&amp;utm_medium=referral">DeepMind</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Roughly speaking, the MCTS allows us to search for the best moves to play relying on statistics rather than on full exploration, hence allowing us to navigate large state spaces with much less limits compared to brute-force approaches.<br>In fact, search is guided in order to explore promising nodes more often and the more statistics are collected, the more reliable the results obtained.</p><p>More precisely, the MCTS is divided in 4 different steps:</p><ul><li><strong>Selection</strong>: we need a smart way to explore tree nodes that leads to more promising outcomes, hence we need to have a way to give value to nodes to choose which one to pick.</li><li><strong>Expansion</strong>: once we reach a leaf node (i.e. a certain state of the game) we need to expand the tree considering all the possible valid actions from that node (i.e. subsequent game states after taking valid actions).</li><li><strong>Simulation</strong>: we need to be able to play a completely random game from a certain node (i.e. game state). Such rollout will result in a random result if taken alone but, the more times we will do rollouts from such node, the more accurate the average value estimate of the node will be.</li><li><strong>Backpropagation</strong>: after the rollout, such results needs to be back-propagated up to the tree, in order to store such information in the upper nodes, so as to transfer information from leafs to root nodes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgWsQ8VuHapz-glp04Fu8Q.png" /><figcaption>The 4 steps of the MCTS algorithm, courtesy of <a href="https://en.wikipedia.org/wiki/File:MCTS-steps.svg">Wikipedia</a>.</figcaption></figure><p>To sum up, the more we apply the 4 steps of the MCTS algorithm, the more reliable and statistically valid information we gather about the next best action to take from a particular state of the game. Apply this for every move, and we have a strategy for playing the game like a boss!</p><p>Let’s see how to implement it and how to use it to play an openAI gym video game.</p><p>The first thing that we need to do is to create an <a href="https://www.gymlibrary.ml/">openAI gym environment</a>, which will be the test bed for our algorithm, and check for the number of possible actions and the observation space in the game.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7482d7b201d0c328dae9c9b3bde4a7f8/href">https://medium.com/media/7482d7b201d0c328dae9c9b3bde4a7f8/href</a></iframe><p>For the CartPole environment, whose goal is to balance a pole by applying forces to the cart to which is attached, there are 2 possible actions (push cart to the left or to the right), and the observation is made of 4 values (cart position, cart velocity, pole angle and pole angular velocity). You can find detailed information about this environment <a href="https://www.gymlibrary.ml/environments/classic_control/cart_pole/">here</a>.</p><p>Next, the definition of the Node class, which will represent a node of the tree:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aed01e5a54c39f922ca8c9a8b4bbb889/href">https://medium.com/media/aed01e5a54c39f922ca8c9a8b4bbb889/href</a></iframe><p>The Node class will store information that we need about the game, the children (i.e. the next states of the game), and value statistics. In particular:</p><ul><li><em>child</em>: is a dictionary of child nodes which, for every possible action from that state, will tell us what the next state of the game is taking that action</li><li><em>T</em>: represents the sum of the value of the rollouts that have been started from this node</li><li><em>N</em>: represents the visit count of the node, i.e. how many times we have visited the node</li><li><em>game</em>: is the game environment in the current state represented by the node. Its a copy of the original game that we are currently playing, so that we can use it to simulate the search. It represents the current state of the game that will result in applying all the actions from the root node to the node itself</li><li><em>observation</em>: is the current state of the game in that node, in our example, it will be the 4 values as described above</li><li><em>done</em>: will tell us if the game at this point is ended, so as to stop the search</li><li><em>parent</em>: a connection to the parent node, for backpropagation</li><li><em>action_index</em>: is the index of the action that lead to this node (i.e. is the action that the parent of the node has taken to get into this node)</li></ul><p>Now let’s define methods of the Node class that we will use for the search.</p><p>The first one will be the definition of the function that will give values to nodes. This is fundamental, as will guide our search along the tree:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b5f8d7eb1af53b9b8e6ba6090c20e0a/href">https://medium.com/media/6b5f8d7eb1af53b9b8e6ba6090c20e0a/href</a></iframe><p>The formula is called UCB (<a href="https://www.geeksforgeeks.org/upper-confidence-bound-algorithm-in-reinforcement-learning/">Upper Confidence Bound</a>) and balances <em>exploitation </em>(i.e. pick the best known action) and <em>exploration </em>(i.e. explore new actions):</p><ul><li>The <em>exploitation </em>term is the current estimated value of the node (<em>self.T / self.N</em>).</li><li>The <em>exploration </em>term is inversely proportional to the number of times the node has been visited, with respect to the number of visits of its parent node (<em>sqrt(log(top_node.N) / self.N)</em>).</li></ul><p>There is also a tunable constant <em>c </em>that will give more or less value to the second term.</p><p>Next we need a function that creates the children of the current node:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd58d602589697494452608c3cc0f255/href">https://medium.com/media/cd58d602589697494452608c3cc0f255/href</a></iframe><p>Notice how we always use the whole game actions available (<em>GAME_ACTIONS</em>) and create a child for each action, associating to it a copy of the game environment, to which we apply such action (<em>game.step(action)</em>), and store the information of the resulting state of the game in the child node.</p><p>We are now ready for the core of the algorithm, where the search happens:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49d15bca4b8709dc16b3c013be2199bc/href">https://medium.com/media/49d15bca4b8709dc16b3c013be2199bc/href</a></iframe><p>The search along the tree starts from a certain node and recursively picks a child node that maximizes the formula as defined before. This guides our search until a leaf node is reached. At this point, if it is the first time we visit such leaf node, we will play a rollout and store the statistics, if it is not the first time we visit such node, then we create its children and play a rollout from one randomly chosen child. In every case the updated statistics, both value and visit count are backpropagated to parent nodes up to the root.</p><p>We are almost there, we just need to define how to do a random rollout, using a copy of the game from the current node (i.e. in the actual game state):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b764722585eddb5b838af61e44c2fc44/href">https://medium.com/media/b764722585eddb5b838af61e44c2fc44/href</a></iframe><p>And we need to define how to pick the next action after the search is done:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa9aa46aa1e8178dd0ff76f928abe9a9/href">https://medium.com/media/fa9aa46aa1e8178dd0ff76f928abe9a9/href</a></iframe><p>In particular, we will pick the child node from the current one that we are searching from which has the maximum visit count, as this is associated with a good value anyway, given how the MCTS formula works (i.e. it visits more often nodes that have higher estimated values).</p><p>We are all set now, and we need to define the policy that we will use to play the game:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77bdb12de26b6921389f06e91acfb1bd/href">https://medium.com/media/77bdb12de26b6921389f06e91acfb1bd/href</a></iframe><p>The policy is straightforward: every time we need to do an action in the game, we will use the MCTS to explore and pick the best possible next move as just discussed. The search goes on for a certain number of iterations based on the value of a fixed parameter (<em>MCTS_POLICY_EXPLORE</em>) and, as discussed, the higher the time we spend collecting statistics with the search, the more reliable the results will be.</p><p>We will apply such policy for every move of the game so as to have an MCTS guided expert player.</p><p>And here we go, the code below allows us to play a game choosing moves according to the MCTS just defined, plotting the results at the end!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf936fab63cb361f7464fe28a29e57b5/href">https://medium.com/media/bf936fab63cb361f7464fe28a29e57b5/href</a></iframe><p>The <em>CartPole-v0 </em>environment used as example is quite simple, and the MCTS algorithm is able to collect enough statistics in a reasonable amount of time, making it a good player constantly reaching 200 points per game (which is the maximum allowed for the environment)!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*4KWJKBo8J_3fSH16MnjCFw.gif" /></figure><p>Congratulations, you made it!</p><p>I hope you had fun as much as me in coding the MCTS algorithm.</p><p><em>You can write the code on your own (suggested) or find the repository on </em><a href="https://github.com/ciamic/MCTS"><em>GitHub</em></a><em>.</em></p><p>For me, the excitement in seeing that such generic algorithm is able to play different video games is very high, but nothing compared to what we will see next, that is, how we can use AI Deep Neural Networks, combined with the MCTS algorithm, to create a simple but working implementation of AlphaZero.</p><p><a href="https://medium.com/@_michelangelo_/monte-carlo-tree-search-mcts-alphazero-and-hopefully-muzero-for-dummies-11ad5d95d9d8">Intro: MCTS, AlphaZero and MuZero for dummies!</a></p><p>Part 1: Monte Carlo Tree Search (MCTS) algorithm for dummies!</p><p><a href="https://medium.com/@_michelangelo_/alphazero-for-dummies-5bcc713fc9c6">Part 2: AlphaZero for dummies!</a></p><p><a href="https://medium.com/@_michelangelo_/muzero-for-dummies-28fa076e781e">Part 3: MuZero for dummies!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74b2bae53bfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>