<?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 Opher Lieber on Medium]]></title>
        <description><![CDATA[Stories by Opher Lieber on Medium]]></description>
        <link>https://medium.com/@opherlie?source=rss-7ea85a9e6f1c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*6UcWXuW31qVuMVOxgU0HFw.png</url>
            <title>Stories by Opher Lieber on Medium</title>
            <link>https://medium.com/@opherlie?source=rss-7ea85a9e6f1c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 01:47:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@opherlie/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[Reinforcement Learning for Mobile Games]]></title>
            <link>https://medium.com/data-science/reinforcement-learning-for-mobile-games-161a62926f7e?source=rss-7ea85a9e6f1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/161a62926f7e</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Opher Lieber]]></dc:creator>
            <pubDate>Mon, 30 Dec 2019 16:03:21 GMT</pubDate>
            <atom:updated>2019-12-30T17:22:37.535Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learning to play Android games at scale using state-of-the-art Reinforcement Learning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BIyWMzBHApWn59n7nVNFPg.jpeg" /><figcaption>Image Source: <a href="https://pixabay.com/illustrations/artificial-intelligence-brain-think-4469138/">pixabay.com</a></figcaption></figure><h3>Introduction</h3><p>Deep Reinforcement Learning has made a lot of buzz since it was introduced over 5 years ago with the original <a href="https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf">DQN</a> paper, which showed how Reinforcement Learning combined with a neural network for function approximation can be used to learn how to play Atari games from visual inputs.</p><p>Since then there have been numerous improvements to the algorithms, continuously beating the previous benchmarks. Research and testing new algorithms typically use the fast and stable <a href="https://github.com/mgbellemare/Arcade-Learning-Environment">Atari Benchmark</a>, as well as custom-tailored environments such as those found in <a href="https://gym.openai.com/">OpenAI Gym</a> and <a href="https://github.com/deepmind/lab">DMLab</a>. In addition, we can run hundreds of classic console games using the <a href="https://github.com/openai/retro">Gym Retro</a> library using emulators.</p><p>For modern games, the main focus has recently been the hardest competitive games, in particular, Dota2 and Starcraft2. Both have achieved very impressive results from <a href="https://openai.com/projects/five/">OpenAI </a>and <a href="https://deepmind.com/blog/article/AlphaStar-Grandmaster-level-in-StarCraft-II-using-multi-agent-reinforcement-learning">DeepMind</a>, training across a huge distributed cluster, reaching total experience of thousands of years of game-play. In both these cases, the observations/inputs were numeric features and not visual frames, bypassing the need for the AI to learn how to extract these features itself as typically done for Atari games. The computing resources required are also not something most researchers or small companies have available.</p><p>Here I attempt to apply RL to some modern mobile android games, using only visual inputs as observations, and a reasonable budget amount of computational resources, on par with what’s typically considered ‘sample efficient’ when learning to play Atari games.</p><h3>Android Environments</h3><p>I use a configurable amount of Android Emulators as the environment for the RL agent to learn to play. Each emulator is controlled by an asynchronous driver which gathers experiences for training by grabbing a visual frame, selecting an action using the RL policy, sending that action back to the emulator, and sending the transition data back to be used for training.</p><h4>Not Really Emulation</h4><p>At its core, the android emulator is a ‘true emulator’, able to emulate the ARM instruction set and potentially able to be used as a fully emulated RL environment similar to the ALE or gym-retro environments, where the emulation can be paused/resumed as needed when the next action/observation step is needed. In reality though, emulation on the Android Emulator is extremely slow, especially for games, and not feasible for our task.</p><p>The only option is to run the emulator with hardware acceleration for the CPU (Using HAXM/KVM on windows/linux). In this case, an x86 android image is used and the android instructions run directly on the host CPU in real-time using virtualization. This lets us reach the stable android performance we need, but has a few drawbacks:</p><ul><li>It means the emulator runs in real-time. This means we need to consistently grab frames, select actions and send those actions with minimal latency. The agent cannot for example pause and wait for a training step to complete, so each environment instance must run asynchronously</li><li>This also means we are confined to the ‘actual play-time’, for example, 60FPS, compared to emulation environments like the ALE which can speed up emulated play-time by orders of magnitude for much faster training</li><li>Because the android emulator is now running with CPU virtualization, it makes it problematic to run the emulators on VM instances from the popular cloud providers. Some of these providers support ‘Nested Virtualization’ for this purpose, but in practice, I could not get this to work well. Either the emulator failed to boot, or it succeeded but ran much slower than on non-VM servers. This limits us to running these environments on custom server builds or ‘bare metal’ cloud servers which are much less common.</li></ul><h4>Frame Grabbing</h4><p>The environment driver grabs visual frames from the emulator at a fixed configurable rate and also tracks how many ‘dropped frames’ it had due to latencies in the agent. The main goal was to ensure minimal such frame drops, which could be detrimental to gameplay. This required to limit the number of emulators running on a single machine, in particular when training was also done on the same machine, to ensure enough CPU bandwidth for acting and training. 2 dedicated CPU cores (4 vCPUs) were needed per emulator to get stable gameplay.</p><p>I configured the frame grabbing to 30FPS with a frame-skip of either 2 or 4 (Compared to 60FPS with a frame-skip of 4 typically used in Atari training).</p><p>The android emulators are run at a 320x480 (Portrait) resolution to minimize the rendering overhead. This was the minimal resolution at which the games still worked normally. This gives us raw observations of size 320x480x3, which were then scaled down to 80x120x3 for the final observation used as the policy input (Compared to 84x84x1 grayscale observations used in most Atari research)</p><h4>Action Delays</h4><p>Another issue I encountered was an inherent delay in the Android Emulator from the time I sent an action until it was actually received/executed by the game. The delay was about 60–90ms, which should seemingly be negligible and something the learning should be able to account for (Even recent Starcraft 2 work from DeepMind mentions delays of around 250ms), but in reality, I found these can hurt the ability to optimally learn how to play.</p><p>To confirm this point I created a custom wrapper for Atari environments from OpenAI gym which inserted an artificial configurable delay from the time an action was sent by the agent until it was sent to the actual environment. Even with a delay of 60–90ms I saw a non-negligible reduction in final performance when training a tuned RL algorithm with the delay, compared to without the delay.</p><p>This isn’t to say we shouldn’t be able to learn how to play with such delays, as these delays can be the common case when applying RL to real-time tasks such as robots or drones. But it might be worthwhile to consider inserting such delays into the commonly used benchmark tasks when testing and comparing RL algorithms, to ensure the algorithms are robust to them.</p><h4>Detecting and Skipping Screens</h4><p>In order to provide an environment which can be used for RL we need to handle detecting and tapping through irrelevant screens:</p><ul><li>Tapping in the right place to start a new game</li><li>Detecting screens which signify the game is over, and tapping the appropriate places to start a new game</li><li>Detecting various popup screens and closing them (Messages, new character unlocks, new item, etc..)</li></ul><p>The above can probably be automated somehow, maybe even using some sort of AI/learning, but that’s a totally different topic which I did not deal with. For now, I just manually configured the relevant screens per game and where to tap when encountering such a screen.</p><h4>Rewards</h4><p>I used a ‘Score Change’ based reward signal. This gives a +1 reward every time the score changes. Instead of dealing with OCR of the actual score value, I found it was enough and easier to just detect the score value changed and give +1 in this case. For most games, this translates to the actual score (Except for some occasional misdetections). Moreover, since many RL algorithms clip the rewards to -1/+1 it is less important to detect the actual score in this case.</p><h3>Sample Efficient Scalable RL</h3><p>Because of the slowness and high resource cost of training on the Android emulators, I went looking for a sample efficient RL algorithm which can scale well to multiple environments.</p><p>I tried various families of RL algorithms but eventually focused on q-learning variants, in particular due to the fact that the games I was trying to learn had discrete action spaces with near-zero tolerance for errors (i.e. choosing a single wrong action will very oftentimes lead to a game-over). This makes value-based methods like q-learning more suitable than stochastic algorithms such as actor-critic variants (Though it is still possible for stochastic algorithms to converge to a good policy, I initially got fairly good results using <a href="https://arxiv.org/abs/1707.06347">PPO</a>, but overall stabler and better with DQN variants).</p><p>The current go-to sample-efficient RL algorithm for discrete actions is <a href="https://arxiv.org/abs/1710.02298">Rainbow</a>. Rainbow takes the original DQN algorithm, and combines 6 independent improvements into a single agent, reaching state-of-the-art results on the Atari benchmark at the 200M total frames threshold (~38 days of ‘play-time’).</p><p><a href="https://arxiv.org/abs/1806.06923">IQN</a> is an improved distributional version of DQN, surpassing the previous <a href="https://arxiv.org/abs/1707.06887">C51</a> and <a href="https://arxiv.org/abs/1710.10044">QR-DQN</a>, and is able to almost match the performance of Rainbow, without any of the other improvements used by Rainbow.</p><p>Both Rainbow and IQN are ‘single agent’ algorithms though, running on a single environment instance, and take 7–10 days to train. Running a single android emulator agent in real-time at 60fps for 200M frames would take 38 days.</p><p>For multi-actor/distributed q-learning, the state-of-the-art is <a href="https://openreview.net/forum?id=r1lyTjAqYX">R2D2</a>. R2D2 is a distributed multi-actor algorithm, improving over the previously published <a href="https://arxiv.org/abs/1803.00933">APEX</a> with additional improvements, in particular using a ‘recurrent’ version of the DQN model with an added LSTM layer in the middle, to help the agent maintain a ‘memory’ of what happened until now and perform better long-term planning of its actions.</p><p>The LSTM is shown to be a big help even on Atari where most games are fully observable (i.e. the full state of the game can be seen on the screen) which should seemingly not benefit from LSTM memory. There is not much research on why it helps, but one possible explanation is it allows the policy to ‘follow a plan’ which allows it to learn and play more efficiently.</p><p>R2D2 reaches extremely high scores on almost all Atari games, leaving little room for improvement, however, it does so at the cost of sample-efficiency, requiring to see over 50x more environment frames than sample efficient algorithms. Still though it is able to achieve this in less time (5 Days) than Rainbow/IQN thanks to its highly distributed architecture running 256 asynchronous actors on the high-speed Atari emulations using 256 CPUs. This would not be feasible though for my android setup, where the environment runs ~10x slower and needs 2 CPUs per instance.</p><p>In order to maximize my resource utilization and minimize training time, I worked on combining features from IQN/Rainbow/R2D2 into a ‘Recurrent IQN’ training algorithm (<a href="https://opherlieber.github.io/rl/2019/09/22/recurrent_iqn">full details here</a>), which achieves improved sample-efficient results on the Atari benchmark with the option of running multiple actors in parallel, allowing me to train on the slow android environments efficiently in a reasonable amount of time (Up to a few days).</p><h3>Training Setup</h3><p>For training, I used a custom (non-VM) server with 32 CPUs and an NVIDIA 1080ti GPU. I ran 12 Android Instances per training session, each gathering experiences asynchronously in separate processes using a shared-memory copy of the main policy, to avoid latencies when one of the actors had to pause (for example to restart after a game-over). Experiences were retrieved from the processes between training steps to fill the training replay buffer.</p><p>I used the same hyperparameters and ‘<a href="https://opherlieber.github.io/rl/2019/09/22/recurrent_iqn">Recurrent IQN’</a> algorithm as the one tuned for the Atari Benchmark, with a few modifications:</p><ul><li>Reduced from 32 to 12 ENVs</li><li>ENVs run asynchronously instead of vectorized, with a shared-memory policy updated every 1000 steps with weights from the training policy</li><li>A fixed decaying exploration rate, from 1.0 to 0.001 per actor (The extra low exploration rate is needed as the games I am using are extremely sensitive to ‘wrong actions’, so the common 0.01 rate would make it hard for the training actors to reach longer episodes)</li><li>Visual game frames are scaled from 320x480x3 resolution to 80x120x3 RGB observations (Compared to 84x84x1 grayscale observations commonly used in Atari)</li><li>Frames are grabbed from the emulator at 30FPS, with a frame-skip of either 2 or 4 depending on the game, without ‘max merging’ (i.e. agent transitions are either 15 or 7.5 steps-per-second, compared to 15 typically done in Atari learning). The lower rate is needed in some games where the actions would otherwise take longer than the step-time (For example swipe actions)</li></ul><h3>Games and Results</h3><p>I use the following 3 games to focus testing on:</p><ul><li><a href="https://en.wikipedia.org/wiki/Flappy_Bird">Flappy Bird</a>: A very hard and frustrating game for human players, requiring very fast and precise reaction time, but has a very simple mechanic and constant visuals, so the overall policy to learn should be a relatively simple one</li><li><a href="https://play.google.com/store/apps/details?id=com.kiloo.subwaysurf&amp;hl=en">Subway Surfers</a>: The popular endless arcade game, dodging trains by swiping between 3 lanes, jumping or crouching above and under obstacles, and trying to collect coins along the way</li><li><a href="https://play.google.com/store/apps/details?id=com.yodo1.crossyroad&amp;hl=en">Crossy Road</a>: The infamous chicken hopper game requires the agent to plan ahead and get moving at the right time while considering the oncoming traffic and car trajectories, floating water logs, and fast passing trains</li></ul><p>All games are evaluated using the final training policy, with no random-action epsilon.</p><h4>Flappy Bird</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9qxBMC5h56g%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9qxBMC5h56g&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9qxBMC5h56g%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd734ff16d93ac8d34a88c813433698c/href">https://medium.com/media/bd734ff16d93ac8d34a88c813433698c/href</a></iframe><p>Flappy Bird was trained at 30FPS with a frame-skip of 2 (15 Steps-Per-Second) for a total of 25M steps (Equivalent to about half the total ‘gameplay time’ used in sample-efficient Atari training). This takes around 40 hours to train using 12 emulators.</p><p>The action space has a single action (Tap) and an additional ‘noop action’. The reward is +1 each time the score changes (i.e. each time the bird passes a pipe)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*nbzASu2l7uYQw7denJLgAw.png" /><figcaption>Training chart for Flappy Bird, average reward of last 100 episodes</figcaption></figure><p>This game is notorious for taking time to start learning because the initial reward is received only after passing the first pipe, which can be extremely hard and random for an untrained agent using random exploration. There are hundreds of thousands of initial steps with 0 reward, which means the agent has no feedback at all and no way to learn. Only after we get some experiences of passing the first pipe (Which is purely random), the agent finally starts to figure it out, from that point it fairly steadily improves, but it takes over 2M steps to reach that point.</p><p>This game is extremely sensitive to wrong actions, for example performing evaluation with a random-action epsilon of 0.001 results in a mean reward of 143 instead of 420, as seen also in the training chart final results (Training also uses 0.001 for the final exploration rate)</p><p>Evaluation Score: Average 420, Max 1363 (10 Eval Episodes)</p><h4>Subway Surfers</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FtwkEl64Ic8s%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DtwkEl64Ic8s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FtwkEl64Ic8s%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/72eb7761e209bc6a90d78a05892a2897/href">https://medium.com/media/72eb7761e209bc6a90d78a05892a2897/href</a></iframe><p>For this game, I used the coin collection count as the reward, to encourage the agent to collect coins, which in itself is not necessary in order to progress, but is an important ability to learn. I also added a negative (-1) reward upon game over to encourage the agent to learn not to lose, regardless of coin collection.</p><p>The game is trained at 30FPS with a frame-skip of 4 (7.5 steps-per-second compared to 15 commonly used in Atari, due to the swipe gesture taking longer than 66ms), for 25M steps (Equivalent in total play-time to common sample-efficient Atari training using 200M frames at 60FPS). This takes around 90 hours to train using 12 emulators.</p><p>The action space here has 4 actions (Swipe up/down/left/right) and the ‘noop action’.</p><p>Interestingly the agent almost never chooses the noop action and prefers to always either jump or slide down even when it doesn’t really need to. This sort of makes sense as there is no downside to doing that and it can only help in some cases (Not all training runs are like this, some had many more noop actions). We can maybe try to mitigate this by adding a small negative reward on each action taken (e.g. -0.1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ejGFkJkstQOuEwl5hGeA9g.png" /><figcaption>Training chart for Subway Surfers, average reward of last 100 episodes</figcaption></figure><p>Evaluation Score: Average 142, max 434 (30 Eval Episodes)</p><h4>Crossy Road</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQ_Ex_LaI9ew%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQ_Ex_LaI9ew&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQ_Ex_LaI9ew%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f823543d5cf6519e233d6e83a034537e/href">https://medium.com/media/f823543d5cf6519e233d6e83a034537e/href</a></iframe><p>Crossy Road is trained at the same frame/step rate as Subway Surfers. The reward is +1 on every score change (Which is every time the chicken moves a step forward).</p><p>The agent clearly has a preference to try to only move forward, but it knows to move left/right and even back when needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*S6225xHezDvr8bGEwN16Dg.png" /><figcaption>Training chart for Crossy Road, average reward of last 100 episodes</figcaption></figure><p>Evaluation Score: Average 41, Max 139 (30 Eval Episodes)</p><h3>Conclusion</h3><p>The results look promising so far, although still not what we would consider ‘superhuman’ (Except maybe Flappy Bird). Still, it’s promising to see RL able to learn modern casual games in real-time from visual inputs, using the same hyperparameters as Atari, within a reasonable amount of time, frames and resources.</p><p>It’s also pretty clear from the charts that learning hasn’t plateaued, and it would be interesting to see what results we can get going to 50M or even 100M steps and beyond, and with some hyperparameter tuning.</p><ul><li><a href="https://opherlieber.github.io/rl/2019/09/22/recurrent_iqn">Fast Sample Efficient Q-Learning With Recurrent IQN</a></li><li><a href="https://github.com/opherlieber/rltime">opherlieber/rltime</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=161a62926f7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/reinforcement-learning-for-mobile-games-161a62926f7e">Reinforcement Learning for Mobile Games</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>