<?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 Nikolaj Goodger on Medium]]></title>
        <description><![CDATA[Stories by Nikolaj Goodger on Medium]]></description>
        <link>https://medium.com/@ngoodger_7766?source=rss-8db1871c3e81------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Mry3PXRtSPeX5apv6qtoOw.png</url>
            <title>Stories by Nikolaj Goodger on Medium</title>
            <link>https://medium.com/@ngoodger_7766?source=rss-8db1871c3e81------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:37:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ngoodger_7766/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[Writing an RL Environment in JAX]]></title>
            <link>https://medium.com/@ngoodger_7766/writing-an-rl-environment-in-jax-9f74338898ba?source=rss-8db1871c3e81------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f74338898ba</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[jax]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tpu]]></category>
            <dc:creator><![CDATA[Nikolaj Goodger]]></dc:creator>
            <pubDate>Sun, 14 Nov 2021 02:23:37 GMT</pubDate>
            <atom:updated>2021-11-14T02:23:37.534Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to run CartPole at 1.25 Billion Step/Sec</h4><p><a href="https://github.com/google/jax">JAX</a> is a relatively new and exciting open-source machine learning framework. Here are some of the great features:</p><ul><li>Compiled using XLA so it can support CPUs, GPUs, and TPUs.</li><li>With the <a href="https://jax.readthedocs.io/en/latest/autodidax.html#part-3-jit-simplified">jit</a> function, it can just-in-time compile multiple operations and optimize the computation graph.</li><li>Automatic vectorization via <a href="https://jax.readthedocs.io/en/latest/jax.html#jax.vmap">vmap</a>.</li><li>Automatic parallelization with <a href="https://jax.readthedocs.io/en/latest/jax.html#jax.pmap">pmap</a>.</li><li>Higher-order differentiation</li><li>Enforces functional programming.</li></ul><p>All these features are useful but the first 3 are especially so when writing RL environments. Currently, the most powerful accelerator available for free via Colab or Kaggle notebooks is a TPU, but these are often hard to use, and yet JAX makes it easy. Accelerating individual operations helps but any non-trivial RL environment will include many operations for each time-step. Optimizing the whole graph via the XLA compiler makes a big difference. And I don’t think I could point to anything that caused me more headaches in deep RL than manually managing the batch-dimension! It’s just so much easier to code for a single instance and let JAX take care of vectorization with vmap. For an example of how effective JAX can be at implementing an RL environment look no further <a href="https://github.com/google/brax">Brax</a>. This is a rigid body simulator written in JAX that is able to speed up the classic Ant or Humanoid environments by 100x to 1000x compared to the <a href="https://mujoco.org/">Mujoco</a> equivalent.</p><p>To start with, let’s explore what a simple JAX environment look like. As an instructive example we can try to convert the classic <a href="https://github.com/openai/gym/blob/master/gym/envs/classic_control/cartpole.py">Cartpole-v1</a> Environment from openai gym. The probably familiar api looks like this</p><pre>env = gym.make(&quot;CartPole-v1&quot;)<br>obsv = env.reset()<br>obsv, reward, done, info = env.step(action)</pre><p>After creating the environment, we reset it to get the initial state and then apply an action with the step function. The env.step function is stateful because the output depends on the internal state of the environment. The env.reset function is also stateful as it depends on the internal state of the random number generator (each time we reset we get a different state). But we already said JAX only allows functional code without any state or side-effects 🤔</p><p>Thankfully the excellent <a href="https://jax.readthedocs.io/en/latest/index.html">JAX documentation</a> has a solution described in <a href="https://jax.readthedocs.io/en/latest/jax-101/07-state.html">Stateful Computations in JAX</a>. Apply this to a skeleton environment with a gym-like we can come to a sample implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dcf461ba0ea88d3887217ff2ec4150e/href">https://medium.com/media/6dcf461ba0ea88d3887217ff2ec4150e/href</a></iframe><p>The environment is designed to automatically reset as this simplifies rollouts on batched environments and doesn’t detract from usability. This is equivalent to using the <a href="https://github.com/openai/gym/blob/master/gym/vector/vector_env.py">gym.vector</a> wrappers.</p><h4><strong>Functions</strong></h4><ul><li>__init__ is the constructor used used to set values on the environment instance likeself.random_limit . This is ok because we never changed and used as as constants rather than state, so calls to the environment are still functional.</li><li>_get_obsv is a private function that maps the state to to an observation since we might want to use different observations than the raw state. For example, we might want to rasterize an image of the environment and keep the compressed internal state hidden.</li><li>_reset<strong> </strong>is a private function that actually generates a new random state. This is used by both the public reset function and the step function to conditionally reset the environment.</li><li>_maybe_reset is used to conditionally reset the environment. It does this using the <a href="https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.cond.html">jax.lax.cond</a> function which allows the branching to be compiled with jit (more on that later).</li></ul><pre>jax.lax.cond(done, self._reset, lambda key: env_state, key)</pre><p>is equivalent to</p><pre><strong>  if</strong> done:<br>    <strong>return</strong> self._reset(key)<br>  <strong>else</strong>:<br>    <strong>return</strong> env_state</pre><p>The <a href="https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#control-flow">challenges in using python control flow in JAX are well documented</a> but the tl;dr version is that JAX uses tracing and doesn’t know which path to take when python control flow is used. This implementation does seem more complicated but it’s worth it for performance.</p><p>After the key has been used <a href="https://www.google.com/search?q=jax+random.split&amp;rlz=1C5CHFA_enAU940AU940&amp;oq=jax+random.split&amp;aqs=chrome..69i57j69i60l2.2550j0j4&amp;sourceid=chrome&amp;ie=UTF-8">jax.random.split</a> functionally generates a new key which we return for subsequent random operations.</p><ul><li>reset is a public function that takes in the <strong>key </strong>and generates a new random state using the _reset function. The <strong>state</strong> and <strong>key</strong> are combined into a tuple called <strong>env_state</strong>. The env_state is the full state of the environment. When I first started this project I thought the state was sufficient, but as I progressed I realized that the key itself is also part of the state since when the environment reaches a terminal state it resets and a new <strong>key</strong> is generated. This also means for a given initial <strong>env_state</strong> we produce the same rollout even if the environment resets multiple times. The <strong>env_state</strong> and the <strong>initial_observation</strong> determined using the _get_obsv function are returned.</li><li>step<strong> </strong>is a public function that takes in the <strong>env_state</strong> and <strong>action</strong>. It applies a transformation to advance the internal state. Next, it calculates the <strong>reward</strong> and <strong>done</strong> values and uses the _maybe_reset function to conditionally reset the <strong>env_state</strong> based on the <strong>done</strong> value. Finally, the updated <strong>env_state</strong>, <strong>obsv</strong>, <strong>reward</strong>, and <strong>done</strong> values are returned with <strong>obsv</strong> again being derived from the _get_obsv function.</li></ul><h4>Usage</h4><p>The usage can be seen in the Gist above below the Class definition. Let’s walk through it. First, we create a <strong>key</strong> using <a href="https://jax.readthedocs.io/en/latest/_autosummary/jax.random.PRNGKey.html">jax.random.PRNGKey</a> function. The reason we need to do this explicitly is that for the random number generation process to be functional (in this case random.uniform) its output must depend on the <strong>key</strong>, i.e. same key = same random output.</p><p>We then instantiate the environment which sets the constants.</p><p>The <strong>reset </strong>function is used with the previously created key to define the initial <strong>env_state</strong> (containing both the <strong>state</strong> and the updated <strong>key</strong>) and get the <strong>initial_obsv.</strong></p><p>The step function can now be called using the <strong>env_state</strong> and an arbitrarily chosen action (1) to advance the environment.</p><p>The main change we have made to gym API is that all the functions in the environment now require the state to be externally managed and passed in or returned to allow for the functional paradigm to be maintained. This may seem burdensome but it has the advantage of making a function’s behavior deterministic for its inputs.</p><h3>JAX Cartpole</h3><p>Now we’ve got a skeleton environment, but it’s not very interesting. Converting the Cartpole Environment to JAX using the skeleton environment as a template we can arrive at the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2adebcbf3a730ab03af51b5d0a10a5e6/href">https://medium.com/media/2adebcbf3a730ab03af51b5d0a10a5e6/href</a></iframe><p>Let’s break down the changes.</p><ol><li>We swap python control flow for an equivalent set of operations when we can as <a href="https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#control-flow">python control flow only has limited support</a>.</li></ol><pre>force = self.force_mag if action == 1 else -self.force_mag<br>---<br>force = self.force_mag * (2 * action - 1)</pre><p>2. We remove side effects from the reset andstep functions in order for them to be strictly functional.</p><pre># Removed<br>assert self.action_space.contains(action), err_msg<br>log.warn</pre><p>print statements are side-effects because they not returned as part of the function.</p><p>3. We replace incompatible math operations with jax.numpy equivalents.</p><pre>costheta = math.cos(theta)<br>sintheta = math.sin(theta)<br>---<br>costheta = jnp.cos(theta)<br>sintheta = jnp.sin(theta)</pre><p>This seems to be required because JAX traces ShapedArray and the math<strong> </strong>functions apply the float function which requires a concrete value.</p><p>4. Replace python control for calculating <strong>done</strong> with an equivalent set of operations</p><pre>done = bool( x &lt; -self.x_threshold <br>             or x &gt; self.x_threshold<br>             or theta &lt; -self.theta_threshold_radians<br>             or theta &gt; self.theta_threshold_radians)<br>---<br>done = ((x &lt; -self.x_threshold) <br>         | (x &gt; self.x_threshold)<br>         | (theta &gt; self.theta_threshold_radians)<br>         | (theta &lt; -self.theta_threshold_radians))</pre><p>5. Set reward always equal to 1 since the environment auto-resets.</p><p>6. jit reset and step function using @partial(jit, static_argnums=(0,)). We need to specify the static_argnums=(0,) because the first argument <strong>self</strong>, is treated as as static (constant). The code is runnable without jit but it is extremely slow. Specifically the jax.lax.cond is slow, so without jit python control flow is faster. This compiles the code to statically-typed expression language called <a href="https://jax.readthedocs.io/en/latest/jaxpr.html">jaxpr</a> which is further compiled to an executation graph by XLA.</p><p>Using a <a href="https://jax.readthedocs.io/en/latest/jax.html?highlight=make_#jax.make_jaxpr">make_jaxpr</a> we can visualize what it the compiled operations look like. Below is a sample from the env.step function. For context the constants come from the <strong>self</strong> argument.</p><pre>y = mul p w<br>z = sub x y<br>ba = integer_pow[ y=2 ] p<br>bb = mul ba 0.10000000149011612<br>bc = div bb 1.100000023841858<br>bd = sub 1.3333333730697632 bc<br>be = mul bd 0.5<br>bf = div z be<br>bg = mul bf 0.05000000074505806</pre><p>This implementation allows us to run the environment for a single environment in the same way as the skeleton environment.</p><h3>Batched Environment</h3><p>Throughput is limited with a single instance of the environment so we want to run many in parallel. One way to achieve that is by using <a href="https://docs.python.org/3/library/multiprocessing.html">multiprocessing</a> and running each new instance in a new process, this tends to scale poorly though and it’s much more efficient if we can vectorize the implementation. Vectorizing code can be tricky because you need to consider the batch dimension in all operations you implement, thankfully JAX makes this much easier with <a href="https://jax.readthedocs.io/en/latest/jax.html#jax.vmap">vmap</a>. Using this function we can automatically vectorize the reset and step functions. Now we can step through many instances of the environment without changing the code!</p><p>Here’s what this looks like. First we take the environment functions and wrap them with vmap and jit. The vmapped function benefits from being jitted because that allows xla to optimize the operation across the batch dimension.</p><pre>vstep = jit(jax.vmap(env.step, in_axes=((0, 0), 0), out_axes=((0, 0), 0, 0, 0, 0), axis_name=&quot;batch_axis&quot;))</pre><pre>vreset = jit(jax.vmap(env.reset, out_axes=((0, 0), 0), axis_name=&quot;batch_axis&quot;))</pre><p>The <strong>in_axes</strong> and <strong>out_axes</strong> specify the batch dimension of the each of the jnp arrays in the arguments.</p><p>Now instead of passing a single <strong>key</strong> to reset we pass as many keys as we want environments.</p><pre>NUM_ENV = 10<br>seed = 0<br>key = jax.random.PRNGKey(seed)<br>keys = random.split(key, NUM_ENV)<br>env_state, obsv = vreset(keys)</pre><p>We then get a vectorized <strong>env_state</strong> back from reset which we can use together with a vectorized <strong>action</strong> which similarly has vectorized return values.</p><pre>action = random.randint(keys[0], (NUM_ENV,), 0, 2)<br>new_env_state, obsv, reward, done, info = vstep(env_state, action)</pre><h3>Batched Environment on Multiple Devices</h3><p>Utilizing a TPU or multiple gpus fully means dealing with multiple devices. We need a way to vectorise across the device dimension as well. JAX provides this functionality through <a href="https://jax.readthedocs.io/en/latest/jax.html#jax.pmap">pmap</a>. Similarly to vmap we can just wrap our jitted vmapped functions with pmap. We don’t need to apply jit again in this case because pmap automatically jits the function.</p><pre>pvreset = jax.pmap(vreset, out_axes=((0, 0), 0), axis_name=&quot;device_axis&quot;)</pre><pre>pvstep = jax.pmap(vstep, in_axes=((0, 0), 0), out_axes=((0, 0), 0, 0, 0, 0), axis_name=&quot;device_axis&quot;)</pre><p>Something that might seem confusing here is the arguments to pmap look the same as vmap, which might make it look like we are using the same dimension as both the device &amp; batch dimension. The way it works in this case is that the pmapped reset and step functions take in a jnp.array with dimensions[device_axis, batch_axis, …] the first dimension as the device axis which is removed by pmap, so vmap only sees the 2-dimensional jnp.array [batch_axis, …].</p><h3>Compiled Rollout</h3><p>Up to this point, we’ve been compiling the environment step and reset functions. This means we execute each step on the CPU or accelerator before returning control to the python kernel. There is a latency cost associated with dispatching execution. I noticed that this seemed to be very small for the CPU, sub-millisecond for the GPU but on the order of several milliseconds on the TPU. This forces very large batch sizes to get good throughput on the accelerators, especially the TPU.</p><p>To address this we can try to jit compile the entire rollout. That way the python kernel simply starts a rollout of the environment and gets data for the whole rollout back. This approach should be viable for RL algorithms that have a data-collection phase and a training phase e.g. Proximal Policy Optimization (PPO) or Q-Learning.</p><p>For this example we randomly select actions in-place of a model but there should be no issue in using a <a href="https://github.com/google/flax">Flax</a> based neural network in the same function.</p><p>See the example implementation below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ec31c581a6bfbae6b387f701efdae0d/href">https://medium.com/media/2ec31c581a6bfbae6b387f701efdae0d/href</a></iframe><p>We define a rollout function that resets the environment, steps through a fixed number of iterations, and returns the data. Note that rather than using a python for loop as is typical we use a JAX control flow equivalent <a href="https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.fori_loop.html">jax.lax.fori</a>. It is actually possible to use python control flow here but it takes a very long time to compile as it needs to trace through every step in the loop. The main downside I see in using JAX control flow is that it’s harder to read.</p><p>The <a href="https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.fori_loop.html">jax.lax.fori</a> is well documented, so that should help understand the loop implementation. Other things worth noting here are:</p><ol><li>We pre-allocate the obsv, reward, and done arrays and at each step functionally create a new array. This sounds inefficient but think of it as providing functional operations as what you want to happen and then letting the XLA compiler can implement that in a performant way.</li><li>We can directly use pmap &amp; vmap as decorators without arguments because by default they assume no static arguments and that the first dimension in the pmapped or vmapped dimension respectively which for the <strong>keys</strong> argument is correct.</li></ol><h3>Benchmarks</h3><p>The chart below shows the number of steps per second achieved for a range of number of environments (NUM_ENV) starting at 1.</p><p>The baseline is Openai Gym Cartpole @ 94.2k steps/sec.</p><p>It’s worth highlighting here is that all benchmarks were running in Colab including the CPU benchmarks (so only one physical core).As mentioned earlier gym environments can be run in parallel using multiprocessing or similar but this only works if you have CPU cycles or cores to spare which is sadly not the case in Colab.</p><p>The GPU version was a k80 and the TPU version was V2.</p><p>The Colab notebook used to collect the benchmark result is available <a href="https://colab.research.google.com/drive/1Xjs_uM5ekiyzJdNbY9MK9-utU51ixNFq?usp=sharing">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mW1hA190wUFPzWxpI8BM6g.png" /></figure><h3>Discussion</h3><p>For the equivalent JAX version single environment on CPU, we see 95k steps/sec so basically equivalent to the baseline. On GPU and TPU it’s much slower. Increasing the batch size to 100 saturates the CPU performance @ 4.7M steps/sec. The GPU and TPU can reach much higher throughput (&gt;400M steps/sec) at very large NUM_ENV (&gt;1M).</p><p>The results for the compiled rollout are more interesting with the CPU rollout reaching 1M steps/sec. That’s 10x faster than either the Gym environment or the vectorized JAX environment when stepping manually. The GPU only has a “marginal” improvement of 2x at the same batch size. The TPU performance improves dramatically (400x) which is probably due to the dispatch latency now being a minor factor whereas it was the dominant factor when stepping the environment. This scales all the way to NUM_ENV=800k across the 8 devices before OOM occurs reaching an incredible 1.25G steps /sec.</p><h3>Conclusion</h3><p>We’ve seen how you might write an RL environment in JAX and how it can be both faster serially by compiling the rollout or made efficiently parallel using vmap and pmap. JAX has the potential to accelerate deep RL research by literally speeding up the environments to bring down the iteration time and making accelerators like TPUs easy to use.</p><p>Best of luck with your experiments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f74338898ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conditional GAN using PyTorch]]></title>
            <link>https://medium.com/@ngoodger_7766/conditional-gan-using-pytorch-7849a62fbcad?source=rss-8db1871c3e81------2</link>
            <guid isPermaLink="false">https://medium.com/p/7849a62fbcad</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nikolaj Goodger]]></dc:creator>
            <pubDate>Sun, 30 Aug 2020 05:56:18 GMT</pubDate>
            <atom:updated>2020-08-30T05:56:18.037Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2LbN7OZ6ZlikfSwnsCVtw.png" /><figcaption>Generated MNIST digits. Each row is conditioned on it’s row number starting at 0.</figcaption></figure><p>Conditioning a GAN means we can control their behavior. In the case of the MNIST dataset we can control which character the generator should generate. Another approach could be to train a separate generator and critic for each character but in the case where there is a large or infinite space of conditions, this isn’t going to work so conditioning a single generator and critic is a more scalable approach.</p><p>This post is an extension of the previous post covering this <a href="https://medium.com/@ngoodger_7766/simple-gan-using-pytorch-99a41691b83f">GAN implementation in general</a>. Here we extend the implementation to be conditional while still using the Wasserstein loss and show how we can use class-labels from MNIST to generate specific digits.</p><p>To make the GAN conditional all we need do for the generator is feed the class labels into the network. These are concatenated with the latent embedding before going through the transposed convolutional layers to generate an image. For the critic, we can concatenate the class label with the flattened CNN features so the fully connected layers can use that information to distinguish between the classes. These changes will cause the generator to generate classes of the digit based on the condition since now the critic knows the class the loss will be high for an incorrect digit, i.e. A perfect 1 is not a very convincing 5.</p><p>Please see the conditional implementation below or refer to the <a href="https://medium.com/@ngoodger_7766/simple-gan-using-pytorch-99a41691b83f">previous post</a> for the unconditioned version.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b899246a89b542e2a7af0c1de59b6226/href">https://medium.com/media/b899246a89b542e2a7af0c1de59b6226/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7849a62fbcad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple GAN using PyTorch]]></title>
            <link>https://medium.com/@ngoodger_7766/simple-gan-using-pytorch-99a41691b83f?source=rss-8db1871c3e81------2</link>
            <guid isPermaLink="false">https://medium.com/p/99a41691b83f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Nikolaj Goodger]]></dc:creator>
            <pubDate>Sun, 30 Aug 2020 05:54:32 GMT</pubDate>
            <atom:updated>2020-08-30T05:57:12.195Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fj2KVcT2n831VQPuCP0LVQ.png" /><figcaption>Generated MNIST digits after 20 epochs</figcaption></figure><p>Generative Adversarial Networks (GANs) are a super cool way to model a high dimensional distribution using deep neural networks. GANs can famously generate photorealistic images. In this implementation though, I wanted to have a <strong>generic, robust implementation that can be easily understood and adapted to other use cases.</strong></p><p>This implementation borrows heavily from DCGAN, specifically the <a href="https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html">PyTorch DCGAN Tutorial</a>. GANs using the original discriminator loss function like DCGAN can be difficult to train and suffer undesirable behavior like mode collapse (GAN loses the ability to model parts or all of the training data distribution). Significant research has gone into mitigating these issues. One improvement that has come out of this is the Wasserstein GAN. This implementation changes the discriminator to be a critic of the realness of the image rather than a binary classifier of real and fake. This is achieved by implementing the proposed <a href="https://arxiv.org/pdf/1701.07875.pdf">Wasserstein loss</a> instead, which was further improved with the introduction of a <a href="https://arxiv.org/pdf/1704.00028.pdf">Gradient Penalty</a>. This loss function has been used to produce some pretty amazing results, such as generating high-resolution celebrity photos with <a href="https://arxiv.org/pdf/1710.10196.pdf">Progressive GAN</a>.</p><p>To keep things simple and relatable the MNIST dataset was chosen but it should be straightforward to replace the dataset and generate new classes of images. The implementation currently requires a GPU as training on a CPU would be very slow, at least with the configured model size. I hope you find it useful!</p><p>There is also a <a href="https://medium.com/@ngoodger_7766/conditional-gan-using-pytorch-7849a62fbcad">conditional implementation</a> available.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1767b474d8fdbe9970bb48a62b8fff4/href">https://medium.com/media/d1767b474d8fdbe9970bb48a62b8fff4/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99a41691b83f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fast GPU based PyTorch model serving in 100 lines of Python]]></title>
            <link>https://medium.com/@ngoodger_7766/fast-gpu-based-pytorch-model-serving-in-100-lines-of-python-9ad3ebd0a1d9?source=rss-8db1871c3e81------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ad3ebd0a1d9</guid>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Nikolaj Goodger]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 09:38:51 GMT</pubDate>
            <atom:updated>2020-04-27T09:38:51.348Z</atom:updated>
            <content:encoded><![CDATA[<p>Consider you need to create an inference service to support the following applications:</p><ol><li>Image classification for an app on a smartphone.</li><li>Predictive text for chats using a pre-trained BERT model.</li><li>Parallel rollouts of a policy in reinforcement learning.</li></ol><p>In these example scenarios batch sizes will be small (often 1) and arrive asynchronously. You could do CPU inference but this will incur higher latency and much lower throughput for the same cost of cloud hardware[1] So for high throughput low latency applications we often want to use a GPU.</p><p>The question and problem I’ll attempt to solve in this blog post are:</p><ol><li>How do we use effectively use a GPU even when dealing with asynchronous requests and small batches?</li><li>How do we serve a PyTorch model from a REST API so the service can be used?</li></ol><h3><strong>Test setup</strong></h3><p>All tests and benchmarks conducted on Google Compute Engine.</p><p>Instance type: n1-standard-4 (4 vCores, 15 GByte Memory)</p><p>GPU: Nvidia K80</p><p>PyTorch Model: Torchvision Resnet18 Pretrained Model in Eval mode.</p><h3><strong>Throughput &amp; Latency vs Batch Size</strong></h3><p>To characterise the hardware and model configuration I measured the throughput and latency from batch sizes 1 to 192 as the GPU ran out of memory for batch sizes bigger than 192. The results were averaged across 1024 examples for each batch size tested. The throughput can be seen in Figure 1 and the Latency in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWaX5DZWjf6vigu90lgpUQ.png" /><figcaption>Figure 1: Throughput vs Batch Size</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sS71W-AmbrbqS2_PUX3uaA.png" /><figcaption>Figure 2: Latency vs Batch Size</figcaption></figure><p>From the plot in Figure 1, the throughput has an interesting spike at 16 and increases up to a batch size of 64 before falling off. Similarly, the latency in Figure 2 increases linearly before undergoing a small positive step change at 64 and increasing linearly again. The Batch size of 1 has a throughput of 128 Examples / Second while a batch size of 64 is above 400 Examples / Second. An increase of more than 3x.</p><p>This is important for our use case because once the GPU is 100% (temporally speaking so the throughput is at maximum regardless of whether the batch size is 1 or 64) <strong>any new requests will just add to the latency their inference time to the latency of all requests</strong> which is bad. By using a maximum batch size of 64 instead of 1 we serve 3x the inference before entering this saturation region.</p><h3><strong>Asynchronous GPU execution</strong></h3><p>It’s common knowledge that PyTorch is limited to a single CPU core because of the somewhat infamous Global Interpreter Lock. This can be a problem when trying to write high-performance CPU but when using the GPU as the primary compute device PyTorch offers a solution. <strong>PyTorch Cuda execution occurs in parallel to CPU execution</strong>[2]</p><p>Here’s a concrete example:</p><pre>y = cuda_model(x) # Perform forward pass with cuda tensor x.<br> time.sleep(0.1) # Wait 100ms<br> y_cpu = y.to(“cpu”) # Move output cuda tensor y to cpu.</pre><p>In this example GPU will be computing cuda_model(x)while the CPU is executing time.sleep(0.1)before they are forced to synchronise by moving the result to the CPU. This is illustrated in Figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYwEKbnE3WqFcT_rVgxIRw.png" /><figcaption>Figure 3: PyTorch Asynchronous GPU Execution</figcaption></figure><p>What if we want to keep doing work on the CPU until the GPU is finished? This can be achieved using the torch.cuda.Eventclass as in the below example.</p><pre>y = cuda_model(x) # Perform forward pass with cuda tensor <br> cuda_event = torch.cuda.Event()<br> cuda_event.record()<br> while not cuda_event.query():<br> time.sleep(0.001) # Wait 1ms<br> y_cpu = y.to(“cpu”) # Move output cuda tensor y to cpu.</pre><p>In this case, we can repeatedly re-run time.sleep(0.001) while we wait for the GPU execution to finish by monitoring the cuda_event.</p><p>All this means long as we keep the CPU execution time shorter than the GPU one we can keep the GPU fully utilised by preparing the next batch of data in the place of time.sleep. This how training in PyTorch can fully utilise the GPU even without using the multiprocess library and we can utilise the same feature for asynchronous batch collection.</p><h3><strong>Asyncio and grouping concurrent requests.</strong></h3><p>To keep the client code simple I wanted to keep the REST API synchronous. i.e. you request inference with the input data x and the response comes back with the result like a function call. That means server-side, we to have some way of running multiple threads concurrently.</p><p>To achieve this I decided to try Asyncio and the Asyncio web framework aiohttp. Having never used Asyncio I found it a little tricky and from what I have read that seems to be a common experience. It does, however solve the concurrency problem at a higher abstraction level than say threading. I found looking at example applications and the official documentation [3] to be very helpful in the learning process.</p><p>What we want from Asyncio is to capture multiple HTTP requests asynchronously perform batch inference synchronously and return the results asynchronously. This together with the asynchronous GPU execution should give us the foundation we need to build the inference server.</p><p>The best pattern (it might be terrible) I found was creating an asyncio.Future for each request and placing them in an asyncio.Queue to be handled by an inference coroutine. The inference coroutine can remove multiple futures from the queue, perform batch inference and set the result for each of the futures in the batch which will allow their respective “awaiting” coroutines to resume.</p><h3><strong>Input/Output Tensors</strong></h3><p>I chose NumPy Ndarrays rather than PyTorch Tensors as the inputs and outputs of the server. Simply because of how ubiquitous and well supported they are. This means that the clients to the server don’t need to know about or have torch installed just NumPy. There are also more options available for serialisation and deserialisation of NumPy NdArrays than PyTorch Tensors.</p><h3><strong>Serialisation &amp; Deserialisation with PyArrow</strong></h3><p>To maximise the utilisation of the gpu we want to make the cpu operations as fast so we have time to batch as many requests together as possible. The bulk of the cpu time in the server is consumed by the serialisation and deserialisation of the input and output tensors before sending them over the network so I spent some time speed testing different options.</p><p>In the end, I chose to use PyArrow because it was the fastest overall both at serialisation and especially deserialisation which is a zero-copy operation so it is very fast.</p><h3><strong>Monitoring</strong></h3><p>I used Prometheus to monitor the code as it is both straight forward and open source. It will also allow dashboards to be built on top using Grafana.</p><h3><strong>Implementation</strong></h3><p>To reiterate the basic principle of operation is <strong>buffer inference requests while GPU inference is in progress</strong>.</p><p>Practically this is achieved by buffering new inference requests until:</p><ol><li>Work has been submitted to the GPU and that work has finished.</li><li>New request ready and no GPU inference in progress.</li><li>Buffer is full to max batch size and another request has been received.</li></ol><p>I found this simple logic gave a good tradeoff between throughput &amp; latency while only requiring max batch size to be set.</p><p>Inference Server code</p><p><strong>Arguments</strong></p><p>— max-batch-size: <em>specifies the maximum batch size to buffer inputs up too.</em></p><p>— model-definition: <em>python code instantiating the “model” object.</em></p><p>— input-shape: <em>Input shape without batch dimension.</em></p><h3><strong>Example call</strong></h3><pre>pytorch_inference_server — max-batch-size 64 — input-shape 3 256 256 — model-definition “import torchvision\nmodel = torchvision.models.resnet18(pretrained=True).eval()”</pre><h3><strong>Requirements</strong></h3><p>Python 3.7.</p><p>numpy==1.15.1</p><p>aiohttp==3.6.2</p><p>torch==1.3.1</p><p>uvloop==0.14.0</p><p>pyarrow==0.15.1</p><p>prometheus_client==0.7.1</p><h3><strong>Testing</strong></h3><h4><strong>Baseline</strong></h4><p>To evaluate the performance of the server we need to establish a baseline of the best possible performance. After playing around for some time this is the fastest implementation I could come up with. Note that x is preallocated to simulate ideal batch preparation.</p><p>The results were:</p><ul><li>Batch size 64 : 153ms latency, 421 Examples / Second throughput.</li><li>Batch size 1: 7.9ms latency and 127 Examples / Second throughput.</li></ul><h4><strong>Results</strong></h4><p>I manually measured the test results using the same server arguments as the above example call. I ran parallel synchronous request processes to increase the number of concurrent requests. See the test code below:</p><p>The results are averaged across 100 iterations batch sizes of 2 and below and 100 for batch sizes above 2. I didn’t collect the results for the fields marked NULL as the GPU was saturated as described earlier what happens Throughput &amp; Latency vs Batch size section. This manifests itself as doubling latency and constant throughput when doubling request batch size or doubling concurrent requests along each axis respectively. In the plots, I did this exact extrapolation to give them the correct shape. The measured results can be had in Tables 1 &amp; 2 and the surface graphs are in Figures 4 &amp; 5.</p><p>Overall I’m super happy with the results. The server seems to do a commendable job at utilising the GPU regardless of what sort of requests you throw at it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2LlcCxVgcI0XnLPR4apexg.png" /><figcaption>Table 1: Throughput (Examples / Second) test results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_Fncu_YGZLUlTO8tcv6Kw.png" /><figcaption>Table 2: Latency (Seconds) test results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEvvGnQYTyc2ONIMPouPig.png" /><figcaption>Figure 4: Throughput test results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxOGTxMKHzZYxho8YccNEg.png" /><figcaption>Figure 5: Latency test results</figcaption></figure><h3><strong>Possible future improvements</strong></h3><ol><li>RPC. I wanted to do this as a RPC implementation since it sounds like that might potentially be faster and a more future proof design. However, I’m not sure how to manage the concurrency, serialisation or deserialisation and isn’t clear to me if it can be made as performant.</li><li>I am considering wrapping this in Kubernetes Knative. To allow for horizontal scaling to multiple GPUs.</li><li>Parameter updates. I plan to use this server for reinforcement learning it there will need to be a parameter server and a mechanism for frequent parameter updates.</li><li>Increase the complexity of the batching algorithm for better performance.</li></ol><p><strong>References</strong></p><p>[1] <a href="https://azure.microsoft.com/en-au/blog/gpus-vs-cpus-for-deployment-of-deep-learning-models/">https://azure.microsoft.com/en-au/blog/gpus-vs-cpus-for-deployment-of-deep-learning-models/</a></p><p>[2] <a href="https://pytorch.org/docs/stable/notes/cuda.html">https://pytorch.org/docs/stable/notes/cuda.html</a></p><p>[3] <a href="https://docs.python.org/3.7/library/asyncio.html">https://docs.python.org/3.7/library/asyncio.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ad3ebd0a1d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NFS Filestore on GCP for free]]></title>
            <link>https://medium.com/@ngoodger_7766/nfs-filestore-on-gcp-for-free-859593e18bdf?source=rss-8db1871c3e81------2</link>
            <guid isPermaLink="false">https://medium.com/p/859593e18bdf</guid>
            <category><![CDATA[file-sharing]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[nfs-server]]></category>
            <category><![CDATA[fn]]></category>
            <dc:creator><![CDATA[Nikolaj Goodger]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 05:46:44 GMT</pubDate>
            <atom:updated>2020-04-27T05:46:44.923Z</atom:updated>
            <content:encoded><![CDATA[<p>I regularly find myself wanting some file storage in the Google cloud environment. Now Google has Filestore offering however at the time of writing the cost is $0.2/Gbyte and the minimum size is 1Tbyte so it’s going to run a minimum of $200 a month! This is quite reasonable for the performance and capacity but what about a budget option?</p><p>Google generously offers an f1-micro instance with 30Gbyte of storage <strong>for free</strong>. Due to the way network and disk bandwidth works on GCE it’s not going to break any speed records, but since NFS isn’t compute intensive this is a good low performance option. <strong>There is nothing secure about this implementation. Anyone can mount and access the nfs volume with read and write permission.</strong></p><h4>Pre-requisites</h4><p>This assumes gcloud tool is setup and connected to a project. <a href="https://cloud.google.com/deployment-manager/docs/step-by-step-guide/installation-and-setup">https://cloud.google.com/deployment-manager/docs/step-by-step-guide/installation-and-setup</a></p><h4>Step 1. Create the GCE VM for running the nfs server.</h4><pre>gcloud compute instances create nfs-server --boot-disk-size=30GB --image=ubuntu-1804-lts --image-project=ubuntu-os-cloud --machine-type=f1-micro --tags=nfs</pre><p>we add the tag nfs to target the firewall rules we create later.</p><h4>Step 2. SSH into the nfs server.</h4><pre>gcloud compute ssh nfs-server</pre><h4>Step 3. Install nfs server.</h4><pre>sudo apt install -y nfs-kernel-server</pre><h4>Step 4. Create shared directory to serve</h4><pre>sudo mkdir /share<br>sudo chown nobody:nogroup /share<br>sudo chmod 777 /share</pre><h4>Step 5. Add share to nfs exports</h4><pre>sudo vim /etc/exports</pre><p>Add the following line to /etc/exports.</p><pre>/share *(rw,sync,no_subtree_check)</pre><h4>Step 6. Restart nfs-kernel-server</h4><p>To update the nfs-server with the new /etc/exports it needs to be restarted.</p><pre>sudo systemctl restart nfs-kernel-server</pre><p>Confirm that the directory is being shared by running</p><pre>sudo exportfs</pre><p>You should see the output /share world.</p><p>After this is complete you can exit the ssh session and return to the host machine.</p><pre>exit</pre><h4>Step 7. Add firewall rules</h4><p>If you want to access the nfs server from outside your Google cloud project you’ll need to add some firewall rules. Again, this is not secure in any way, so be careful.</p><pre>gcloud compute firewall-rules create nfs \<br>--allow=tcp:111,udp:111,tcp:2049,udp:2049 --target-tags=nfs</pre><h4>Step 7. Test!</h4><p>To test the nfs server we can first use gcloud to get the external ip of the new instance. Create a local directory for mounting the nfs file share. The below code was tested on macOS Catalina.</p><p>If you are on an Ubuntu host you may need to install Install nfs-common.</p><pre>NFS_SERVER_IP=$(gcloud compute instances describe nfs-server \<br>--format=&#39;get(networkInterfaces[0].accessConfigs[0].natIP)&#39;)</pre><pre>mkdir ~/test_mount</pre><pre>sudo mount -t nfs -o vers=4 -o resvport \<br>$NFS_SERVER_IP:/share ~/test_mount</pre><pre># Test nfs before cleaning up.</pre><pre>sudo umount ~/test_mount &amp;&amp; rm -r ~/test_mount</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=859593e18bdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proximal Policy Optimisation in PyTorch with Recurrent models]]></title>
            <link>https://medium.com/@ngoodger_7766/proximal-policy-optimisation-in-pytorch-with-recurrent-models-edefb8a72180?source=rss-8db1871c3e81------2</link>
            <guid isPermaLink="false">https://medium.com/p/edefb8a72180</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Nikolaj Goodger]]></dc:creator>
            <pubDate>Thu, 13 Feb 2020 11:20:22 GMT</pubDate>
            <atom:updated>2020-02-13T11:20:22.499Z</atom:updated>
            <content:encoded><![CDATA[<h3>Proximal Policy Optimisation with PyTorch using Recurrent models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dv03czgVt90Y_ITUWsYIvQ.png" /></figure><p>Proximal Policy Optimisation (PPO) is a policy gradient technique that is relatively straight forward to implement and can <strong>develop policies to maximise reward</strong> for a wide class of problems [1].</p><p>Like other policy gradient methods PPO can optimise recurrent neural network policies. This can be very useful because in many environments the observations do not represent the complete state of the system but the <strong>recurrent model can figure out what the states are from a series of observations </strong>i.e.<strong> </strong>Partially Observable Markov Decision Processes (POMDP) can be solved as though they were Markov Decision Processes (MDPs). This approach was used by OpenAI Five to beat the world champions in Dota [2].</p><p>At a much smaller scale the utility of this approach is demonstrated in the partially observable environment [3] below:</p><h4>HardcoreBipedalWalker-v2</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*hTV0r53aeUGLokG_Si7cLQ.gif" /><figcaption>Training Iteration: 6830, Reward: 328</figcaption></figure><p>To further qualify the approach It tested some more contrived examples. Many of the Gym environments provide observations with velocity terms so they are fully observable and able to be solved using the observations as states. To test the LSTMs ability to learn the state I masked the velocity terms and the results can be seen below:</p><h4>CartPole-v2 (Masked velocity terms in observations)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*CSrEc-dsZoJkGDwtJni9Yw.gif" /><figcaption>Training Iteration 420, Reward = 500.</figcaption></figure><h4>Pendulum-v0 (Masked velocity terms in observations)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*_iO2OuYmb5V1-yLRJpXmRw.gif" /><figcaption>Training Iteration 660, Reward = -475.</figcaption></figure><h4>LunarLander-v2 (Masked velocity terms in observations)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*7iuZ9-coeHhBWLs4p3jknA.gif" /><figcaption>Training Iteration 3490, Reward 280</figcaption></figure><h4>LunarLanderContinuous-v2 (Masked velocity terms in observations)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KGV5jHuVCEJCRJHg8RiGPw.gif" /><figcaption>Training Iteration 4480, Reward 269</figcaption></figure><h4>BipedalWalker-v2 (Velocity terms not masked)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*eVSPMGUk6oztYGP-YszsWw.gif" /><figcaption>Training Iteration 2160, Reward 310</figcaption></figure><h3>Further justification</h3><p>Hopefully, the above examples have demonstrated recurrent models can help in environments where partial observability is a problem. However, I would go further and think there are good reasons to use it as the default general method for solving environments:</p><ol><li>The model can compute the state from the observations for us</li></ol><p>Many environments consist of or include a dynamic mechanical system. To be MDP the environment must include both the position and velocity terms which is exactly what the Gym environments like CartPole, Pendulum and LunarLander do. Without a recurrent model and using the observations directly as a state only low scores can be achieved because the policy can’t know whether to brake or accelerate for a given position. For this simple case, we know the answer but as the complexity of the observations grows it will become increasingly difficult to design an appropriate state and easier to let to model compute it for us. An example of this is the BipedalWalkerHardcore where [2] explains that the walker needs to remember may have seen in the previous frames to avoid falling into them.</p><p>2. Sometimes the observations are controlled by the agent itself</p><p>As the agent moves around in a partially observable world it may need to learn where we look to be able to get the observations needed for optimal actions.</p><p>3. The model can protect us from our ignorance of the problem</p><p>Even if we think we have designed a state based on the observations to reduce the problem complexity to an MDP we can make mistakes e.g. Maybe we lack relevant domain knowledge, there is a bug or the complexity of the state is beyond our understanding. For me, this is both intimidating and exciting because the recurrent model can automatically learn to address this for us.</p><h3><strong>Noteworthy Implementation Details</strong></h3><p>Most of the relevant algorithm details can be obtained from [1] so I’ll focus on some of the engineering details here:</p><p>1. Gym Vector implementation</p><p>The standard gym environment runs a single environment at a time. Other RL implementations I’ve seen work around this by running separate processes in parallel. This works but consumes a lot of resources especially when inferencing on multiple separate models. Gym now features a nice solution to this problem by wrapping the environment so that multiple instances of the same environment can run together either synchronously in the same process or asynchronously using multiple processes. Increasing the batch size for the policy and critic from 1 (single environment) to 32 parallel environments is much much faster than 32 models running in parallel doing inference on a single batch.</p><p>2. Google Colab</p><p>The model training and testing were conducted on Google’s Colab. The main reason for this is that environment generously offers a free GPU. It’s not without limitations however and in my experience, it will not allow continuous GPU usage more than about 12hrs. There are also other problems such as disconnections that occur. Meaning that for training jobs taking multiple days like the BipedalWalkerHardcore-v2 the ability to save and resume from checkpoints saved onto Google Drive had to be added.</p><p>3. State Initialisation</p><p>When capturing a trajectory for training a model it is easy to initialise the LSTM hidden state and cell state to zero. Then iterate through a complete episode allowing the LSTM to update its own state for each step. At training time, we split the episode into chunks usually around 8 steps long. During training, we can also initialise the hidden state and cell state to zero however under these conditions the pi / pi_old ratio can be quite different even under the same policy parameters. This problem gets better the bigger with longer training sequence lengths like 16 or 32 because the init state has less influence on the final state, but the inverse is also true and it gets worse for shorter sequence lengths. To mitigate this problem we can save the LSTM states at rollout time and used them for initialisation at training time. For the first training iteration in each PPO iteration, these saved hidden and cell states are accurate but as the parameters change these become less accurate. However, it’s still a much more accurate initialisation than zero and as such produces more accurate gradients for training allowing using very short sequence lengths.</p><p>4. Reward shaping</p><p>The received rewards can have a big impact on how PPO solves a problem. In the BipedalWalker and BipedalWalkerHardcore environments reward is given for forward motion, a penalty is applied for torque and a large negative reward (-100) for falling over. I used the same approach as in <a href="https://github.com/jet-black/ppo-lstm-parallel">[</a>4] to limit the reward to a minimum of -1 for the walker environments. The difference in behavior is quite dramatic:</p><p>Unshaped reward:</p><ol><li>Walker learns to adopt a very stable stance and remains there until the end of the episode.</li><li>Walker slowly learns to shuffle forward.</li><li>Walker’s gait slowly becomes less conservative and faster moving.</li></ol><p>Shaped reward:</p><ol><li>Walker quickly learns to fall forward.</li><li>The Walkers fall becomes longer and longer as it learns to “catch” itself with its legs.</li><li>Walker no longer falls and has found a high-speed gait.</li></ol><p>While PPO can solve both these problems the unshaped reward takes a lot longer to solve the problem and the gait is less satisfying because it is so conservative.</p><h3>Implementation links &amp; Setup</h3><p>The implementation consists of two Notebooks. One for training a policy in a chosen environment: <a href="https://gitlab.com/ngoodger/ppo_lstm/-/blob/master/recurrent_ppo.ipynb">recurrent_ppo.ipynb</a></p><p>and one for generating a test video: <a href="https://gitlab.com/ngoodger/ppo_lstm/-/blob/master/test_recurrent_ppo.ipynb">test_recurrent_ppo.ipynb</a></p><p>The notebooks expect the following directories in Google Drive:</p><p>/workspace/checkpoints</p><p>/workspaces/logs</p><p>/workspace/videos</p><p>The checkpoints directory is used for saving the model and optimiser parameters so a model can be resumed or tested. The logs directory is used for saving the Tensorboard logs and the videos directory is used for saving the video output from the test notebook.</p><p>The saved checkpoints used to generate the results are included here: <a href="https://gitlab.com/ngoodger/ppo_lstm/-/tree/master/checkpoints">checkpoints</a>, these could be added to google cloud to resume from, to test with or even transfer learning.</p><h3>15 Minutes of Trained BipedalWalkerHardcore-v2</h3><p>This video consists of about 70 episodes. Notice that it still fails fairly often. The mean reward was about 160 when I lost patience training it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPWGOsQuBp8Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPWGOsQuBp8Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPWGOsQuBp8Y%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/f84c88f4f81a4bfa26a87736a5cd3192/href">https://medium.com/media/f84c88f4f81a4bfa26a87736a5cd3192/href</a></iframe><h3>Conclusion</h3><p>The PPO algorithm together with a recurrent model is a really powerful combination. Capable of producing good results on a wide range of problems, solving both MDPs and POMDPs in continuous and discrete action spaces.</p><h3>References</h3><p>[1] Proximal Policy Optimization Algorithms <a href="https://arxiv.org/pdf/1707.06347.pdf">https://arxiv.org/pdf/1707.06347.pdf</a></p><p>[2] Dota 2 with Large Scale Deep Reinforcement Learning <a href="https://arxiv.org/pdf/1912.06680.pdf">https://arxiv.org/pdf/1912.06680.pdf</a></p><p>[3] Recurrent Deterministic Policy Gradient Method for Bipedal Locomotion on Rough Terrain Challenge <a href="https://arxiv.org/pdf/1710.02896.pdf">https://arxiv.org/pdf/1710.02896.pdf</a></p><p>[4] PPO with LSTM and Parallel processing <a href="https://github.com/jet-black/ppo-lstm-parallel">https://github.com/jet-black/ppo-lstm-parallel</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edefb8a72180" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>