<?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 Bentou on Medium]]></title>
        <description><![CDATA[Stories by Bentou on Medium]]></description>
        <link>https://medium.com/@bentou.pub?source=rss-575c6b7e47d4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DSrQUwkvt9QrwtL6SyKh0g.png</url>
            <title>Stories by Bentou on Medium</title>
            <link>https://medium.com/@bentou.pub?source=rss-575c6b7e47d4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:27:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bentou.pub/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[Implementing Switch Transformers from scratch in PyTorch — Part 1]]></title>
            <link>https://medium.com/@bentou.pub/implementing-switch-transformers-from-scratch-in-pytorch-part-1-e8823b474a91?source=rss-575c6b7e47d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8823b474a91</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-translation]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Bentou]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 13:18:26 GMT</pubDate>
            <atom:updated>2023-02-05T13:18:26.788Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Switch Transformers from scratch in PyTorch — Part 1</h3><p><em>Reflecting upon the potential of transformers and scaling them with an efficient version: Switch Transformers.</em></p><h3>Tracing Evolution: Mind &amp; Machines</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rrpS8jTpZY0rZfXKLPGOtg.png" /><figcaption>A person reflecting on the importance of language.</figcaption></figure><p>The origin of language was one of the key moments that defined the fate of humankind as we see it today. Empowered with the ability to share and discuss ideas, unlike any other species, our evolution was dramatically accelerated. This led to brilliant works of art, inventions and ambitious collaborations. Language is an indispensable part of our lives, making it impossible to even think about something that doesn’t have an associated word. With the evolution of language, our conversations became richer. This was accompanied by an evolved cognitive ability, enabling us to comprehend complex structures, long passages and intricacies like humor and sarcasm. <em>But what about machines?</em></p><h4>Recurrent Neural Networks (RNNs)</h4><p>Language is inherently sequential. We interpret it one word after the other, at the same time remembering the context. Inspired by this design, <strong>Recurrent Neural Networks (RNNs)</strong> dominated the world of <strong>Natural Language Processing (NLP)</strong>. The text was treated as a sequence of words and they would be fed one word at a time. Along with the input word, the RNNs would feed the output at the last time step, as the hidden state, to themselves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DY_wnDIqYacNFm-FKCkGUw.png" /><figcaption>A RNN cell <em>(unrolled version)</em> processing the text ‘bentou is amazing’. Variables <strong>x</strong>, <strong>y </strong>&amp; <strong>h</strong> represent input, output &amp; hidden state respectively. Subscript <strong>t</strong> reflects the time step.</figcaption></figure><p>But there was a serious problem. It was terribly difficult to train RNNs using backpropagation. The final output was obtained after the last time step, which meant that the gradients had to be transferred up to the first. This was problematic for long sequences on two fronts: first, it took really long to train as it couldn’t be parallelized and second, it led to <strong>vanishing</strong> and <strong>exploding gradients</strong>. The repeated multiplication of gradients made them either infinitesimally small or astronomically big. Consequently, even if the models were somehow trained, they didn’t perform well.</p><h4>Convolutional Neural Networks (CNNs)</h4><p>Things took a different turn in the world of <strong>Computer Vision (CV)</strong>. Since images don’t have a sequential nature, RNNs were never impressive here. A different type of architecture, <strong>Convolutional Neural Networks (CNNs)</strong> dominated the CV space. They had the operation of convolution at their heart, which operated on a region of the image at a time, completely independent of the rest. This gave brilliant results and was easily parallelized, enabling the models to be trained efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4z2rA-q0oRTE4ZrD2JtBag.png" /><figcaption>A CNN with different components labelled.</figcaption></figure><h4>A Unified Approach</h4><p>The great results CNNs brought in CV prompted their application in NLP, in combination with RNNs. The convolutional layers worked on sections of the input and extracted features, which were then processed by recurrent layers. This definitely reduced the sequence length and helped with training time and gradient problems, but the results weren’t much impressive. Unlike images, sentences have words that are related to each other, and they can be located at arbitrary distances. It fundamentally made using convolutional layers that operated on sections, ineffective.</p><blockquote><em>It was a time in AI history which was calling out for leapfrog design enhancements. </em>Enter: The Transformer!</blockquote><h3><strong>Transformers: Rise &amp; Reign</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DdvKCsIP6Mu9eOa8bQk2zQ.png" /><figcaption>A person awestruck with the potential of transformers.</figcaption></figure><h4>Genesis</h4><p>The world was forever changed in 2017 with the introduction of the <strong>transformer</strong>. An architecture built entirely with an attention mechanism and linear layers, it solved the issues that had been holding back CNNs and RNNs. In a blink of an eye, there was a parallelizable architecture that allowed all words in an input sequence to attend to each other. Benchmarked on machine translation, it outperformed the state-of-the-art results of that time and quickly replaced RNNs across NLP field.</p><h4>Promises</h4><p>As of now, transformers have taken the world by storm. They have become the go-to choice for every NLP task but have significantly shone in sequence transduction problems, where we map an input sequence to an output sequence. These problems are at the heart of the most interesting things in NLP, such as language modeling and machine translation.</p><p>Originally designed for NLP, transformers have managed to enter CV too. The introduction of <strong>Vision Transformer (ViT)</strong> marked a paradigm shift in the world of CV. Images, that aren’t inherently sequential, were divided into sequence of patches and modeled in the style of texts.</p><p>Generative AI is the next wave and transformers are pushing the boundaries of innovation. <strong>Large Language Models (LLMs)</strong> like <em>BERT </em>and <em>GPT-3</em> family, which powers <em>ChatGPT</em>, have a transformer architecture at their core and are shaking the text-to-text domain. Diffusion-based generative models like <em>Stable Diffusion</em> and <em>Dall E-2</em> have made a lot of noise in the image generation space, but text-to-image transformer models have started to appear. Google’s <em>Muse</em> indicates that transformers might completely overtake other architectures in the Generative AI space.</p><p><em>Will a world exist where transformers are the only architectures that people use? But can they render every other architecture designed for specific tasks obsolete?</em></p><h4>Double-Edged</h4><p>The supernatural performance of transformers comes at an unfortunate cost. The community has somehow reached a consensus that the way to enhance transformers is to dramatically increase their learnable parameters and train them on gigantic datasets. This demands enormous compute resources for both training the model and then serving it to end-users. <em>Not every team is adequately deep-pocketed!</em></p><p>Fortunately, research is being focused on making the training and deployment of these huge models pocket-friendly. This has given birth to the family of <strong>Efficient Transformers</strong>, that have compute friendly architectural tweaks. One of them has captivated us: <strong>Switch Transformer</strong>.</p><h4>Theme</h4><p>In this series, we’re not going to talk about the transformer architecture. There’s an overabundance of blogs out there that do exactly this. Instead, we’re going to spotlight the key design concepts in transformers, that are a testament to human ingenuity. We’ll connect these concepts and form a story that’ll lead us to the transformer architecture and then we’ll quickly move to scaling it to trillion parameters with Switch Transformers.</p><p>We implemented a Switch Transformer from scratch in PyTorch for <strong>Machine Translation</strong>, translating from <em>German</em> to <em>English</em>. The observations and results we got in doing so form the backbone of this series. We’ve reflected upon the potential of transformers and it’s time that we do it again with the technicalities.</p><h4>Modeling</h4><p>A thing that’s indispensable to our discussion is the modeling of human-readable text into something that a model can understand. A model’s parameters are numerical and it learns a mathematical function. It means that the words, their meanings, context and every other thing has to be encoded into numbers. It starts with a <em>corpus</em>.</p><h4>Corpus</h4><p>A <strong>corpus</strong> <em>(plural corpora)</em> is a collection of written or spoken texts and serves as the training data. It’s crucial that the corpus be properly cleaned and structured and is machine readable. Starting with a huge corpus with texts from varied sources already solves the major part of the problem.</p><p>We used the training set from <a href="https://pytorch.org/text/stable/datasets.html#torchtext.datasets.Multi30k">Multi30k</a> as our corpus and visualized the words present in it with a word cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*P-yYx9zvAMJ9rQ-cawMhwg.png" /><figcaption>Word cloud made with the words (/tokens) present in the corpus (/vocabulary). The size reflects the frequency of occurrence and the colors are for aesthetics. Implemented using <a href="https://github.com/minimaxir/stylecloud">stylecloud</a>.</figcaption></figure><h4>Tokenization</h4><p>Our world is made up of atoms, but the world of NLP is made up of <em>tokens</em>. If we take a piece of text and continue breaking it into smaller meaningful units, we’ll eventually arrive at a point beyond which we cannot do anything and what remains with us will be <strong>tokens</strong>. All of us use tokenization in our daily interpretations. We process a sentence by breaking it into smaller understandable units and making sense of them. For example, we cannot process <em>“Do’nt go!”</em> unless we’ve broken it into <em>Do</em>, <em>n’t</em>, <em>go</em> and <em>!</em>. We do it effortlessly, but a machine needs a tokenizer. Think of a tokenizer as something that takes a piece of text, goes over it and breaks it into tokens by referring to a set of rules. These rules are the crux of the entire process of tokenization. How can we ensure that it splits <em>“Mr. Detective.”</em> to <em>Mr.</em>, <em>Detective</em> and <em>.,</em> instead of <em>Mr</em>, <em>.</em>, <em>Detective</em> and <em>.</em> ? We can either build a tokenizer from scratch by writing all the rules or use a pre-built version. We did the latter.</p><p>We used <strong>spaCy</strong> to get the tokenizer. SpaCy is an open-source library built for advanced NLP tasks and contains different components as pretrained pipelines. Since we were dealing with two languages, we needed two tokenizers. We got the tokenizer for German from <strong>de_core_news_sm</strong> and English from <strong>en_core_web_sm</strong>. We’ll explore the tokenizer from <strong>en_core_web_sm</strong> a bit.</p><p>We need to download en_core_web_sm from spaCy, after which we can load the tokenizer with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eAaym-lUYlV7_PiOq95pEg.png" /><figcaption>Code for loading tokenizer | <a href="https://gist.github.com/BentouAI/b20d249be636eead52ead543b19b7b46">Gist</a></figcaption></figure><p>The tokenizer should know the rules. Let’s check what it does to <em>Mr. Detective.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzRqWA2nsCGso3reh3eS9Q.png" /><figcaption>Code for testing tokenization | <a href="https://gist.github.com/BentouAI/587a06aa6b326fdbac0d5cc85eefb2c2">Gist</a></figcaption></figure><p>It works. Our tokenizer has tokenized “<em>Mr. Detective”</em> to <em>Mr.</em> and <em>Detective</em>. Let’s make things harder and see what it does to entities like <em>Don’t</em>, <em>U.K.</em> and <em>:)</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZeliM_mCEzTAhz9_4toHg.png" /><figcaption>Code for testing tokenization | <a href="https://gist.github.com/BentouAI/4f709b02fc277d1d898cbc722098def3">Gist</a></figcaption></figure><p>Our tokenizer works with these complex entities too. The most important thing to notice is that it hasn’t separated <strong><em>:)</em></strong> into <strong><em>:</em></strong> and <strong><em>)</em></strong>. It really understands the intricacies to an incredible extent.</p><p><em>But how does this magic unfold? How is the tokenizer able to handle these intricacies?</em> The answer to these troubling questions lies in the set of rules and the algorithm it operates on. The tokenizer separates the text with a whitespace delimiter, then parses it from left-to-right. When it encounters an entity, it looks it up in a set of tokens and if a match isn’t found it refers to the set of rules and breaks it further. It then works on the newly birthed entities until no further breaks can be made. It then moves forward in the whitespace delimited string and repeats itself.</p><p>We can in fact see this in action. With the below lines, we can see what rules are used for breaking down “<em>“Do’nt worry!””</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*amlMlKPJw50fJzwTlUX_gQ.png" /><figcaption>Code for viewing rules used for tokenization | <a href="https://gist.github.com/BentouAI/bd61625c45eba731c18d5b71e1c2e851">Gist</a></figcaption></figure><p>It’s so satisfying to look at how it breaks down the text, just like a human would’ve.</p><h4>Vocabulary</h4><p>Tokenization is great, but it’s useless if we don’t know the meanings of the tokens. This applies to our daily interpretations as well. We won’t be able to comprehend what <em>Do</em>, <em>n’t</em>, <em>worry</em> &amp; <em>!</em> means if we don’t know their meanings. We all have a mental vocabulary which contains all the words that we know. We need to replicate this for a machine. We build a vocabulary of the unique tokens present in the training corpus and call it <strong>vocab</strong>. The model will have knowledge only about the tokens present in the vocab and any other token it sees will be <strong>unknown </strong><em>(&lt;unk&gt;)</em>.</p><h4>Embedding</h4><p>Once the vocab is ready, we have the tokens that our model needs to know. It’ll learn the meanings on its own. <em>But how will it represent these meanings?</em> We need to figure out a way for our model and it has to be something numerical. We can assign an index to every token in the vocab, with tokens similar in meanings being consecutive. As a result, positive tokens like <em>enjoys</em> and <em>celebrates</em> will be consecutive and negative tokens like <em>bored</em> and <em>frustrated</em> will be consecutive, at the same time being far from each other. But as we increase the number of tokens, it becomes difficult to represent their meanings using a single number. We have to switch to vectors, hoping their dimensionality is sufficient to capture the meanings. And we call these vectors <strong>embeddings</strong>.</p><p>Embeddings are the n-dimensional vectors that represent the tokens present in the vocab. The intuition behind them is that in the learned n-dimensional space, tokens with similar meanings will be close to each other <em>(have high cosine similarity)</em> and tokens with dissimilar meanings will be far <em>(have low cosine similarity)</em>. Larger the n, the better. A larger n reflects more dimensions to encode the difference between tokens, capturing their meanings better.</p><p>We used the Embedding module from PyTorch to store the embeddings. It’s a simple lookup table and retrieves the embeddings using indices for the corresponding tokens. We can instantiate an Embedding object with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMYFpTnf-jo3qEvq6XbuaA.png" /><figcaption>Code for instantiating an Embedding object | <a href="https://gist.github.com/BentouAI/78d79429d13ab8afffa9a9ffef272aa2">Gist</a></figcaption></figure><p>We set the dimension to <em>256</em> and trained the embeddings from scratch. Our embeddings improved with epochs and we visualize them in this GIF. We needed to reduce their dimensionality to 2 and used <strong>Principal Component Analysis (PCA) </strong>for this. We selected 15 <em>positive </em>and 15 <em>negative </em>tokens and plotted them for the epochs. <em>The result? </em>We got a beautiful visualization that reflects how our embeddings improved over the course of training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcsqaIRaO7XGVWMokPnkbQ.gif" /><figcaption>A visualization of embeddings over the course of training. We trained the model for 20 epochs but the validation loss increased after the 11th. | <a href="https://www.python-graph-gallery.com/web-scatterplot-astronaut">Inspiration</a></figcaption></figure><p>We had a relatively tiny corpus because of which our embeddings didn’t entirely separate into distinct regions for <em>positive </em>and <em>negative </em>sentiments. However, in order to show how great embeddings can get when trained on a huge corpus, we do the same visualization using the embeddings from <strong>GloVe</strong>. The embeddings that we use were trained on a corpus of <em>840 Billion</em> tokens, a vocab of <em>2.2 Million</em> tokens and had the dimensionality of <em>300</em>. For a comparison, our embeddings were trained on a vocab of <em>5888</em> tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KDFl26wO31qroZ8cIWYng.png" /><figcaption>A visualization of embeddings pre-trained and provided in <a href="https://nlp.stanford.edu/projects/glove/"><strong>GloVe</strong></a>. | <a href="https://www.python-graph-gallery.com/web-scatterplot-astronaut">Inspiration</a></figcaption></figure><p>We can clearly see the distinct regions for positive and negative sentiments. This is the true power of embeddings when they’re trained gracefully.</p><h4>Conclusion</h4><p>In this part we reflected upon the origin &amp; potential of transformers and some key design concepts. In the next part we’ll dissect attention mechanism, the heart of transformers, followed by an analysis of our implementation and results of Switch Transformer.</p><p>Written by <a href="https://www.linkedin.com/in/aayush-pandey-765a94200/">Aayush Pandey</a>, with help from <a href="https://thunderinfy.github.io/portfolio/">Aditya Rastogi</a>. We used <a href="https://excalidraw.com/">Excalidraw</a> for sketches and <a href="https://carbon.now.sh/">Carbon</a> for code snippets.</p><h3>References</h3><ul><li><a href="https://www.enjoyalgorithms.com/blog/text-data-pre-processing-techniques-in-ml">Text Data Preprocessing in Machine Learning</a></li><li><a href="https://www.enjoyalgorithms.com/blog/word-vector-encoding-in-nlp">Word Vector Encoding in NLP</a></li><li><a href="https://www.python-graph-gallery.com/web-scatterplot-astronaut">Custom scatterplot with annotations in Matplotlib | The Python Graph Gallery</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8823b474a91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AlphaZero from scratch in PyTorch for the game of Chain Reaction — Part 3]]></title>
            <link>https://medium.com/@bentou.pub/alphazero-from-scratch-in-pytorch-for-the-game-of-chain-reaction-part-3-c3fbf0d6f986?source=rss-575c6b7e47d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3fbf0d6f986</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[alphazero]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Bentou]]></dc:creator>
            <pubDate>Sun, 27 Nov 2022 13:45:50 GMT</pubDate>
            <atom:updated>2022-11-27T13:45:50.964Z</atom:updated>
            <content:encoded><![CDATA[<h3>AlphaZero from scratch in PyTorch for the game of Chain Reaction — Part 3</h3><p><em>Neural Network Architecture, Self-learning, Board Symmetries, Playout Cap Randomization and other pieces to make it all work.</em></p><p>From our previous parts, we now understand how Monte Carlo Tree Search (MCTS) works and how we can use it to get an output policy, given a board state. We also understand the role of the neural network in MCTS, which is two-fold; <strong>to guide exploration through the neural network’s policy output and to use its value output in place of traditional Monte Carlo rollouts</strong>.</p><p>In this part, we will start with the architecture of this neural network, examining its different layers, inputs, and outputs. We’ll then move on to understand how the network is trained using self-play, and we will look at the loss function that we use to train the neural network. We’ll also look closely at the training details, including data augmentation techniques specific to the Chain Reaction game and a method called as Playout Cap Randomization to improve the training efficiency. And then, we would look at some results, visualizations, and future directions.</p><h3>Neural Network</h3><h4>Architecture</h4><p>The input to our neural network model has a shape of MxNx7, where M and N are the number of rows and columns in the chain reaction board, respectively. The number “7” in the shape indicates that there are seven channels where each channel stores some specific information about the board in the form of binary data, as shown below:</p><pre>Description of the encoded state<br><br>Size of the state: M*N*7<br><br>channel 1 : stores the MxN map where red orbs are 1 in number<br><br>channel 2 : stores the MxN map where red orbs are 2 in number<br><br>channel 3 : stores the MxN map where red orbs are 3 in number<br><br>channel 4 : stores the MxN map where green orbs are 1 in number<br><br>channel 5 : stores the MxN map where green orbs are 2 in number<br><br>channel 6 : stores the MxN map where green orbs are 3 in number<br><br>channel 7 : MxN map of ones if it is red player&#39;s turn otherwise <br>a map of zeroes</pre><p>The following images show the neural network architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t57HYzb2CT03osl0TY52Eg.png" /><figcaption>Our neural network architecture is a resnet architecture — it has conv2d, batchnorm2d and relu layers with dropout layers and two heads at the end.</figcaption></figure><p>The value head has a tanh activation function and hence produces a number between -1 and +1. The policy head has a softmax function which helps us to get the probability distribution over all actions on the board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kduMZqcl2VQdCJA92dHK-A.png" /><figcaption>A basic block that is used in the construction of many other blocks</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*boYZ7X13cJ3oJRP9MWbXLg.png" /><figcaption>The first block through which our input passes — made up of conv2d, batchnorm2d and relu layers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jraqvegi-n5q9LBlB1tmcw.png" /><figcaption>Made up of small blocks (conv2d and batchnorm2d layers) with relu layers in between and also has a skip connection</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAwQ_oikg1NKswukgS-8NA.png" /><figcaption>Five resnet blocks make up the middle blocks of our neural net</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3K-iQvOZN9sy_wN-J2VrXQ.png" /><figcaption>Activations from the previous block are flattened and passed to the dropout block</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRqBPfDKBQSu6IJd9tnMMQ.png" /><figcaption>Two dropout blocks are used in our architecture</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmhdCiWQfUnnerITvx8Omg.png" /><figcaption>Produces a number between -1 and +1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GYiogMjh7Ma0_mOdxA19SQ.png" /><figcaption>Output is used as the probability distribution over all actions on the board</figcaption></figure><p>The following image shows the code implementation of this architecture in Python using PyTorch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcCeH1_wTHQn39oG0G1bxQ.png" /><figcaption><a href="https://gist.github.com/BentouAI/6b61e0f01a913e30101bd96a802b1716">https://gist.github.com/BentouAI/6b61e0f01a913e30101bd96a802b1716</a></figcaption></figure><h4>Self-play</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LLuFSmvUl11HdT-oAKVUdw.png" /><figcaption>Steps that show how a move is played during a chain reaction game</figcaption></figure><p>The above image shows how any single move is played during the game. In the self-play framework, we have two players (both AI players), say red and green. Each player makes a move using the above steps. <strong>Now imagine that red wins the game. The value target would be +1 for all the red moves and -1 for all the green moves.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzFbUcRIGxrvi1lneUUbPw.png" /><figcaption>Value assignment after the end of the game</figcaption></figure><p><strong>The policy targets would be the policy obtained using Monte Carlo playouts.</strong></p><h4>Loss function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ycnOij2UuOBoaUDyhniAZg.png" /><figcaption>Loss function comes from loss for both value and policy</figcaption></figure><p>The loss function for AlphaZero comes from the following:</p><ul><li>Value loss: A<strong> mean-squared loss</strong> between the predicted value and the value target obtained using value assignment at the end of the game.</li><li>Policy loss: A <strong>cross-entropy loss</strong> is calculated between the predicted policy and the policy target obtained from MCTS playouts.</li></ul><p>The loss for training the neural network in AlphaZero is the <strong>sum of these two losses</strong>. We call it “<strong>Alphaloss</strong>”.</p><h3>Data Augmentation</h3><p>To increase the training efficiency for Chain Reaction, we use the fact that <strong>if we know the right policy for a board state, then we know the right policy for seven other board states that are obtained by rotating, flipping, or transposing the board matrix.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMwrEMRFTLWlgPGcgGvkwg.png" /><figcaption>Flips, rotations and transposes of the board can generate 7 more board states. The policy can be obtained easily for all these equivalent board positions.</figcaption></figure><p>To implement this in code, we maintain a temp buffer in which we store the board state and the policy targets, and then at the end of the game when we get the actual reward value, we assign the value targets to every element in the temp buffer.</p><p>We then construct the buffer using this temp buffer by adding all the additional board states and policy targets using the flips, rotations, and transposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rSXN8axH5mXZ3NDuX48Ymw.png" /></figure><h3>Playout Cap Randomization</h3><p>Playout Cap Randomization was introduced in <a href="https://arxiv.org/abs/1902.10565v5">[1]</a>. It helps in increasing training efficiency.</p><p>If we look at the self-play training process in AlphaZero, the only true rewards it receives are at the end of the games. So, rewards are scarce. Because the value head is focused on predicting this reward, <strong>if we want to improve value training, we can focus on increasing the number of games that AlphaZero plays.</strong></p><p><strong>If we want to improve policy training, we can focus on more Monte Carlo playouts.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOtVbIjIM0c6kNf4YFQ4Kg.png" /><figcaption>How can we improve value and policy training?</figcaption></figure><p>Instead of increasing the number of playouts on all moves in a game, <strong>we can increase it only on some randomly selected moves and only use the data from those moves for training</strong>. On other moves, we can decrease the number of playouts. This technique is called playout cap randomization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQD239dr-atFi0YgmJ8ieQ.png" /><figcaption>Playout Cap Randomization</figcaption></figure><h3>Buffer</h3><p>We have seen how data augmentation methods change the temp buffer. The temp buffer lies inside the buffer class. The buffer class is a child class of the torch dataset class. Therefore, a buffer object stores the policy targets and <strong>also acts as a torch dataset</strong> that can be passed to a torch dataloader during the training process.</p><h3>Results</h3><h4>Against a random agent</h4><p>The following are the win percentages against a random agent on 3x3, 4x4 and 5x5 boards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*K2Fjl2trSvbEoC2ErYTLwA.png" /><figcaption>For a 3 x 3 board, we see that even with zero MCTS playouts, atleast 75% win rate can be achieved after 80 epochs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*IvVhUjBG9hyFQ89YqdSpOA.png" /><figcaption>For a 4 x 4 board, the training saturates after 500 epochs and then becomes oscillatory, but we do see greater than 80% win rate near 1300 epochs for the agent with zero MCTS playouts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*esrZ1hPoS3F2pwKgm89J0g.png" /><figcaption>Training saturates at around a thousand epochs for a 5 x 5 board</figcaption></figure><h4>Visualization</h4><p><strong>Each Monte Carlo playout involves a sequence of moves on the board</strong>. For a 5x5 board, there are 25 possibilities for the first move. As the training progresses, the value head of the neural network improves, improving the Monte Carlo search. The following are the visualizations of these moves for a thousand Monte Carlo playouts for untrained and trained value heads. The visualizations are for a 5 x 5 board, so there are 25 possibilities. These 25 possibilities are either mapped to a circle (at the beginning) or an arc (at later depths) to form these visualizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*7PEqNGR3KjONRACmzlWYfg.png" /><figcaption>The actions taken during 1000 Monte Carlo playouts with an untrained value network. (5 x 5 board -&gt; 25 actions). The 25 actions are mapped to angles in a circle/ circular arc. The search only goes to a maximum depth of 4 moves.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dDrGzU44MzgSGw5yp-Ia2Q.png" /><figcaption>The actions taken during 1000 Monte Carlo playouts with a trained value network. (5 x 5 board -&gt; 25 actions). The 25 actions are mapped to angles in a circle/ circular arc. The search even goes to 20 moves deep, because of the existence of a value network heuristic.</figcaption></figure><p>The code for this work lies <a href="https://github.com/BentouAI/AlphaZero-Chain-Reaction">in this GitHub repository</a>.</p><h3>Future Directions</h3><ul><li>The game of chain reaction <a href="https://brilliant.org/wiki/chain-reaction-game/">has a human-crafted heuristic strategy</a> [2]. It would be interesting to train an AlphaZero agent and try to make it compete with such a strategy.</li><li>There is a variant of chess called “hidden queen chess”/ “secret queen chess” in which each player chooses one of their pawns as a queen at the beginning of the game, and that choice is not revealed to the opponent. AlphaZero is applicable to perfect information games. It would be interesting to read and implement papers that train agents to navigate through states with imperfect information [3].</li><li>It would be interesting to <a href="https://arxiv.org/pdf/1805.09613.pdf">go beyond discrete action spaces</a> [4]. Continuous action spaces would be more common in robotics or self-driving car applications. [4] takes a beta distribution and learns parameters for it. It then uses a scaled version of this distribution to approximate bounded continuous spaces.</li><li>Imagine we have a trained agent on a 3x3 chain reaction board. It would be great if we can transfer this knowledge to a 4x4 sized or other sized boards. <a href="https://arxiv.org/pdf/2107.08387.pdf">This work focuses in this direction </a>[5]. Without such transfer mechanisms, it’s computationally very expensive to train on much larger boards, for ex: 15x15 or 20x20 chain reaction boards.</li></ul><p><em>Written by </em><a href="https://thunderinfy.github.io/portfolio/"><em>Aditya Rastogi</em></a><em>. Thanks to </em><a href="https://www.linkedin.com/in/aayush-pandey-765a94200/"><em>Aayush Pandey</em></a><em> for the help. The figures have been drawn using </em><a href="https://excalidraw.com/"><em>Excalidraw</em></a><em>. Images for code snippets have been generated using </em><a href="https://carbon.now.sh/"><em>Carbon</em></a><em>.</em></p><h3>References</h3><ol><li>Wu, D.J. (2020) <em>Accelerating self-play learning in go</em>, <em>arXiv.org</em>. Available at: <a href="https://arxiv.org/abs/1902.10565v5">https://arxiv.org/abs/1902.10565v5</a>.</li><li>Chain Reaction (Game). <em>Brilliant.org</em>. Retrieved 17:59, November 27, 2022, from <a href="https://brilliant.org/wiki/chain-reaction-game/">https://brilliant.org/wiki/chain-reaction-game/</a></li><li><a href="https://www.deepmind.com/blog/alphastar-grandmaster-level-in-starcraft-ii-using-multi-agent-reinforcement-learning">https://www.deepmind.com/blog/alphastar-grandmaster-level-in-starcraft-ii-using-multi-agent-reinforcement-learning</a></li><li>Moerland, T.M., Broekens, J., Plaat, A. and Jonker, C.M., 2018. A0c: Alpha zero in continuous action space. <em>arXiv preprint arXiv:1805.09613</em>.</li><li>Ben-Assayag, S. and El-Yaniv, R., 2021. Train on small, play the large: Scaling up board games with alphazero and gnn. <em>arXiv preprint arXiv:2107.08387</em>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3fbf0d6f986" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AlphaZero from scratch in PyTorch for the game of Chain Reaction — Part 2]]></title>
            <link>https://medium.com/@bentou.pub/alphazero-from-scratch-in-pytorch-for-the-game-of-chain-reaction-part-2-b2e7edda14fb?source=rss-575c6b7e47d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2e7edda14fb</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[monte-carlo-tree-search]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Bentou]]></dc:creator>
            <pubDate>Sat, 08 Oct 2022 09:46:34 GMT</pubDate>
            <atom:updated>2022-10-08T09:53:46.565Z</atom:updated>
            <content:encoded><![CDATA[<h3>AlphaZero from scratch in PyTorch for the game of Chain Reaction — Part 2</h3><p><em>Understanding Monte Carlo Tree Search — the search algorithm that sits at the core of AlphaZero</em></p><p><a href="https://medium.com/@bentou.pub/alphazero-from-scratch-in-pytorch-for-the-game-of-chain-reaction-part-1-8cffdc399233">The previous part</a> discussed the game of Chain Reaction and the relation between AlphaZero &amp; slow and fast thinking in the brain.</p><h3>Monte Carlo Tree Search (MCTS)</h3><p>You might be familiar with the term “Monte Carlo” <a href="https://en.wikipedia.org/wiki/Monte_Carlo_method">[1]</a> which is a class of algorithms in which we do random sampling repeatedly to obtain some result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*vIteVKDRzcN0TmCsAwCpGQ.png" /><figcaption>Selecting random points in a unit square and counting how many points lie inside the circle can be used to estimate the value of pi/4</figcaption></figure><p>We’ll understand all the steps of MCTS in detail. But for now, speaking from a broad level of understanding, in MCTS on games, we perform repeated simulations of gameplay starting from a given board state. In traditional MCTS, we perform these simulations till the end of the game. But AlphaZero’s [2] implementation of MCTS is different from the traditional one because in AlphaZero we also have a neural network that is being trained to give us policy and value for a given board state.</p><p>The inputs to the search algorithm in AlphaZero are a board state (say σ) and the number of iterations (also called the number of playouts) for which we want to run MCTS. In our case, the output of this search algorithm would be the policy from which we would sample an action to play at σ.</p><p>The tree would be iteratively built. Each node of the tree contains a board state and information about what possible valid actions can be taken in that board state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uriLq7OHudKuAVkWOUmcpw.png" /><figcaption>A node consists of a board state and key-value pairs where the key would be an action tuple and the corresponding value would be the node obtained after applying that action tuple on the parent node’s state. <strong>The child nodes are initialized lazily (i.e., initialized only when they are needed)</strong></figcaption></figure><p>In the beginning, the tree would just have the root node. And it would contain the input state σ and the valid actions that can be taken at σ.</p><p>Here is the code for the Node class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZS013WmucNLCjUJBwidGw.png" /><figcaption><a href="https://gist.github.com/thunderInfy/eb987f297e87d8f9ef45a22ec3510625">Gist </a>for Node class</figcaption></figure><h4>Selection</h4><p>The first step in MCTS is <strong>selection</strong>. We select the best edges starting from the root node until we reach the end of the tree (i.e. either a terminal node that signifies the end of the game or some node that hasn’t been explored yet, e.g. nodes marked as None in the above figure).</p><p><strong>But what do we mean by “best edges”? How should we traverse the tree? </strong>We do tree traversal in a way to have a balance between exploration and exploitation where exploration is also guided by our neural network.</p><blockquote>For readers who are new to the terms “exploration” and “exploitation”: Imagine you’ve never had waffles before and you cannot know from anywhere else which flavors of waffles would be the best to try first. You can only try them yourself. And then suppose you tried blueberry waffles and you loved them. There can be some other waffle flavor that you may like more in the future, but you haven’t tried it yet. So you also wish to explore many flavors in search of the best waffle out there for you. But say, you can only eat one waffle a day and you know you liked blueberry waffles and want to have them again. That’s exploitation.</blockquote><blockquote><em>Choosing actions for which you have an idea that they will give you some positive reward is an </em><strong><em>exploitation </em></strong><em>of your current knowledge of the reward distribution and choosing actions in the hope that you may find some actions that get you even better rewards is </em><strong><em>exploration</em></strong><em>.</em></blockquote><p>A good balance between both is required to find the best waffle flavor out there for you or to find the best playing strategy for an AlphaZero agent playing some board game.</p><p>AlphaZero uses something known as the <strong>PUCT</strong> (<strong>P</strong>redictor <strong>U</strong>pper <strong>C</strong>onfidence bounds applied to <strong>T</strong>rees) rule to achieve this balance. This rule was designed empirically, and it was also motivated by Rosin’s work in a bandits-with-predictors setting <a href="http://gauss.ececs.uc.edu/Workshops/isaim2010/papers/rosin.pdf">[3]</a>. There’s a recent paper<a href="https://deepmind.com/research/publications/2022/Policy-improvement-by-planning-with-Gumbel">[4]</a> from DeepMind that discusses some alternatives to PUCT. We’ll discuss those alternatives later in the section on future directions. For now, let’s try to understand the PUCT rule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPDiaDXiNB-CUT8wsEy-vQ.png" /><figcaption>The PUCT rule used in AlphaZero</figcaption></figure><p>An action-value <strong>Q(s, a)</strong> means the <strong>average reward</strong> obtained by taking action “a” at state “s”. In the beginning, Q(s, a) would be zero. This action-value term represents our knowledge of the reward function at any given time, so it is related to exploitation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9G1jvK8-yK3DsXVnzO7fDQ.png" /><figcaption>Factors affecting exploration</figcaption></figure><p>Suppose our neural network trained so far says with 0.3 probability that we should play some action a. We include that 0.3 prior in the exploration part of our PUCT rule. In this discussion, state s belongs to the parent node, and the state obtained by taking action “a” on “s” belongs to the child node. Now imagine that we are visiting a particular node too often in MCTS. To avoid that and encourage exploration of other nodes, the visit count of the child node is included in the denominator and it’s normalized using the total visits of the parent node.</p><p>Why are we taking the square root of the parent node visit count? So, this PUCT rule was designed empirically and this is what worked the best among all the choices that the authors tried. Having said that, we can think of it as a way of normalizing the <em>child.N +1</em> term in the denominator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5iinDh5zzi7YSRNICC_2A.png" /><figcaption>Entire PUCT rule</figcaption></figure><p>There’s a hyperparameter c_puct that can be seen in the above figure. This constant balances the exploitation and exploration terms. A typical value for this hyperparameter is 2.</p><p>So, now that we have some understanding of how to obtain PUCT(s, a) , let’s revisit the selection step in MCTS.</p><p>The selection step is just as shown in the block below, i.e., starting from the root, repeatedly finding the child node that has the maximum PUCT value until we reach a node whose state is still None (yet to be expanded/initialized).</p><pre><strong>consider_node = root</strong></pre><pre>// terminal nodes also have a None state</pre><pre><strong>while consider_node.state is not None:<br>    best_node = find_child_with_maximum_puct_value(consider_node)<br>    consider_node = best_node</strong></pre><pre><strong>consider_node has to be expanded</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0LR-nijX-0zZK2gdYTrKKA.gif" /><figcaption>Monte Carlo Selection for some intermediate tree; repeatedly finding the child node with the maximum PUCT value until we reach a node whose state is still None</figcaption></figure><h4>Expand and Evaluate</h4><p>After selection, the next step is to <strong>expand and evaluate </strong>that node (whose state is still None). <strong>Expansion </strong>here means, to expand the tree by initializing the selected node’s state. This new state is obtained from the rules of the game. Note that in case it turns out to be a terminal node we leave the state as None and set a flag in the node marking it as a terminal node with the winner information.</p><p>All the new edges for the selected node are also initialized. For instance, the tree shown in the above gif would look like this (shown in the figure below) after the expansion of the selected node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CcbYzyH24ttLDSRofPZYcw.png" /><figcaption>The above tree after the Monte Carlo node expansion</figcaption></figure><p>Next comes the evaluation of the expanded node. By evaluation, we mean what’s the expected reward for the player at that node. Traditional MCTS performs rollouts from the expanded node using a rollout policy to find out the value at the end of the game. One such rollout policy can be uniformly random.</p><p>AlphaZero’s MCTS is different from traditional MCTS in this respect. In AlphaZero’s MCTS, we use the neural network’s value output to determine the value of the expanded node.</p><p>It’s similar to the idea that while evaluating a chess position, for instance, we calculate some moves in our mind, and then at the end of that calculation, we just use our intuition of how good that resulting position would be. At the end of that calculation, we don’t do rollouts like traditional MCTS, we don’t simulate that position till the end of the game with random actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uq7qZvbHqEhu2XNI7SGxAg.png" /><figcaption>Evaluating the expanded node using the neural network</figcaption></figure><p>The following figure shows these ideas implemented in code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yig2faoAaSI-XX5kST3rNA.png" /><figcaption><a href="https://gist.github.com/thunderInfy/fa6ec4c0fe065120b65f88ec0a7add41">Gist </a>for MCTS Expand and Evaluate function</figcaption></figure><h4>Backup</h4><p>After evaluating the expanded node, Q values (realized by total reward values and total visit counts) for all the nodes from the root to the expanded node need to be updated. This is known as the backup step of MCTS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-b7Fm-Fk0iYiNwo8RxhAXg.png" /><figcaption>MCTS Backup, update node statistics for all the nodes in the path from the root to the newly expanded node</figcaption></figure><p>An easy way to implement this is to implement the selection function recursively, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30vcPt7v5YvvLbfymp9-zQ.png" /><figcaption><a href="https://gist.github.com/thunderInfy/5d4c711b4dc5f12cc598a9019c47edec">Gist</a> for MCTS selection (includes code for MCTS backup step, handled through recursive calls)</figcaption></figure><h4>Play</h4><p>The above three steps are run for some number of iterations. If say, they are run for a thousand iterations, then a maximum of thousand new nodes in total will be expanded (we’re saying maximum because some terminal node may be visited more than once).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CLwNnOaaAvdPgSwPePxvcg.png" /><figcaption>The entire MCTS</figcaption></figure><p>At the end of these iterations, if we look at the root node and its children, they might look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6TGe4-hxvLPl4W7m9f1uA.png" /><figcaption>The root node with its children; visit counts of child nodes are also shown</figcaption></figure><p>We use these visit counts to output a policy at the root node. The idea that AlphaZero uses is that if a node is visited more, then we should assign a higher probability of playing the action at the root that gives us that node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TnWImppxjVtXxVWXya7yXA.png" /><figcaption>The output policy probability value for some action is proportional to N^(1/τ), where N is the visit count for the child node of the root obtained through that action, and τ is some temperature value.</figcaption></figure><p>We can see in the above figure that the output policy for each action that is obtained from the search in AlphaZero is proportional to the visit count of the resulting child node raised to 1/τ where τ is some temperature value. A high value of τ would result in a more uniform policy. We just keep the temperature at 1 in our code.</p><p>We can then sample some action from this output policy to play some move for the given state.</p><p>It feels reasonable to use visit counts to construct the output policy because we use PUCT values to guide the Monte Carlo tree search. And these PUCT values balance exploration and exploitation. Nodes that return more value to the root node will be visited more often, while some nodes will be visited just randomly through exploration.</p><p>We’ll look at how MCTS is used in a self-learning framework to train the neural network in AlphaZero in the next part.</p><p><em>Written by </em><a href="https://thunderinfy.github.io/portfolio/"><em>Aditya Rastogi</em></a><em>. Thanks to </em><a href="https://www.linkedin.com/in/aayush-pandey-765a94200/"><em>Aayush Pandey</em></a><em> for the help. The figures have been drawn using </em><a href="https://excalidraw.com/"><em>Excalidraw</em></a><em>. Images for code snippets have been generated using </em><a href="https://carbon.now.sh/"><em>Carbon</em></a><em>.</em></p><h3>References</h3><p>[1] <a href="https://en.wikipedia.org/wiki/Monte_Carlo_method">https://en.wikipedia.org/wiki/Monte_Carlo_method</a></p><p>[2] Silver, D., Hubert, T., Schrittwieser, J., Antonoglou, I., Lai, M., Guez, A., Lanctot, M., Sifre, L., Kumaran, D., Graepel, T., Lillicrap, T., Simonyan, K., &amp; Hassabis, D. (2018). A general reinforcement learning algorithm that Masters Chess, Shogi, and go through self-play. <em>Science</em>, <em>362</em>(6419), 1140–1144. <a href="https://doi.org/10.1126/science.aar6404">https://doi.org/10.1126/science.aar6404</a></p><p>[3] Rosin, C. D. (2011). Multi-armed bandits with episode context. <em>Annals of Mathematics and Artificial Intelligence</em>, <em>61</em>(3), 203–230. <a href="https://doi.org/10.1007/s10472-011-9258-6">https://doi.org/10.1007/s10472-011-9258-6</a></p><p>[4] Danihelka, I., Guez, A., Schrittwieser, J., &amp; Silver, D. <em>Policy Improvement by planning with Gumbel</em>. Deepmind. Retrieved February 23, 2022, from <a href="https://deepmind.com/research/publications/2022/Policy-improvement-by-planning-with-Gumbel">https://deepmind.com/research/publications/2022/Policy-improvement-by-planning-with-Gumbel</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2e7edda14fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AlphaZero from scratch in PyTorch for the game of Chain Reaction — Part 1]]></title>
            <link>https://medium.com/@bentou.pub/alphazero-from-scratch-in-pytorch-for-the-game-of-chain-reaction-part-1-8cffdc399233?source=rss-575c6b7e47d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cffdc399233</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Bentou]]></dc:creator>
            <pubDate>Sat, 24 Sep 2022 08:29:55 GMT</pubDate>
            <atom:updated>2022-09-24T08:32:20.495Z</atom:updated>
            <content:encoded><![CDATA[<h3>AlphaZero from scratch in PyTorch for the game of Chain Reaction — Part 1</h3><p><em>Implementing one of the most fascinating AI algorithms from the last decade, exploring ideas that make it more efficient, and future directions.</em></p><p>In this article, we’ll be implementing DeepMind’s <strong>AlphaZero</strong><a href="https://kstatic.googleusercontent.com/files/2f51b2a749a284c2e2dfa13911da965f4855092a179469aedd15fbe4efe8f8cbf9c515ef83ac03a6515fa990e6f85fd827dcd477845e806f23a17845072dc7bd"><strong>[1]</strong></a><strong> from scratch in PyTorch</strong> for the game of <strong>Chain Reaction</strong><a href="https://brilliant.org/wiki/chain-reaction-game/"><strong>[2]</strong></a>. To make the learning process more efficient in AlphaZero, we’ll also be using a relatively recent improvement called as <strong>“Playout Cap Randomization”</strong><a href="https://arxiv.org/pdf/1902.10565.pdf"><strong>[3]</strong></a>, and some other techniques from <a href="https://medium.com/oracledevs/lessons-from-implementing-alphazero-7e36e9054191">[4]</a>. During training, we’ll be using multiprocessing to simulate multiple games in parallel. We’ll also be discussing some future directions for AlphaZero with some relevant research papers.</p><p>Please note that the objective of these posts is not to build the best Chain Reaction bot using AlphaZero (as that would require huge amount of computational resources), but rather to build a decent bot that can at least defeat a random agent and to understand how AlphaZero works using the game of Chain Reaction as an example.</p><p>The next section starts with explaining how Chain Reaction works. Feel free to skip the next section and directly move to the AlphaZero section if you just want to understand how AlphaZero works.</p><h3>Chain Reaction</h3><p>Let’s first start with understanding the game of Chain Reaction. It’s a <strong>perfect information game</strong>. We used to play this game with our friends in college and sometimes, the game after a few moves used to look quite chaotic and unpredictable to us. So we were curious about how powerful AlphaZero trained on this game would be. Chain Reaction can be played among many players but we will restrict ourselves to two players in this article.</p><h4><strong>Rules of Chain Reaction</strong></h4><p>Let’s start with the rules of this game. We have <strong>a board with M rows and N columns, and we have two players</strong>. Each player has an assigned color. For the purposes of this article, say we have a red and a green player, and red moves first. The picture below shows some intermediate states in the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oT8eXyt1rlK0dvLFD_kKkQ.png" /><figcaption>The game of Chain Reaction — some intermediate states. <strong>Note that the board’s colour tells us whose turn it is.</strong></figcaption></figure><p>We have M rows and N columns in the board, in the above picture, M=N=5. So, there are M*N = 25 cells in the board. All of the cells are empty in the beginning of the game.</p><p>Also, these red and green circular objects are called as <strong>orbs </strong>in the game. The picture below shows the orbs that we can have in the game (1, 2 or 3 in number, and red or green).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNKaHQ-ufD6o4vYsHpI_rw.png" /><figcaption>Chain Reaction orbs</figcaption></figure><p><strong>In a move, the player clicks at any cell which is either vacant or is colored the same as that player, and it increases the number of orbs in that cell by one.</strong> The gif below shows some moves in the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*V6boL7w4WMzc9KmImlK9pA.gif" /><figcaption>Some moves in the beginning</figcaption></figure><p>There is a limit to how many orbs can reside in a particular cell. <strong>A cell can at most hold “Number of orthogonally adjacent neighbors of that cell -1”</strong>. For cells in the middle, that number is 3, for cells at the edges that number would be 2, and for corner cells, that would be 1. The picture below shows this maximum number of orbs for each cell in a 5x5 board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmCysUX6dhTIw-KFQo0-Bw.png" /><figcaption>Left: The maximum number of orbs that can reside in each cell. Right: All filled cells except the one in the center-left.</figcaption></figure><p>But what happens when a player clicks at a cell which already holds the maximum number of orbs? <strong>The orbs in that cell split, pushing all its orbs to its neighboring cells</strong>. The gif below shows the split for different kinds of orbs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*W3GTsWtnWDMOpFQn0nL8Eg.gif" /><figcaption>Orbs split when the number of orbs exceed the limit in any cell</figcaption></figure><p>During a split,<strong> if the neighboring cell contains orbs from the other player, then those orbs change their color to the current player</strong>. Such a split can be seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*JhM9p0-6jr46KR15th-hyw.gif" /><figcaption>Enemy orbs in the neighboring cells change color after a split happens in the current cell</figcaption></figure><p>A cell after a split increases orbs in its neighborhood. Thus, it can lead to further multiple splits, starting a <strong>chain reaction</strong> of splits, which is where the game gets its name from. Long chain reactions after just a single move is what makes this game unpredictable towards the end.</p><p>Now we know how the game proceeds from one state to the next state, there can be splits; or there can just be an increment of orbs in a single cell. But how does a player win? The goal of the game is straightforward, <strong>a player has to eliminate all its enemy orbs from the board</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*tzwItWumPWBMxbVzzmZohA.gif" /><figcaption>A player wins when all enemy orbs are eliminated from the game</figcaption></figure><h4>State of the game</h4><p>What information do we need to store to capture any state of this game? We need two things — firstly, <strong>an M x N array which tells us the number and type of orbs in each of the M*N cells on the board, </strong>and secondly<strong>, whose turn it is, ‘red’ or ‘green’</strong>. We can use positive numbers to represent number of red orbs and negative numbers to represent number of green orbs. The following image shows an example of how to represent a board state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSCqT8jcH11bR-f_NKKG6w.png" /><figcaption>State Representation</figcaption></figure><h4>State Transition</h4><p>Now that we know how to represent a state, we want to focus on a more important question, <strong>how can we get the next state given the current state</strong>. To get the next state, we need to know the cell where the player has clicked. Let’s call that cell as the <strong>event cell</strong>.</p><p>We’ll do some processing on the event cell, which’ll look something like this. We’ll add an orb to it, and check if the number of orbs exceed the cell’s limit. If the orbs exceed in number, then we need to split the orbs.</p><p>In case of a split, each of the neighbors of the event cell would get one orb, and then we would process those neighbors, and so on. We observe that we are first processing the event cell, then the neighbors of the event cell, then the neighbors of the neighbors of the event cell and so on. The neighbors at some level i, can be processed in any order; the end result of processing all the neighbors at level i in any order would be the same. An example of this can be seen in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*DzpQ4mMpTTRpnbMJJK3a3g.jpeg" /><figcaption>Processing cells at the same level in two different ways give the same final state. The reason why the processing order at level i doesn’t matter is because, there are two types of cells at level i, those which split and those which don’t. Those cells which don’t split, their orb count just gets increased by one irrespective of the processing order. And those cells that split, they only add orbs to the cells at level i+1. Now, here is the fact that holds the whole argument, the sets of cells at level i and level i+1 are always disjoint, therefore the sum of those additions taken over all the cells at level i is always the same for each cell at level i+1.</figcaption></figure><p>So, what we are essentially doing is a <strong>breadth-first traversal, which is why we would implement state transition with the help of a queue</strong>.</p><h4>Implementation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u48UDMRlShg9kz-VsyDJ3w.png" /><figcaption>Some important components for implementing the Chain Reaction Game</figcaption></figure><h4>State</h4><p>Implementing state representation is somewhat straightforward. We store the board info as number of orbs and color of orbs in different numpy arrays. The state representation also includes the player’s turn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inYlRqG2nnUL4iy7yz1i1g.png" /><figcaption><a href="https://gist.github.com/thunderInfy/a5594e1a17c8f90321992828669e72c6">Gist</a> showing code for class State</figcaption></figure><h4>Visualizer</h4><p>And here is some code to draw the grid and orbs using rectangles and circles respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0dV55P_4KgTQYUCAmB_5BA.png" /><figcaption><a href="https://gist.github.com/thunderInfy/7e2f865d9c07cef253bcab559db8d657">Gist</a> showing code for class Visualizer</figcaption></figure><h4>Controller</h4><p>Here we will look at the most important code segment in controller, which is the state transition, i.e., getting the next state, given the current state and an event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5bIgpnn9sBmvgGd4BlT2QQ.png" /><figcaption><a href="https://gist.github.com/thunderInfy/45e6d3c25889bd1f9245a03d05c47d34">Gist </a>showing code for state transition</figcaption></figure><p>There can be a condition, in which the orbs keep on splitting, and the other player’s orbs vanish, as shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2U3KlnDO2DtNWSGm2wPEQ.png" /><figcaption>The orbs keep on splitting, and green has won the game</figcaption></figure><p>So, <strong>we need to check if a player has won the game inside the breadth first traversal while loop</strong>. We have checked it by keeping track of red and green orbs counts (as <em>myorbs</em> and <em>opporbs</em>), and updating them with each iteration of the loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhmpkaYlFDlCqadXPBy4CQ.png" /><figcaption><a href="https://gist.github.com/thunderInfy/654661aa13c00ec7677197ded4615542">Gist </a>showing code to track counts of orbs of both the current player and the opponent</figcaption></figure><h3>AlphaZero</h3><h4>So what’s really happening in AlphaZero</h4><p><a href="https://www.youtube.com/watch?v=v9M2Ho9I9Qo">[5]</a> would be a good starting point to understand AlphaZero. There are two kinds of thinking involved in human reasoning <a href="https://arxiv.org/pdf/1705.08439.pdf">[6]</a> — a slow and a fast mode of thinking. The fast mode is guided by intuition and the slow mode is guided by explicitly following some rules or steps like that of a traditional computer algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZbLxqnZxxi--nO9ODqKQUg.png" /></figure><p>In AlphaZero, <strong>the fast mode or</strong> <strong>the intuition is implemented through a neural network</strong> that takes a board state and outputs a policy (a probability distribution over actions) and a value (a score that tells how good is the given board state for the current player); and t<strong>he slow mode of thinking is implemented through Monte Carlo Tree Search</strong>.</p><p>Imagine that we’re thinking what to play in a particular board state for any perfect information game (here we’re taking the example of Chain Reaction). We might have some intuition about which actions are better and which are not. This original intuition can be expressed as a probability distribution over actions. We’ll assign a higher probability to good actions and lower to bad actions (good actions being those that give us a winning position). If we don’t have any such intuition, then we can just start with a uniform probability distribution.</p><p>This probability distribution over the actions is our “policy” for the given state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gtT3H5Pk0FHj2LRLN6gQg.png" /><figcaption>A cycle of Amplification and Distillation can build expert agents</figcaption></figure><p>There is a way to improve this original policy — <strong>by thinking of possible future moves ahead in time</strong>. Starting from our current state, we can think about what moves we can play and what moves our opponent can play and so on. So we are essentially talking about a tree search. This tree search can be improved by using our original intuition to evaluate the intermediate board states (getting values), and probably not spending a lot of time in exploring nodes which have low value. <strong>After doing this tree search, we will have a better idea of what to play in the current board state, in other words, we get an improved policy</strong>. This entire process is known as <strong>amplification</strong>. This is done using <strong>Monte Carlo Tree Search</strong> in AlphaZero.</p><p><strong>Distillation </strong>is <strong>using this improved policy (obtained through the slow process) to improve our fast mode of thinking</strong>. In the case of AlphaZero, this means optimizing the neural network to minimize the cross entropy loss between the improved policy and the original policy. There would also be another loss term between value predictions of the neural network and actual value obtained at the end of a game. We will discuss this in implementation-level detail later.</p><p><em>Written by </em><a href="https://thunderinfy.github.io/portfolio/"><em>Aditya Rastogi</em></a><em>. Thanks to </em><a href="https://www.linkedin.com/in/aayush-pandey-765a94200/"><em>Aayush Pandey</em></a><em> for the help. The figures have been drawn using </em><a href="https://excalidraw.com/"><em>Excalidraw</em></a><em>. Images for code snippets have been generated using </em><a href="https://carbon.now.sh/"><em>Carbon</em></a><em>.</em></p><h3>References</h3><p>[1] Silver, D., Hubert, T., Schrittwieser, J., Antonoglou, I., Lai, M., Guez, A., Lanctot, M., Sifre, L., Kumaran, D., Graepel, T., Lillicrap, T., Simonyan, K., &amp; Hassabis, D. (2018). A general reinforcement learning algorithm that Masters Chess, Shogi, and go through self-play. <em>Science</em>, <em>362</em>(6419), 1140–1144. <a href="https://doi.org/10.1126/science.aar6404">https://doi.org/10.1126/science.aar6404</a></p><p>[2] <a href="https://brilliant.org/wiki/chain-reaction-game/">https://brilliant.org/wiki/chain-reaction-game/</a></p><p>[3] Wu, D. J. <em>[PDF] accelerating self-play learning in go: Semantic scholar</em>. <a href="https://www.semanticscholar.org/paper/Accelerating-Self-Play-Learning-in-Go-Wu/f244ffb549a61806d00f614e70fa1c3fbe5fffc6">https://www.semanticscholar.org/paper/Accelerating-Self-Play-Learning-in-Go-Wu/f244ffb549a61806d00f614e70fa1c3fbe5fffc6</a></p><p>[4] <a href="https://medium.com/oracledevs/lessons-from-implementing-alphazero-7e36e9054191">https://medium.com/oracledevs/lessons-from-implementing-alphazero-7e36e9054191</a></p><p>[5] “How to Keep Improving When You’re Better Than Any Teacher — Iterated Distillation and Amplification.” <em>YouTube, </em>uploaded by Robert Miles, 3 Nov. 2019, <a href="https://www.youtube.com/watch?v=v9M2Ho9I9Qo">https://www.youtube.com/watch?v=v9M2Ho9I9Qo</a>.</p><p>[6] Anthony, T., Barber, D., &amp; Tia, Z. <em>Thinking fast and slow with deep learning and Tree Search</em>. <a href="https://arxiv.org/pdf/1705.08439.pdf">https://arxiv.org/pdf/1705.08439.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cffdc399233" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>