<?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 DarylRodrigo on Medium]]></title>
        <description><![CDATA[Stories by DarylRodrigo on Medium]]></description>
        <link>https://medium.com/@darylrodrigo2020?source=rss-8313e98b89a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EmBt6Y1BTWQu22o1YZv7Ow.jpeg</url>
            <title>Stories by DarylRodrigo on Medium</title>
            <link>https://medium.com/@darylrodrigo2020?source=rss-8313e98b89a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 08:12:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@darylrodrigo2020/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[Building a TypeScript Version of Auto-GPT: Implementation and Findings]]></title>
            <link>https://javascript.plainenglish.io/building-a-typescript-version-of-auto-gpt-implementation-and-findings-166edd5356c8?source=rss-8313e98b89a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/166edd5356c8</guid>
            <category><![CDATA[auto-gpt]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[DarylRodrigo]]></dc:creator>
            <pubDate>Wed, 03 May 2023 07:51:46 GMT</pubDate>
            <atom:updated>2023-05-04T15:02:28.958Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The purpose of this blog post is to share my experience and findings while implementing my own bare-bones TypeScript version of </em><a href="https://github.com/Significant-Gravitas/Auto-GPT"><em>Auto-GPT</em></a><em>. I’ll provide an overview of the </em><strong><em>architecture</em></strong><em> I used, discuss my </em><strong><em>observations</em></strong><em> on the system, </em><strong><em>hacks</em></strong><em> that I found significantly improved performance, and suggest potential improvements and further ideas. I hope that others might find my journey and technical insights interesting or useful.</em></p><p><em>This blog post assumes some knowledge of </em><a href="https://github.com/Significant-Gravitas/Auto-GPT"><em>AutoGPT</em></a><em>.</em></p><p><em>Github Repo: </em><a href="https://github.com/DarylRodrigo/auto-gpt-ts"><em>https://github.com/DarylRodrigo/auto-gpt-ts</em></a></p><h3>Architecture</h3><p>Overall, most of the core concepts and ideas are related to Auto-GPT; an LLM still thinks and provides actions which are then stored in memory to be used later.</p><p>The main difference between my implementation and the original Auto-GPT codebase is that I took a more OOO (Object Oriented Programming) approach and added concepts from DDD (Domain Driven Design) — specifically for commands (or tools). In my experience, it has been easier to maintain the code base this way and allowed for more abstraction and modularity.</p><p>A fairly standard approach was taken to build the main control loop. There is an Agent and a Memory class, which together handle coming up with a plan of action, they then also save those memories to be later used as part of the prompt.</p><p>The acting system is fairly unique in that it uses a commandBus where commands can be registered which can then be invoked by the Agent (see command handling for more details).</p><figure><img alt="Overview of the architecture of the system — created by Author" src="https://cdn-images-1.medium.com/max/1024/1*8pfor7rb1fzDLm5MJid-Ew.jpeg" /><figcaption>Overview of the architecture of the system — created by Author</figcaption></figure><h4>The Agent and Memory Module</h4><p>I won’t go into much detail here as I think there wasn’t much difference between my implementation and that of Auto-GPT.</p><p><strong>Similarities with the original Auto-GPT: </strong>The agent I built can think and act, much like the Auto-GPT system. It uses a similar structure for generating prompts and interacting with the GPT-3.5 language model.</p><p><strong>Memory Module: </strong>The memory module was fairly standard, it saves all the thoughts generated by the agent and then re-structured them when injected as part of the prompt. I spent a lot of time trying to come up with different ways of constructing the memory, which was relatively easy to do given that prompts were derived from a get method in the memory class. There is also a vectorDB implementation using <a href="https://python.langchain.com/en/latest/ecosystem/pinecone.html">langChain</a> and pinecone, but it was never actually needed for my use cases.</p><p><strong>Type validation: </strong>One thing that is worth mentioning is that similar to Auto-GPT, I also found that if a return value from GPT-3.5 didn’t match the required JSON format, just re-querying the LLM would often result in the correct format. My implementation has a wrapper for this around this in an <a href="https://github.com/DarylRodrigo/auto-gpt-ts/blob/efcb8fdc53a4f6a63c2b3cb48168c4af4a3f0481/src/utils/OpenAIManager.ts#L51">OpenAiManager</a> class; it will continually query (with max retries) until the expected type is returned.</p><p><strong>Docker Container to Execute code: </strong>I was a little uneasy about just letting Auto-GPT arbitrarily run code and commands on my device so all interactions done on a code and command level are run within a docker container.</p><h3>Command Handling</h3><p><em>tl;dr — Command correction allowed for much better performance and the modularity of the command handler allowed GPT-4 to fully generate its own capabilities/tools.</em></p><p><strong>Command Bus Design: </strong>The commandBus in this architecture allows for the modular addition of commands through registering to command handlers (as implemented in DDD). This allows for easy extensibility of the system by adding new commands as required, without affecting the existing codebase. Below is an example of a command handler being registered to the command bus.</p><pre>// Create command bus<br>const commandBus = new CommandBus()<br><br>// docker command handler to execute code in contained environment<br>const dockerCommandHandler = new DockerCommandHandler(dockerManager, openAiManager)<br>dockerCommandHandler.registerTo(commandBus)<br><br>// Invoking the the command.<br>await commandBus.execute(&quot;WRITE_TO_FILE&quot;, [&quot;hello.py&quot;, `print (&quot;Hello World!&quot;)`]);<br>await commandBus.execute(&quot;RUN_PYTHON&quot;, [&quot;hello.py&quot;, &quot;-i&quot;, &quot;1&quot;]);</pre><p><strong>Command Architecture: </strong>The command architecture includes the command name, a description to pass to the agent and arguments (which in hindsight should have been a JSON object, not an array — but this allowed for easier type checking), as well as an optional callback function.</p><p>This callback function allows for corrections to be made to the arguments before executing the command. This feature is especially useful in cases where the initial command returns code that requires user interaction to be executed properly. In such cases, the corrections made to the arguments ensure that the system-generated code is invokable via the command line with arguments.</p><p>Without this callback function, I would receive at least 50% of the time unusable Python code. However, with this, I always got back correct, executable code.</p><p>Below is an example of a command, which is then registered to the command bus.</p><pre>// function to write to a file<br>async writeToFile(args: string[]): Promise&lt;CommandResult&gt; {<br>    const [fileName, content] = args;<br>    await this.dockerManager.containerExec([<br>      &#39;sh&#39;,<br>      &#39;-c&#39;,<br>      `cat &gt; ${fileName} &lt;&lt;&#39;EOF&#39;\\n${content}\\nEOF`,<br>    ]);<br>    return { ok: true, message: &quot;succesfull&quot; };<br>  }<br><br>// Registering to command bus<br>registerTo(commandBus: CommandBus) {<br>	commandBus.registerCommand(<br>	    &quot;WRITE_TO_FILE&quot;,<br>	    &#39;Writes content to file eg: [&quot;file_to_write&quot;, &quot;content&quot;]&#39;,<br>	    &#39;[&quot;file_name&quot;, &quot;content&quot;]&#39;,<br>	    async (args) =&gt; await this.writeToFile(args),<br>	    async (args) =&gt; {<br>	      const systemPrompt = `<br>	      Can you check if the syntax of this code is correct and make sure the input command is not used. <br>	      - If an input command is used please replace it for command line arguments. <br>	      - Make sure all functions are imported or defined before used.<br>	<br>	      Respond with JUST the new code.`<br>	<br>	      if (args[0].includes(&quot;.py&quot;) &amp;&amp; this.options.correctCode) <br>	        args[1] = await this.openAiManager.chatCompletion(OpenAiManager.toPrompt([systemPrompt], [args[1]] ), String, false);<br>	      return args<br>	    }<br>	  );<br>}</pre><p><strong>Modularity: </strong>Beyond the fact that the way the command system is built up is nicely encapsulated (and this really blew my mind), it enabled GPT-4 to generate fully functional commands and tests for it. For example, the <strong>whole</strong> of the searchGoogle and queryWolframAlpha the section in the command handler was written by GPT-4. I was completely amazed (prompts in appendix).</p><p><strong>Closing Thoughts: </strong>Overall the command architecture is flexible and can accommodate a wide variety of command implementations, making the system adaptable to various use cases. The use of the optional correctional callback function adds an extra layer of versatility to the system, allowing for more complex queries to be made while ensuring the validity of the commands.</p><h3>Results &amp; Observations</h3><p><strong>Too many commands confuse the Agents: </strong>During the development of the architecture, it became apparent that adding too many commands can confuse the agent and negatively impact its performance. As a result, future versions of the architecture will have the ability to choose specific commands. The <a href="https://github.com/DarylRodrigo/auto-gpt-ts/blob/efcb8fdc53a4f6a63c2b3cb48168c4af4a3f0481/src/infra/CommandBus.ts#L14">skillsEnabled field</a> was added to allow for this flexibility.</p><p><strong>Planning is Poor: </strong>Additionally, the planning aspect of the agent’s behaviour was often poor, resulting in inefficient command execution. The implementation of a meta-cognition agent would likely help improve this aspect of the architecture.</p><p>Another potential improvement for the architecture would be to allow the spawning of agents with specific abilities, rather than relying on a single agent to perform all tasks. This could potentially improve the overall performance of the system and allow for better task distribution.</p><p><strong>Debugging is hard: </strong>One challenge faced during the development process was the difficulty of debugging and understanding the system. The implementation of a good interface and logging system would be helpful for future development.</p><p><strong>The capability of underlying LLM is incredibly important: </strong>Finally, while the GPT-3.5 architecture was used in the current implementation, it may not be sufficient for more complex tasks. Further research and experimentation with different architectures may be necessary for more advanced applications.</p><p><strong>Successful runs: </strong>Created a calculator app in Python, tested the code, wrote tests, ran the tests and then ran the calculator app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*0rU0cJ-DXMfZMvPWFEhsLg.png" /><figcaption>Output from Auto-GPT when creating the calculator. See Appendix for full transcript — Image generated with Carbon</figcaption></figure><h3>Improvements and Further Ideas</h3><p>Based on my observations and interactions with the agent, the main improvements I will be making are to the planning element of the agent and how memory is retrieved.</p><p><strong>Planning:</strong> Separating out creating the plan and execution section, similar to BabyAGI. I saw a great implementation in <a href="https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html">LangChain</a> for agents with custom tool retrieval. Additionally, concepts like specific planning capabilities systems could be helpful — <a href="https://arxiv.org/pdf/2304.11477.pdf">LLM+P: Empowering Large Language Models with Optimal Planning Proficiency</a>.</p><p><strong>Memory:</strong> Designing specific memory retrieval for the planning agents and the execution agents. I think I will base my implementation on <a href="https://arxiv.org/pdf/2304.13343.pdf">Unleashing Infinite-Length Input Capacity for Large-scale Language Models with Self-Controlled Memory System</a> (great for ensuring not too much information is passed to the Agent, only as much as required) and <a href="https://arxiv.org/pdf/2304.03442.pdf">Generative Agents: Interactive Simulacra of Human Behavior</a> (great for making sure the most relevant information is sent to the agent).</p><h3>Appendix</h3><ul><li>Notion page with a prompt to generate commands [<a href="https://darylrodrigo.notion.site/Prompt-to-Create-commands-e07419ae2cbe4e01bb5b86d11227818d">link</a>]</li><li>Notion page with runs of the agent creating a calculator app [<a href="https://darylrodrigo.notion.site/Creating-a-Calculator-App-79b4593ee6044b9ab2bdfb94641b282e">link</a>]</li></ul><p><em>I would like to thank Faraz Khan and Daniel Ratke for looking over this post and helping refine it!</em></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=166edd5356c8" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/building-a-typescript-version-of-auto-gpt-implementation-and-findings-166edd5356c8">Building a TypeScript Version of Auto-GPT: Implementation and Findings</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Graphic Guide to Implementing PPO for Atari Games]]></title>
            <link>https://medium.com/data-science/a-graphic-guide-to-implementing-ppo-for-atari-games-5740ccbe3fbc?source=rss-8313e98b89a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5740ccbe3fbc</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[atari]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[ppo]]></category>
            <dc:creator><![CDATA[DarylRodrigo]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 09:22:16 GMT</pubDate>
            <atom:updated>2022-02-11T08:34:47.357Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learnings from a journey to code Proximal Policy Optimisation</h4><p><em>Written by </em><a href="https://github.com/DarylRodrigo"><em>Daryl</em></a><em> and </em><a href="https://github.com/instance01"><em>Daniel</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*haPvLvI2duxS8v-7.png" /><figcaption>Image by <a href="https://pixabay.com/users/sergeitokmakov-3426571/">sergeitokmakov</a> on <a href="https://pixabay.com/illustrations/computer-8-bit-old-retro-isolated-4812105/">Pixabay</a></figcaption></figure><p><em>Learning how Proximal Policy Optimisation (PPO) works and writing a functioning version is hard. There are many places where this can go wrong — from misunderstanding the maths and mismatching tensors to having a logical error in the implementation. It took a friend and me around a month of work to get to a fully running PPO, where we successfully implemented the algorithm and were confident that we understood how it operated.</em> <em>This guide summarises all the areas where we struggled building our final algorithm and intuitions we developed. This blog aims to cover the basic theory of PPO, how we decided to implement our version, working with tensor shapes, testing, and using the recorded metrics to debug what we built. I hope you enjoy it!</em></p><blockquote>Because this blog post intends to cover PPO, it will assume some prior knowledge of basic reinforcement learning (RL). In particular the basic setup of an RL problem, some notion on how an actor-critic model works, concepts behind the Bellman equation and a vague understanding of what <a href="https://towardsdatascience.com/an-intuitive-explanation-of-policy-gradient-part-1-reinforce-aa4392cbfd3c">policy gradient methods</a> are.</blockquote><p>Github Repo — [<a href="https://github.com/DarylRodrigo/rl_lib/tree/master/PPO">link</a>]</p><h3>🏔 High-Level Theory</h3><p>As a recap — PPO belongs to a class of algorithms called policy gradients (PG). The fundamental idea is to update the policy directly to make the probability of taking actions which provide a larger future reward more likely. This is done by running the algorithm in an environment and collecting the state change based on an agent’s actions — a collection of these interactions is called a trajectory. Once one or more trajectories have been collected, the algorithm will look at each step and check whether the chosen action led to a positive or negative reward and update the policy accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTlhmOsaXgpaSEzIlY2kAw.jpeg" /><figcaption>Figure 1.1: High-level diagram on training a Policy Gradient Algorithm. (Image by Author)</figcaption></figure><h4>Sampling Actions and Collecting a Trajectory</h4><p>Trajectories are sampled by interacting with the environment step by step. To take a single step an agent selects an action and passes it into the environment.</p><p>PG algorithms decide on which action to take by accepting an input (the state or observation of an environment) and then, for a discrete action space, output a probability for each possible action. A neural network typically calculates this probability. The neural network’s output is dictated by its weights and is typically written as π_θ, where π denotes the policy and θ the weights of the network (important for the next part).</p><p>To select an action, the agent samples from the distribution of probabilities given by the neural network (called logits) — this action is then used to provide the environment with its next input. For example, in Figure 1.2, the action right has a 50% chance of being selected (left 12.5%, up 25% and down 12.5%). As a consequence of selecting an action from probabilities, exploration is inherently present in PG algorithms as the randomness in actions comes from the selection probabilities. As the agent becomes more sure of what the correct action is, exploration will decrease as the probabilities for incorrect actions decrease. Once the action has been taken, all metrics are stored for later use in training (observation, action, log action probabilities, value, reward, done).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKpfH62Oi8yL7GywlU8Dvg.jpeg" /><figcaption>Figure 1.2: Diagram illustrating the methodology for selecting an action in a policy gradient reinforcement learning algorithm. (Image by Author)</figcaption></figure><h4>Updating the Agent</h4><p>Before diving into PPO, it is useful to breeze over the maths for PG algorithms from a high level to get a complete image of what the algorithm will be doing. However, since this blog post is about implementing PPO, we’ll have to skip over the details of how the derivation behind calculating the loss and updating the agent works (also, if you’re not interested in the maths behind PG, then feel free to skip the next 3 headings).</p><p><strong>Updating the Policy:</strong> The building block of any PG algorithm is the formula on how a network is updated. The update formula in Figure 1.3 shows that the new weights of a network [1] are updated to the current weights [2] + the gradient of the current network given a specific state-action pair [4] times the learning rate [3]. This is the underpinning formula of how to update the network weights. Intuitively the gradient is the direction (+/-) of the weights in which the change of the policy will make taken actions more likely in a given state (reverse them to make them less likely).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htGBjTzGmxwjRIdiZTfj3w.jpeg" /><figcaption>Figure 1.3: Policy Gradient weight update equation. (Image by Author)</figcaption></figure><p>A full explanation of how policy gradient updates work from a mathematical standpoint there is no better place than <a href="https://www.youtube.com/watch?v=KHZVXao4qXs&amp;ab_channel=DeepMind">David Silvers lecture</a>.</p><blockquote>So how do we calculate this gradient? Thankfully, all the most common deep learning frameworks will keep a computational graph of information passing through a neural network and keep a record of the gradient part of the network.</blockquote><p><strong>Adjusting Weight Direction and Amount:</strong> With the update equation we know what direction the “gradient” of a specific state-action pair is — that is to say, to make that action (in a specific state) more likely by changing the neural networks weights in the direction of the gradient. Of course, we do not want to make every action more likely, if a bad result was obtained we want to reduce the probability of taking that action. This is what the advantage function [1] embodies — how much better or worse an action was than we expected. If a action led to a scenario where we are better off than before (positive advantage), the weights are change in the gradients direction, effectively making it more likely that that action is chosen again. If it’s worse, we decrease the weights in the direction of the gradient, making it less lightly</p><p>Another consideration is the amount weights are updated by, if just the advantage times the gradient were to be updated, there would be very aggressive updates (great explanation of why <a href="https://towardsdatascience.com/an-intuitive-explanation-of-policy-gradient-part-1-reinforce-aa4392cbfd3c">here</a>). So in order to counteract this, we divide the update by the output of the policy [2], this is called importance sampling (how much weight to place on a particular update).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mi7fNFi3k3paqTpT9BxZWw.jpeg" /><figcaption>Figure 1.4: Update rule with additional variables to inform which direction and by how much the gradient needs to be updated. (Image by Author)</figcaption></figure><p>For example, if the action output was [2,3,5,1] and the action with value 5 (action 3) was chosen, the gradient would be divided by 5 to reduce the amount the gradient is updated. This is to stop action 3 quickly increasing in value, and hence and no other value getting the chance of being chosen (as it is done on a probability basis and if we have [2,3,100,1] the other actions are unlikely to be chosen), even if they might yield a higher return in the long run.</p><p><strong>Chaining it up:</strong> This leaves the last step to the update rule, which comes from using the magic of the chain rule. Using this we can substitute out our partial derivative fraction with the <em>gradient log of the action which was taken</em>. This part is important because it’s what builds the foundation of PG and PPO algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vF5Du99iUD1Tl-IkYyklSw.jpeg" /><figcaption>Figure 1.5: Final update rule. (Image by Author)</figcaption></figure><p>Again, this is not intended to be a full explanation on the mathematical theory behind policy gradient algorithms but rather a quick review/recap on where the log values are coming from.</p><p><strong>Visualising the update:</strong> When the theory is placed in practice it would look something as Figure 1.6 describes. First, the trajectory is run [step 1], and all relevant values are saved (log probabilities, value and reward — amongst other things). Once the trajectories have been completed, the discounted returns and advantages can be calculated [step 2] (great article <a href="https://example.com/">here</a> explaining what advantages are, but as a reminder, the advantages = discounted_return - expected_return where expected return is calculated by the critic as value). [step 3] Next the loss of each step is calculated by looking at the log probabilities and multiplying it by the advantage, just as shown in Figure 1.5. [step 4] Lastly we take the average of all these losses and do a backwards pass with gradient descent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6K3NDhwXvmwBBQszdssUyg.jpeg" /><figcaption>Figure 1.6: Diagram showing the process of updating weights in policy gradient through a 4 step process. Collecting trajectories, calculating advantages, calculating loss and finally updating network weights. Note that the learning rate is set in the optimiser upon initialisation. (Image by Author)</figcaption></figure><h4>PPO — The Main Idea</h4><p><em>Original PPO paper — </em><a href="https://arxiv.org/pdf/1707.06347.pdf"><em>link</em></a></p><p>With policy gradient methods, once a few trajectories have been collected a model will be updated a number times using the same trajectories in order to learn from the new data that has been collected. Remember that the size of this update is determined by both the magnitude of the advantage as well as the importance sample (which is expressed as the log probability of the action).</p><p>PPO adds an additional factor which is the <strong>probability ratio</strong> to prevent large updates from occurring. This is defined as the difference between the original action log probability and the new model’s action log probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lA33EVIPnJz7dqmyQkJKBw.jpeg" /><figcaption>Figure 1.7: Loss function using ratios from new and old policy action log probability called conservative policy iteration (CPI). Formula from PPO paper, section 3 (6). (Image by Author)</figcaption></figure><p><strong>Problem:</strong> The problem with PG algorithms is that when an update is performed, its magnitude by which the policy change can happen (i.e. the weights change) can push the policy into a region that when another gradient descent is performed, all direction are essentially the same and the peak of the reward is missed. This is demonstrated in Figure 1.8 — a single update has missed the peak of the reward, and now when gradient descent is performed on a new trajectory it’s hard to say whether “left” of “right” movement will lead to a better policy loss. This causes the update to destroy the policy to an unrecoverable extent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKBMeLch_p3tD2IxXJq37A.jpeg" /><figcaption>Figure 1.8: Graph showing how a policy update can overshoot and the high reward being missed with large updates are taken. (Image by Author)</figcaption></figure><p><strong>Solution:</strong> The PPO paper’s solution is to create a ratio between the original action log probability and the new model’s action log probability. If that ratio becomes too large or too small, it will be clipped to +/- a set amount (typically 0.2). This will prevent the policy from taking too large of an update step; this can be seen in Figure 1.9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eK4OyXYVkdgtr_YewqReKA.jpeg" /><figcaption>Figure 1.9 Graph showing how a policy can be clipped by PPO to force smaller policy updates. (Image by Author)</figcaption></figure><p>Mathematically this is expressed using a clipping function, also known as a surrogate function, in the PPO paper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TNeEhvhKv7T22YmzIA-6g.jpeg" /><figcaption>Figure 1.10: Clipped surrogate (loss) function as proposed by the PPO paper, selecting the minimum for the clipped and unclipped probability ratios. Formula from PPO paper, section 3 (6). (Image by Author)</figcaption></figure><blockquote>If you’d like to understand this in more detail, <a href="https://www.youtube.com/watch?v=5P7I-xPq8u8">Arxiv Insights</a> has an insanely good YouTube explanation of how PPO works from a theoretical standpoint.</blockquote><p><strong>Visual implementation of flow:</strong> From a practical standpoint following happens;</p><ul><li>First, we collect a few trajectories using our initial model (model_1), making sure to save the action log probability for the actions taken. Using our trajectory, the initial model gets updated to model_2 and is now different from the original.</li><li>Then with the same states that we collected from the trajectories [3], the new log probabilities are calculated [2] (these will be different to the initial model as the model has changed).</li><li>The ratio between the new model and the old model’s action log probabilities is then used to calculate the scalar by which the new policy should be updated. Ratios are calculated on a per-step basis. If the ratio is too large or too small, it will be clipped according to the surrogate function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QSpPm4H5E6P_6ZQHJ1xW5A.jpeg" /><figcaption>Figure 1.11 — Flow of updates for PPO. (Image by Author)</figcaption></figure><h3>💻 Implementing the Code</h3><p><em>Hopefully, the theory section was adequate to give some intuition about how an agent takes actions, the model is updated, why PPO works and why the clipping and probability ratio are required. The following section explains how we implemented PPO for ourselves — some of it might be obvious some not. However, it’s probably helpful to go through everything if you want to fully understand our implementation, as there will be differences. Throughout this section, there will be references made back to our code, so it might be helpful to split your screen in half, with one section having the blog post open and the other section the code, having said that, of course, read through this as works best for yourself!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RSub1CHnbKsv3YvB" /><figcaption>How I usually analyse code with a blog post next to it 😋 (Image by Author)</figcaption></figure><h4>Overview</h4><p>As an overview there are three main classes and a file which runs the whole system:</p><ul><li>Model.py [<a href="http://models.py/">class</a>] - This contains the logic for the agent to both, act on given inputs and learn from data collected from trajectories.</li><li>Memory.py [<a href="https://github.com/DarylRodrigo/rl_lib/blob/master/PPO/Memory.py">class</a>] - This contains all the data from the trajectories and calculates the advantages. It also allows the agent to sample random sections of the trajectory to update the agent in batches.</li><li>Config.py [<a href="https://github.com/DarylRodrigo/rl_lib/blob/master/PPO/Config.py">class</a>] - This contains all the settings required in RL &amp; PPO, such as learning rate, number of steps to take, and hyperparameters like epsilon for the clipping size.</li><li>Utils.py [<a href="https://github.com/DarylRodrigo/rl_lib/blob/master/PPO/util.py">File</a>] - This is the main file which runs the sampling and training loop.</li></ul><p>As you might be able to tell from the flow chart in Figure 2.1, the way an agent is trained is essentially an expansion of the overview in Figure 1.1. First, the program initialises all our variables, and then the algorithm runs in two distinct stages, collecting trajectories and updating the agent from the collected data.</p><p><strong>Collecting Trajectories:</strong> Trajectories are collected by playing in a gym environment; the agent takes actions in the simulation based on its observations. Whilst this loop is active, the individual steps are saved in the agent’s memory.</p><p><strong>Updating the Agent:</strong> Once enough steps are taken, the discounted returns and advantages are calculated — the agent then samples all the steps from the “memory” to calculate the losses and update the agent (all captured data is trained over). Once all the updates are performed, the loop starts at the beginning again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52DvpJXyElA2ldGwJOKxrw.jpeg" /><figcaption>Figure 2.1 — Flow chart showing how our PPO agents trains and how this relates to our classes. (Image by Author)</figcaption></figure><h3>Setup</h3><p>To start with, all the components used in the experiment need to be initialised. The main pieces of this are:</p><ul><li>The gym environment</li><li>The agent, which includes adding the model and the memory</li><li>Logging our experiments (we use weights and biases)</li></ul><h4>Creating the Atari Environment</h4><p>The environments which agents train in is typically created with <a href="https://gym.openai.com/">OpenAI gym</a>, a framework that creates a simulation environment for physics tasks and Atari games. Actions are entered which the environment reacts to — this change is then returned to the agent as a set of observations. With this also comes rewards and whether the game has finished letting the agent know whether or not their actions were “good” or “bad”.</p><p>When human players look at an Atari game, we see the RGB colours which make up the image and a steady change in frames as we play the game. We could feed every frame directly into our agent; this would be portrayed as a tensor of 160,192,3, representing the game&#39;s dimensions and RGB pixels. However, in typical Atari game implementations (and those done in the <a href="https://www.google.com/search?client=safari&amp;sxsrf=ALeKk03DgJ7SRuOmI-jvEFhNqTxiRF8jsw%3A1609836514548&amp;source=hp&amp;ei=4if0X-W6H8Hbgwept76QCA&amp;q=Original+PPO+atari+paper&amp;oq=Original+PPO+atari+paper&amp;gs_lcp=CgZwc3ktYWIQAzIFCCEQoAEyBQghEKABOgQIIxAnOggIABDJAxCRAjoFCC4QkQI6CAgAELEDEIMBOggILhCxAxCDAToOCC4QsQMQgwEQxwEQowI6CAguEMkDEJECOgQIABBDOgUIABCRAjoECC4QQzoHCAAQyQMQQzoHCAAQsQMQQzoNCC4QsQMQxwEQowIQQzoICC4QxwEQrwE6CwguEMkDEJECEJMCOgsILhCxAxDHARCjAjoFCAAQsQM6AggAOgIILjoFCC4QsQM6BQgAEMkDOgYIABAWEB46BAghEBU6BwgAEMkDEA06BAgAEA06BggAEA0QHjoICAAQDRAFEB46CAgAEAgQDRAeOggIABANEAoQHjoICCEQFhAdEB5QkA9YwClgkypoA3AAeAGAAZoCiAHeFZIBBjE0LjkuMpgBAKABAaoBB2d3cy13aXo&amp;sclient=psy-ab&amp;ved=0ahUKEwjls-CstITuAhXB7eAKHambD4IQ4dUDCAw&amp;uact=5">original paper</a>) a few tricks are used to train more effectively, which we&#39;ve included in the env.py file (this was heavily influenced and partly copied from Costa&#39;s <a href="https://github.com/vwxyzjn/cleanrl/tree/master/cleanrl">CleanRL</a> implementation).</p><p><em>Changing the game styles:</em></p><p>The first few tricks pertain to changing how the game fundamentally operates to help the agents along a little bit.</p><ul><li>Episodic Life Env (<a href="http://envs.py:61/">envs.py:61</a>) — This makes sure that the episode is only finished when all lives are lost, rather than when one. As a result, discounted rewards will get carried through the whole game rather than individual lives — this is important as it will allow the agent to get further into the game.</li><li>NoopResetEnv (<a href="http://envs.py:12/">envs.py:12</a>) — As a technicality in the Atari engine, the game will always be the same if you start playing from the start. To get random behaviour in the game engine (rather than the same version every time), a random set of actions are taken to set the game in a pseudo-random state [<a href="https://www.cs.utexas.edu/~pstone/Papers/bib2html-links/AAAI15-hausknecht.pdf">paper</a>]. This is critical to help the agent generalise its learnings.</li><li>FireResetEnv (<a href="http://envs.py:41/">envs.py:41</a>) — If the game only starts when the fire command is pressed it will automatically hit fire when is initialised, this is so that the agent doesn’t have to learn how to start the game.</li><li>Max and Skip (<a href="http://envs.py:97/">envs.py:97</a>) — Any action taken by the agent will be applied to four-time steps within the game. The max of each pixel for all the produced frames will be returned — similarly to max pooling. The reward for those frames will also be added up. The short of the long is that this is all to avoid flickering experienced when playing the game [<a href="https://danieltakeshi.github.io/2016/11/25/frame-skipping-and-preprocessing-for-deep-q-networks-on-atari-2600-games/">Better explanation</a>].</li><li>Clip Reward (<a href="http://envs.py:125/">envs.py:125</a>) — Typically speaking in RL, agents train best if rewards are kept in a “reasonable range” (around +/- 1), this is to avoid too large updates when calculating the discounted returns. Clip rewards cut the rewards to +/- 1 for this reason.</li></ul><p><em>Augmenting the Atari observation output:</em></p><ul><li>Frame Stack (<a href="http://envs.py:187/">envs.py:187</a>)- The agent is passed a stack of frames, representing four time steps in the actual game. This is so that the agent can have a sense of movement. For example, in Breakout, the ball might be in 4 different positions indicating movement in a particular direction.</li><li>WrapFrame (<a href="http://envs.py:134/">envs.py:134</a>) — This is a custom method that reframes the Atari gym environment’s output. After all the augmentations have taken place, a tensor of (4, 84, 84) is produced - with WrapFrame, this is then converted to (84, 84, 4) for every frame. This is so that it is compatible with the CNN head from our agent.</li></ul><p>What this ends up looking like, in terms of tensor sizes for a single environment, is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Chxr05RCfPRHIcQ8bDC_iw.jpeg" /><figcaption>Figure 2.2: Single environment sampling of action, acting on an environment and producing the associated outputs. (Image by Author)</figcaption></figure><p>All these techniques of augmenting the output and altering gameplay are designed for the agent to learn more effectively from the Atari game environment. It can be thought of as data augmentation in machine vision tasks.</p><p>Implementation: The augmentations are implemented in env.py, where they are grouped in a thunk function called make_env(env_id, seed). This function can be invoked at any point, specifying the seed and game type to return an environment; it is implemented this way to help when creating multiple environments.</p><p>Note: One might have noticed that there is an <em>Augment input</em> block in Figure 2.2, which adds a dimension to the input of the agent, this is present because the PyTorch 2D CNN block expects a batch to be entered. In our case, this is a batch of one.</p><h4>Multiple Environments</h4><p>We chose to implement multiple environments to take advantage of our home DL machines’ extra CPU and GPU. This sped up training and was a good learning exercise on how multiple environments worked.</p><p>When multiple environments are added, all outputs from the gym environment gain an extra dimension <em>n</em>, where <em>n</em> is the number of environments. Our agent’s input, however, is not any different. That is because we already augmented the input in the single environment to have 4 dimensions (as seen in Figure 2.2.).</p><p>Multiple environments are implemented is in our Config.py, here the environments are initialised by wrapping the make_env function in the <a href="https://stable-baselines.readthedocs.io/en/master/guide/vec_envs.html#vectorized-environments">Open Baseline&#39;s</a> DummyVecEnv, as seen below.</p><pre>envs = VecPyTorch(<br>	DummyVecEnv(<br>		[make_env(env_id, self.seed+i, i) for i in range(self.num_env)]<br>	), <br>self.device)</pre><p>This function expects “a list of functions that will create the environments (each callable returns a Gym.Env instance when called)”, which is why make_env returns a thunk function that creates a gym-env rather than the gym-env itself. The VecPyTorch is essentially based on <a href="https://stable-baselines.readthedocs.io/en/master/guide/vec_envs.html#vecenv">VecEnv</a>, which &quot;abstracts asynchronous vectorised environments&quot;. It&#39;s an easier way of interacting with the vectorised environments.</p><p>Multiple environments take what we did for single environments and vectorise them in an easy to handle manner. All other game augmentations and reshaping of the environments happen the same way as they did in single environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y0xNCEzSGJynkRvDkRfhLw.jpeg" /><figcaption>Figure 2.3: Diagram showing the data flow for multiple environments starting at the sampling of actions, to placing in the environment and the resultant outputs. (Image by Author)</figcaption></figure><h4>Creating the Agent</h4><p>The Atari PPO agent is created from a base class which (Figure 2.4), with the hyperparameters, initialise two key sections:</p><ul><li><strong>The Model</strong> - This houses the CNN model, we’ve configured so that this is split into a “head” “actor”, and “critic. The head pre-processes incoming data, which the actor and critic then use to calculate their respective values.</li><li><strong>The Memory</strong> - There is a deep dive on this topic later, but basically the memory stores state transitions collected during the acting phase. The initialisation determines the shape and size of the memory, and consequently, how long roll-outs will be.</li></ul><p>With these two class instances the agent is able to perform 3 essential functions:</p><ul><li><strong>Act</strong>: This takes in the observations (of multiple environments), and provides the corresponding actions and log probabilities of those actions.</li><li><strong>AddToMemory</strong>: Once an action has been taken, all the data for that step must be stored for later use. That is what the AddToMemory function does; it stores the information in PyTorch tensors.</li><li><strong>Learn</strong>: This will be explored further in a later section — but essentially, this will take processed data from memory and update the model accordingly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fyGie6nGd10Tw36pwP1Kg.jpeg" /><figcaption>Figure 2.4: Diagram showing the structure of the Agent. (Image by Author)</figcaption></figure><p><strong>The Model</strong></p><p>The model is a vanilla actor-critic network. A CNN head takes in the frames of the game as input, with the addition of all pixels being scaled down by 255, this is to ensure that the input range is between 0 and 1. The output from the CNN is then passed into two fully connected layers. The first layer outputs a single value acting as the critic, and then the second network outputs the number of actions available in the game environment acting as the actor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTE5z0Qxv8zhVRhJYwHsWg.jpeg" /><figcaption>Figure 2.5 — Actor-Critic Network. (Image by Author)</figcaption></figure><p>The class is set up so that an act method (models.py:76) can be invoked to return the action, log probabilities and entropy produced by the actor, as well as the value predicted by the critic. To obtain the action, the logits from the actor are immediately sampled (models.py:79).</p><p><strong>Initialising Network Weights</strong></p><p>One last important factor is to ensure that that each layer has been initialised. A generic function called layer_init surrounds every layer in the network, this is to avoid vanishing or exploding gradients (great post by explaining how this works <a href="https://www.deeplearning.ai/ai-notes/initialization/">here</a>).</p><h3>Memory</h3><p>The decision to make a memory class (rather than just storing the individual variables as PyTorch arrays) in part stemmed the <a href="https://discord.gg/gbruDPv9">Reinforcement Learning Discussion Discord</a> (shout-out to the community who has been incredible in facilitating discussions), where we were discussing tests for core functionality. RL algorithms notoriously fail silently, meaning that they will either not throw an error but never learn, or even worse, learn but not to its maximum potential. This is a huge problem because it makes debugging incredibly hard and requires many, many experiments; and when using simple environments such as CartPole-v1 might never surface. This is why we decided to create a class that stored the saved trajectories, but whose responsibility it also is to calculate the advantages, discounted returns and sample the correct data from memory. This way, we could write tests for each individual function (the tests can be found in /tests/test_memory.py) to ensure that the output is exactly what was expected. It was also instrumental in validating our understanding of advantages and discounted returns.</p><p>The memory itself (as seen in Figure 2.6) has three key aspects:</p><ul><li><strong>Saved Variables</strong> — Trajectories are stored to memory here. The data is stored in predefined PyTorch tensors, as this avoids having to convert arrays to tensors etc.</li><li><strong>Calculating Advantages</strong> — how this is done will be explained in the next section; the important part is that it calculates the advantages and discounted returns based on the trajectories sampled.</li><li><strong>Sampling from Memory</strong> — Because all of our data is in order and still in the format of our n number of environments, this function essentially squashes all our trajectories into on long tensor and then samples random sections to train on (the implementation is explained in more detail in the Updating Model section).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HvDwt-lfWykQOSadGfRkvw.jpeg" /><figcaption>Figure 2.6 — Diagram showing the structure of the Memory class. (Image by Author)</figcaption></figure><p>The initialisation of the memory dictates it’s shape and size and requires various arguments. This includes the number of environments and the environment itself to get the observation and action space. To will determine how many “steps” are taken it also requires the size of the memory. Lastly, hyperparameters such as gamma are also needed.</p><h3>Weights and Biases (<a href="https://wandb.ai/">W&amp;B</a>)</h3><p>Lastly, we initialise W&amp;B — this has been a key tool for us to understand how our agents are performing. It has allowed Daniel and myself to analyse data and run experiments on our own machines and making the results available for both of us, all whilst working remotely.</p><p>Having some logging tool has been critical in understanding where mistakes were being made and what affect different hyperparameters have on the model. In a later section, we’ll dig into how various metrics helped us debug our work.</p><h3>Collecting a Trajectory</h3><p>The first stage in training the PPO agent is to collect trajectories — this happens as seen in Figure 2.7 after the agent and environment have been initialised. The agent takes actions based on the observations from the environment, which is then used to take the next step. The sequence of states and actions are then finally saved to the memory for the training phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YyA1RbMw9ilIv7xzSgZK1g.jpeg" /><figcaption>Figure 2.7 — Flow chart overview of how trajectories are collected. (Image by Author)</figcaption></figure><h3>Calculating the Action of the Agent</h3><p>The action is taken by with act function on the agent [Models.py:109].</p><pre>class ActorCritic(nn.Module):<br>	# ...</pre><pre>	def act(self, x, action=None):<br>		values = self.critic(self.forward(x))<br>		logits = self.actor(self.forward(x))<br>		probabilities = Categorical(logits=logits)<br>		if action is None:<br>		    action = probabilities.sample()<br>		return action, probabilities.log_prob(action), values, probabilities.entropy()</pre><p>To act, the model receives observations from the gym environment (x). The observations then pass through the critic network which returns the value (what the value of that state is) and then the actor-network, which returns the logits (the output of the neural network).</p><p>The value is returned as-is. However, we want to convert our logits into a probability distribution on which we can then sample an action. This is done with the <a href="https://pytorch.org/docs/stable/distributions.html#categorical">Categorical function of PyTorch</a> — this function turns our logits into a distribution proportional to the logits, summing up to one. The benefit of the categorical class is that the class can also sample an action from the distribution, calculate the log probability of action and the entropy (entropy will be further explained in a later section).</p><h3>Saving Trajectories</h3><p>Saving trajectories is fairly intuitive, but is useful to have a visual representation of how the rewards, observations and done’s come out of the gym environment. For each step in an environment, 3 variables of different dimensions are returned (observation, reward and done — shown in Figure 2.8).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*cxLFPoqDCWnu3suXb6G_Ug.jpeg" /><figcaption>Figure 2.8 — Visual representation of data returned from individual environments. This diagram shows various scenarios for different steps, some receiving reward and some finishing the episode. The numbers in the legend represent the dimensions of the tensors returned. (Image by Author)</figcaption></figure><p>Every interaction the agent has with the environment (acting on multiple environments) returns an observation, reward, and done. In the example of Figure 2.8, the first step shows no reward, and the episode has not terminated yet, this is assumed to be the case for every step after that unless indicated otherwise. This illustrates that the data collected is appended into the memory as entire steps across multiple environments, indicated by the blue box. This means that what is being saved into the memory is:</p><ul><li>Observations (n, 80, 80, 4)</li><li>Rewards (n, 1)</li><li>dones (n, 1)</li></ul><p>And will then be saved in the memory in a tensor of dimensions:</p><ul><li>Observations (x, n, 80, 80, 4)</li><li>Rewards (x, n, 1)</li><li>dones (x, n, 1)</li></ul><p>Where x is the number of steps, this implies that the “global” number of steps which the agent trains on will, in reality, be x times n, as we have x steps for n number of environments.</p><h3>Updating the Policy</h3><p>The second stage in our PPO is to learn from our collected trajectories — this is initiated by the learn function in Models.py and invoked by the training loop in util.py:L113. When this starts, the advantages are calculated first, this is important to do as all trajectories are required to remain in sequence to calculate the correct discounted return. Once this is finished, we can sample from memory at random, calculate our losses and update the model. Updating over the trajectories happens a set number of times, dictated by a hyper-parameter. Once completed, the old model is replaced with the updated one and the process start over again, but this time with a (hopefully) better performance. This process can be seen in Figure 2.9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DPmxG2khvFEXQz6uvZ6-w.jpeg" /><figcaption>Figure 2.9 — Flow chart showing the learning stage of PPO, the chart blends together functions being called on the Agent and Memory class and the flow of actions. (Image by Author)</figcaption></figure><h3>Calculating the Advantages</h3><p>The Advantage is defined as the expected return minus the actual return — this indicates how much better or worse the model performed than anticipated. Calculating these advantages occurs in two steps — first, the discounted returns need to be computed. The expected values (calculated by the critic) are then subtracted from the discounted returns to obtain the advantage.</p><p>In case you’re not familiar with <strong>discounted returns</strong>, this is a <a href="https://www.youtube.com/watch?v=36IgkgHW0MM&amp;ab_channel=LearnVentures-DeepReinforcementLearning">great video</a>, but essentially it takes the current reward + the value of the next state times a discount factor (gamma) as per Figure 2.10 (G is the discounted returns).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*krjCvAA_vuylJ2_kK9GJHw.png" /><figcaption>Figure 2.10: Formula for discounted returns. (Image by Author)</figcaption></figure><p>In order to calculate the discounted returns, we cannot start at the beginning of the trajectory but rather have to start at the end. This is because we need to iteratively calculate what the value of the next state is. This presents a problem at the very last state as there is no next value, which is why the function also takes last_value and last_done, which are used in the very first calculation of the discounted returns (in the case of Figure 2.11 it&#39;s -0.5 as the last value and the episode not being done). In many books, you might see this as n-step bootstrapping. We do not (necessarily) wait for the whole episode to finish but rather estimate after n-steps what the value of that state would be if the episode were to finish.</p><p>As an example of what might happen, in Figure 2.11 assumes the trajectories have already been collected (step 1) and then iteratively calculates the discounted return backwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*9_3PpRGwKMz8d-ycRJe1AQ.jpeg" /><figcaption>Figure 2.11: Example calculation of discounted returns. (Image by Author)</figcaption></figure><p>This logic is implemented in our <a href="https://github.com/DarylRodrigo/rl_lib/blob/master/PPO/Memory.py">Memory.py</a>class:</p><pre>def calculate_discounted_returns(self, last_value, next_done):<br>    with torch.no_grad():<br>      # Create empty discounted returns array<br>      self.discounted_returns = torch.zeros((self.size, self.num_envs)).to(self.device)<br>      for t in reversed(range(self.size)):<br>        # If first loop<br>        if t == self.size - 1:<br>          next_non_terminal = 1.0 - torch.FloatTensor(next_done).reshape(-1).to(self.device)<br>          next_return = last_value.reshape(-1).to(self.device)<br>        else:<br>          next_non_terminal = 1.0 - self.dones[t+1]<br>          next_return = self.discounted_returns[t+1]<br>        self.discounted_returns[t] = self.rewards[t] + self.gamma * next_non_terminal * next_return</pre><p>The reverse for loop iterates over the collected trajectories in reverse order to calculate the discounted returns. As in Figure 2.11, the first calculation uses the last predicted value, outputted by the critic, all other cases will have the previous discounted return available. The new discounted return is the reward + gamma * the previous discounted return. next_non_terminal is used to check if the discounting should be set to 0 because the episode ended. Finally to get the advantages the memory simply takes the discounted_returns and subtracts the collected values at the corresponding time steps.</p><p>Calculating the discounted returns can be a headache, and making sure that they are correctly calculated for the many different scenarios is even harder. It’s easy to make a mistake, in some cases meaning the algorithm will still train but doesn’t perform as well as it could. To really check all the edge cases it is suggested to write test cases and run the calculations against them. For our implementation, this can be found in /tests/test_memory.py.</p><h3>Updating Model</h3><p><strong>Fetching the data</strong></p><p>To update the model, the memory is sampled first — this is done by extracting mini-batches (random subsection) from the trajectory saved in memory. This is done with the get_mini_batch_idxs function. The function creates an index for every entry in the memory and randomly assigns them into the arrays for the mini-batch; for example, this could return</p><pre>[ <br>	[1013,456, ... 147,328], <br>	..., <br>	[295, 1937, ..., 49,846]<br>]</pre><p>The first element in the mini-batch array([1013,456, ... 147,328]) is then passed into the sample function, which expects an array of indexes to pull out of the memory. For every index in that array the following values are returned:</p><ul><li>prev_states</li><li>prev_actions</li><li>prev_log_probs</li><li>discounted_returns</li><li>advantage</li><li>prev_values</li></ul><p><strong>Policy Loss</strong></p><p>The loss function consists of the policy and value loss. As a reminder, it might be worth to check out Figure 1.11 to remember the method of updating the PPO model.</p><p>First, the two surrogate functions (clipping of the ratios) need to be calculated. The surrogate function requires the <strong>probability ratios</strong> — this uses the updated model’s log probabilities and the current model’s log probabilities (used to collect the trajectory). This is the primary reason the action and observations were saved — the observations can now be passed into the updated model and calculate what new log probabilities are outputted given the action taken during the trajectory.</p><p>Once the ratios are calculated the surrogate function is relatively straight forward, we simply multiply through by the advantage (calculated in the previous section) and use the <a href="https://pytorch.org/docs/stable/generated/torch.clamp.html">clamp</a> function to limit this by 1 + ϵ and 1- ϵ. The loss is then the minimum of the two.</p><pre># Grab sample from memory<br>prev_states, prev_actions, prev_log_probs, discounted_returns, advantage, prev_values = self.mem.sample(mini_batch_idx)</pre><pre># find ratios<br>actions, log_probs, _, entropy = self.model.act(prev_states, prev_actions)<br>ratio = torch.exp(log_probs - prev_log_probs.detach())</pre><pre># calculate surrogates<br>surrogate_1 = advantages * ratio<br>surrogate_2 = advantages * torch.clamp(ratio, 1-self.epsilon, 1+self.epsilon)</pre><pre># Policy Gradient Loss<br>pg_loss = -torch.min(surrogate_1, surrogate_2).mean()</pre><p><strong>Value Loss</strong></p><p>To calculate the value loss we take the mean squared error of what we thought the value of that observation was and what the discounted returns actually were.</p><pre># Grab sample from memory<br>prev_states, prev_actions, prev_log_probs, discounted_returns, advantage, prev_values = self.mem.sample(mini_batch_idx)</pre><pre># Calculate values from new model<br>new_values = self.model.get_values(prev_states).view(-1)</pre><pre># Generate loss<br>value_loss = F.MSE(new_values, discounted_returns)</pre><p><strong>Updating</strong></p><p>Updating is also very standard, we simply backpropagate all the loss added together and include the entropy.</p><pre># Loss<br>loss = pg_loss + value_loss - self.entropy_beta*entropy_loss</pre><pre># calculate gradient<br>self.optimiser.zero_grad()<br>loss.backward()<br># Clip grad to avoid massive updates<br>nn.utils.clip_grad_norm_(self.model.parameters(), 0.5)<br>self.optimiser.step()</pre><p>This process gets repeated will the model has been updated n times for the whole memory set. Then we repeat the whole process over again and hope the model converges!</p><h3>Finally</h3><p>To run our the environment navigate to the PPO folder and run:</p><pre>python main_atari.py</pre><p>To get weights and biases set up you will need to do your own configuration and register the project if you do not have this, tensorboard will still record all of the experiments data.</p><h3>🕵️‍♂️ Analysing our Results</h3><p>When running the experiment the key values which are measured are:</p><p><strong>Episode Reward</strong></p><p>This is the most obvious metric to record, it tells us how well an agent is performing at a given step.</p><p><strong>Learning Rate</strong></p><p>The learning rate is logged in case this is changed throughout the life cycle of the experiment. For this experiment, it will remain constant, however, annealing is required to get state of the art results. Another blog post will cover why and how this works.</p><p><strong>Policy Loss</strong></p><p>The policy loss is generally agreed to be a difficult metric to draw conclusions from, depending on whether the advantages are normalised, or if learning rate annealing is used this will look different.</p><p><strong>Value Loss</strong></p><p>This is defined as the mean squared error between what the discounted return was and what the critic thought, it shows how well the critic is predicting the value of a state. Typically this sits quite low, however, when an agent performs much better or worse than expected the value loss will shoot up indicated that the critic is updating how it thinks about this state.</p><p><strong>Entropy</strong></p><p>Entropy in RL is the predictability of whether an action is taken (so how certain we are that in a given state we might go left); because the actions are sampled from a distribution, if one those outputs are very high that means it’s fairly certain what action will be taken. Conversely, if all the probabilities sit at the same level, it’s going to be hard to predict which action is taken next (great article that goes more <a href="https://awjuliani.medium.com/maximum-entropy-policies-in-reinforcement-learning-everyday-life-f5a1cc18d32d">in-depth</a>).</p><p>From an insight perspective, what this means is that if the entropy is very high, the agent doesn’t really know what the right action is and when it’s lower is start be more certain about its actions. This is why, in general, the entropy will be going down.</p><p><strong>KL Divergence</strong></p><p>When calculating which action to take in with policy gradient methods, the actions are going to be represented as a set of probabilities — the log of these probabilities is then used to calculate the loss of our model.</p><p>When you update the model using the log probabilities in the “learning” phase, typically you would clone your model and update that new model. Once your model has gone through all the updates, it will differ slightly from the original model.</p><p>The KL divergence is a measure of how different the log probabilities from the original model are to the new one. The higher the KL divergence is the more the model has changed. As a rule of thumb, a KL divergence which sits around +/- 0.03 from 0 means that the model is updating nicely, whereas a high KL divergence can indicate that the model is taking too big of an update step, this can cause the model to not converge. This is what makes KL divergence such a useful metric to observe.</p><h3>Using Metrics</h3><p>It’s hard to pin down what the exact problems in an experiment are when looking at metrics, especially because it’s hard to work out whether or not something just isn’t converging or if there is something wrong with the algorithm. One thing that has helped us tremendously is looking for how “on average” performance looks on different metrics. For example from Figure 3.1 it might look like the agent is learning, and then just cannot converge — but when also looking at the value loss (so the MSE between the discounted returns and what the critic thought), it’s clear that the critic was behaving very suspiciously, the value loss is all over the place and it’s frequently far too high. On closer inspection, we found that the calculation for value loss had a wrong variable name in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/0*Uq-NG6E-jcCuns2A" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*tOhPVSB8dqU3MoG3" /><figcaption>Figure 3.1 — Rewards (left) and Value loss (right) from PPO Agent which had an incorrect value loss calculation. (Image by Author)</figcaption></figure><p>When we were building our agent — Costa’s <a href="https://wandb.ai/cleanrl/cleanrl.benchmark/runs/thq5rgnz">CleanRL</a> metrics were of great help to us.</p><p><strong>Our Metrics</strong></p><p>After much work, we managed to get a reward of around 50. Clearly not ideal, there is still a lot to work at, but this will require adding some additional tricks to the algorithm, it’s also very possible that after more training it will reach ~400.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NlpTBxBhg_jCFrnajAJjUA.png" /><figcaption>Figure 3.3: All recorded metrics for PPO Agent. (Image by Author)</figcaption></figure><p><em>When creating your own PPO, it might be helpful to have these metrics as reference.</em></p><h3>Looking at Agents</h3><p>Visual display of agents performing at various stages of training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*QbjJ-FQEgQzOIzF5EFdvIw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*5XuaDHEQNp8UflfpEAVdDg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*erctlLNDK448NkEzt94LeQ.gif" /><figcaption><em>Agent after 0, 10m and 20m Steps. </em>(Image by Author)</figcaption></figure><h3>🙏 Closing Comments &amp; Future work</h3><p>Implementing PPO from scratch has been an interesting challenge which has certainly stretched my understanding of RL and patients to its limits. What has really helped is having somebody to work with, this was both a motivation as well as helpful to bounce ideas off when either of us got stuck.</p><p>From our experiments, it’s clear that running just a vanilla PPO algorithm will not achieve top-level performance. As such, we have also implemented PPO as per the baselines specifications which reach a reward of <strong>400</strong>. I aim to post a blog post on the modifications required to obtain the result soon!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qb_iM-eFaRlQBlY9Fv8gEA.png" /><figcaption>Figure 3.5 — Training of PPO breakout agent with all baseline features implemented. (Image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*nfGpvrufzZyTBMvr" /><figcaption>PPO breakout agent playing with all baseline features implemented. (Image by Author)</figcaption></figure><h3>🔥 Acknowledgements</h3><p>Daniel and I would like to thank <a href="https://costa.sh/">Costa Huang</a> for all his help in explaining how his PPO implementation worked. Without his help, it would surely have been a much longer road.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5740ccbe3fbc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-graphic-guide-to-implementing-ppo-for-atari-games-5740ccbe3fbc">A Graphic Guide to Implementing PPO for Atari 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>
        <item>
            <title><![CDATA[Navigating the Changing Future]]></title>
            <link>https://darylrodrigo2020.medium.com/navigating-the-changing-future-d4289f7887e5?source=rss-8313e98b89a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4289f7887e5</guid>
            <category><![CDATA[education]]></category>
            <category><![CDATA[future]]></category>
            <category><![CDATA[change]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[governance]]></category>
            <dc:creator><![CDATA[DarylRodrigo]]></dc:creator>
            <pubDate>Fri, 06 Apr 2018 16:11:23 GMT</pubDate>
            <atom:updated>2018-04-06T16:11:23.084Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“It is change, continuing change, inevitable change, that is the dominant factor in society today” </em><a href="https://www.forbes.com/quotes/11334/">— Isaac Asimov</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*3O8zpcXke0sqQ_xk." /></figure><p>If one thing is certain, then it is that change is inevitable; and that’s alright. The world has been constantly changing since the dawn of mankind and we’ve fared well, so far. Unlike the past, however, change is happening exponentially faster, in fact, “<a href="http://www.ipa.co.uk/Page/IPA-Social-Principle-Nine-Change-will-never-be-this-slow-again#.Wo7AzxPFKRs">change has never happened this fast before, and it will never be this slow again</a>”.</p><p>Throughout history, we could roughly understand and navigate a world 100 years in the future. If you took someone from the 13th Century and placed them in a city in the 14th Century, chances are they wouldn’t be too confused; society was fairly similar. Conversely, if you took somebody from the 1910s and placed them in the 21st Century, they would probably be completely amazed how the world looks, and possibly even confused about how to interact with it. Change is happening at such an unprecedented rate, we have no idea what the future is going to look like in the next 100 years or any idea on how to operate in it. By our nature, we perceive the world as linear; however, the change which is occurring is exponential and as such most people will not understand the scale and speed at which the world is going to transform.</p><p>Here are some things we do know about the present: pollution levels are rising; climate change is real, and is happening at a faster rate than ever and there is no indication that the rate of population growth is slowing. These are all potential catastrophes which can impact our environment and billions of people within the next 100 years.</p><p>Thankfully, we are also about to undergo another societal and technological change: <a href="https://www.weforum.org/about/the-fourth-industrial-revolution-by-klaus-schwab"><em>the fourth industrial revolution</em></a>. The development in fields such as AI, autonomous vehicles and smart factories provides us with the capabilities to bring us into a new era. A revolution which might work in our favour, giving us abundance and luxuries beyond our current understanding or it might work against us and start an era of extreme inequality or worse. Due to the variety of industries being affected and the speed at which these developments are happening, this shift is going to affect us all for better or for worse in a far more impactful way than any time before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*qh-LfbEA1kFHZEPleAhqdQ.png" /><figcaption>Various dimensions of the Fourth Industrial Revolution — <a href="https://www.avvanz.com/blog/critical-skills-for-industry-4-0/">source</a></figcaption></figure><p>In every industrial revolution, when the dust settles and society adjusts to the technological advances, the overall quality of life has increased. Inevitably, adaptation to these new industrial and economic processes/strategies will take time and may result in, for example, an increase in the inequality gap. Usually, this is always followed by political and institutional change. With every other industrial revolution; however, we have had the chance to adapt. This sort of linear thinking — being able to change after the fact — is simply not going to work with the new technological advances as the change is so swift and will profoundly affect every sector. Political and company leaders need to start preparing for a complete shock on how the world operates or we will leave the future in the hands of chance.</p><p><strong>This rapid change leaves two questions in my mind; how can we ensure that the current generation thrives with all this technological change, and how can we prepare the future generations to thrive in this changing world.</strong></p><p>One of the biggest barriers to our technological innovation benefiting society is not the technology itself but rather how society and governments uptake this technology. The blockchain has evolved over a hundred times and yet no government is truly using it’s potential or understands what the potential implications of this technology are, and as a result is<a href="https://cointelegraph.com/news/the-7-uses-of-bitcoin-and-the-best-way-to-buy-it"> predominantly used for trading and illegal transaction</a>s. Some countries, such as <a href="https://www.theverge.com/2017/9/20/16325084/matternet-autonomous-drone-network-switzerland">Switzerland are working on drone laws</a>; however, drones have been around for a long time, and with the rapid improvements made on this technology the rest of the world also needs to stay ahead of the curve. We’ve also had plenty of warnings about the potential danger of AI from Elon Musk to Stephen Hawking. So, who is controlling the safety of AI? Whilst industries are paving initiatives such as OpenAI should governments not play an active role in this too? The job displacement of autonomous vehicles has been well documented and governments are making moves into the legal angle on this but what about the impact this will have on people’s jobs.</p><p>Policy makers need to ensure that they keep up-to-date with developing technologies, to guide innovation to benefit society as a whole and not the few. This is going to require us to rethink how we govern — because when we get politics wrong people suffer. Besides the fact we have a declining number of people participating in the electoral system since the 1950s and thus participating in deciding how our society is shaped; policies around AI, drones and the blockchain, lag far behind where the technology is. We need a value shift whereby we stop focusing on growth and instead on human well being and sustainability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*rTVVNTYtqMHSg_kP." /></figure><p>To keep up with change, the burden is far larger for government than a company, as governments must administer over a much larger group. So in order to stay relevant with new technologies, private and public sectors need to work together to develop policy. In this agile government policymakers acknowledge that policy development is no longer a singular effort but rather a multi-stakeholder effort. In turn companies benefit from this cooperation by working with government to remove regulations they see as barriers to innovation and work together with governments to safely implement these technologies.</p><p>Preparing the next generation for the realities of the 4th Industrial revolution naturally lends itself to the education system. Our current education system has been designed for a time when you could learn skills and they would be relevant for the rest of your life. Whilst this holds true for meta-skills such as critical thinking and communication, this thinking isn’t when it comes to skills for the workplace (data entry, being able to write up reports etc) which will be obsolete in the not too distant future. <a href="http://reports.weforum.org/future-of-jobs-2016/chapter-1-the-future-of-jobs-and-skills/">Studies show that 65% of the children entering primary school education today will have jobs that do not exist yet.</a> How can we teach concepts, skills or ideas that are yet to be invented? We need to understand what an education system and curricula which equips a child for the 21st Century looks like. One which is extremely robust in the face of unprecedented change. Skills such as creativity, communication and problem solving — which are hard to automate — will initially see an increase in demand. However, ultimately machines will be able to catch up to most of it. The most important skill an individual will be able to have is how to learn, unlearn and relearn, allowing them to be most adaptable and flexible to any given situation.</p><p>Education is meant to prepare the next generation for the future and this is supposed to be applied to everybody. Education should be treated as a social passport which allows individuals increase their current economic status. As such, it should be universally accessible, so that not only the wealthy and privileged benefit from a reformed education system. We should consider not only what it would look like across the social and geographic landscape, but also what impact this might have on gender equality. Jobs which are becoming more in demand are generally STEM based, and these are still seeing far fewer female than male and ethnically diverse enrolment.</p><p>Just as governments needs to work with non-state actors to create policy, the education system needs to start working with multi-stakeholder leadership and governance. To ensure that what is being taught at school remains relevant and actually prepares students for the future. Most importantly, we need to ensure that students learn how to unlearn and relearn so that they can continually improve themselves as the world changes around them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*qAcgrdujL5D2NKb1." /></figure><p>The next 100 years could see a utopian like change in the world, one full of abundance and luxuries. However, it could also see unprecedented unemployment and an even greater divide between the rich and the poor. We need to start preparing for the future now, so that we can see a better tomorrow.</p><p>I certainly do not know what the future will look like; however, I do wish to prepare myself as much as I can. In my search for answers on how to navigate this new world, I have decided to publish my thoughts so that I can get feedback and develop my ideas with everybody’s input over time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4289f7887e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>