Deep Dive: From Dynamic Programming to Monte Carlo Sampling or How to learn without a Model
From the publisher’s feed, collected in the ZeroLabs newsroom.
One thing that is boring with Value Iteration (VI) or Dynamic Programing in general is that it requires to have a transition probability model and a reward model ! In our previous post on the application of VI in a robotic navigation task, we derived a transition probability model ourself using our knowledge of the robot kinematic model. That was too easy and let’s be honest this is not always going to be the case. For instance, we can have a robot in an environment with unknown disturbance before deployment, actually even during deployment. Or worse, not even the sensor readings are deterministic ! In fact, they are noisy and the noise follows some unknown distribution making it almost impossible to derive the expression of the transition probability model.Also, in some other fields such as finance, the stochasticity in the environment is very difficult to model. Or even worse, the transition probability function is often non-stationary, that is, it changes with time. Just imagine the behavior of the market changing with time, and unpredictably with events.In fact, dynamic programming is a theoretical solution to the MDP problems. But, where is that learning by trial-and-error that Reinforcement Learning is famously known for !?In today post, we will introduce the methods that learn from experience, by trial-and-error, without any model required whatsoever, just as we did in the Multi-armed bandit post. Actually, you’re good to go if you understood very well that case.Value Function: a Quick ReminderThe goal of RL is to find the optimal policy by maximizing the expected cumulative reward. To do so, most RL algorithms iteratively alternates between Policy Evaluation, that is, estimating the value function given a policy; and Policy Improvement which improves the policy toward optimality: we called this scheme Generalized Policy Iteration (GPI).Let’s zoom in the value function. What is it ? We know that already, it’s a function that maps each state to a real number representing the state value, which is, the expected cumulative reward starting from that state. Literally, it’s the mean of all possible returns obtainable from all possible trajectories starting from that state by following the given policy. Clearly, if we know the probability of all possible trajectories from that state and their returns, we can obtain the value of the state by merely doing a weighted average of the return of each trajectory where the weight is the probability of the given trajectory. Here’s a quick reminder of the value function expression:The first three sum symbols are basically averaging all possible next transitions, and weight their return by the probability of the transition. The return here being the next reward plus the bootstrapped (estimated) value of the next state.This explanation should already be comprehensible at this stage, I am simply repeating what was already said in the post on deriving the value function from scratch. As you can see, this formula assumes access to the transition model which is very constraining as I pointed in the introduction.Fortunately, RL is not the first to face such an issue of computing the expectation of a random variable without access to the probability distribution expression. This issue has already been solved and the solution is … Monte Carlo Sampling !Learning the Value Function Without a Model With Monte Carlo SamplingImagine you would like to estimate the expected value of a function f(x) where x is sampled according to the distribution p(x). The expectation is given by the formulasHowever, if you don’t have the expression of the probability distribution but you can sample from it, one can simply approximate the expectation using the Monte Carlo sampling strategyThe more samples you have, the most precise this method is because it’s convergence is governed by the law of large numbers (LLN). Why this expectation calculation even works at all even though we don’t know the probability p(x)? Well, it works because of the very fact that the weights of f(xi) are now implicitly governed by the empirical sampling of xi which is done according to p(xi). Remember, we do not know p(x) expression, but we can sample from it !Note: a condition, though for this sample mean to converge to the true mean is that the f(x_i) are independent and identically distributed (i.i.d) which basically means there shouldn’t be a correlation between the x_i.You get where I am arriving, we can do the same for the value function without access to the transition probability function by using the original expression of the value function, that is, the expectation of the future cumulative reward given a state.A Monte Carlo sampling strategy will give the following formula for the value function:Below is a pseudo-python straightforward and naive implementation of this algorithm.# This is a pseudo-python code to compute the value of a statedef compute_value(state): # Get a bunch of returns first by simulating a lot of episode from that state returns_list = [] for ep in range(NUM_EPISODES): # This trajectory variable should have the rewards at each step of the #episode trajectory = simulate_episode_from(state) # compute the return as the discounted cumulative reward from state G_state_ep = discounted_sum(trajectory["reward"]) # maintain a list of return from each episode and average them to obtain #the value of the state returns_list.append(G_state_ep) return average(returns_list)Note that in order to compute the value of the state, we need not the value of any other state at all. This estimate of the value of the state is completely independent, unrelated, uncorrelated, to that of other states, therefore, there is no bootstrapping as in Dynamic Programming ! The value is guaranteed to converge to the true average return i.e. the value of the state by the LLN and because the returns are independent and identically distributed (i.i.d).This formula of the state value function resembles a lot to the action value expression in the Multi-armed bandit method we saw. Except that instead of an average of rewards obtained by taking an action, we are averaging a lot of returns from a lot of trajectories. Therefore, as in the bandit case, we will prefer using the incremental update of the value function to avoid storing all the returns following for a given state in an array in order to average them.This formula is really simple ! But, that is the learning from experience I mentioned, the so-called trial-and-error learning that RL is famously known for. It’s merely averaging, dynamic programming is that as well and this is just a model free-way. Note that this cannot performed well than dynamic programming, dynamic programming is kind of the upper bound in RL. But it requires the full knowledge of the world which is unrealistic to expect in many problems.Of course, there are more advanced version of this, mostly using Deep Learning methods, but the core idea remains the same.First-visit and Every-visit Monte Carlo PredictionThere is an important practical choice to deal with when one tries to implement the Monte Carlo sampling approach. Consider an example episode like this: (S0, R1, S1), (S1, R2, S2), (S2, R3, S3), (S3, R4, S4), (S0, R5, S5), (S5, R6, S6), (S6, R7, S7), (S7, RT, ST). The goal here is to compute the return of state S0. One thing you might have noticed, because it’s in bold, is that the state S0 is visited twice in this episode. Now the question is, how many returns following S0 do we consider here: one or two ?Note: The term Prediction is simply another way to say Policy Evaluation. Hope you recall it from the chapter on value iteration.Well, actually the answer is: both are valid choice. Someone can choose to consider only the returns following the first visit of state S0 until the end of the episode, then the return is simply the [discounted] sum of the rewards:However, we can also use the return of the shorter segment that follows the second visit of the state S0 as another return, then the final return will be the average of all the returns following each visit of the state S0. In our case, it gives the following formulas:Below is the algorithm for Monte Carlo prediction from Sutton & Barto [1] for the first-visit MC technique. The every-visit MC is the same but without the condition “Unless S_t appears in S0, S1, …, S_{t-1}”.Algo. 1. First-visit MC prediction algorithm from Sutton & Barto [1]Algorithm 1. above seems different from the pseudo python implementation that I gave above, but it’s actually doing the same thing in much more efficient way. In my naive implementation, only a single state is updated in the whole simulation. If I wanted to compute the value of another state with that code, I would run a new simulation from that new state. However, in Algorithm 1., the official implementation, every state that was visited during an episode will be updated !In order to assimilate well what this implementation is doing, mostly the backward technique to compute the return G_t, I recommend taking a pen and a paper and literally simulate an episode yourself !Illustration of the Monte Carlo Sampling ApproachOne of the strength of the MCS approach above is that I can single out a state and compute its value independently of the value of other states. For instance, we will compute the value of the state (-1., -1., 45°), for a uniform random policy i.e. actions “stop”, “move”, “turn_left” and “turn_right” have equal probability to be selected, from the navigation task in the previous post.A quick recap for those who may haven’t read that post, the environment is a 2D plane in which the state of a robot is given as (x, y, θ) representing the robot horizontal and vertical coordinates, and its orientation about the horizontal axis. The goal is always fixed at state (0, 0, theta). The reward received is 0 if the goal reached and -1 everywhere else. The action space, well you know that ! We discretized the state space with 1m spacing between positions and 45° for angles.Fig. 1. Value evolution of the state (-1, -1, 45°) using MCS first and every-visit. The mean and std result from 20 seed runsI the Figure 1. above, I showed the evolution of the value of the state as function of the episode. Clearly, we can see that both first-visit and every-visit Monte Carlo approaches end up converging to the true value of that state under the uniform random policy as the number of episode grows. The red horizontal line represents the ground truth value computed using the policy evaluation algorithm from Dynamic Programming.Actually, I adapted the value iteration algorithm from the previous chapter to obtain this. Instead of taking the max value, I just averaged the action-value of all actions ! You will find the implementation on my github page anyway !The every-visit seems to have less variance than the first-visit MC approach. In practice, the every-visit MC is more often used than the first-visit MC because it makes good use of all visits to the state S that we evaluate whereas the first-visit uses only a single return from a whole episode. Even though the subsequent visits to the same state don’t provide as much information to final average as the first return, they are still useful in estimating the value of the state and help stabilizing the average of the final returns, which is the state value. Also, we do not need to check the condition to exclude subsequent visits to compute the return in the every-visit, which is great during implementation.Important Note: The reason I said that returns from subsequent visits do not equal a first-visit return is because they are correlated to the first visit return, like, the return of the first visit literally contains the subsequent returns. So if I visit a state S0 three times within one episode, it’s not as if I visited that state 3 times across three different episodes. For instance, G¹_S0 and G²_S0 are not i.i.d because G¹_S0 contains G²_S0. Therefore, G²_S0 and G¹_S0 are correlated. Therefore, the average of these two, G_S0, is not worth the average of two independent first-visit returns from state S0. However, G_S0 in this episode is still i.i.d with the other G_S0 from other episodes, and I guess this is why the every-visit is still guaranteed to converge by the Law of Large Numbers !Application of Monte Carlo Prediction on the Navigation TaskThe idea of this section is to evaluate the full random policy using the Monte Carlo Prediction algorithm provided in Algorithm 1.Fig. 2.a. Heatmap of the Value function of the random policy using Policy Evaluation algorithmFig. 2.b. Heatmap of the Value function of the random policy using Monte Carlo Prediction algorithm with the every-visit approachThe beautiful figures above show the heatmap of value function on the 2D discrete plane. Figure 2.a was generated via Policy Evaluation and Figure 2.b was generated using the Monte Carlo Prediction algorithm in Algorithm 1. with the every-visit approach. If you look at these figures from far away, you see no difference. They look exactly the same in all states ! That’s a great news though, we are able to estimate the value function directly by interacting with the environment, without requiring the expression of any transition model at all, neither do we need a reward model ! Welcome to the World of Model-Free Reinforcement Learning (MFRL) ! 🎉🎉🎉🎉🎉Of course, they do not take the same time since we are literally estimating the value solely with samples, so we need many samples to obtain a reliable estimate of the value function (remember the post on the bandit, we discussed similar issues). For instance, I ran this experiment by sweeping exhaustively the full state space and rollout from all of them. This is not required though, but I wanted to eliminate any risk of having non-updated states. One could sample states randomly as well, as per Algorithm 1., but some states might get poorly visited leading to their poor value estimates which really is not a big deal in many problems. We will see in MC control, that’s even desirable !Now let’s zoom in those figures, and terminates this section. The scales are not exactly the same ! 🥲 In Figure 2.a. the visible scale number starts from — 30 up to -90 while in Figure 2.b the number starts at -20 and finish at -80. Why this ? You might say that since the value iteration is the ground truth, the problem must be from the MC estimate. Well, you are completely right !It comes from a design choice, a bias introduced by me ! I didn’t say, but I actually run the rollout for a maximum of 10000 environment time steps because some rollouts were lasting too much time ! So, many episodes have actually been cut before the agent reached the goal leading to underestimating the value of some states. Since each step is -1 until the goal is reached, I literally annihilated the rest of the penalties had the rollout continued ! Mea Culpa ! But, the state space is quite huge, often leading to very long rollouts !Notes: Ok, here, to decrease the bias a bit, we can introduce a bootstrapping. Basically if you rollout up to 10k steps, you consider your return as a discounted sum of all these 10k steps rewards + the value or the return of the last state in your trajectory (which you estimate using your current value function). !Monte Carlo Control or How to obtain the optimal policy without a ModelSo far, we have only discussed the policy evaluation which consists of updating the value function given a fixed policy. Now the next step obviously is to obtain the optimal policy, which is the sole goal of Reinforcement Learning.In fact, value function is just a means to achieve our goal. We could obtain the optimal policy by literally ghosting the value function at all ! That is actually what the Policy Gradient Methods actually magically achieve: learning an optimal policy, without a value function at all ! But … hum… we will see that in future !Just a quick reminder of how we found the policy in the previous chapters on Dynamic Programming.Given the value function, one simply must look at the next state and choose the action that maximize the expected immediate reward plus value of the next state.For an obvious reason, we simply can’t use this formula here ! Neither do we have the transition function, nor do we even know the next states unless you want to keep a record of all transitions, which, honestly, is against the philosophy of MFRL. This formula is also, in a very simple way, derived from the policy improvement theorem that we saw in earlier chapter and the term in the argmax is none other than the state action-value function Q(s, a). Therefore, we must simply the take the action with the max Q(s, a), but this requires to estimate Q(s, a) in the first place.Estimating Q(s, a) is very similar to estimating V(s). The only difference is that instead of states, we do rollouts starting from pairs of state-action to compute the returns. Q(s, a) represents the expected return by taking action a and behaving according to the current policy. So we are literally doing a policy evaluation again, but we are computing the value of state-action pairs instead of the value of states only.And to improve the policy, we simply perform the argmax operation using the following formula:By iteratively alternating between policy evaluation and policy improvement, we end up converging to the optimal policy at the end of training: that is the Generalized Policy Iteration (GPI) that we saw in the Dynamic Programming chapter.Algo. 2. Monte Carlo Control algorithm, with exploring start from Sutton & Barto [1]Algorithm 2. describes an approach called Monte Carlo with Exploring Starts. The goal here is to find the best action in each state. This is very similar to the bandit problem, except that we have multiple states instead of one. In order to obtain a reliable estimate of the Q(s, a) of each pairs of state-action, you want to make sure at least each state-action pair is visited enough number of times, that’s why the exploring start proposes to start an episode with a randomly chosen pair of state-action with all pairs having a non-zero probability of getting selected. In fact, one can always start from the same initial state, but you must then use a stochastic policy, such as epsilon-greedy, softmax policy, etc. The goal is simply to visit all states often and not commit to the states that your greedy action lead you to !No miracle here, it’s just Monte Carlo sampling, and the convergence to the optimal value is guaranteed as the number of averaged returns from each pair approaches infinity.The good news is that we do not have to wait for the state-action value function to converge in order to obtain the optimal policy ! In fact, it might seem surprising, but we do not even necessarily seek the optimal policy in all tasks, a decent safe sub-optimal policy can do the job sometimes !Application of Monte Carlo Control in Robotics NavigationLet’s see if this Algorithm 2. can find a decent policy for the robotic navigation task on the 2D plane. First, I did not do the exploring start at all, I merely sweep through all state-action pairs ! In our task, we can do that because the states space is merely ~3500 with 4 actions per states which makes a total of 14000 pairs ! And I used a softmax as my policy with a scheduling over the softmax temperature parameter beta.# This is pseudo python code to compute the softmax policy, full implementation# on my githubdef mc_policy(self, state, beta) # beta is the softmax parameter that controls the temperature of the distribution state_idx = state_space.index(state) # compute the action distribution action_dist = np.exp(beta*action_value_array[state_idx])/(np.exp(beta*self.action_value_array[state_idx]).sum()) # sample an action action = random.choices(self.env.action_space, weights=action_dist, k=1)[0] return actionIn order not make this post too long, I let you find the details on the implementation on my githubFig. 3.a. Max_a Q(s, a) a each state resulting form the Monte Carlo Control algorithmFig. 3.b Trajectory of the final sub-optimal policy in the robotic navigation taskFig .3.c Trajectory generated using the random uniform policyThe figures above should be self descriptive at this stage of our series so far ! Anyway, a quick comment on it. The policy found here is of course not optimal as you can see in Figure 3.b, because the paths are definitely not the quickest path to the goal. For some states, yes, but not for all states. If you have read the previous post, these plots clearly are different from the one in the previous chapter where the policy was obtained through value iteration. Needless to say that the value function visualized in Figure 3.a. is not optimal either ! If it were, we would have obtained the optimal policy and thus the quickest paths !Nevertheless, the policy that resulted from the training is pretty decent. I mean, just have a look at Figure 3.c that shows the trajectory obtained with the random policy ! The state is literally at one step from the goal but the policy still manages to do a world tour before finding the goal ! Okay, this is just a sample trajectory, so not all rollouts will be like that. However, if you remember Figure 1., we saw that the value of the state (-1, -1, 45°) is nearly -48 ! which is crazy ! The goal is next door, but still takes so much time step to reach with the random policy.Compared to the random policy, our resulting policy from the MC control is really, really decent ! That’s the beauty of Reinforcement Learning: from chaos to order ! from total noise to something meaningful !Conclusion and TakeawayIn this post, we did learn how to train a RL agent to learn the value function and derive the optimal policy without requiring the knowledge of any model: neither the transition probability function, nor the reward model !We introduced the Monte Carlo Sampling approach from first principles which consists on performing a lot of rollouts to obtain returns that we can average to obtain the expected return, that is the value function.IMPORTANT NOTE: Even tough the MC methods are dynamic-free, this does not mean that the policy or the value function obtained are dynamic-agnostic. We clearly showed in the beginning of this chapter that the transition probability actually intervenes implicitly through sampling while we interact with the environment. Thus, a policy trained on one environment will be optimal only for that environment. If the deployment environment is different from the training environment, your policy might behave unexpectedly. In fact, the policy will behave as it is supposed to do, YOU will be surprised !A great advantage of MC methods is that now you can train your agent in any environment without worrying whether you have or have not the transition function. No need ! You just need to interact, and learn on the fly, that is, online !Some drawbacksObviously, MC methods have many drawbacks ! They inherit most of the drawbacks from Dynamic Programming except the transition function. They still work in Discrete World, of course, since we are using tabular methods only now. But it can use Neural Network of course, we’re heading towards that !Another drawback that is a bit more subtle is that one must wait until an episode is terminated to obtain the return G_t in order to update the value of a state. Now, what if your episode does not terminate at all ? Even though I truncated some episodes with my max rollouts, but we saw that led to underestimation of some states value. But if your task is a non-episodic, continuous task, truncating like I did is simply deadly !Also, if you are learning online, from episode to episode, the value function will be bouncing quite sometimes, mostly in the beginning of episodes as we saw in the Figure 1., that is because rollouts may be quite different from each other. For environments with a huge state space, imagine hundreds of thousands or even millions, where states are visited only few time and rollouts can last very very long, the variance in your value function will go absolutely CRAZY !Future post:In the next post, we will introduce one very interesting idea, absolutely central in Reinforcement Learning, called Temporal Difference Learning and many of its affiliated methods that any serious RL folk should know such as SARSA, Q-Learning, etc.Notes: We focused on the On-policy MC methods in this post, there are very important concepts such as Off-policy Monte Carlo in Sutton & Barto. This requires more complex basis such as importance sampling and will require a dedicated post on its own. Don’t worry, I will explain off vs on policy very clearlyWe are really getting in the most interesting stuff now, and again only few steps from Deep Reinforcement Learning ! I am very excited about it ! 😁References[1] Sutton & Barto, Reinforcement Learning: an introduction[2] https://github.com/Fousseyni-Sang/rl-blog/blob/main/ch3/ch3_part1_MC_Sampling_application.ipynbDeep Dive: From Dynamic Programming to Monte Carlo Sampling or How to learn without a Model was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.