<?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 Wesley Liao on Medium]]></title>
        <description><![CDATA[Stories by Wesley Liao on Medium]]></description>
        <link>https://medium.com/@wesleyliao3?source=rss-7b95d571024d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lFtgRr3kE1WUWRNfqpNQaQ.jpeg</url>
            <title>Stories by Wesley Liao on Medium</title>
            <link>https://medium.com/@wesleyliao3?source=rss-7b95d571024d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:44:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wesleyliao3/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[Achieving human-level performance in QWOP using Reinforcement Learning and Imitation Learning]]></title>
            <link>https://medium.com/data-science/achieving-human-level-performance-in-qwop-using-reinforcement-learning-and-imitation-learning-81b0a9bbac96?source=rss-7b95d571024d------2</link>
            <guid isPermaLink="false">https://medium.com/p/81b0a9bbac96</guid>
            <category><![CDATA[thoughts-and-theory]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Wesley Liao]]></dc:creator>
            <pubDate>Fri, 26 Feb 2021 00:09:28 GMT</pubDate>
            <atom:updated>2021-03-12T21:23:58.522Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/thoughts-and-theory">Thoughts and Theory</a></h4><h3>Achieving super-human performance in QWOP using Reinforcement Learning and Imitation Learning</h3><h4>The game is surprisingly difficult and shows the complexity of human locomotion.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fynBZlGDIbGBf7ppGWoaMA.png" /><figcaption>Agent training hard! Game from <a href="http://www.foddy.net/Athletics.html">QWOP</a>. (Image by author)</figcaption></figure><h3>Introduction</h3><p><a href="http://www.foddy.net/Athletics.html">QWOP</a> is a simple running game where the player controls a ragdoll’s lower body joints with 4 buttons. The game is surprisingly difficult and shows the complexity of human locomotion. Using machine learning techniques, I was able to train an AI bot to run like a human and achieve a finish time of 47 seconds, a <a href="https://www.speedrun.com/qwop">new world record</a>. This article walks through the general approach as well as the training process. Huge thanks to Kurodo (<a href="https://twitter.com/cld_el">@cld_el</a>), one of the world’s top speedrunners, for donating encoded game recordings to help train the agent.</p><h3>Environment</h3><p>The first step was to connect the QWOP to the AI agent so that it can interact with the game. To retrieve the game state, I wrote a Javascript adapter that extracted key variables from the game engine and made them accessible externally. Then Selenium was used to read game variables in Python and to send key presses to the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDfsjzx2vNxYLwq6xOmyFQ.png" /><figcaption>Environment setup. Game screenshot from <a href="http://www.foddy.net/Athletics.html">QWOP</a>. (Image by author)</figcaption></figure><p>Next, the game was wrapped in an OpenAI gym style environment, which defined the state space, action space, and reward function. The state consisted of position, velocity and angle for each body part and joint. The action space consisted of 11 possible actions: each of the 4 QWOP buttons, 6 two-button combinations, and no keypress.</p><h3>Approach</h3><p>The first agent’s learning algorithm was Actor-Critic with Experience Replay (ACER)². This Reinforcement Learning algorithm combines Advantage Actor-Critic (A2C) with a replay buffer for both on-policy and off-policy learning. This means the agent not only learns from its most recent experience, but also from older experiences stored in memory. This allows ACER to be more sample efficient (i.e. learns faster) than its on-policy only counterparts.</p><p>To address the instability of off-policy estimators, it uses Retrace <em>Q</em>-value estimation, importance weight truncation, and efficient trust region policy optimization. Refer to the original paper² for more details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*vwu2JBpTXa7O-NuT6K7mKw.png" /><figcaption><em>ACER learning step pseudo-code for discrete actions. Taken from </em><a href="https://arxiv.org/pdf/1611.01224.pdf"><em>ACER paper</em></a><em>.</em></figcaption></figure><p>ACER is fairly complex compared to most RL algorithms, so I used the Stable Baselines³ implementation instead of coding it myself. Stable Baselines also provided custom environment integration and pre-training capabilities which later proved to be very valuable.</p><p>The underlying Neural Network consisted of 2 hidden layers of 256 and 128 nodes, all fully connected with <a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)">ReLU</a> activations. The diagram below illustrates how the network ingests game states and produces candidate actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8IRAKK2XVCy1-iVfy76ieg.png" /><figcaption>Illustrative: reinforcement learning agent neural network architecture. Actions are sampled during training but can be made deterministic during testing. (Image by author)</figcaption></figure><p>The full architecture is a bit more complex and contains more network outputs including a <em>Q</em>-value estimator.</p><p>In the second iteration of the agent, Prioritized DDQN⁷ was used to perfect the running technique and optimize for speed. This algorithm combines DQN with a number of features to stabilize and accelerate off-policy learning. This agent used the same network structure and activation function as the ACER one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwgX1NzmQkZcWcv_SwTKEw.png" /><figcaption><em>Prioritized DDQN pseudo-code. Taken from </em><a href="https://arxiv.org/pdf/1511.05952.pdf"><em>PER paper</em></a><em>.</em></figcaption></figure><h3>Training</h3><h4><strong>Initial Trials</strong></h4><p>I first attempted to train the agent entirely through self-play. I was hoping the agent could learn to perform human locomotion similar to what DeepMind achieved in Mujoco environments⁴. However, after a number of trials, I noticed the only way it learned to finish the 100m was through “knee-scraping.” This was consistent with many previous attempts at solving QWOP with machine learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/0*JiygbO62KUCWBWQi.gif" /><figcaption>AI learns to finish through knee scraping. Recoded from <a href="http://www.foddy.net/Athletics.html">QWOP</a>.</figcaption></figure><p>The agent simply wasn’t discovering the stride mechanic and instead learns the safest and slowest method to reach the finish line.</p><h4>Learning to Stride</h4><p>I then tried to teach the concept of strides to the agent myself. This is similar to the approach used by DeepMind for the original AlphaGo⁴, where the agent was first trained to mimic top players before self-play. However, I didn’t know any top players at the time so I tried to learn the game myself. Unfortunately, I’m quite terrible at the game and after a day of practice, I could only run about 28 meters.</p><p>Although I played poorly, I was still using legs in a way that a human would. I thought maybe the agent can pick up some signals from that mechanic. So I recorded and encoded 50 episodes of my mediocre play and fed it to the agent. Not surprisingly, the result was quite poor — the agent understood the <em>idea</em> of a stride but had no idea how to apply it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*sXGxEfXtIc9QmQuE.gif" /><figcaption>AI trying to imitate my striding behavior. Recoded from <a href="http://www.foddy.net/Athletics.html">QWOP</a>.</figcaption></figure><p>I then let the agent train by itself to see if it could make use of the new technique. To my surprise, it actually learned to take strides and run like a human! After 90 hours of self-training, it was able to run a decent pace and complete the race in 1m 25s, which is a top 15 speedrun but still far from the top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*5yqeZSp6BIKDJsGC.gif" /><figcaption>AI finally learns to take strides. Recoded from <a href="http://www.foddy.net/Athletics.html">QWOP</a>.</figcaption></figure><p>The agent wasn’t discovering a special technique used by all of the top speed runners: swinging the legs upwards and forwards to create extra momentum. I wanted to show the AI this technique but I was definitely not skilled enough to demonstrate it myself, so I reached out for help.</p><h4>Learning Advanced Techniques</h4><p>Kurodo (<a href="https://twitter.com/cld_el">@cld_el</a>), one of the world’s top QWOP speedrunners, was generous enough to record and encode 50 episodes of his play for my agent to learn from. I first tried supervised pre-training like before but the results were not great. The agent could not make use of the data immediately, and then quickly forgets/overwrites the pre-training experience.</p><p>I then tried injecting the experience directly into the ACER replay buffer for off-policy learning. Half of the agent’s memory would be games it played and the other half would be Kurodo’s experiences. This approach is somewhat similar to Deep Q-learning from Demonstrations (DQfD)⁶ except we don’t add all the demonstrations at the start, we add demonstrations at the same rate as real experience. The behavior policy <em>µ(·|s)</em> must also be included with each injection. Although there is little theoretical basis for this scheme, it worked surprisingly well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/0*img6ipBSfcHYAeEA.gif" /><figcaption>AI learns advanced leg swing technique. Recoded from <a href="http://www.foddy.net/Athletics.html">QWOP</a>.</figcaption></figure><p>However, the agent’s policy (actions) would become unstable after a while because it was unable to fully reconcile the external data with its own policy. At which point I removed the expert data from its memory and let it continue training by itself. The final agent had the following training schedule: pre-training, 25 hours by itself, 15 hours with Kurodo’s data, and another 25 hours by itself. The best recorded run of this agent was 1m 8s, which is a top 10 speedrun.</p><h4>Optimizing for speed</h4><p>Now that the agent mastered the correct techniques, I created a new agent solely for the purpose of improving speed. I recorded runs of the ACER agent and fed it to a new Prioritized DDQN⁷ agent. This DQN variant was chosen because it’s much more sample efficient so it can quickly optimize the techniques already learned by ACER.</p><p>The reward function was also modified. Previously it had a number of penalties including penalties for low torso height, vertical torso movement, and excessive knee bending. When the agent was just learning to stride, these helped stabilize its running technique. But now that it knows how to stride, I took the training wheels off and let it optimize purely for forward velocity.</p><p>The effective frame-rate for both training and testing were increased to 18 and 25 (from 9 previously) so that the agent could make more precise actions. The new agent was first pre-trained with ACER’s runs and then improved through self-learning. It did not do mixed memory training with Kurodo’s data like ACER did. It was trained for a total of 40 hours, of which all of it was self-learning except for a couple of minutes of pre-training.</p><h3>Results</h3><p>The best recorded run of the final agent was 47.34 seconds(below) which is faster than the best recorded run by a human (<a href="https://www.speedrun.com/qwop">48.34 seconds</a>). With this, QWOP is added to the list of games where AI has surpassed humans.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSFgqjM3tFtw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSFgqjM3tFtw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSFgqjM3tFtw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/29bd2a299b2052c895bf72c0f49e0df1/href">https://medium.com/media/29bd2a299b2052c895bf72c0f49e0df1/href</a></iframe><h3>Links</h3><ul><li>1st Agent Video Summary: <a href="https://youtu.be/-0WQnwNFqJM">https://youtu.be/-0WQnwNFqJM</a></li><li>2nd Agent Video Summary: <a href="https://youtu.be/82sTpO_EpEc">https://youtu.be/82sTpO_EpEc</a></li><li>Github Repository: <a href="https://github.com/Wesleyliao/QWOP-RL">https://github.com/Wesleyliao/QWOP-RL</a></li></ul><p><em>Article updated on 3/6/21 with new DQN model and world record run.</em></p><h3>References</h3><ol><li>QWOP (Foddy, 2008)<br><a href="http://www.foddy.net/Athletics.html">http://www.foddy.net/Athletics.html</a></li><li>Sample Efficient Actor-Critic with Experience Replay (Wang et al., 2017)<br><a href="https://arxiv.org/pdf/1611.01224.pdf">https://arxiv.org/pdf/1611.01224.pdf</a></li><li>Stable baselines (Hill, et al., 2018) <br><a href="https://github.com/hill-a/stable-baselines">https://github.com/hill-a/stable-baselines</a></li><li>Emergence of Locomotion Behaviours in Rich Environments (Heess et al., 2017)<br><a href="https://arxiv.org/pdf/1707.02286.pdf">https://arxiv.org/pdf/1707.02286.pdf</a></li><li>Mastering the game of Go with deep neural networks and tree search (Silver et al., 2016)<br><a href="https://doi.org/10.1038/nature16961">https://doi.org/10.1038/nature16961</a></li><li>Deep Q-learning from Demonstrations (Hester et al., 2017)<a href="https://arxiv.org/pdf/1704.03732.pdf"><br>https://arxiv.org/pdf/1704.03732.pdf</a></li><li>Prioritized Experience Replay<br><a href="https://arxiv.org/pdf/1511.05952.pdf">https://arxiv.org/pdf/1511.05952.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81b0a9bbac96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/achieving-human-level-performance-in-qwop-using-reinforcement-learning-and-imitation-learning-81b0a9bbac96">Achieving human-level performance in QWOP using Reinforcement Learning and Imitation Learning</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[Life as a Randomized Optimization Problem]]></title>
            <link>https://wesleyliao3.medium.com/life-as-a-randomized-optimization-problem-edcaccfccab8?source=rss-7b95d571024d------2</link>
            <guid isPermaLink="false">https://medium.com/p/edcaccfccab8</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[life-lessons]]></category>
            <dc:creator><![CDATA[Wesley Liao]]></dc:creator>
            <pubDate>Sat, 13 Feb 2021 23:33:54 GMT</pubDate>
            <atom:updated>2021-02-13T23:47:37.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeZYF9PgaIkhMGqiAKGoNA.jpeg" /><figcaption>Pyrenees mountains from above [<a href="https://www.flickr.com/photos/39997856@N03/8648153744">source</a>]</figcaption></figure><p>Suppose the purpose of life can be captured in some mathematical function. That function would reflect the amount of money you have, the number of meaningful relationships in your life, your mental &amp; physical health, and any other factors you find important. The function would take as an input the state of the universe, and output a number quantifying how fulfilled you are with life. Since we all have different values and goals, everyone’s function is different.</p><p>Naturally, the purpose of one’s life would be to maximize their function, but it’s not that easy. The behavior of this function is not very transparent. Given some other state of the universe, we can’t be sure if the function will evaluate higher or lower, or how it will evolve over time. When we ask ourselves questions like “how happy would I be if I dating him/her?” or “how successful would I be if I had taken that career path?” we really don’t know the answer for certain unless we live that other universe. However, as we go through life, we gain information and develop heuristics for evaluating states.</p><p>So how does one go about maximizing this function over the long run? Well, it just so happens that optimizing black-box functions has been well studied in the field of Randomized Optimization.</p><h3><strong>Exploration vs. Exploitation</strong></h3><p>There are two general approaches to decision making: exploration and exploitation. Exploration is the idea that we don’t always have to take the action that most immediately benefits us; sometimes it’s to our benefit to make random choices. By exploring options outside of what is obviously good right now, we can stumble upon states of faster improvement and greater heights.</p><p>Exploitation is taking the action that is most immediately beneficial. This is also called the greedy approach since we’re only doing what’s best for us now, but not thinking about the possibilities that are outside of our current reach.</p><h3>Hill Climbing / Gradient Ascent</h3><p>The easiest way to live life is to live one day at a time, only maximizing our function in the local domain. In optimization, this algorithm is called Hill Climbing or Gradient Ascent.</p><p>In our lives, we can predict with some confidence if some candidate state will improve our function or not, but only if that candidate closely resembles our current state. For example, I know that eating ramen tonight will make me happier than if I eat broccoli, so I will choose the former to maximize my function. However, there are serious drawbacks to this approach, which is that you may be sacrificing longer term benefits for short term gain, and not sufficiently exploring alternative paths.</p><h3>Simulated Annealing</h3><p>A more balanced approach to life would be to incorporate some exploration into exploitation, to take a risk once in a while. A well known algorithm called Simulated Annealing does just that. The idea is that there is a set “temperature” schedule, which dictates how willing you are to take a non-beneficial move. As time goes on, the temperature decreases and the algorithm only makes exploitative moves. This is analogous to risk-tolerance in our every day lives. As we’re younger, it’s best to explore a variety of state types, this could be academic interests, career interests, or choice of romantic partners. As we get older, it’s best to not take as many downward steps (i.e. big risks) and instead focus on improving based on your local neighborhood of states.</p><h3>Estimation of Distribution Algorithms</h3><p>One crucial aspect that the algorithms above do not account for is that, as you evaluate the function at different states, the less black-box the function becomes. You gain information on where optimums might lie and how you might get there. Estimation of Distribution Algorithms (EDAs) use this idea and constructs a candidate distribution which is refined after each action with new information gained. This helps greatly improve the optimization process and usually allows the user to find an optimum in much fewer steps than without. However, the trade-off is that you spend more time at each step infusing new information into the candidate distribution.</p><p>The analog in life is that, as you gain experience, you learn from those experiences and build up a mental model of what might improve your life function. You learn about what makes you happy, what makes you more money, and other key pieces of knowledge that allow you to foresee the results of your decisions to some extent. This information isn’t perfect however, they’re only heuristics. By reflecting and introspecting, we can build better mental models of our life function and make more beneficial decisions in our life.</p><p><em>Originally written: Mar 7, 2019</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edcaccfccab8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>