<?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 Max Lefarov on Medium]]></title>
        <description><![CDATA[Stories by Max Lefarov on Medium]]></description>
        <link>https://medium.com/@mlefarov?source=rss-6e9c71f9fa00------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JY0aIlKCHqRxOiKRHF6jSA.jpeg</url>
            <title>Stories by Max Lefarov on Medium</title>
            <link>https://medium.com/@mlefarov?source=rss-6e9c71f9fa00------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 19:32:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mlefarov/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[Numpy’s random choice in Go]]></title>
            <link>https://medium.com/data-science/numpys-random-choice-in-go-d65bc2838191?source=rss-6e9c71f9fa00------2</link>
            <guid isPermaLink="false">https://medium.com/p/d65bc2838191</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Max Lefarov]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 16:37:51 GMT</pubDate>
            <atom:updated>2024-01-23T16:37:51.787Z</atom:updated>
            <content:encoded><![CDATA[<h3>Numpy’s random choice in GoLang</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2enDpuNRjqnuz2daemnWIQ.png" /><figcaption>Generated with ChatGPT</figcaption></figure><p>Recently I’ve assisted with implementing some logic in Java that could easily be achieved with a single call of Numpy’s random.choice. It ended up being one of those tasks that allow looking into things you’re using every day but never have time to fully understand how they work. Also for quite some time I wanted to start learning Go, so why not kill two birds with one stone and reimplement random.choice once again this time in Go?</p><p>random.choice allows us to sample N elements from a provided collection according to the specified probabilities. Importantly (for the use case that motivated this work), it allows us to sample these elements without replacements. I.e. if an element of collection was already sampled it won’t be sampled again. For example, if we have a collection [A, B, C] with associated probabilities [0.1, 0.7, 0.2] and we want to sample 3 elements without replacements, most of the time we’ll get [B, C, A] as an output. If we sample with replacement, the expected output would be [B, B, B].</p><p>First, let’s define the signature of the Go function. We want to keep it as close to Numpy’s counterpart as possible.</p><pre>func Choice[T any](<br> arr []T,<br> size int,<br> replace bool,<br> probs []float64,<br> rng *rand.Rand,<br>) ([]T, error) {}</pre><p>A few things to notice about the function signature:</p><ul><li>We’re using the generic type T. It allows calling this function for arrays of different types (as long as it satisfies the type constraint, which is none in our case). This should mimic the Pythonic semantics of random.choice, i.e. it doesn’t care about the type of elements stored in the input array.</li><li>We also pass the pointer to a random number generator (rng) object that we’ll use for sampling. I’ve picked up this style of defining random functions (compared to accessing the global instance of rng) from Jax. In my experience, it simplifies testing and reproducibility.</li><li>The function has two returns, one is the array of samples, and the second one of the type error . That’s the way to handle the “exception” execution flow in Go (Go doesn’t have assertions or exceptions).</li></ul><p>Now we need to figure out how to sample elements from the discrete probability distribution defined by the probs argument using only float random numbers sampled uniformly between [0, 1] returned by the rng. Luckily there’s a method for doing exactly that.</p><h3>CDF Inversion Method</h3><p>First of, CDF stands for cumulative distribution function. In the discrete case, it can be represented as the array where an element at index i is equal to the sum of all input probabilities up to and including the position i. Let’s materialize this formulation in a simple helper function.</p><pre>func CDF(probs []float64) []float64 {<br> cdf := make([]float64, len(probs))<br> cum := 0.0<br><br> for i := range cdf {<br>  cum += probs[i]<br>  cdf[i] = cum<br> }<br><br> return cdf<br>}</pre><p>With CDF of the discrete probability distribution and the random number generator, we can sample elements from the input collection by:</p><ol><li>Sample a random float between [0, 1] from the Unirofrm distribution.</li><li>Find the first index where the CDF value is ≥ to the random float.</li><li>Return the element of the original collection at this index.</li></ol><p>To understand why it works, we can do a simple visual experiment. We can think about values in the CDF array being the right borders of the bins placed on the interval between [0, 1]. The width of a bin is proportional to the input probability. When generating the uniform random float between [0, 1] we can think about randomly throwing the ball on the interval and choosing the bin that we hit. The probability of hitting the bin is then proportional to the input probability (exactly what we need). Here’s the visual demonstration for our last example of collection [A, B, C] with associated probabilities [0.1, 0.7, 0.2].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_IZVPQmt-jQHJ-HzvlS89Q.png" /><figcaption>Created by the author in Excalidraw</figcaption></figure><p>To get the index of the bin we can return the index of the first right border that is greater or equal to the sampled value. Again, a simple helper function for doing exactly this:</p><pre>func FindIndexFromRight(val float64, cdf []float64) int {<br> for i, cumProb := range cdf {<br>  if cumProb &gt;= val {<br>   return i<br>  }<br> }<br><br> return len(cdf) - 1<br>}</pre><h3>Putting everything together</h3><p>With that, we have everything to implement random.choice with repetitions. Sampling without repetitions requires one more trick. To ensure that we don’t draw the element that was already sampled, we can mask its probability with 0 after sampling. This, however, will invalidate our discrete probability distribution because its sum will no longer amount to 1. To correct for that we need to re-normalize the probabilities by dividing them by the new total sum. As a bonus, we can perform re-normalization directly on CDF instead of re-normalizing input probabilities and then computing CDF. Putting everything together:</p><pre>func Choice[T any](<br> arr []T,<br> size int,<br> replace bool,<br> probs []float64,<br> rng *rand.Rand,<br>) ([]T, error) {<br> if !replace &amp;&amp; (size &gt; len(arr)) {<br>  return nil, errors.New(&quot;cannot sample more than array size without replacements&quot;)<br> }<br><br> samples := make([]T, size)<br> probsCopy := make([]float64, len(probs))<br> copy(probsCopy, probs)<br><br> for i := 0; i &lt; size; i++ {<br>  cdf := CDF(probsCopy)<br><br>  if !replace {<br>   total := cdf[len(cdf)-1]<br>   for cdfInd := range cdf {<br>    cdf[cdfInd] /= total<br>   }<br>  }<br><br>  randFloat := rng.Float64()<br>  sampledIndex := FindIndexFromRight(randFloat, cdf)<br>  samples[i] = arr[sampledIndex]<br><br>  if !replace {<br>   probsCopy[sampledIndex] = 0.0<br>  }<br> }<br><br> return samples, nil<br>}</pre><p>Again, a few things to pay attention to:</p><ul><li>If we sample without replacement we can’t sample more than the initial size of an input collection.</li><li>Go passes “slices” (arrays without defined size) as mutable arguments. Thus, we make a copy the of input probabilities for not to mess up the original array with masking.</li></ul><p>And the driver code:</p><pre>rngSource := rand.NewSource(time.Now().UnixNano())<br>rng := rand.New(rngSource)<br><br>arr := []string{&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;}<br>probs := []float64{0.1, 0.6, 0.2, 0.1}<br><br>samples, err := Choice(arr, 3, false, probs, rng)<br>if err != nil {<br> log.Fatal(err)<br>}<br><br>fmt.Println(&quot;Samples: &quot;, samples)</pre><p>That’s it, feel free to drop a question in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d65bc2838191" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/numpys-random-choice-in-go-d65bc2838191">Numpy’s random choice in Go</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blind Chess Log [0]]]></title>
            <link>https://medium.com/data-science/blind-chess-log-0-d6b05c6cf90c?source=rss-6e9c71f9fa00------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6b05c6cf90c</guid>
            <category><![CDATA[alphazero]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[games]]></category>
            <dc:creator><![CDATA[Max Lefarov]]></dc:creator>
            <pubDate>Mon, 18 Oct 2021 14:01:12 GMT</pubDate>
            <atom:updated>2021-10-18T14:01:12.197Z</atom:updated>
            <content:encoded><![CDATA[<h4>Monte Carlo Tree Search for partially-observed environments</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RiUm11pE-X75YR2C3KLmWQ.png" /><figcaption>Produced by the author.</figcaption></figure><p>Welcome to Blind Chess Log index 0. Here I’m planning to share weekly experiences of working on a Machine Learning pet-project together with my friend <a href="https://www.linkedin.com/in/gleb-tkachev-851b6096/">Gleb Tkachev</a>. The goal of the project is to develop an ML bot for Reconnaissance Blind Chess that wouldn’t do outstandingly stupid moves and maybe would be able to beat a random bot. A full set of rules can be found in <a href="https://reconchess.readthedocs.io/en/latest/">the documentation</a> for reconchess python package. But in a nutshell, it’s a Chess variant where you don’t see the opponent’s moves, and every time before deciding on your move you can choose 3-by-3 square and get the actual true state of the board there. Sounds exciting? Let’s go…</p><h4>Quite a quest</h4><p>If you read through the <a href="https://reconchess.readthedocs.io/en/latest/rules.html">rules</a> of Reconnaissance Chess and think about RL algorithm that might be applicable here, what first comes to mind? I bet that for the majority of readers it’s AlphaZero. That’s of course not without a reason. However, AlphaZero is undoubtedly a kind of “don’t try it at home” project. Despite being quite a simple approach conceptually, It’s an engineering masterpiece built by a team of outstanding scientists and engineers with quite an un-affordable budget. Its scale is what makes it so unbeatable. Of course one could try to develop some DIY clone for a single machine but the chances that it will train some reasonable behavior are quite slim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*hlZGkBGwfl-cWb7h-7Nl8Q.gif" /><figcaption>Animation is from <a href="https://www.tumgir.com/static/about">Tumgir</a>.</figcaption></figure><p>Knowing all that and without too much hesitation we of course decided to go with AlphaZero-like approach. We do have one little excuse though. We’re not aiming to reimplement AlphaZero 1-to-1, rather trying to build something inspired by it, i.e. an algorithm that combines search and learning.</p><p>My personal favorite bird-eye view on AlphaZero is that we train Policy function to compress Monte Carlo Tree Search (MCTS) iterations and Value function to predict a value estimate for the unvisited state. We then use both of them to improve the convergence of MCTS by narrowing the search with the Policy and bootstrapping the estimates with the Value function. That allows computing strong moves even when running with a restricted computational budget during the evaluation. In principle, given the infinite compute, one could solve games like Go and Chess with MCTS only. Thus starting by implementing MCTS and letting it play (even if quite miserably) sounded quite reasonable.</p><h4>Where the problem begins</h4><p>Conveniently, I had an MCTS implementation resting on my private cemetery of unfinished projects. The only problem though is that standard MCTS works for fully observed environments. Blind Chess by contrast is partially observed since you don’t see the opponent’s actions. This poses some complications…</p><p>MCTS maintains its own simulator of the environment (game) to search through the space of available actions. In order to run the search from some given state, we need to be able to reset our simulator to this state. You can see the problem, right? It isn’t so simple in the case of partially-observed environments since we DON’T know the state. To put it in the context of Blind Chess, if we assume the opponent’s moves to be a part of the simulation we can build the tree only for the first state and only if we play for White. After the first move we don’t know the actual position of our opponent’s pieces thus we don’t know from which state to start the search for the next move.</p><p><strong>Here’s an important point for the later explanations:</strong> an internal simulator of MCTS that is used for search from one single state can still return you true states. You’ll code it up and be free to do whatever you deem reasonable. However, that won’t help you to go beyond the first move and only if the first state is known (as for White player in Blind Chess). Of course, during the training we can hack anything we want, even make a true simulator return the moves of the opponent and recover the true state. But that clearly wouldn’t work for evaluation especially if your bot should play some online matches with other players.</p><p>Fortunately enough, there have been proposed quite a number of methods to adapt MCTS for partially-observed settings. We found <a href="https://papers.nips.cc/paper/2010/hash/edfbe1afcf9246bb0d40eb4d8027d90f-Abstract.html">POMCP by David Silver et al.</a> (yeah, that guy) to be the most straightforward and easy to implement and decided to go with it. The idea of this method is to combine MCTS with the particle filter estimator of the true state. I won’t go into the full fetched explanation of the paper, but here’s a summary:</p><ol><li>You branch your tree by actions and observations (instead of states as in classics) and for every node in your tree you maintain a set of possible true states. What you also will need is an internal simulator that returns the states in addition to observations (as mentioned above it isn’t a show-stopper).</li><li>At the beginning, you sample N states from the initial state distribution, which should be known (that’s the case even for the Blind Chess), and add them to the set of the Root.</li><li>For every MCTS iteration, i.e. expansion and back-propagation, you sample one of the states from the set in the current Root and reset your simulator to it. As you move through the tree, you add every new state returned by your internal simulator to the set in the next node that corresponds to the observation you got.</li><li>Once you built a tree or exceeded your computations budget you select the best move given the collected statistics and feed it to the true simulator. True simulator returns you only an observation that you use to select the correct node at the next level of the tree and promote it to Root. Then you repeat step 3.</li></ol><p>Even considering the numerous hacks provided in the paper to make your state estimate stable it still seemed to be the simplest way to address partial observability with MCTS. So we spent a good fraction of our free time in the evenings to implement it. In the beginning, we were actually worried a bit and didn’t know if “sense” actions (those where you get a true state of some 3-by-3 square) would “make sense” in this method. Fortunately, after quite some brainstorming, drawings, and coding the first prototype up we realized that they integrate quite naturally. Essentially, you spread the particle estimates of your true state over the different branches of the tree since “good” sense actions reveal additional information and result in different observations. In theory that should reduce the variance of state estimate and everything should work smoothly. However, not after a long, we realized that there’s one more problem…</p><h4>Let’s play together</h4><p>Another key ingredient of AlphaZero that is considered to be crucial for superhuman performance is Self-play. For MCTS Self-play is implement by searching for the best moves for two players in the round-robin fashion in the same tree.</p><p>Let’s forget about partial observability for now and assume that we’re building a tree for some Root state and select an action according to some statistics we’ve collected previously (or randomly if statistics isn’t available). We now transition into the state where our opponent has to make a move. So which move should we assume? I’ve already mentioned that the simplest way would be to use some fixed strategy for the opponent. However, that wouldn’t work if our true opponent plays differently. In Self-play MCTS instead, we add this state as a node and continue tree search from it as if we would play for the opponent. In essence, when expanding the tree you assume that you’re playing against an opponent who also uses MCTS. That should allow you to come up with much stronger moves. This approach also scales nicely with your computation budget. One additional benefit is that for zero-sum games (such as Chess) extending MCTS to Self-play doesn’t take much, well at least conceptually. All you need is to negate the rewards that one player gets during the rollout when back-propagating the statistics for the nodes of the opponent. Of course, that requires a general enough implementation which tracks the id of a player and carefully handles statistics updates. After quite some “design discussions” we managed to implement something like that and it seems to work reliably.</p><p>Let’s come back to our partially-observed setting, where everything gets “a bit more complicated”. Now, when building a tree for a single known state (that might be the initial state for example), we can still do Self-play thanks to our internal simulator. As mentioned, we do have full control over it and we can implement it in a way to return the opponent’s observations and actions so that we could branch on them and add corresponding nodes to our tree. The problem shows up when we exceeded our computation budget for a single move, have chosen the best one we’ve found so far, and fed it into the true simulator. The simulator state was advanced, the opponent also has made his move, but we know nothing about it. Now we need to find a new Root node in our sub-tree that corresponds to the observation where it’s our turn again and that likely contains the true state in the set of state estimates. Since we don’t know which observation our opponent got and which move he’s chosen we don’t know which branch to traverse. Thus we don’t have an estimate for the current true state and cannot reset our internal simulator to run the search again…</p><p>Sorry, I know that it might be quite difficult to grasp without some drawings, but I really don’t want to turn these logs into the full-fetched tutorial. Otherwise, I would spend more time preparing those than actually working on the project. So if you have any questions, or are excited about the topic in general, please reach out in the comments or on <a href="https://www.linkedin.com/in/mlefarov/">LinkedIn</a>. I’ll be glad to discuss it with you.</p><p>Of course, there are some simple hacks that come to mind, like traverse into the branch that corresponds to our player’s move and then pool and merge all available state estimates from the children at the next level that correspond to our turn. However, that would probably bring quite some variance into our true state estimate. In addition, according to the rules, when the opponent captures your piece you actually get some information about his move. So you might end up in a situation where you pool some states from the children that are not possible given the new information you’ve just got. Or even worse, in a situation where you don’t have any particle estimate that is consistent with the new information. In any case, that sounds like the most straightforward approach to start with, so most probably will go with it for the next week.</p><p>So, that was it for this iteration of Blind Chess Log. Stay tuned for the next update in about a week (probably).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6b05c6cf90c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/blind-chess-log-0-d6b05c6cf90c">Blind Chess Log [0]</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning for Production Scheduling]]></title>
            <link>https://medium.com/data-science/reinforcement-learning-for-production-scheduling-809db6923419?source=rss-6e9c71f9fa00------2</link>
            <guid isPermaLink="false">https://medium.com/p/809db6923419</guid>
            <category><![CDATA[machie-learning]]></category>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Max Lefarov]]></dc:creator>
            <pubDate>Mon, 26 Apr 2021 12:54:08 GMT</pubDate>
            <atom:updated>2021-04-26T12:54:08.301Z</atom:updated>
            <content:encoded><![CDATA[<h4>Application-oriented overview of our latest paper on Reinforcement Learning for Combinatorial Optimization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9nUK2z3DM_D7KDgtgBPR7A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@smudgern6">Daniel Smyth</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently I was lucky enough to be a part of the team that has published the paper <a href="https://arxiv.org/abs/2104.01646">“SOLO: Search Online, Learn Offline”</a> at SoCS’21. Though the paper is rather applied, it was still written as a scientific publication and might be a tough read for someone who isn’t used to it. Therefore I’ve decided to write a short overview and highlight its main findings.</p><p>To begin with, let me describe the problem of production scheduling, which has motivated SOLO in the first place.</p><h3>Problem Setup</h3><p>Given a set of heterogeneous machines and a set of heterogeneous production jobs, compute the processing schedule that minimizes specified metrics. Heterogeneous means that both, the machines and the jobs can have different properties, e.g. different throughput for the machines and different required processing time for the jobs, and many more in practice. Additionally, the real problem is complicated by a set of imposed constraints, e.g. jobs of class <strong>A</strong> cannot be processed on machines of class <strong>B</strong>, etc.</p><p>Theoretically, this problem is a complicated instance of the “Job scheduling” problem which together with the “Capacitated vehicle routing” is considered to be a classic of Combinatorial Optimization (CO). Though this problem is NP-hard (no exact solution in polynomial time), it is rather well-studied by the CO community, which offers a handful of methods to solve its theoretical (simplified) version. However, the majority of the methods cannot cope with real-world problem sizes or additional constraints that I’ve mentioned above. That is why most of the time people in the industry resort to some form of stochastic search combined with domain-specific heuristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ulanPBi568CHWX4EtmlaA.png" /><figcaption>Productions scheduling overview. The schedule is presented as a timeline plot. The color of a bar corresponds to the jobs and its length defines the processing time. The red-striped bar corresponds to the downtime of a machine. [The machine icon via `flatcoin.com` under the “Flatcoin license with attribution”. The rest is by author]</figcaption></figure><p>From my point of view, the problem of production scheduling combines the potential impact on real-world applications with exciting research opportunities in the domain of learning methods. Sounds like a match made in heaven for an applied research group, doesn’t it? Therefore, I assume it was quite an easy decision to establish the project for developing a learning-based solution to this problem. I’ve joined the project shortly after that.</p><h3>From Combinatorial Optimization to Markov Decision Process</h3><p>Our effort began with the well-known observation that some CO problems can be converted to Markov Decision Processes (MDPs) or Online Combinatorial Problems as they are referred to in the CO community. For that, we define the states that represent a partial solution, actions, and transition function that describes how the problem state evolves with every action taken. Let’s consider an example of an online formulation for the “Job Scheduling” problem. At a high level, we can define our state as aggregated information about all jobs in our queue and all the machines. Action can be defined as “process job <strong>J1</strong> from the queue on a free machine <strong>M1”</strong>. The transition function would then take care of removing job <strong>J1</strong> from the queue and updating the status of machine <strong>M1</strong>, advancing the current time and whatever else is needed for your specific formulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*WHoUd8ormJ3T6QIh3rJLUA.gif" /><figcaption>Online scheduling problem. The legend is equivalent to the overview plot. Green shading on the machine name indicates that it’s free at the current times step (red — is occupied). The Red dashed line in the schedule plot indicates the current time step. [The machine icon via `flatcoin.com` under the “Flatcoin license with attribution”. The rest is by author]</figcaption></figure><p>Given the MDP formulation, the sequence of actions can be optimized for a specified metric (reward). The first step down this road is the development of a simulator for your decision-making process. We’ve implemented our simulator for the production scheduling problem as a discrete event simulator based on SimPy<strong> </strong>package. Since we were targeting a real use-case we had to make sure that:</p><ol><li>The distributions over the job and machine properties match the reality as close as possible. This required a considerable Data Science effort.</li><li>The simulator includes the arrival of additional jobs. This is necessary to imitate the conditions where the scheduling solution operates continuously on a real factory. Once again, this arrival process has to be stochastic with the distributions matching the reality as close as possible (Data Science effort).</li></ol><h3>The classic of search or in search of classic</h3><p>Well, you have a simulator for your MDP, now what? Again, there are a few methods that can be applied here. As I’ve already mentioned the most popular choice in practice would be some form of random search combined with heuristics. For our project, we decided to start with the Monte Carlo Tree Search (MCTS) due to its appealing theoretical guaranties and popularity in the Reinforcement Learning community (where we come from, by the way). The main points to understand about MCTS in the context of our scheduling problem:</p><ol><li>MCTS has to run in real-time in production and its performance is limited by the number of iterations (i.e. tree expansions) that fit in your time budget. You don’t want to optimize a schedule for the next few jobs longer than it takes to process these jobs, do you?</li><li>For stochastic problems, MCTS requires a significant number of iterations to compute a decent result. As described above our problem has to be stochastic to imitate the real-world setting.</li><li>For any stochastic process in a problem, MCTS computes a Monte Carlo estimate. There’s no trivial way to use a reliable estimate for the job arrival distribution (computed from historical data) explicitly during the search.</li></ol><p>The first two points could potentially be addressed by optimizing the runtime of your simulator and MCTS implementation and scaling your compute to the Moon. However, for the majority of the real use cases, you’ll have a limit on how much you can scale. That is why there was a significant amount of research work aiming to optimize the convergence of MCTS by exploiting some form of learning (you know where it’s going don’t you?). The third point is of a more interesting kind though. One could imagine that taking into account a well-estimated job arrival distribution can unlock some advanced strategies. For example, reserving one machine for the job of a specific class (that arrive frequently), or betting on the arrival of the jobs with the better fit to the current schedule, etc. These strategies could potentially result in better schedules and depending on the scale of your production in significant cost savings.</p><h3>Search or Reinforcement Learning or both?</h3><p>So, what could we do to advance beyond the performance of MCTS? Well, given our backgrounds and bias towards the learning-based methods, the answer was quite straightforward. “Let’s apply Reinforcement Learning”. Some points why we were convinced that RL is a good fit for this problem:</p><ol><li>Most RL algorithms require a considerable offline training time. However, once trained, they can be executed much faster than search-based methods. This property is also known as compute compression.</li><li>Given the powerful enough function approximations (i.e. neural networks) and enough training time, RL algorithms are crushing the competition in the simulations. Luckily for our production scheduling problem, using the historical data we can build a quite precise simulation and can close the “sim to real” gap to an extent.</li><li>It’s possible to inject explicit knowledge about stochasticity in your environment into RL algorithms. Some of the RL methods can even address the stochasticity of the problem in a principled manner (Bayesian RL). Thus we could potentially unlock the “pro” scheduling strategies described above.</li></ol><p>When devising our RL solution, we were inspired by the significant amount of recent research proving that the Alpha* family of algorithms can be successfully applied to CO problems. Alpha* refers to AlpahGo, AlphaZero (you must’ve heard about them), and for the context of our problem any RL algorithms that exploit MCTS or other forms of search during the training or execution.</p><p>AlphaZero is quite an advanced algorithm that requires a considerable amount of engineering effort as well as significant training time. It relies on one neural network that combines the roles of policy and state value estimator. During training, MCTS iterations are compressed into the policy “part” of a network. The value “part” of the network is trained to predict the Monte Carlo estimate of a state value. Projecting MCTS into the policy network allows for an incredible performance at execution with the compute cost of a single forward pass. Even though it might be the most appealing point for our setting, the policy network is also arguably the most data and compute-hungry component of the method. It was not feasible for us at the time. That is why we decided to start simple.</p><p>We left MCTS at the execution time and worked on its faster convergence instead. We trained the Q-network offline using the well-known DQN with all the recent modifications such as Dueling, Double-Q, prioritized replay, etc. Once trained, we used it to prune the set of possible actions during the MCTS run by discarding the actions that were predicted to have a low value during the tree expansion. Besides, we used Q-network as a policy during the rollout from the non-visited state. Given that the network is properly trained, both points should result in faster convergence to the reliable state value estimate required by MCTS. Thus you can get better actions within your computation budget when running scheduling in production.</p><h3>The problem of problem encoding</h3><p>The last question to be answered is how to encode the problem states and which architecture to choose for the Q-network. The most orthodox approach would be to embed the observed information about the queued jobs and machines into vector space and define a discrete action as an index in the set of all possible “job to machine” combinations. Then one could use convolutional, recurrent, or fully connected layers to construct the network architecture. But, you’ve guessed it, two important points have to be taken into account:</p><ol><li>Different states of the simulation could include different amounts of jobs in a queue and potentially different numbers of machines.</li><li>Q-network should be insensitive (or rather sensitive in a special way) to the order of the jobs in the queue and the order of machines.</li></ol><p>The first point implies that our state-action vector space could be of varying size. This problem, however, still can be addressed by some implementation tricks like cropping the job queue and action masking. The second point is way more important and deserves a small example:</p><p><em>Let’s assume that for some state of the scheduling process the action “job </em><strong><em>J1</em></strong><em> to machine </em><strong><em>M1</em></strong><em>” got the highest Q-value. Now we swapped the first and the second job in the queue and left everything else the same. I bet, you would expect to see that the action with the highest score has now become “job </em><strong><em>J2</em></strong><em> to machine </em><strong><em>M1</em></strong><em>”.</em></p><p>Mathematically speaking, for our problem, Q-network should represent an equivariant mapping. Equivariance means that for any permutation in the mapping’s input the same permutation has to be observed in the output. Training an equivariant CNN or RNN is quite a challenging task. Fortunately, there’s a different kind of neural network that allows for easy implementation of equivariant mappings — Graph Neural Network (GNN). That is why we decided to encode the scheduling problem state in form of a bipartite graph. The graph consists of two disjoint and independent components representing jobs and machines. Each job node is connected to every machine node. The edges correspond to the actions and can be interpreted as “schedule job <strong>U</strong> on machine <strong>V</strong>”. Additionally, we maintain the global feature vector for the information in the state that can be directly attributed neither to the jobs nor to the machines. Due to the design of the GNNs and the bipartite structure of our graph, our Q-network is now equivariant to the permutations in job and machine order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBBq9apWFGlBSrQfZiRFkQ.png" /><figcaption>Q-network architecture overview. In the input bipartite graph squares correspond to the job vertices and circles to the machine vertices. The rectangle at the bottom represents the global feature vector of the entire graph. In the processed graph, action advantages are highlighted in green and state value in yellow. [Image by author]</figcaption></figure><p>Another useful property of GNN is the ability to handle an arbitrary graph topology as long as all nodes have the same feature dimensionality (same should hold for the edges). In other words, GNN can process graphs with different amounts of nodes and edges, which means that we’ve also successfully solved the problem of varying jobs number in the problem state.</p><p>In the proposed Q-network architecture GNN is a free design component. It can be adjusted for the specific problem. In particular, for the production scheduling problem, we used the Message-passing GNN with Attention and Encoding-decoding layers. After the forward propagation through GNN, we decode the edges of the output graph as advantages of the state-action pair and the global graph state as a value of the current sub-problem (state), i.e. dueling Graph-Q-network.</p><h3>Conclusion</h3><p>When putting everything together, we get our method — SOLO: Search Online, Learn Offline. Now you understand where the name comes from. I hope that I’ve managed to make the method more transparent for the reader who isn’t used to scientific publications. However, I’ve left quite a lot of details and interesting insights behind the scenes of this post. So if I’ve managed to spark at least a small interest, I highly recommend reading the original paper.</p><p>Although, the paper won’t in any way convey the huge engineering effort that went into this project just to make this seemingly simple approach run. For that, I would once again like to thanks all the collaborators.</p><p>If you have any additional questioning, feel free to write a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=809db6923419" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/reinforcement-learning-for-production-scheduling-809db6923419">Reinforcement Learning for Production Scheduling</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pattern Search with the Knuth-Morris-Pratt (KMP) algorithm]]></title>
            <link>https://medium.com/data-science/pattern-search-with-the-knuth-morris-pratt-kmp-algorithm-8562407dba5b?source=rss-6e9c71f9fa00------2</link>
            <guid isPermaLink="false">https://medium.com/p/8562407dba5b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[pattern-matching]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Max Lefarov]]></dc:creator>
            <pubDate>Sun, 20 Dec 2020 13:43:45 GMT</pubDate>
            <atom:updated>2021-09-20T17:54:55.548Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to search a pattern or a sub-string with O(n) complexity, implementation in Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7nVsiq8tcYqo82iRDsRrQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ahmadirini">Ahmad Dirini</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>So here you are, sitting and being interviewed for the position in your dream company. The interviewer, your fellow developer, whose seniority and proficiency are beyond doubt and cannot be challenged by anyone, presents you with a problem that boils down to pattern matching. Being happy and excited you announce that you would like to use a naive approach with O(nk)<strong> </strong>complexity. However, the interviewer is frowning, he’s disappointed. You can see in his eyes, filled with wisdom and experience, that he’s quickly losing interest in this conversation. His attention is fading and his thoughts are gravitating towards a free lunch, which he’ll soon get in one of those company’s legendary food courts. The rumors is that the retired Michelin chefs themselves are forging the food of gods in those shrines of catering. So what should you do, how to regain the interviewer’s favor, how to make sure that you’ll also be able to taste that fast-food miracle in a few months? The only way is to give your interviewer what he wants, the O(n) solution. “But which O(n) solution?!” — you ask me. No worries. I got your back. Please welcome our today’s guest the <strong>KMP (Knuth-Morris-Pratt) Pattern Search </strong>algorithm.</p><p>A good overview of KMP and the reasoning behind it is provided in <a href="https://medium.com/@giri_sh/string-matching-kmp-algorithm-27c182efa387">this article on Medium</a>. TL;DR when doing naive pattern matching every time you’ve encountered a mismatch between the pattern and the target string you move only one step forward in the target and start to re-match the entire pattern from the very beginning. KMP, on contrary, can help to skip several unnecessary comparisons, which will, of course, positively impact your complexity. How positively, you ask me? O(n) positively is KMP’s answer. But how does this tricky guy do that? Well, he’s using the help from his little friend an array of <strong>Longest Proper Prefix which is Suffix (LPS)</strong>, which is constructed for the pattern prior to the main phase of the algorithm. First things first, let’s understand what is LPS (the essential building block of KMP) and how it can be constructed, then write an algorithm to do so. Once we have it in our arsenal, KMP<strong> </strong>won’t seem so scary anymore, believe me.</p><h3>Longest Proper Prefix which is Suffix (LPS) array</h3><p>As the name suggests, the LSP array contains the information about the “Longest Proper Prefix which is Suffix”. No worries, I was also quite confused when I’ve seen this formulation for the first time. What does make a prefix “Proper” after all? Well, believe me, or not, but it turned out that it’s just any prefix of a word that is not equal to the word itself. So let’s take an example. For the word <strong>ACA</strong> we have the following proper prefixes: , <strong>A</strong>, <strong>AC</strong>, and the suffixes: , <strong>A</strong>, <strong>CA</strong>, <strong>ACA</strong>. Thus, the longest proper prefix that is equal to the suffix is <strong>A</strong>.</p><p>So the LPS array of some string at any position i contains the length of such a prefix for the sub-string from 0<strong> </strong>till<strong> </strong>i<strong> </strong>(pattern[:(i+1)] for my Python friends out there).<strong> </strong>In the .gif below, you can see how the LPS array is constructed manually step by step for the pattern string <strong>ACABACACD</strong>. No rush here, take your time and make sure that everything is clear for you so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*OIb4erqMedwaze8aTUi9gw.gif" /><figcaption>The manual step by step construction of the LPS array for the pattern ACABACACD. Red arrow indicates the current element of LPS. Dash bar shows the sub-string of a pattern considered for the current LPS index. Equal prefixes and suffixes are highlighted with green. [Image by Author]</figcaption></figure><p>Well, now, when we understand what is an LPS array and have seen how to construct it manually, let’s write an algorithm to do so for any given pattern. I have bad news for you though. This algorithm requires us to operate two pointers (indices). Yes, I know, I know… These kinds of algorithms are also among my least favorite, partially because it’s quite challenging to write them in a clean “Pythonic” way, and partially because my short-term memory gives up quite quickly on a task of tracking more than one pointer at once. So, in order to understand the algorithm for LPS array construction, I would propose for you to think about it in terms of “Phases” and a state-machine. That is my favorite way of approaching a new algorithm, and I hope it might be useful for you as well. Below you’ll see the picture summarizing the algorithm, followed by a detailed description in the next paragraph. If you are the kind of person who would rather read through the code than any lengthy description, please jump straight to the implementation section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgyFxDwQUoG2ygOIpjLwdg.png" /><figcaption>The description of the algorithm for the LPS array construction in terms of “Phases” and a state-machine. Triangles represent the pointers (indices). Rectangles depict the pattern string. The state-machine is plotted on the right. The resulting LPS is not presented on the plot for clarity reasons. [Image by Author]</figcaption></figure><h4>The LPS algorithm: detailed description</h4><p>As you might infer from the picture above, we’re working on a single pattern string and using two pointers which for now carry the abstract names “top” and “bottom”. The bottom pointer bp iterates over our pattern string. The top pointer tp is used to determine the LPS of the current sub-string. Additionally, we have the LPS array where the lengths of LPSs are stored. The size of LPS is equal to the pattern string’s size and is initialized with 0s.</p><p>The algorithm begins with “Phase 1”, where we move the bottom pointer and trying to find a symbol in our pattern string that is equal to the first symbol (still tracked by the tp). This phase corresponds to the search of the sub-string with the LPS of length 1<strong> </strong>(i.e., a single-letter prefix is equal to a single-letter suffix). Once found, we can write 1<strong> </strong>into our LPS<strong> </strong>array at the position of the bp. Now we can shift to “Phase 2”. Here we move both pointers while they are pointing to the equal symbols and write tp+1,<strong> </strong>i.e. the length of LPS<strong>, </strong>to the LPS at the position of the bp. In this phase we’re continuously discovering the sub-string with the longer LPS with every subsequent step. But, it might very well be that we’ll eventually run out of luck and come to the situation where the pointers are pointing towards two different symbols. That indicates that we’ve found the sub-string whose LPS is shorter than the previous one.</p><blockquote>“We are in the endgame now.”</blockquote><p>In “Phase 3” we roll back the top pointer to find the new LPS (which is smaller than the LPS at the previous bottom index). “But where should I place the top pointer?” — you ask me. Let’s figure that out. First of all, let’s consider an example of such a situation to have something to look at. We’ll crop one frame from our .gif example from the previous section. Please see the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8XYp9asoHyXkACfg2hwHg.png" /><figcaption>An example for the situation when the top pointer has to be rolled back. The triangle pointing down is the top pointer, the one pointing up is the bottom pointer. The Symbols shaded with the same colors are equal. The red dash lines indicate the pattern sub-strings up to the top and the bottom indices. [Image by Author]</figcaption></figure><p>Well, we’ve discovered that the symbol at the top pointer (3<strong> </strong>in our example) doesn’t match a symbol at the bottom pointer 7. Let’s consider the pattern’s sub-string till the bottom pointer exclusively (pattern[:bp] for those speaking Parseltongue). It’s guaranteed that its prefix from 0 to tp matches the suffix staring at (bp-tp), i.e.</p><pre>pattern[:tp] == pattern[(bp-tp):bp] </pre><p>(shaded with light green in our example). This always holds due to the definition of “Phase 1” and “Phase 2”. Thus we can state that patterns[:tp]’s LPS, is equal to the ending part of the pattern[:bp]’s suffix (shaded in blue). That allows us to move the top pointer to the next index after the patterns[:tp]’s LPS, which is already stored in LPS[tp-1] (blue 1 in the example above). The described procedure is repeated until the symbol at the new top pointer position matches the symbol at the bottom pointer (transition to the second phase), or the top pointer has become 0 (back to “Phase 1”). The algorithm terminates when the iteration over the pattern string with the bottom pointer is completed.</p><h4>The LPS algorithm: implementation</h4><p>Below you can find the “Pythonic” implementation of the algorithm for the LPS array construction. “Phases” are implemented in a reverse order here for the readability concerns. If you didn’t skip the previous section, please replace prefi and i<strong> </strong>with the “top” and “bottom” pointers in your mind.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86c927a8e78084efce695c6dc90b7b6e/href">https://medium.com/media/86c927a8e78084efce695c6dc90b7b6e/href</a></iframe><h3><strong>KMP (Knuth-Morris-Pratt) Pattern Search</strong></h3><p>Now, finally, we’re at the “main” part of KMP. But actually, there’s not too much to do for us in this main part. Once we have the LPS array constructed for our pattern string, KMP becomes quite similar to the naive pattern search. The only difference is that on a mismatch, instead of moving one symbol forward in a target text and starting from the very beginning of a pattern string, KMP uses LPS to continue from exactly the same place where the mismatch occurred. First, let’s look at the KMP’s main part “Phases” and the state-machine, similarly to what we did for the LPS construction. Then, we’ll describe in detail how exactly KMP manages to continue from the mismatch position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u1IAKPw4QfZ0hN2KU2Y2ag.png" /><figcaption>The description of the KMP’s main part in terms of “Phases” and a state-machine. The Black rectangle and triangle represent the target string and the target pointer respectively. The Blue rectangle and triangle are the pattern and the pattern pointer. [Image by Author]</figcaption></figure><p>As demonstrated in the picture above, we have a target string (black) and a pattern string (blue). We iterate over the target with the target pointer and over the pattern string with the pattern pointer. Similar to the LPS construction, the main part of KMP consists of three phases. “Phase 1” and “Phase 2” are identical to the naive pattern search. In the first phase, we’re moving in a target until we find a symbol that matches the first symbol in a pattern string. That is where the transition into the second phase happens. In “Phase 2” both, the target and the pattern pointers, are moved while the symbols, that they point to, match. If the end of the pattern string is reached, the solution is found. If the mismatch is encountered the algorithm transitions to the third phase. That is the only phase different from the naive approach. In the naive pattern search when a mismatch is found, you’re moving the target pointer one symbol forward from the place where you’ve started the comparison, and the pattern pointer (index) is reset to 0. On contrary, when running KMP, the target pointer remains at the same place, but the pattern pointer is rolled back using the information from the LPS array. In order to understand how it’s done, let’s consider an example in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGaxEHtNvfYJDxHeFV171g.png" /><figcaption>An example of the mismatch found during the patter search. The red dashed line indicates the part of a pattern and a target string matched so far. The green shading represents the Longest prefix, which is the suffix for the current pattern sub-string. [Image by Author]</figcaption></figure><p>So we did encounter the mismatch at some point in the comparison between the pattern and the target text. <strong>E</strong> is not equal to <strong>C</strong>, what a bummer. However, we can be sure that the pattern sub-string till the pattern pointer matches the target sub-string till the target pointer (red dashed line). Otherwise, we wouldn’t reach this point according to our definition of the second phase. Additionally, our LPS array for the current pattern sub-string tells us that the prefix of length 3 is equal to the suffix (shaded in green). With this information in hand, we can safely move the pattern pointer back to the fourth symbol (the first symbol after LPS) and leave the target pointer at the same place, as demonstrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPepYjAnJqlP495bjI0p8w.png" /><figcaption>An example of the KMP’s pattern pointer rollback. [Image by Author]</figcaption></figure><p>It’s guaranteed that the part of the pattern before the new pattern pointer matched the target string due to the definition of the LPS. It also holds true that we didn’t miss any possible matches between the current target pointer and the index at which we’ve started to compare last time. This shift or roll-back operation is repeated until a symbol at the new pattern pointer position matches one at the target pointer (transition to the second phase), or the pattern pointer is 0 (transition to the first phase).</p><p>We’re at the home stretch. Below you can find the code implementing the main part of KMP. As for the LPS algorithm, the “Phases” are written in reverse order here for better readability. patterni is our patter pointer from the above description and the target pointer holds a rather boring name i. One minor detail implemented below that was not discussed above is the search for all occurrences. I’m leaving it as an exercise for the curious reader (I’ll be happy to answer any question in the comments).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31c19bc11d8854e70044b7d93936e395/href">https://medium.com/media/31c19bc11d8854e70044b7d93936e395/href</a></iframe><p>So, you declare your KMP based solution to your interviewer and hope that you didn’t miss some minor detail. But apparently, it’s not important anymore. With each word spoken, his excitement is rising, he cannot believe his eyes. Finally, he managed to find the candidate who will be a good fit for the team’s most important mission of re-implementing pattern search for every standard library in every language. Maybe you’ll get that free lunch after all..</p><p>Good luck with the behavioral questions, and let me know if I can help you with anything else 😃.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8562407dba5b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/pattern-search-with-the-knuth-morris-pratt-kmp-algorithm-8562407dba5b">Pattern Search with the Knuth-Morris-Pratt (KMP) algorithm</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>