본문으로 건너뛰기

RL 012

· 약 57분

Sequential Decisions, MDPs and Bandits​

  • Decision making
    • Choosing which action to take at each step, based on what the agent currently knows.
  • Sequential decision making
    • Making a sequence of decisions in a certain order to maximize the total expected future reward.
    • Actions can have long-term consequences and rewards can be delayed, so sometimes we sacrifice an immediate reward for a bigger long-term gain.
    • Q. Why do we call RL sequential decision making?
      • Because the decisions must be made in a certain order. Each decision affects what comes next, and the rewards can be delayed.
  • Agent–environment loop
    • The cycle where the agent takes an action and the environment sends back an observation and a reward.
    • It repeats every time step.
  • Time step: St→AtRt+1,St+1S_t \xrightarrow{A_t} R_{t+1}, S_{t+1}
    • One turn of the agent–environment loop.
    • At each step the agent is in a state and takes an action, and the environment answers with a reward and the next state.
    • That reward is indexed t+1, because it only arrives after the action.
  • Episode
    • One run of transitions from a start state to the terminal state.
    • It is one sample of the whole process, and we don't know its length in advance.
  • Reward
    • A scalar signal that tells the agent how well it did at a time step.
    • The agent's only objective is to maximize the cumulative reward in the long run, so the reward signal defines the goal.
    • Q. Must a reward be a number?
      • Yes, it is a scalar, because the agent has to compare rewards and maximize them.
  • Reward design
    • Defining the reward so that it matches the goal of the task.
    • If the reward is defined properly, the agent learns properly, and if not, the agent is in trouble.
    • It requires understanding the whole sequence problem first.
  • Intermediate rewards
    • Rewards the agent receives at steps during an episode, before it ends.
    • They give feedback on progress, so the agent learns the sequence faster than with a single final reward.
    • Q. Can we always give intermediate rewards?
      • No. In chess, for example, we can't judge a move in the middle of the game, so the only reward is the win, draw or loss at the end.
  • Sparse reward
    • A reward that comes rarely and unpredictably.
    • The agent only gets meaningful feedback now and then, such as only at the end of a game, so it needs much more exploration to learn.
  • History: Ht=O1,A1,R1,…,Ot,At,RtH_t = O_1, A_1, R_1, \ldots, O_t, A_t, R_t
    • The sequence of all past observations, actions and rewards up to now.
    • The agent selects actions based on it, but it grows huge very quickly.
  • State: St=f(Ht)S_t = f(H_t)
    • The information used to decide what happens next.
    • It is a compact summary, a function of the history.
    • There are three kinds, the environment state, the agent state and the Markov state.
  • Environment state
    • The environment's private representation, which it uses to produce the next observation and reward.
    • It is never shown to the agent.
    • That is why the agent has to learn by trial and error.
  • Trial and error
    • Trial and error is learning by trying actions, observing the rewards they bring, and repeating the ones that worked.
    • Nobody tells the agent the right action, so this is how RL learns.
    • It needs many trials, and the failures are part of the learning.
  • Agent state
    • The agent's internal representation, the brain of the agent.
    • It is the information the agent uses to pick the next action.
    • It is the part our RL algorithms build, and we never build the environment.
    • Q. How does the environment state differ from the agent state?
      • The environment state is private and never shown to the agent. The agent state is the agent's own representation, and we only build algorithms on the agent side.
    • Q. What makes a good agent state?
      • It should be small, but still contain enough information to predict the next state and reward. The full history is always Markov but huge, while a small state is cheap but may lose information, so every choice is a trade-off between information and how hard it is to learn.
  • Markov property
    • The future is independent of the past given the present.
    • The next state depends only on the current state, not on the history.
  • Markov state: P[St+1∣St]=P[St+1∣S1,…,St]\mathbb{P}[S_{t+1} \mid S_t] = \mathbb{P}[S_{t+1} \mid S_1, \ldots, S_t]
    • A state that has the Markov property.
    • It contains all the useful information from the history, so once we know it, we can throw the history away.
    • Q. Why is the Markov property useful?
      • Because the current state carries everything we need. We don't have to store the whole history, which would blow up memory, computation and the amount of data needed.
  • Fully observable environment: Ot=Sta=SteO_t = S_t^a = S_t^e
    • An environment where the agent sees the complete environment state.
    • So the agent state is the same as the environment state.
    • This gives an MDP.
  • Partially observable environment and POMDP: ⟨S,A,O,P,R,Z,γ⟩,Zs′oa=P[Ot+1=o∣St+1=s′,At=a]\langle \mathcal{S}, \mathcal{A}, \mathcal{O}, \mathcal{P}, \mathcal{R}, \mathcal{Z}, \gamma \rangle, \quad \mathcal{Z}_{s'o}^a = \mathbb{P}[O_{t+1} = o \mid S_{t+1} = s', A_t = a]
    • A partially observable environment is an environment where the agent only sees observations, not the true state.
    • So the agent has to build its own state.
    • In the tuple, O\mathcal{O} is the set of observations and Z\mathcal{Z} the observation function, on top of the MDP's S,A,P,R,γ\mathcal{S}, \mathcal{A}, \mathcal{P}, \mathcal{R}, \gamma.
    • Zs′oa\mathcal{Z}_{s'o}^a is the probability of seeing observation oo after taking action aa and landing in state s′s'.
    • It is modeled as a POMDP, an MDP plus a set of observations and an observation function, which gives the probability of each observation after an action lands in a state.
    • An MDP is like driving on a clear sunny day, and a POMDP is like driving in fog.
    • A soccer robot with no sensor on the ball is an example.
  • Belief state: b(s)=P[Ste=s∣Ht]b(s) = \mathbb{P}[S_t^e = s \mid H_t]
    • A probability distribution over the possible environment states.
    • It is one way to build the agent state in a POMDP, along with keeping the full history or using the hidden state of a recurrent network.
  • Exploration and exploitation
    • Exploration means trying new actions to learn more about the environment, even if it costs immediate reward.
    • Exploitation means using what we already know to maximize reward.
    • The goal is to find a good policy while balancing the two.
  • Policy: π(a∣s)=P[At=a∣St=s]\pi(a \mid s) = \mathbb{P}[A_t = a \mid S_t = s]
    • The agent's behavior, the probability of taking each action in each state.
    • It depends only on the current state.
    • It is learned over many trials and episodes, and it is the RL equivalent of a trained model.
    • Q. Is a policy just a defined set of rules?
      • No. A policy is not defined up front. It is an optimized set of actions that the agent learns over many episodes.
  • Multi-armed bandit
    • A very simplified RL problem with one state, where the action is pulling an arm and the reward is immediate.
    • Past pulls do not influence the next one.
    • The task is to learn the unknown reward probabilities of the arms by trial and error while balancing exploration and exploitation.
  • Greedy: Q(A)←Q(A)+1N(A)(R−Q(A))Q(A) \leftarrow Q(A) + \frac{1}{N(A)} \left( R - Q(A) \right)
    • A strategy that always pulls the arm with the highest average reward so far.
    • Each arm's average is updated a little toward every new reward it pays.
    • It never explores, so it can lock onto a sub-optimal arm.
  • Epsilon-greedy: At={arg⁡max⁡aQ(a)with probability 1−ϵrandom actionwith probability ϵA_t = \begin{cases} \arg\max_a Q(a) & \text{with probability } 1 - \epsilon \\ \text{random action} & \text{with probability } \epsilon \end{cases}
    • A strategy that pulls a random arm with a small probability epsilon to explore, and exploits the best arm the rest of the time.
    • The exploration is random and at a fixed rate.
  • Upper Confidence Bound: At=arg⁡max⁡a[Q(a)+2ln⁡tN(a)]A_t = \arg\max_a \left[ Q(a) + \sqrt{\frac{2 \ln t}{N(a)}} \right]
    • A strategy that chooses the arm with the highest estimated value plus an exploration bonus.
    • The bonus is large for arms we have rarely tried and shrinks as we try them more.
    • It follows the idea of optimism in the face of uncertainty, so the exploration is informed instead of random.
    • Q. How do epsilon-greedy and UCB differ?
      • Epsilon-greedy explores randomly at a fixed rate. UCB explores in an informed way, by giving a bonus to arms we have tried less, so it finds the best arm faster. Over a very large number of episodes, both end up with similar rewards.
  • Q. Why is RL not supervised learning?
    • There are no labeled answers. The agent learns by trial and error from rewards, which are often delayed, and it needs many trials.

Building an MDP step by step​

  • State transition matrix: Pss′=P[St+1=s′∣St=s]\mathcal{P}_{ss'} = \mathbb{P}[S_{t+1} = s' \mid S_t = s]
    • A square matrix of the probabilities of moving from each state to each next state.
    • Each entry is the probability of moving from one state to another.
    • Each row must sum to one, because it covers every possibility from that state.
  • Markov process (MP): ⟨S,P⟩\langle \mathcal{S}, \mathcal{P} \rangle
    • A random sequence of states over time, where the next state depends only on the current state.
    • In the tuple, S\mathcal{S} is the finite set of states and P\mathcal{P} is the state transition matrix.
    • It is memoryless, because the history before the current state is not needed.
    • It has no rewards and no actions, so it is not yet RL.
    • It answers the observer's question, which state comes next.
  • Terminal state
    • The state where the episode ends.
    • Once the agent reaches it, it stays there with probability one, so it is also called an absorbing state.
  • Episodic and continuing tasks
    • An episodic task has a terminal state, and the environment resets after it ends.
    • A continuing task has no defined end and runs without resets.
    • A game of chess is episodic, and controlling room temperature is continuing.
  • Markov reward process (MRP): ⟨S,P,R,γ⟩,Rs=E[Rt+1∣St=s]\langle \mathcal{S}, \mathcal{P}, \mathcal{R}, \gamma \rangle, \quad \mathcal{R}_s = \mathbb{E}[R_{t+1} \mid S_t = s]
    • A model for judging how good each state is, by the rewards collected from it in the long run.
    • It is a Markov chain plus a reward function and a discount factor.
    • In the tuple, S\mathcal{S} is the set of states, P\mathcal{P} the transition matrix, R\mathcal{R} the reward function and γ\gamma the discount factor.
    • Rs\mathcal{R}_s is the reward we expect at the next step when we are in state ss.
    • The reward is an expectation, because the process is stochastic.
    • There is still no agent and no decision.
    • It answers the evaluator's question, how good this state is in the long run.
  • Return: Gt=Rt+1+γRt+2+γ2Rt+3+⋯=∑k=0∞γkRt+k+1G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1}
    • The total discounted reward from a time step to the end of one episode.
    • It belongs to one episode, so it is an actual value, not an expectation.
    • Q. Is the goal the reward of one state or of the whole episode?
      • It is the cumulative return over the whole episode.
  • Discount factor gamma: γ∈[0,1]\gamma \in [0, 1]
    • How much the agent values future rewards compared with immediate ones.
    • It is a number between zero and one, and a reward k steps ahead is multiplied by gamma to the power k.
    • With gamma zero, the agent is myopic and only cares about the immediate reward.
    • With gamma one, the agent is far-sighted and counts every future reward equally, which only works when every episode ends.
    • Q. How do you choose gamma?
      • It depends on the problem, and we have to justify it. A smaller gamma puts more weight on near-term rewards, and a larger one on long-term rewards.
    • Q. How do you stop an agent looping in a high-reward state forever?
      • Discounting makes repeated rewards shrink. We can also lower the reward after the agent stays too long, so the episode still ends.
  • Value function: v(s)=E[Gt∣St=s]v(s) = \mathbb{E}[G_t \mid S_t = s]
    • The goodness of being in a state.
    • It is the expected return from that state onwards, averaged over many episodes.
    • Q. How does the return differ from the value function?
      • The return is the actual discounted reward of one episode. The value function is the expected return over many episodes.
  • Markov decision process (MDP): ⟨S,A,P,R,γ⟩,Rsa=E[Rt+1∣St=s,At=a]\langle \mathcal{S}, \mathcal{A}, \mathcal{P}, \mathcal{R}, \gamma \rangle, \quad \mathcal{R}_s^a = \mathbb{E}[R_{t+1} \mid S_t = s, A_t = a]
    • A framework that describes the environment for sequential decision making, so RL algorithms can be run on it.
    • In the tuple, S\mathcal{S} is the set of states, A\mathcal{A} the set of actions, P\mathcal{P} the transition probabilities, R\mathcal{R} the reward function and γ\gamma the discount factor.
    • Rsa\mathcal{R}_s^a is the reward we expect at the next step when we take action aa in state ss.
    • It is an MRP plus actions.
    • Both the transitions and the rewards now depend on the action taken.
    • It answers the decision maker's question, which action to take now to maximize the long-term reward.
    • Q. What are the limitations of MDPs, and how do we address them?
      • MDPs assume the Markov property, which we can patch with frame stacking or recurrent networks. They assume a known model, which model-free RL removes. They assume finite states and actions and suffer from the curse of dimensionality, which function approximation and deep RL address. They also assume full observability, which POMDPs and belief states address.
  • Transition dynamics: Pss′a=P[St+1=s′∣St=s,At=a]\mathcal{P}_{ss'}^a = \mathbb{P}[S_{t+1} = s' \mid S_t = s, A_t = a]
    • How the environment responds to an action, meaning the probability of each next state given the current state and action.
    • They are independent of the policy.
    • The policy decides whether to brake at a yellow light, and the dynamics decide how much the car actually slows down.
    • Q. What is the difference between the policy's action probability and the transition probability?
      • The policy probability is how likely the agent is to pick an action. The transition probability is how likely that action leads to each next state, and it is set by the environment.
  • State value and action value: vπ(s)=Eπ[Gt∣St=s],qπ(s,a)=Eπ[Gt∣St=s,At=a]v_\pi(s) = \mathbb{E}_\pi[G_t \mid S_t = s], \quad q_\pi(s, a) = \mathbb{E}_\pi[G_t \mid S_t = s, A_t = a]
    • State value is the expected return of being in a state and following the policy.
    • Action value is the expected return of committing to a particular action in that state and then following the policy.
  • Planning and learning
    • Planning is finding the optimal policy in a known MDP, where the transition probabilities and the reward function are given.
    • Learning is improving the policy from experience in an unknown MDP, where they are missing.
    • In that case the agent has to explore.
    • Q. If the environment is fully observable, is the agent learning?
      • Only if the dynamics or rewards are unknown. If the agent also knows the transition probabilities and the reward function, finding the policy is planning, not learning.
  • Q. What does each step of the build-up add?
    • A Markov process has states and transitions. An MRP adds rewards and discounting. An MDP adds actions. A POMDP adds observations.

From Markov process to POMDP, each step adds one ingredient

Formulating an MDP​

  • Formulating a problem as an MDP
    • Identifying the states, actions, reward function, transition probabilities and discount factor, and then drawing the state transition diagram.
  • Finite-horizon MDP: max⁡πE[∑t=0TγtRt+1],πt(s)\max_\pi \mathbb{E}\left[ \sum_{t=0}^{T} \gamma^t R_{t+1} \right], \quad \pi_t(s)
    • An MDP restricted to a fixed, finite number of steps.
    • Every episode must reach an end state and stop, so the return can't blow up and gamma can be one.
    • Its optimal policy can depend on how many steps are left.
    • Q. How does a finite-horizon MDP differ from an infinite-horizon one?
      • A finite-horizon MDP has a fixed end, so gamma can be one and the best action can change with the remaining time. An infinite-horizon MDP runs forever, usually needs gamma below one to converge, and has a policy that doesn't depend on time.

Dynamic Programming​

  • Bellman equation: v(s)=Rs+γ∑s′Pss′v(s′),v=R+γPv  ⇒  v=(I−γP)−1Rv(s) = \mathcal{R}_s + \gamma \sum_{s'} \mathcal{P}_{ss'} v(s'), \quad v = \mathcal{R} + \gamma \mathcal{P} v \;\Rightarrow\; v = (I - \gamma \mathcal{P})^{-1} \mathcal{R}
    • The recursive relation that says the value of a state is the immediate reward plus the discounted value of the states that come after it.
    • It breaks the long-term return into one step plus the rest.
    • Q. What is the Bellman equation for the state-value function used for?
      • It calculates the expected return of a state under a given policy, as the immediate reward plus the discounted value of the next states. Every DP method is built on it.
    • Q. Can the Bellman equation be solved directly?
      • For a given policy it is a linear system, so small MDPs can be solved directly by matrix inversion. But that costs about the cube of the number of states, so large MDPs need iterative methods like DP, Monte Carlo or TD.
  • Bellman expectation equation: vπ(s)=∑aπ(a∣s)(Rsa+γ∑s′Pss′avπ(s′)),qπ(s,a)=Rsa+γ∑s′Pss′a∑a′π(a′∣s′)qπ(s′,a′)v_\pi(s) = \sum_a \pi(a \mid s) \left( \mathcal{R}_s^a + \gamma \sum_{s'} \mathcal{P}_{ss'}^a v_\pi(s') \right), \quad q_\pi(s, a) = \mathcal{R}_s^a + \gamma \sum_{s'} \mathcal{P}_{ss'}^a \sum_{a'} \pi(a' \mid s') q_\pi(s', a')
    • The Bellman equation for a given policy.
    • A state's value is the policy-weighted average of its action values, and an action's value is the immediate reward plus the discounted expected value of the next states.
  • Optimal value function: v∗(s)=max⁡πvπ(s),q∗(s,a)=max⁡πqπ(s,a)v_*(s) = \max_\pi v_\pi(s), \quad q_*(s, a) = \max_\pi q_\pi(s, a)
    • The maximum value any policy can achieve from each state.
    • The optimal action-value function is the maximum value achievable after taking a given action in a given state.
  • Optimal policy: π∗(a∣s)=1[a=arg⁡max⁡a′q∗(s,a′)]\pi_*(a \mid s) = \mathbb{1}\left[ a = \arg\max_{a'} q_*(s, a') \right]
    • A policy whose value is greater than or equal to every other policy's value in all states.
    • Every MDP has at least one, there is always a deterministic one, and all optimal policies share the same optimal value function.
    • Q. If we know the optimal action-value function, how do we get the optimal policy?
      • In each state we pick the action with the highest optimal action value. That greedy policy is optimal.
  • Bellman optimality equation: v∗(s)=max⁡a(Rsa+γ∑s′Pss′av∗(s′)),q∗(s,a)=Rsa+γ∑s′Pss′amax⁡a′q∗(s′,a′)v_*(s) = \max_a \left( \mathcal{R}_s^a + \gamma \sum_{s'} \mathcal{P}_{ss'}^a v_*(s') \right), \quad q_*(s, a) = \mathcal{R}_s^a + \gamma \sum_{s'} \mathcal{P}_{ss'}^a \max_{a'} q_*(s', a')
    • The Bellman equation for optimal values, where a state's value is the best action's immediate reward plus the discounted expected optimal value of the next states.
    • Because of the max, it is non-linear, so it can't be solved by matrix inversion and must be solved iteratively.
    • Q. What is the difference between the Bellman expectation equation and the Bellman optimality equation?
      • The expectation equation averages over the actions of a given policy, so it is linear and used for evaluation. The optimality equation takes the max over actions, so it is non-linear and gives the optimal values.
  • Dynamic programming
    • An optimization method for sequential problems that breaks a big problem into sub-problems and combines their solutions.
    • Dynamic means the sequential part, and programming means optimizing a policy.
    • In RL it solves a known MDP recursively with the Bellman equation.
    • Q. What are the strengths and limits of DP?
      • It is guaranteed to converge to an optimal policy in polynomial time, which is far faster than searching every possible policy. But it needs a model, and it becomes impractical for huge state spaces because of the curse of dimensionality.
    • Q. Can dynamic programming only be applied with perfect information about the environment?
      • No. DP needs a model of the environment, but that model can be stochastic, and it can be a learned, approximate model, as in model-based RL.
  • Policy evaluation: vk+1(s)=∑aπ(a∣s)(Rsa+γ∑s′Pss′avk(s′))v_{k+1}(s) = \sum_a \pi(a \mid s) \left( \mathcal{R}_s^a + \gamma \sum_{s'} \mathcal{P}_{ss'}^a v_k(s') \right)
    • Computing the value function of a given policy.
    • It is a prediction problem.
    • It repeatedly applies the Bellman expectation backup to every state until the largest change falls below a small threshold.
    • Q. How do values propagate during policy evaluation?
      • Value propagation is how values spread outwards from the states with terminal rewards, one step further with each sweep.
  • Policy improvement: π′(s)=arg⁡max⁡aqπ(s,a)=arg⁡max⁡a(Rsa+γ∑s′Pss′avπ(s′))\pi'(s) = \arg\max_a q_\pi(s, a) = \arg\max_a \left( \mathcal{R}_s^a + \gamma \sum_{s'} \mathcal{P}_{ss'}^a v_\pi(s') \right)
    • Making a new policy by acting greedily with respect to the current policy's values.
    • The new policy is at least as good as the old one.
    • Q. How do you extract a greedy policy from the values?
      • Greedy policy extraction is getting a policy from the values by picking, in each state, the action that moves toward the highest-valued next state.
  • Policy iteration: π0→Evπ0→Iπ1→Evπ1→I⋯→Iπ∗\pi_0 \xrightarrow{E} v_{\pi_0} \xrightarrow{I} \pi_1 \xrightarrow{E} v_{\pi_1} \xrightarrow{I} \cdots \xrightarrow{I} \pi_*
    • An algorithm that evaluates the current policy and then improves it by acting greedily on its values.
    • It repeats these two steps until the policy stops changing.
    • Q. Should value iteration and policy iteration give different policies?
      • No, both should give the same optimal policy. They differ in convergence speed and in the number of iterations.
    • Q. Which converges first, the policy or the values?
      • The policy. It becomes stable after a few iterations, while the values keep changing.
  • Value iteration: vk+1(s)=max⁡a(Rsa+γ∑s′Pss′avk(s′))v_{k+1}(s) = \max_a \left( \mathcal{R}_s^a + \gamma \sum_{s'} \mathcal{P}_{ss'}^a v_k(s') \right)
    • An algorithm that turns the Bellman optimality equation into an update rule.
    • It keeps updating the values using the best action in each state until the change is tiny, and then extracts the policy by taking the action with the best value.
    • Q. What is the difference between policy iteration and value iteration?
      • Policy iteration alternates full policy evaluation and greedy improvement until the policy stops changing. Value iteration skips the separate evaluation, keeps updating the values with the best action, and extracts the policy at the end.
  • Modified policy iteration
    • Policy iteration that stops the evaluation after a few sweeps before improving.
    • With one sweep it becomes value iteration, and with many sweeps it becomes full policy iteration.
  • Synchronous DP
    • DP that updates every state from the values of the previous sweep.
    • It keeps two arrays, an old one and a new one.
    • New values are computed only from the old ones, so it needs more memory and more iterations.
  • In-place DP
    • DP that uses each new value as soon as it is computed.
    • It keeps one array and overwrites values straight away, in any order.
    • New values are used immediately, so it needs less memory and fewer iterations.
    • It still converges as long as every state keeps getting updated.
    • Q. What is the difference between synchronous and in-place DP?
      • Synchronous DP uses two arrays and only updates from the old values. In-place DP uses one array and uses the new values immediately, so it converges in fewer iterations. Both converge.
  • Real-time DP
    • DP that only updates the states relevant to the agent's current trajectory while it acts.
    • It suits large problems where sweeping the whole state space is impossible, and it gives a near-optimal policy for the relevant region.
  • Approximate DP
    • DP that replaces the value table with a function approximator, such as a linear model or a neural network.
    • It is used to handle the curse of dimensionality.

Model-free learning with Monte Carlo​

  • Model-based and model-free
    • Model-based methods have or learn the MDP and plan with it by computation.
    • Model-free methods have no access to the dynamics or the reward function.
    • They learn directly from sampled experience.
  • Prediction and control
    • Prediction is evaluating a given policy to tell how good it is.
    • Control is finding the best policy.
    • Q. What is the difference between Monte Carlo prediction and control?
      • Prediction values a fixed policy from episodes. Control finds the optimal policy using Q and epsilon-greedy improvement.
  • Generalized policy iteration
    • The general loop of evaluation and improvement behind RL control methods.
    • We start with any policy, evaluate it, improve it, and repeat until we reach the optimal value function and the optimal policy.
    • Q. Why can't we use V for model-free control?
      • Greedy improvement over V needs a one-step lookahead with the transition matrix, which we don't have. With Q we just pick the best action, so it stays model-free.

Generalized policy iteration, evaluation and improvement converge to the optimal value and policy

  • Monte Carlo methods
    • Ways of estimating an unknown quantity by random sampling and averaging what we observe.
    • They are useful when an analytical solution is hard or impossible, and more samples give better estimates.
  • Monte Carlo in RL
    • Learning from complete episodes of experience without bootstrapping.
    • The agent can start anywhere, but each episode must end.
    • Q. What is the key shift from DP to Monte Carlo?
      • We drop the assumption that the model is known. We move from planning to learning from episodes.
    • Q. What is a complete episode, and why does Monte Carlo need one?
      • It is an episode that reaches a terminal state. Monte Carlo needs the actual return, and that is only known at the end.
    • Q. What are the limitations of Monte Carlo?
      • It needs complete episodes, so it only works for episodic tasks and gets feedback late. It also has high variance, so it needs many episodes, and it is impractical when data is expensive. The need for complete episodes is what motivates TD.
    • Q. Which method is designed for episodic tasks where the reward only comes at the end?
      • Monte Carlo. It waits until the end of the episode and learns from the actual return, so it doesn't need intermediate rewards.
  • Monte Carlo prediction: vπ(s)=Eπ[Gt∣St=s]≈1N(s)∑i=1N(s)G(i)v_\pi(s) = \mathbb{E}_\pi[G_t \mid S_t = s] \approx \frac{1}{N(s)} \sum_{i=1}^{N(s)} G^{(i)}
    • Estimating a policy's value as the average of the returns we actually observe, instead of the true expected return.
    • Q. Where is the policy in Monte Carlo prediction?
      • The policy generates the sample episodes, and Monte Carlo returns its value function.
    • Q. Why do we need many episodes?
      • So that every state is visited often enough to give a stable estimate.
  • First-visit Monte Carlo
    • Monte Carlo prediction that only counts the first visit to a state in each episode when averaging the returns.
  • Every-visit Monte Carlo
    • Monte Carlo prediction that counts every visit to a state in each episode.
    • Q. What is the difference between first-visit and every-visit Monte Carlo?
      • First-visit only averages the first visit to a state in each episode, so its samples are independent and unbiased. Every-visit averages all the visits, so it uses more data and is simpler, but it is slightly biased with few samples. Both converge as the number of episodes grows.
  • Incremental mean: μk=μk−1+1k(xk−μk−1),V(St)←V(St)+α(Gt−V(St))\mu_k = \mu_{k-1} + \frac{1}{k}(x_k - \mu_{k-1}), \quad V(S_t) \leftarrow V(S_t) + \alpha \left( G_t - V(S_t) \right)
    • A way to update an average a little toward each new return, instead of storing all the returns.
    • With a step size of one over the count it matches the exact average.
    • With a constant step size it becomes a moving average that forgets old experience, which suits non-stationary problems.
    • Q. Why update the value incrementally instead of overwriting it?
      • If we overwrote it, the value would only reflect the latest episode.
  • Epsilon-greedy policy improvement: π(a∣s)={ϵm+1−ϵif a=arg⁡max⁡a′Q(s,a′)ϵmotherwise\pi(a \mid s) = \begin{cases} \frac{\epsilon}{m} + 1 - \epsilon & \text{if } a = \arg\max_{a'} Q(s, a') \\ \frac{\epsilon}{m} & \text{otherwise} \end{cases}
    • Making the new policy epsilon-greedy with respect to Q.
    • It exploits the best action with probability one minus epsilon and acts randomly with probability epsilon.
    • The policy improvement theorem says the new policy is better than or equal to the old one.
    • Q. Why is greedy improvement on Q not enough?
      • It never explores, so it can get stuck on a sub-optimal action. Epsilon-greedy fixes that.
  • Monte Carlo control
    • Finding the best policy from complete episodes, without a model.
    • It is GPI with Monte Carlo evaluation of Q and epsilon-greedy improvement after every episode.
    • It doesn't wait for a full evaluation before improving.
    • That is noisier, like SGD compared with batch, but it reaches the optimal Q and policy much faster.
  • GLIE Monte Carlo control: lim⁡k→∞Nk(s,a)=∞,lim⁡k→∞πk(a∣s)=1[a=arg⁡max⁡a′Qk(s,a′)],ϵk=1k\lim_{k \to \infty} N_k(s, a) = \infty, \quad \lim_{k \to \infty} \pi_k(a \mid s) = \mathbb{1}\left[ a = \arg\max_{a'} Q_k(s, a') \right], \quad \epsilon_k = \frac{1}{k}
    • Monte Carlo control that keeps exploring early on but becomes fully greedy in the end.
    • GLIE stands for Greedy in the Limit with Infinite Exploration.
    • Every state-action pair keeps being visited, and the policy becomes greedy in the limit.
    • In practice we update Q after every episode and decay epsilon, such as one over the episode number.
    • Q. Why use GLIE instead of a fixed epsilon?
      • Once we have a good policy we want to exploit it. A fixed epsilon keeps exploring forever, so GLIE decays it.
  • Q. What is the difference between DP and Monte Carlo?
    • DP is model-based and bootstraps from estimated values, so it has lower variance. Monte Carlo is model-free and uses actual returns from complete episodes, so it has higher variance and needs episodic tasks.

Temporal Difference Learning, SARSA and Q-learning​

  • Temporal Difference learning
    • A model-free method that, unlike Monte Carlo, learns from incomplete episodes.
    • It takes one step and then immediately updates the previous state's value.
    • It combines Monte Carlo sampling with DP bootstrapping, so it is updating a guess toward a guess.
    • Q. Why does TD do better in Markov environments?
      • TD builds the underlying MDP step by step from one-step transitions. Monte Carlo just averages full returns, so it suits non-Markov environments.
  • TD target and TD error: V(St)←V(St)+α[Rt+1+γV(St+1)⏟TD target−V(St)],δt=Rt+1+γV(St+1)−V(St)V(S_t) \leftarrow V(S_t) + \alpha \big[ \underbrace{R_{t+1} + \gamma V(S_{t+1})}_{\text{TD target}} - V(S_t) \big], \quad \delta_t = R_{t+1} + \gamma V(S_{t+1}) - V(S_t)
    • The TD target is the immediate reward plus the discounted value of the next state.
    • It uses the real reward for the first step and the current guess for the rest.
    • The TD error is the target minus the current estimate, and the value moves a step toward the target.
    • Q. Why can't the Monte Carlo update be used directly in TD?
      • Without a complete episode the full return is unknown. So TD replaces it with the TD target.
    • Q. What does the step size alpha control?
      • The step size alpha is how fast the estimate moves toward the target. A constant alpha gives more weight to recent experience.
  • Bootstrapping and sampling
    • Bootstrapping means updating an estimate from another estimate.
    • TD and DP bootstrap.
    • Monte Carlo uses actual returns instead.
    • Sampling means learning from sampled experience instead of the full model.
    • Monte Carlo and TD sample.
    • DP doesn't sample, because the dynamics are known.
    • Q. How deep are the backups in TD, Monte Carlo and DP?
      • A backup is updating a state's value from the states that follow it. TD does shallow one-step backups on one sampled path, Monte Carlo does deep backups along a full sampled path to the end, and DP does full backups over every branch weighted by probability.

Backups in Monte Carlo, TD and DP

  • TD lambda: TD(0)→TD(λ)→TD(1)≈MC\text{TD}(0) \rightarrow \text{TD}(\lambda) \rightarrow \text{TD}(1) \approx \text{MC}
    • A method that sits between one-step TD and Monte Carlo, where lambda controls how far into the future it learns from.
    • Lambda zero is TD zero, and lambda one approaches Monte Carlo.
  • On-policy and off-policy
    • On-policy learning is learning about and improving the same policy that the agent follows.
    • Off-policy learning is following a behavior policy to explore while learning a different target policy, so it can even learn from logs or human demonstrations.
    • Q. Why is SARSA on-policy and Q-learning off-policy?
      • SARSA updates with the next action from the policy it follows. Q-learning updates with the max action, which is a greedy target policy, while a separate behavior policy explores.
  • SARSA: Q(St,At)←Q(St,At)+α[Rt+1+γQ(St+1,At+1)−Q(St,At)]Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha \left[ R_{t+1} + \gamma Q(S_{t+1}, A_{t+1}) - Q(S_t, A_t) \right]
    • A TD method that learns the value of the policy it follows and improves that same policy.
    • It is on-policy TD control.
    • The name comes from state, action, reward, next state and next action.
    • The next action comes from the same epsilon-greedy policy that is being improved, and it doesn't need to finish evaluation before improving.
    • Q. Are SARSA and TD different methods?
      • No. SARSA is a control algorithm that uses TD to update the Q values.
    • Q. Can you explain the SARSA update in words?
      • The target is the immediate reward plus the discounted Q value of the next state and the next action actually taken. We move the current Q value toward that target by alpha times the error.
  • Q-learning: Q(St,At)←Q(St,At)+α[Rt+1+γmax⁡aQ(St+1,a)−Q(St,At)]Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha \left[ R_{t+1} + \gamma \max_a Q(S_{t+1}, a) - Q(S_t, A_t) \right]
    • A TD method that learns the optimal action values, whatever policy it uses to explore.
    • It is off-policy TD control.
    • A behavior policy, such as epsilon-greedy, explores.
    • The update uses the maximum Q value at the next state, which is the greedy target policy, so it replaces the actual next action with the best possible one.
    • It directly approximates the Bellman optimality equation.
    • Q. Can you explain the Q-learning update in words?
      • The target is the immediate reward plus the discounted maximum Q value at the next state. We move the current Q value toward that target by alpha times the error.
    • Q. In Q-learning, what does the Q value of a state-action pair represent?
      • It is the expected cumulative reward of taking that action in that state and then following the optimal policy afterwards.
    • Q. Will Q-learning be accurate after a few episodes?
      • No. Q starts as a guess and needs very many episodes, often millions of steps for complex problems.
  • Q. What is the difference between Monte Carlo and TD?
    • Monte Carlo waits for the end of the episode and learns from the actual return, so it only works for episodic tasks. TD learns after every step from the TD target, so it works for both episodic and continuing tasks. Monte Carlo has high variance and zero bias, while TD has low variance and some bias.
  • Q. Why does Monte Carlo have high variance but zero bias, and TD the opposite?
    • The Monte Carlo return adds up many random steps, but it is an actual return, so it is unbiased. The TD target only has noise from one step, but it bootstraps from an estimate, so it is biased.
  • Q. Is TD always faster than Monte Carlo?
    • There is no proof that either one is always faster, so it depends on the problem. In practice TD often learns faster, because it can update after every step instead of waiting for the episode to end.
  • Q. In the AB example, why do Monte Carlo and TD disagree on the value of A?
    • There are two states. A always goes to B with reward 0, and B ends with reward 1 in six of eight episodes. Monte Carlo saw A once with a return of zero, so it gives zero. TD sees that A always leads to B with a reward of zero, so A gets the same value as B, which is 0.75.

AB example, Monte Carlo fits the returns while TD fits the MDP

  • Q. What does each of SARSA and Q-learning end up learning?
    • SARSA learns the value of the policy it actually follows, including its exploration. Q-learning learns the value of the optimal policy, whatever the behavior policy does.
  • Q. Why does Q-learning take the risky path in cliff walking, and when would you choose SARSA?
    • The max makes Q-learning learn the optimal path regardless of exploration, so it sometimes falls off while exploring. SARSA accounts for exploration and learns the safer path, so I would choose it when safety during learning matters.

Cliff walking, SARSA learns the safer path and Q-learning the optimal path

Function Approximation for Model-free Prediction​

  • Function approximation and generalization: v^(s,w)≈vπ(s),q^(s,a,w)≈qπ(s,a)\hat{v}(s, \mathbf{w}) \approx v_\pi(s), \quad \hat{q}(s, a, \mathbf{w}) \approx q_\pi(s, a)
    • Function approximation is estimating an unknown function from the observations we have, here a function that gives values for states instead of a table.
    • Because it learns from the states the agent has seen, it also gives values for unseen states, which is generalization.
    • A weight vector parameterizes the function, and Monte Carlo and TD still update it.
    • Q. Are tabular Monte Carlo and TD values exact?
      • No, they are approximations too. Function approximation does the approximation better and generalizes.
    • Q. Is approximating the state-value function prediction or control?
      • It is prediction. It evaluates a given policy by approximating its value function. Control needs action values.
    • Q. What is the scaling problem that motivates function approximation?
      • The scaling problem is that tabular methods store one value per state or state-action pair, which doesn't work for huge or continuous spaces like Go, backgammon or Atari. Such spaces can never be visited often enough, and the table blows up the memory.
  • Types of function approximators
    • Function approximators range from tables, through decision trees and nearest neighbor, to linear combinations of features and differentiable models like neural networks.
    • In RL they must be trainable on non-stationary data.
    • Q. What are the three approximator configurations?
      • The first takes a state and outputs its value. The second takes a state and an action and outputs one Q value. The third takes a state and outputs the Q values for all actions, and then we take the max.
    • Q. Which approximator configuration would you choose?
      • It depends on the problem. Outputting Q for all actions suits discrete actions and real-time settings like Atari, because one forward pass gives every action value.
  • Gradient descent: w←w−α∇wJ(w)\mathbf{w} \leftarrow \mathbf{w} - \alpha \nabla_{\mathbf{w}} J(\mathbf{w})
    • An iterative optimization method that moves the weights against the gradient of the loss to reduce the error between the prediction and the target.
    • The step size controls how far each update goes.
  • Value function approximation with SGD: Δw=α(vπ(S)−v^(S,w))∇wv^(S,w)\Delta \mathbf{w} = \alpha \left( v_\pi(S) - \hat{v}(S, \mathbf{w}) \right) \nabla_{\mathbf{w}} \hat{v}(S, \mathbf{w})
    • Updating the weights after each sampled state, by the step size times the error times the gradient of the prediction.
    • On average this equals the full gradient update.
    • It suits TD's one-step updates, and it also works for Monte Carlo.
  • Oracle target: J(w)=Eπ[(vπ(S)−v^(S,w))2]J(\mathbf{w}) = \mathbb{E}_\pi\left[ \left( v_\pi(S) - \hat{v}(S, \mathbf{w}) \right)^2 \right]
    • The true value of the policy, assumed to be given at first.
    • That makes it supervised learning, which minimizes the mean squared error to that value.
    • It is only a starting assumption to set up the method.
  • Feature vectors: x(S)=(x1(S),…,xn(S))⊤\mathbf{x}(S) = \left( x_1(S), \ldots, x_n(S) \right)^\top
    • A list of numbers that describes a state.
    • Examples are speed, distance and fuel, or the distances to obstacles for a robot.
    • We need it because RL has experience, not features.
  • Linear value function approximation: v^(S,w)=x(S)⊤w,∇wv^(S,w)=x(S),Δw=α(vπ(S)−v^(S,w))x(S)\hat{v}(S, \mathbf{w}) = \mathbf{x}(S)^\top \mathbf{w}, \quad \nabla_{\mathbf{w}} \hat{v}(S, \mathbf{w}) = \mathbf{x}(S), \quad \Delta \mathbf{w} = \alpha \left( v_\pi(S) - \hat{v}(S, \mathbf{w}) \right) \mathbf{x}(S)
    • Approximating the value as a weighted sum of the features.
    • Its gradient is just the feature vector, so the update is step size times error times features.
    • With SGD it converges to an approximate solution, not the exact value function.
    • Q. How does linear approximation compare with neural networks?
      • Linear approximation is efficient, but it needs handcrafted features and scales less. Neural networks can handle nonlinear inputs like raw frames, but they are a black box.
  • Monte Carlo and TD targets: MC:Δw=α(Gt−v^(St,w))∇wv^(St,w),TD:Δw=α(Rt+1+γv^(St+1,w)−v^(St,w))∇wv^(St,w)\text{MC}: \Delta \mathbf{w} = \alpha \left( G_t - \hat{v}(S_t, \mathbf{w}) \right) \nabla_{\mathbf{w}} \hat{v}(S_t, \mathbf{w}), \quad \text{TD}: \Delta \mathbf{w} = \alpha \left( R_{t+1} + \gamma \hat{v}(S_{t+1}, \mathbf{w}) - \hat{v}(S_t, \mathbf{w}) \right) \nabla_{\mathbf{w}} \hat{v}(S_t, \mathbf{w})
    • Monte Carlo and TD targets are what replace the true value when we train the approximator.
    • We need them because the true value is never given.
    • The Monte Carlo return is an unbiased but noisy sample of the true value, and the TD target is a biased sample.
    • Each state paired with its target becomes a supervised training example.
    • Q. Why is the Monte Carlo target unbiased and the TD target biased?
      • The Monte Carlo return is an actual return. The TD target uses an estimate of the next state's value.

VFA for Control, Experience Replay and DQN​

  • Control with function approximation
    • Finding the best policy when the action values come from a function approximator instead of a table.
    • It is GPI where the Q network does the approximate evaluation and epsilon-greedy does the improvement at every step.
  • Action-value approximation: J(w)=Eπ[(qπ(S,A)−q^(S,A,w))2],q^(S,A,w)=x(S,A)⊤wJ(\mathbf{w}) = \mathbb{E}_\pi\left[ \left( q_\pi(S, A) - \hat{q}(S, A, \mathbf{w}) \right)^2 \right], \quad \hat{q}(S, A, \mathbf{w}) = \mathbf{x}(S, A)^\top \mathbf{w}
    • Approximating Q instead of V, using features of the state and action together.
    • The target Q is replaced with the Monte Carlo return or the TD target.
  • Deadly triad
    • Three ingredients that together can make value learning diverge.
    • They are function approximation, bootstrapping and off-policy learning.
    • Q. What is wrong with Q-learning plus a neural network?
      • It is not the max, which is the core of the algorithm. The problem is that the same weights give both the prediction and the target. That causes correlated samples and a moving target, so it can diverge.
    • Q. What is the deadly triad?
      • It is function approximation, bootstrapping and off-policy learning used together. Q-learning with a neural network has all three, which is why it can diverge without extra tricks.
  • Batch methods
    • Methods that store experience as a dataset, sample from it repeatedly to fit the approximator, and then refresh it.
    • They look for the value function that best fits all the stored data.
    • Q. What problem do batch methods solve?
      • Sample inefficiency. Incremental updates use each sample once, while batch methods reuse stored experience.
    • Q. What is sample inefficiency?
      • Sample inefficiency means using each experience once and then throwing it away, which wastes data.
  • Least squares prediction: LS(w)=∑t=1N(vtπ−v^(st,w))2,wπ=arg⁡min⁡wLS(w)LS(\mathbf{w}) = \sum_{t=1}^{N} \left( v_t^\pi - \hat{v}(s_t, \mathbf{w}) \right)^2, \quad \mathbf{w}^\pi = \arg\min_{\mathbf{w}} LS(\mathbf{w})
    • Finding the weights that minimize the sum of squared errors between the approximate values and the target values in the stored dataset.
    • Sampling from the dataset with SGD converges toward this least squares solution.
  • Deep neural networks
    • Universal approximators built from layers of linear and non-linear transformations and trained end to end with backpropagation.
    • They generalize to unseen states, handle continuous spaces and raw pixels, but they are a black box.
  • Convolutional neural network
    • A neural network for images.
    • Convolution layers extract features with learned filters, pooling layers shrink the size while keeping important information, and fully connected layers turn the features into the output.
  • Deep reinforcement learning
    • Using deep neural networks to represent the value function, the policy or the model.
    • RL creates the target, and SGD trains the network to fit it.
  • Non-stationary target
    • A target that moves every time the weights update.
    • It is like food tied to a stick on a donkey's head.
    • The food moves with the donkey, so it never reaches it.
  • Experience replay
    • A technique that stores transitions in a buffer and samples them randomly.
    • Each transition is a state, action, reward and next state.
    • Random sampling breaks the correlation between consecutive samples, and experience gets reused.
    • Q. What limits the replay buffer?
      • Memory. A bigger buffer holds more experience over a longer horizon.
  • Fixed Q-targets: target=r+γmax⁡a′Q(s′,a′;w−)\text{target} = r + \gamma \max_{a'} Q(s', a'; \mathbf{w}^-)
    • A technique that uses a separate target network, frozen for a while, to give the target.
    • The online network learns toward it, only the online weights are updated, and the weights are copied over periodically.
  • DQN: L(w)=E(s,a,r,s′)∼D[(r+γmax⁡a′Q(s′,a′;w−)−Q(s,a;w))2]\mathcal{L}(\mathbf{w}) = \mathbb{E}_{(s, a, r, s') \sim \mathcal{D}}\left[ \left( r + \gamma \max_{a'} Q(s', a'; \mathbf{w}^-) - Q(s, a; \mathbf{w}) \right)^2 \right]
    • A deep RL method that learns Q values straight from raw inputs, such as game frames.
    • It is Q-learning with a deep network, experience replay and fixed Q-targets.
    • On Atari it takes the last four frames as input and outputs Q for every joystick action, with the change in score as the reward.
    • The same architecture and hyperparameters worked across all games, and it reached human level on many of them.
    • Q. Which DQN technique fixes which problem?
      • Experience replay with random sampling fixes the correlated samples. Fixed Q-targets fix the non-stationary target.
    • Q. What is frame stacking, and why is it used?
      • Frame stacking is feeding several consecutive frames together as one input, because a single frame can't show motion.
  • Q. Why might nonlinear TD diverge when Monte Carlo does not?
    • TD bootstraps from its own estimates one step ahead. Monte Carlo uses the actual return to the end of the episode.
  • Q. Do these methods converge with function approximation?
    • Tabular methods converge. Linear approximation converges for prediction and only chatters near the optimum for control, because all values share one weight vector. Nonlinear TD and off-policy TD may diverge. Monte Carlo converges in more cases than TD. It is hard to prove in theory, but in practice it often works.

Policy Search, REINFORCE, Actor-Critic, TRPO and PPO​

  • Policy search
    • Learning the policy directly, instead of deriving it from V or Q.
    • If all we care about is the optimal behavior, the policy is what we should learn.
    • Q. Why learn the policy directly instead of a value function?
      • If all we need is the optimal behavior, the policy can be simpler than the values. It can also be stochastic, and it works in high-dimensional and continuous action spaces.
    • Q. Is policy search model-based?
      • No. It is still model-free, and it learns from sampled experience.
  • Parameterized policy: πθ(a∣s)=P[a∣s,θ]\pi_\theta(a \mid s) = \mathbb{P}[a \mid s, \theta]
    • A function with its own parameters, often a neural network, that takes a state and outputs a probability for each action.
    • It is still model-free.
  • Value-based, policy-based and actor-critic
    • Value-based methods learn V or Q, and the policy is implicit.
    • Policy-based methods only learn the policy.
    • Actor-critic methods learn both.
    • Q. What is the difference between value-based and policy-based methods?
      • Value-based methods derive a usually deterministic policy from V or Q. Policy-based methods learn the policy directly, have better convergence and can be stochastic, but they usually reach a local optimum and don't generalize well.
  • Gradient-based and trust-region methods
    • Gradient-based methods update the policy by following the policy gradient directly.
    • REINFORCE, actor-critic and DDPG are gradient-based.
    • Trust-region methods also use the policy gradient, but restrict how big each update can be.
    • TRPO and PPO are trust-region methods.
    • Q. Why do we need trust-region methods at all?
      • A gradient can point in a really bad direction, so one unbounded update can give a really bad policy. A trust region keeps each update small, so the policy doesn't jump off the cliff.
    • Q. Are TRPO and PPO really gradient-free?
      • No. They are sometimes called non gradient based, but they still use the policy gradient. What changes is that the update is constrained or clipped.
  • Deterministic and stochastic policies: π(s)=avsπ(a∣s)=P[At=a∣St=s]\pi(s) = a \quad \text{vs} \quad \pi(a \mid s) = \mathbb{P}[A_t = a \mid S_t = s]
    • A deterministic policy maps each state to exactly one action.
    • A stochastic policy gives a probability for each action, so it is more general.
    • Sometimes the optimal policy is random, and value-based methods usually can't learn that because they derive one deterministic action.
    • Rock-Paper-Scissors is one example, because a deterministic policy is easily exploited.
    • Another is two states that look identical, where a deterministic policy picks the same, sometimes fatal, action in both.
  • Policy objective: J1(θ)=vπθ(s1),JavV(θ)=∑sμπθ(s)vπθ(s),JavR(θ)=∑sμπθ(s)∑aπθ(a∣s)RsaJ_1(\theta) = v_{\pi_\theta}(s_1), \quad J_{avV}(\theta) = \sum_s \mu_{\pi_\theta}(s) v_{\pi_\theta}(s), \quad J_{avR}(\theta) = \sum_s \mu_{\pi_\theta}(s) \sum_a \pi_\theta(a \mid s) \mathcal{R}_s^a
    • A measure of how good the policy is.
    • For episodic tasks it is the expected return from the start state.
    • For continuing tasks it is the average value or the average reward per step, weighted by how often the agent visits each state.
  • Gradient ascent: Δθ=α∇θJ(θ)\Delta \theta = \alpha \nabla_\theta J(\theta)
    • Climbing the gradient of the objective.
    • We use it because RL maximizes reward instead of minimizing a loss.
  • Gradient-free policy search
    • Optimizing the policy without gradients, using methods like hill climbing or genetic algorithms.
    • They exist but are less predictable.
  • Score function: ∇θπθ(s,a)=πθ(s,a)∇θπθ(s,a)πθ(s,a)=πθ(s,a)∇θlog⁡πθ(s,a)\nabla_\theta \pi_\theta(s, a) = \pi_\theta(s, a) \frac{\nabla_\theta \pi_\theta(s, a)}{\pi_\theta(s, a)} = \pi_\theta(s, a) \nabla_\theta \log \pi_\theta(s, a)
    • A way to estimate the policy gradient from sampled episodes.
    • It measures how sensitive the policy is to a change in its parameters, and tells us which direction makes an action more likely.
  • Policy gradient theorem: ∇θJ(θ)=Eπθ[∇θlog⁡πθ(s,a) Qπθ(s,a)]\nabla_\theta J(\theta) = \mathbb{E}_{\pi_\theta}\left[ \nabla_\theta \log \pi_\theta(s, a) \, Q^{\pi_\theta}(s, a) \right]
    • The result that tells us how to compute the gradient of the objective in a multi-step MDP.
    • The gradient is how the policy changes times how good the action is, measured by its action value.
    • It holds for the start value, average value and average reward objectives.
  • REINFORCE: Δθt=α∇θlog⁡πθ(st,at) Gt\Delta \theta_t = \alpha \nabla_\theta \log \pi_\theta(s_t, a_t) \, G_t
    • The Monte Carlo policy gradient method.
    • It plays a full episode, then makes the actions that led to a high return more likely and the actions that led to a low return less likely.
    • It uses the return as an unbiased sample of the action value, so it has low bias but high variance and is slow to converge.
    • Q. What kind of policy does REINFORCE use?
      • A stochastic policy. It outputs action probabilities and pushes up the probability of actions that led to higher returns.
  • Actor-critic: δ=r+γQw(s′,a′)−Qw(s,a),θ←θ+α∇θlog⁡πθ(s,a)Qw(s,a),w←w+βδϕ(s,a)\delta = r + \gamma Q_{\mathbf{w}}(s', a') - Q_{\mathbf{w}}(s, a), \quad \theta \leftarrow \theta + \alpha \nabla_\theta \log \pi_\theta(s, a) Q_{\mathbf{w}}(s, a), \quad \mathbf{w} \leftarrow \mathbf{w} + \beta \delta \phi(s, a)
    • A method where an actor learns the policy and a critic judges the actor's actions.
    • The actor holds the policy and acts.
    • The critic estimates the value function with Monte Carlo or TD and gives feedback through the TD error.
    • In GPI terms the critic evaluates and the actor improves, like a coach advising a player during the game.
    • Q. How does actor-critic improve on REINFORCE?
      • The critic's value estimate replaces the noisy full return, and that reduces the variance.
    • Q. What does the critic's TD error do?
      • It tells the actor whether its action was better or worse than expected. It is used to update both the critic and the actor.
  • Advantage function: A(s,a)=Q(s,a)−V(s)A(s, a) = Q(s, a) - V(s)
    • How much better an action is than the average action in that state.
    • It is Q minus V.
    • It is used in TRPO, PPO and other deep RL methods.
    • Q. Why use the advantage function in policy gradient methods?
      • Because it reduces the variance of the policy updates. It focuses the update on how much better an action is than average, not on the raw value.
  • KL divergence: DKL(P∥Q)=∑xP(x)log⁡P(x)Q(x)D_{KL}(P \parallel Q) = \sum_x P(x) \log \frac{P(x)}{Q(x)}
    • A measure of how much one probability distribution differs from another.
    • In TRPO it measures how far the new policy has moved from the old one.
  • TRPO: max⁡θE^t[rt(θ)A^t]s.t.DKL(πθold∥πθ)≤δ\max_\theta \hat{\mathbb{E}}_t\left[ r_t(\theta) \hat{A}_t \right] \quad \text{s.t.} \quad D_{KL}\left( \pi_{\theta_{old}} \parallel \pi_\theta \right) \le \delta
    • A policy search method that only accepts an update if the new policy stays within a trust region, measured by the KL divergence from the old policy.
    • It is conservative and stable, but computationally expensive.
    • It is like a climber taking one small step before the next hook, instead of running toward the cliff.
    • Q. How does a trust region differ from plain gradient descent?
      • Gradient descent picks the steepest direction and moves a fixed step. A trust region first defines how far it is safe to move and then finds the best point inside that region.
    • Q. Isn't a trust region just a smaller step size?
      • No. The step size controls the speed. The trust region limits how far the new policy can move away from the old one.
    • Q. When would you use TRPO or PPO?
      • For complicated, continuous state and action spaces, where learning the policy directly is the goal.

A plain gradient step versus a trust region step

  • PPO
    • A policy search method that clips the policy ratio to a small range around one, instead of computing a trust region.
    • It is simpler and much faster than TRPO.
    • Q. What is the difference between TRPO and PPO?
      • TRPO enforces a KL trust region at every iteration, which is stable but expensive. PPO clips the policy ratio instead, which is simpler and much faster.
    • Q. What is the main purpose of clipping in PPO?
      • Clipping prevents excessively large policy updates. It removes the benefit of pushing the policy ratio beyond the clip range, so the new policy stays close to the old one.
    • Q. Is the epsilon in PPO the same as in epsilon-greedy?
      • No. In PPO it sets the clipping range and is usually around 0.1 or 0.2. It is not an exploration rate.
  • Clipped surrogate objective: JCLIP(θ)=E^t[min⁡(rt(θ)A^t,  clip(rt(θ),1−ϵ,1+ϵ)A^t)]J^{CLIP}(\theta) = \hat{\mathbb{E}}_t\left[ \min\left( r_t(\theta) \hat{A}_t, \; \text{clip}\left( r_t(\theta), 1 - \epsilon, 1 + \epsilon \right) \hat{A}_t \right) \right]
    • PPO's objective, which rewards better actions but stops rewarding the policy for moving too far from the old one.
    • It is the policy ratio times the advantage, with the ratio clipped.
    • If an action was better than expected, PPO increases its probability but gets no extra benefit beyond the clip range, and the same in the other direction.
    • So clipping removes the incentive for very large updates.
    • Q. What is the policy ratio?: rt(θ)=πθ(at∣st)πθold(at∣st)r_t(\theta) = \frac{\pi_\theta(a_t \mid s_t)}{\pi_{\theta_{old}}(a_t \mid s_t)}
      • The policy ratio is the probability of an action under the new policy divided by its probability under the old policy. One means no change, above one means the action became more likely, and below one means less likely.

PPO clipped objective for positive and negative advantage

  • Q. What are the problems with vanilla policy gradient?
    • Each update creates a new policy, so the data is non-stationary. The step size is also hard to choose. If it is too big, the next data comes from a bad policy and it may never recover. If it is too small, experience is used inefficiently.
  • Q. Why not use experience replay in on-policy policy gradient?
    • The stored data comes from older, different policies, but the update needs data from the current policy.

Model-based RL, MCTS and RLHF​

  • Model-based RL
    • An approach that learns the transition dynamics and the reward model from experience, and then plans with them using value iteration, policy iteration or tree search.
    • So learning and planning are combined.
    • Q. What is the difference between model-free and model-based RL?
      • Model-free RL learns a value function or a policy directly from experience. Model-based RL learns a model and then plans with it.
    • Q. What are the advantages and the weakness of model-based RL?
      • Learning the model is an efficient supervised problem, and the model can also estimate its own uncertainty. But it is a two-step process, and the model error and the planning error compound.
    • Q. What is a model?
      • The model is the MDP itself, meaning the states, actions, transition probabilities, reward function and discount factor. Model-based RL tries to approximate the environment's underlying MDP.
  • Model learning: (St,At)→(Rt+1,St+1),η∗=arg⁡min⁡ηL(η)(S_t, A_t) \rightarrow (R_{t+1}, S_{t+1}), \quad \eta^* = \arg\min_\eta L(\eta)
    • Fitting the model from experience as a supervised learning problem, with the state and action as input and the reward and next state as targets.
    • Predicting the reward is regression, and predicting the next state is density estimation.
    • Q. How do we get the experience to learn a model?
      • By interacting with the environment, collecting either complete Monte Carlo episodes or one-step TD transitions.
  • Table lookup model: P^ss′a=N(s,a,s′)N(s,a),R^sa=1N(s,a)∑t=1T1[St=s,At=a]Rt+1\hat{\mathcal{P}}_{ss'}^a = \frac{N(s, a, s')}{N(s, a)}, \quad \hat{\mathcal{R}}_s^a = \frac{1}{N(s, a)} \sum_{t=1}^{T} \mathbb{1}\left[ S_t = s, A_t = a \right] R_{t+1}
    • The simplest model, a table of transition probabilities and rewards estimated from experience.
    • It estimates the transition probabilities by counting how often each next state follows each state-action pair, and the rewards by averaging.
  • Parameterized model: St+1∼Pη(St+1∣St,At),Rt+1∼Rη(Rt+1∣St,At)S_{t+1} \sim \mathcal{P}_\eta(S_{t+1} \mid S_t, A_t), \quad R_{t+1} \sim \mathcal{R}_\eta(R_{t+1} \mid S_t, A_t)
    • A learned approximation of the environment's MDP, with its own parameters.
    • It is made of a transition model and a reward model.
    • It assumes the state and action spaces are known, the Markov property holds, and the next state and the reward are conditionally independent, so they can be modeled separately.
  • Sample-based planning
    • Using the learned model only as a simulator to generate experience.
    • Model-free methods, such as Q-learning, then learn from that experience, which reduces real interactions with the environment.
  • Simple Monte Carlo search: Q(st,a)=1K∑k=1KGt(k),at=arg⁡max⁡aQ(st,a)Q(s_t, a) = \frac{1}{K} \sum_{k=1}^{K} G_t^{(k)}, \quad a_t = \arg\max_a Q(s_t, a)
    • A search that uses a model and a simulation policy to simulate many episodes from the current state for each action, and takes the action with the highest average return.
  • Expectimax tree: Q(s,a)=∑s′P(s′∣s,a)[R(s,a,s′)+γV(s′)],V(s)=max⁡aQ(s,a),O((∣S∣∣A∣)H)Q(s, a) = \sum_{s'} \mathcal{P}(s' \mid s, a) \left[ \mathcal{R}(s, a, s') + \gamma V(s') \right], \quad V(s) = \max_a Q(s, a), \quad O\left( (|\mathcal{S}| |\mathcal{A}|)^H \right)
    • A full search tree from the current state where action nodes take the max and chance nodes take the expected value over next states.
    • It computes optimal Q values for the current state, but its size grows exponentially with depth.
    • Q. How does MCTS differ from an expectimax tree?
      • An expectimax tree expands every branch up to a depth and computes exact expectations, so it is exhaustive but exponential in depth. MCTS builds a partial tree, picks branches with UCB and estimates values from sampled returns, so it is approximate but its cost is controlled by the simulation budget.
  • Monte Carlo Tree Search: UCB(s,a)=Vˉi⏟exploitation+cln⁡n(s)n(s,a)⏟exploration\text{UCB}(s, a) = \underbrace{\bar{V}_i}_{\text{exploitation}} + \underbrace{c \sqrt{\frac{\ln n(s)}{n(s, a)}}}_{\text{exploration}}
    • A model-based search that puts the current state at the root and grows a partial search tree by simulating episodes with the model.
    • Then it takes the action with the highest value.
    • AlphaGo and AlphaZero use it.
    • Q. Is MCTS used in model-free RL?
      • No. MCTS needs a model to simulate episodes from the current state, so it is a model-based planning method.
    • Q. What are the four steps of MCTS?
      • Selection with UCB, then expansion with a new child node, then a random rollout to the end, and finally backpropagation of the return to the root, updating visit counts and values along the path.
    • Q. In UCB, which part is exploitation and which is exploration?
      • The average value is exploitation, and the bonus term for less-visited actions is exploration. Calling the average value exploration is a common mistake.
    • Q. Why does MCTS build only a partial tree?
      • The full tree is too large, so it only expands where UCB points.
    • Q. What are the strengths and limits of MCTS?
      • It is a highly selective best-first search that evaluates states dynamically, uses samples to break the curse of dimensionality and works with a black-box model. But it needs a finite horizon and clear rules, and the tree has to fit in memory, so it suits games like Go but not every problem.
    • Q. What is a rollout?
      • A rollout is a random simulation from a newly expanded node until the episode ends or a depth limit is reached, giving a return for that node.

The four steps of MCTS

  • Alignment problem
    • The gap between what an LLM is trained to do, predicting likely text, and what humans want, useful and safe answers.
    • So its output can be fluent but still incorrect, biased or harmful.
    • Traditional metrics like BLEU don't capture human preferences either.
  • RLHF: Pre-training:max⁡θ∑tlog⁡Pθ(xt∣x<t),RLHF:max⁡θEy∼πθ(⋅∣x)[R(x,y)]\text{Pre-training}: \max_\theta \sum_t \log P_\theta(x_t \mid x_{<t}), \quad \text{RLHF}: \max_\theta \mathbb{E}_{y \sim \pi_\theta(\cdot \mid x)}\left[ R(x, y) \right]
    • Fine-tuning a model with RL using a reward learned from human preferences.
    • Pre-training maximizes the likelihood of the next token, while RLHF maximizes the expected reward of human-preferred responses.
    • In RL terms the policy is the LLM, the state is the context, the action is generating tokens, and the reward comes from the reward model.
    • Q. Why not train an LLM with an automatic reward or with likelihood alone?
      • Most prompts have no automatic reward, and likelihood only predicts text. RLHF pushes the output toward what humans prefer.
    • Q. What are the four steps of the RLHF pipeline?
      • Pre-training, then supervised fine-tuning, then reward model training, and finally RL optimization with an algorithm like PPO.
    • Q. What are the benefits of RLHF?
      • Responses align better with human behavior and values, they are safer and more acceptable, and it handles tasks where the reward is hard to define. It also means less content moderation and higher user satisfaction.
    • Q. What are the challenges of RLHF?
      • Human labeling is costly, human bias gets carried into the reward model and the policy, the model can hack the reward, and it is hard to scale feedback to large models.

The four-step RLHF pipeline

  • Human feedback
    • Human judgment given as preferences between two outputs, rankings of several outputs, or evaluations of whether an answer is better or worse.
    • Q. Why collect preferences rather than numeric scores?
      • A numeric score might not represent the preference correctly. Choosing the better of two responses captures it directly.
  • Pre-training
    • Training the model on a massive corpus with next-token prediction to learn language and general knowledge.
    • Its output can still be biased, irrelevant or unsafe.
  • Supervised fine-tuning
    • Fine-tuning the model on high-quality instruction and response demonstrations so that it follows instructions.
    • But following instructions doesn't guarantee alignment with human preferences.
    • Q. What does SFT give that pre-training does not, and what is still missing?
      • SFT gives instruction following. It still lacks human preferences, which the reward model and the RL step add.
  • Reward model
    • A model that scores responses the way humans would.
    • Humans compare or rank several responses to the same prompt, and the reward model is trained on those preferences, so it turns human judgment into a numeric reward function.
    • Q. Why is the reward model central to RLHF?
      • It is the only source of reward for the policy. If it is wrong, PPO optimizes the wrong behavior.
  • RL fine-tuning with PPO
    • The step where PPO updates the LLM to get a higher score from the reward model.
    • The policy generates responses, the reward model scores them, and a KL penalty stops the policy drifting too far from the reference model.
    • Q. What is the KL penalty?: max⁡θ  E[R(x,y)]−βDKL(πθ∥πref)\max_\theta \; \mathbb{E}\left[ R(x, y) \right] - \beta D_{KL}\left( \pi_\theta \parallel \pi_{ref} \right)
      • The KL penalty is a term that penalizes the updated policy for moving far from the reference policy. A higher penalty gives more conservative updates and reduces over-optimization.
    • Q. Why does the RL fine-tuning step need a penalty?
      • Without it, the policy can change drastically and over-optimize the reward. The KL penalty keeps it close to the reference model, just as PPO and TRPO limit their updates.
  • Reward hacking
    • A model exploiting the reward function to get a high score without producing genuinely better responses.
    • It is the over-optimization problem in RLHF.
  • Full fine-tuning and PEFT
    • Full fine-tuning is fine-tuning that updates all the weights.
    • PEFT, parameter-efficient fine-tuning, is fine-tuning that freezes most of the weights and only trains a small set of parameters, such as LoRA, which is far cheaper.

Hierarchical RL​

  • Hierarchical Reinforcement Learning
    • RL that breaks a complex task into smaller sub-tasks at different levels.
    • A high-level policy chooses which sub-task to do, and low-level policies carry it out.
  • Options
    • A temporally extended action, like a sub-policy or skill.
    • It has a set of states where it can start, its own policy, and a condition for when it terminates.
    • Q. What concept does HRL introduce to simplify complex tasks?
      • Options. Each option is a reusable sub-policy, so the agent can plan over a few big steps instead of many small actions.

Contact Interview Slides

· 약 1분

Outline​

  1. Title and name, current affiliation and position
  2. Education, experience, and research interests
  3. One paper from the master's, plus skills
  4. One paper from my time as a researcher, covered in detail because it is close to the professor's work
  5. Projects and papers from my time as a researcher
  6. What I want to do in the PhD

RL 011

· 약 12분

Model Based RL​

  • Model: Transition Probability, Reward Function, State, Action, Discount Factor
  • Planning: use the learned models to evaluate possible actions, construct or iprove a value function or policy using Value/Policy Iteration.
  • Underlying MDP: The env's actual state transitions and reward structure.
    • Transition Model P(s′∣s,a)P(s'|s,a)
    • Reward Model R(s,a)R(s,a)
    • Goal: Approximate the env's MDP and use if for planning.
AspectModel-Free RLModel-Based RL
Environment ModelNo model available (transition dynamics)Learn a model from experience
LearningDirectly learn a value function and/or policy from experienceUse the learned model to plan a value function and/or policy
MethodsLearn directly from experienceUse a simulator with DP, Model-Free RL, or Policy Search

Advantages of Model-Based RL​

  • Efficient Model Learning: Supervised learning can efficiently learn transition and reward models from experience.
  • Model Uncertainty: The learned model can estimate uncertainty in its prediction

Disadvantages of Model-Based RL​

  • Two-Step Process: First learn the environment model, then use it to construct a value function or policy.
  • Two Sources of Approximation Error:
    • Approximated Model Error: The learned model may inaccurately predict transitions or rewards.
    • Approximated Planning Error: Planning with the learned model may produce approximate or suboptimal results.
    • Compounding Error: Model and planning errors can accumulate, reducing the accuracy of the final policy.

MDP Model​

MDP=⟨S,A,P,R⟩η\text{MDP} = \langle S, A, P, R \rangle_{\eta}

  • Assumption: State space SS and Action space AA are known and the env satisfies the Markov property.
  • Model μ=⟨Pη,Rη⟩\mu = \langle P_{\eta}, R_{\eta} \rangle is parameterized by η\eta and represents state-transitions and rewards.
    • Pη≈PP_{\eta} \approx P
    • Rη≈RR_{\eta} \approx R

St+1∼Pη(st+1∣st,at)S_{t+1} \sim P_{\eta}(s_{t+1} | s_t, a_t) Rt+1∼Rη(rt+1∣st,at)R_{t+1} \sim R_{\eta}(r_{t+1} | s_t, a_t)

P(st+1,Rt+1∣st,at)=P(st+1∣st,at)P(Rt+1∣st,at)P(s_{t+1}, R_{t+1} | s_t, a_t) = P(s_{t+1} | s_t, a_t) P(R_{t+1} | s_t, a_t)

  • Assume that the next state and reward are conditionally independent given the current state and action (not a consequence of the Markov property).
  • This allows transition and reward distributions to be modeled separately.

Model Learning​

  • Goal: Approximate a model μη\mu_\eta from experience {S1,A1,R2,…,ST}\{S_1, A_1, R_2, \ldots, S_T\}.
  • Supervised Learning: Use (St,At)(S_t, A_t) as input and (Rt+1,St+1)(R_{t+1}, S_{t+1}) as targets.
  • Loss Function: Measure prediction errors using a loss function (e.g., MSE).
  • Empirical Loss: Average prediction error over observed training data.
  • Use supervised learning framework, find parameters η\eta that minimize empirical loss (MSE).
η∗=arg⁡min⁡ηL(η)\eta^* = \arg \min_\eta L(\eta)

Lookup Table Model​

  • Underlying Model is presented as a lookup table.
  • A model is an explicit MDP,P^,R^\text{MDP}, \hat{P}, \hat{R}

P^ss′a=1N(s,a)∑t=1T1((St,At,St+1)=(s,a,s′))\hat{P}_{ss'}^a = \frac{1}{N(s,a)} \sum_{t=1}^T 1((S_t, A_t, S_{t+1}) = (s,a,s'))

  • N(s,a)N(s,a) is the number of times State-Action pair has been visited.
  • 11: Indicator function that is 1 if the condition is true, 0 otherwise.
  • P^ss′a\hat{P}_{ss'}^a is the estimated probability of transitioning from state ss to state s′s' under action aa.

P^(s′∣s,a)=N(s,a,s′)N(s,a)\hat{P}(s'|s,a) = \frac{N(s,a,s')}{N(s,a)}

  • Estimated Transition Probability by counting the number of times the State-Action-Next State tuple has been observed.
R^sa=1N(s,a)∑t=1T1((St,At)=(s,a))Rt+1\hat{R}_s^a = \frac{1}{N(s,a)} \sum_{t=1}^T 1((S_t, A_t) = (s,a)) R_{t+1}
  • Calculate the average reward for the State-Action pair.

Single Action MRP Example​

Two States {A,B}\{A, B\} and no discount, 8 episodes of learning.

  • A → B: 100% transition probability, reward = 0.
  • B → Terminal: 75% chance of reward 1, 25% chance of reward 0.
EpisodeExperience
1A, 0, B, 0
2B, 1
3B, 1
4B, 1
5B, 1
6B, 1
7B, 1
8B, 0
  • MC: Estimates values using observed complete returns.
    • V(B)=6/8=0.75V(B) = 6/8 = 0.75
    • V(A)=0V(A) = 0
  • TD: Uses bootstrapping, updates a state's value using the estimated value of the next state.
    • V(B)=0.75V(B) = 0.75
    • V(A)←γ+γV(B)=0+0.75=0.75V(A) \leftarrow \gamma + \gamma V(B) = 0 + 0.75 = 0.75
    • Requires a backup of AA after V(B)V(B) has been learned.

Planning with a model​

  • Given Model μη=⟨Pη,Rη⟩\mu_\eta = \langle P_{\eta}, R_{\eta} \rangle
  • Solve MDP⟨S,A,Pη,Rη⟩\text{MDP} \langle S, A, P_{\eta}, R_{\eta} \rangle by η\eta.
  • With Planning algorithm:
    • Value Iteration
    • Policy Iteration
    • Tree searching
    • etc.

Sample-based Planning​

  • Generate a lot of samples or data then, use model free methods such as MC, SARSA, Q-learning, etc. to plan.
  • St+1∼Pη(St+1∣St,At)S_{t+1} \sim P_{\eta}(S_{t+1} | S_t, A_t)
  • Rt+1∼Rη(Rt+1∣St,At)R_{t+1} \sim R_{\eta}(R_{t+1} | S_t, A_t)
  • Data Efficiency: Reduce real environment interactions by learning from simulated experiences.
  • Given a model μv\mu_v and simulated policy π\pi
  • For each a∈Aa \in A:
Q(St,a)=1K∑k=1KGtQ(S_t, a) = \frac{1}{K} \sum_{k=1}^K G_t
  • Simulate kk episodes from current state st:{st,a,Rt+1k,…,STk}∼μv,πs_t: \{ s_t, a, R_{t+1}^k, \ldots, S_T^k \} \sim \mu_v, \pi
  • Evaluate actions by mean returns (MC evaluation)
  • Gt(k)G_t^{(k)}: Return from the kk-th simulation.
  • Select current action with max value

at=arg⁡max⁡a∈AQ(st,a)a_t = \arg\max_{a \in A} Q(s_t, a)

e.g.

ActionEpisode 1Episode 2Episode 3
Left354
Right213
  • Q(st,Left)=3+5+43=4Q(s_t, \text{Left}) = \frac{3 + 5 + 4}{3} = 4
  • Q(st,Right)=2+1+33=2Q(s_t, \text{Right}) = \frac{2 + 1 + 3}{3} = 2
  • Select action with max value: Left\text{Left}

Expectimax Tree​

Expectimax Tree

  • White Node: Choose action with max value.
  • Black Node: Average state values of all possible actions.
  • Compute Optimal Q(s,a)Q(s,a) values for the current state by construction an expectimax tree.
Q(s,a)=∑s′Pν(s′∣s,a)[Rν(s,a,s′)+γV(s′)]Q(s,a)=\sum_{s'}P_\nu(s'|s,a) \left[R_\nu(s,a,s')+\gamma V(s')\right] V(s)=max⁡aQ(s,a)V(s)=\max_a Q(s,a)
  • Pν(s′∣s,a)P_\nu(s'|s,a): Transition probability.
  • Rν(s,a,s′)R_\nu(s,a,s'): Expected Reward
  • V(s′)V(s'): Value of the next state.

Limitations of Expectimax Tree​

O((∣S∣×∣A∣)H)O((|\mathcal S|\times|\mathcal A|)^H)
  • Scaling Exponentially with Depth: Tree size grows exponentially with depth HH.
  • ∣S∣|\mathcal S|: Number of possible states.
  • ∣A∣|\mathcal A|: Number of possible actions.
  • HH: Depth of the tree.

Monte Carlo Search Tree, MCTS​

  • Given a model μv\mu_v
  • Build a search tree rooted at the current state sts_t, sample actions and next states.
  • Iteratively Construct and update the tree by performing KK simulation episodes starting from the root node.
  • Once search is finished, select the current action with maximum value in the search tree.

at=arg⁡max⁡a∈AQ(st,a)a_t = \arg\max_{a \in A} Q(s_t, a)

AspectMCTSExpectimax Tree
ExpansionConstruct partial search treeConstruct full search tree up to a given depth
ExplorationSelect branches using UCBExplore all possible branches
EvaluationEstimate values using sampled returnsCalculate expected values using transition probabilities
Action SelectionSelect actions based on estimated valuesSelect actions with maximum expected values
Computational CostControlled by simulation budgetExponential in search depth
Trade-offMore efficient, but approximateMore exhaustive, but computationally expensive

Tree Traversal​

Q(s,a,i)=Vi⏟Exploitation+cln⁡n(s)n(s,a)⏟ExplorationQ(s,a,i) = \underbrace{V_i}_{\text{Exploitation}} + \underbrace{c\sqrt{\frac{\ln n(s)}{n(s,a)}}}_{\text{Exploration}}
  • Use Upper Confidence Bound (UCB) to select which branches to explore.
  • cc: Exploration coefficient.
  • n(s)n(s): Number of visits to state ss.
  • n(s,a)n(s,a): Number of visits to state-action pair (s,a)(s,a).
  • Exploration Bonus: Encourages selecting less-visited actions.
  • UCB: Balances exploitation of high-value actions and exploration of less-visited actions.
    • In bandit problems, cc is a constant to balance exploration and exploitation.

Node expansion​

  • Add a new child node to the search tree for an unexplored action.

Rollout​

  • Perform a random simulation from the expanded node until termination or a depth limit.
  • Calculate the total return from the simulation.
ROLLOUT(Si)Loop: if Si is a terminal return Sielse Ai=random available action SiSi=Simulate (Ai,Si)\begin{aligned} & \text{ROLLOUT}(S_i) \\ & \quad \text{Loop: } \\ & \quad \quad \text{if } S_i \text{ is a terminal } \\ & \quad \quad \quad \text{return } S_i \\ & \quad \quad \quad \text{else } \\ & \quad \quad \quad \quad A_i = \text{random available action } S_i \\ & \quad \quad \quad \quad S_i = \text{Simulate } (A_i, S_i) \\ \end{aligned}

Backpropagation​

  • Propagate the simulation return back through the selected path to the root.
  • Update visit counts and estimated values of the visited nodes.

Advantages of MCTS​

  • Highly Selective Best-First Search
  • Evaluates states dynamically, unlike DP.
  • Use Samples to break curse of dimensionality.
  • Works for "black box" model.
  • Computationally efficient.

Reinforce Learning with Human Feedback, RLHF​

Why Human Feedback?​

  • Some tasks do not have clear or automatically measurable rewards.
  • Humans can provide:
    • Preferences: Choose between two outputs (A > B).
    • Rankings: Rank multiple outputs (1st, 2nd, 3rd).
    • Evaluations: Judge whether an answer is better or worse.
  • Example: Evaluating which chatbot response is more polite.

Alignment Problem​

  • LLMs are pretrained to predict text, not necessarily to generate useful responses.
  • Generated text may be harmful, biased, or factually incorrect.
  • Traditional evaluation metrics (e.g., BLEU) do not directly capture human preferences.
  • Human feedback helps align model behavior with human preferences for helpfulness, truthfulness, and safety.
  • Example: A model may generate plausible but impractical coding advice.

Core Idea of RLHF​

  • Human Feedback: Use human evaluations and preferences to guide model training.
  • Alignment: Align model behavior with human expectations and preferences.
  • Optimization: Train models to maximize rewards reflecting human preferences rather than only next-token likelihood.
    • Goal of LLM's pretraining: max⁡θ∑tlog⁡Pθ(xt∣x<t)\max_\theta \sum_{t}\log P_\theta(x_t | x_{<t})
      • Maximize the likelihood of the next token.
    • Goal of RLHF: max⁡θEy∼πθ(⋅∣x)R(x,y)\max_\theta \mathbb{E}_{y \sim \pi_\theta(\cdot|x)} R(x, y)
      • Maximize the expected reward of human-preferred responses.
  • Application: Widely used in NLP and LLM alignment.

RLHF Training Pipeline​

Pre-training → SFT → Reward Model Training → RL Optimization

  1. Pre-training: Train a base model on a large text corpus using next-token prediction.
  2. Supervised Fine-Tuning (SFT): Fine-tune the base model on high-quality instruction-response examples.
  3. Reward Model Training: Train a reward model using human-labelled preferences to predict response quality.
  4. Reinforcement Learning: Optimize the model's policy to maximize rewards predicted by the reward model.

Step 1. Pre-training​

  • Select a base model pretrained on a massive text corpus.
  • Learns general knowledge and language patterns.
  • Limitation: May produce biased, unsafe, or irrelevant responses.

Step 2. Supervised Fine-Tuning (SFT)​

  • Goal: Train the base model to follow instructions and generate reasonable responses.
  • Collect high-quality demonstration data (instruction, input, output).
  • Fine-tune the base model on the curated dataset.
  • Limitation: Instruction-following does not guarantee alignment with human preferences.

Step 3. Reward Model Training​

  • Goal: Learn a reward function that reflects human preferences.
  • Generate multiple responses for the same prompt.
  • Humans compare or rank the responses.
  • Train a reward model to assign scores based on human preferences.
  • Example: A professional, polite response (B) is preferred over a blunt response (A): B > A.
  • Outcome: Convert human judgments into numerical reward scores.

Step 4. RL with Human Feedback​

  • Goal: Optimize the LLM policy using the trained reward model.
  • Algorithm: PPO (example).
  • Generate responses using the current policy.
  • Score responses using the reward model from Step 3.
  • Update the policy to maximize reward.
  • Use a KL penalty to limit deviation from the reference policy and reduce over-optimization.
    • KL Penalty: Penalizes large deviations between the updated policy and the reference policy.
    • Higher KL Penalty → More conservative policy updates.
DKL(P∥Q)=∑xP(x)log⁡P(x)Q(x)D_{KL}(P\|Q)=\sum_x P(x)\log\frac{P(x)}{Q(x)} max⁡θ[E[R(x,y)]−βDKL(πθ∥πref)]\max_\theta\left[ \mathbb E[R(x,y)] -\beta D_{KL}(\pi_\theta\|\pi_{\mathrm{ref}}) \right]
StrategyCNNLLM
Feature ExtractionFreeze backbone, train classifier headFreeze base model, train task-specific head
Partial Fine-TuningFreeze early layers, update selected layersPEFT (e.g., LoRA): Freeze base weights, train small additional parameters
Full Fine-TuningUpdate all pretrained weightsUpdate all pretrained weights (not PEFT)

Chatgpt​

Chatgpt

Benefits of RLHF​

  • Alignment: Aligns model behavior with human values and preferences.
  • Safety & Usefulness: Encourages safer, more useful responses with higher human acceptance.
  • Ambiguous Goals: Handles tasks where rewards are difficult to define explicitly.

Challenges of RLHF​

  • Cost: Requires extensive human annotations, making training expensive.
  • Human Bias: Biases in human feedback can be transferred to the reward model and policy.
  • Over-optimization: Models may exploit the reward function rather than produce genuinely better responses (Reward Hacking).
  • Scalability: Collecting and applying human feedback becomes difficult as models and tasks scale.

Applications of RLHF​

  • ChatGPT: Improvement in safety and helpfulness
  • Claude: Constitutional AI for more nuanced alignment
  • Gemini: Large-scale RLHF for multimodal capabilities
  • Robotics: Learning task from human demonstrations
  • Teaching robots via human feedback to cook
  • Medical AI systems trained with doctor's feedback to align with human expert medical standards.

RL 010

· 약 15분

Policy Search Methods​

Instead of VV and QQ functions, we directly estimate the optimal policy.

πθ(a∣s)≈P(a∣s,θ)\pi^{\theta}(a|s) \approx P(a|s, \theta)

  • Policy was generated directly from the value function (e.g. ϵ\epsilon-greedy)
  • Parameterize the policy directly.
    • Instead of v(s,w)v(s,w) or q^(s,a,w)\hat{q}(s,a,w), we have πθ(a∣s)\pi^{\theta}(a|s)
    • Given a particular state ss, what actions should we take? (What is probability of that particular action?)
    • θ\theta is a learnable parameter which could be a neural network.

Value-based and Policy-based Methods​

  • Value-based: Learnt value function, Implicit policy (e.g. ϵ\epsilon-greedy)
  • Policy-based: No value function, Learnt policy.
    • Good convergence properties
    • Effective in high-dimensional or continuous action spaces
      • if it is really continuous and large, it is not efficient as well.
    • Can learn stochastic policies.
    • Sometimes policies are relatively simple, values and models are complex.
    • Typically reaches local optima.
    • Obtained knowledge is specific and does not generalize well.
  • Actor-Critic: Learnt value function, Learnt policy.

Policy Gradient Techniques​

  • Trust-Region Based: Optimize the policy in a trust zone (closer circle).

Stochastic policies​

Rock-Paper-Scissors​

  • A deterministic policy is easily exploited
    • Deterministic policy: If we follow a set of action or sequence of actions, we will definitely reach the goal and will always reach teh same location.
  • A uniform random policy is optimal policy.

Grid World​

Grid World

ϕ(s,a)=(1010⏟walls,0100⏟actions)\phi(s,a) = \big(\underbrace{1 0 1 0}_{walls}, \underbrace{0 1 0 0}_{actions}\big)
  • Agent cannot differentiate between the grey states.
  • ϕ(s,a)\phi(s,a) features describing state ss and action aa.
  • ϕ(s,E)=(1,0,1,0⏟NESW,0,1,0,0⏟NESW)\phi(s,E) = (\underbrace{1, 0, 1, 0}_{\text{NESW}}, \underbrace{0, 1, 0, 0}_{\text{NESW}}) is the North and the South are walls and the agent will move to the East.
  • If π(grey)=W\pi(\text{grey}) = W, then when the agent is in the left grey state, it will move west, get stuck in a loop, and never reach the goal.

Grid World Stochastic

  • Therefore, an optimal stochastic policy moves randomly EE or WW in grey states.
    • πθ(wall to N and S, move E)=0.5\pi_{\theta}(\text{wall to N and S, move E}) = 0.5
    • πθ(wall to N and S, move W)=0.5\pi_{\theta}(\text{wall to N and S, move W}) = 0.5
  • The agent will reach the goal with high probability.
  • Policy-based methods can learn Stochastic policies. 4563

Objective Function in Policy-based Methods​

Given a policy πθ(a∣s)\pi_{\theta}(a|s) with parameters θ\theta, the goal is to find the best θ\theta.

J1(θ)=vπθ(S1)J_1(\theta) = v_{\pi_{\theta}}(S_1)
  • In an episodic task (with an end state), J1(θ)J_1(\theta) is for that particular start state and measures how much expected return we can get.
  • S1S_1 is the start state.
  • J(θ)J(\theta) is the measure of the quality of the policy or the objective function to optimize.
JavV(θ)=∑sμπθ(s)vπθ(s)J_{avV}(\theta) = \sum_{s}\mu_{\pi\theta}(s)v_{\pi\theta}(s)
  • In continuing environments (doesn't have an end state), consider the states and take the average value weighted by how often the agent visits each state.
  • μπθ(s)\mu_{\pi\theta}(s) is how often the agent is visiting that particular state ss.
JavR(θ)=∑sμπθ(s)∑aπθ(a∣s)∑rp(r∣s,a)rJ_{avR}(\theta) = \sum_{s}\mu_{\pi\theta}(s)\sum_{a}\pi_{\theta}(a|s)\sum_{r}p(r|s,a)r
  • Use the average reward per time step.
  • Small batches can be used to estimate this average reward during training.

Policy-based Methods​

  • Policy-based RL is an optimization problem, find θ\theta that maximize J(θ)J(\theta).
    • J(θ)J(\theta) is the policy objective function.
  • Gradient-free methods: Hill Climbing, Genetic Algorithms, ...
  • Gradient-based

Δθ=α∇θJ(θ)\Delta{\theta} = \alpha \nabla_{\theta} J(\theta)

  • Policy gradient method will search for a local minimum in J(θ)J(\theta) by ascending the gradient of the Policy.
    • why ascending? because we want to maximize the objective function's value/rewards.
    • ∇θJ(θ)=(∂J(θ)θ1⋮∂J(θ)θn)\nabla_{\theta} J(\theta) = \begin{pmatrix} \frac{\partial J(\theta)}{\theta_1} \\ \vdots \\ \frac{\partial J(\theta)}{\theta_n} \end{pmatrix}
    • α\alpha is the step size.
ΔθJ(θ)=∇θEd[vπθ(s)]\Delta{\theta} J(\theta) = \nabla_{\theta} \mathbb{E}_d[v_{\pi\theta}(s)]
  • Assume the policy πθ\pi_{\theta} is differentiable.
  • Compute an estimate of the policy gradient.
  • Compute ΔθJ(θ)\Delta{\theta} J(\theta) using Monte Carlo samples since we need to explore the environment, gather information, and then learn the policy.

Score Function​

  • Assume the policy πθ\pi_{\theta} is differentiable.
  • ∇θπθ(s,a)\nabla_{\theta} \pi_{\theta}(s, a) is the gradient.
∇θπθ(s,a)=πθ(s,a)∇θπθ(s,a)πθ(s,a)=πθ(s,a)∇θlog⁡πθ(s,a)(∵ ∇θlog⁡f(θ)=1f(θ)∇θf(θ))\begin{aligned} \nabla_\theta \pi_\theta(s,a) &= \pi_\theta(s,a) \frac{\nabla_\theta \pi_\theta(s,a)} {\pi_\theta(s,a)} \\ &= \pi_\theta(s,a) \nabla_\theta \log \pi_\theta(s,a) \quad \big( \because \ \nabla_\theta \log f(\theta) = \frac{1}{f(\theta)} \nabla_\theta f(\theta) \big) \end{aligned}
  • Multiplying and dividing by πθ(s,a)\pi_\theta(s,a) is called the Likelihood Ratio Trick.
    • Since πθ(s,a)πθ(s,a)=1\frac{\pi_\theta(s,a)}{\pi_\theta(s,a)} = 1, this does not change the original value.
      • ∇θπθ(s,a)\nabla_\theta \pi_\theta(s,a) is Gradient of the policy
      • πθ(s,a)\pi_\theta(s,a) is the policy.
      • ∇θπθ(s,a)πθ(s,a)\frac{\nabla_\theta \pi_\theta(s,a)}{\pi_\theta(s,a)} measures how sensitive the policy is to changes in θ\theta, relative to the policy value itself.
    • From the derivative rule of the logarithm, ∇θπθ(s,a)πθ(s,a)=∇θlog⁡πθ(s,a)\frac{\nabla_\theta \pi_\theta(s,a)}{\pi_\theta(s,a)} = \nabla_\theta \log \pi_\theta(s,a).
  • Score Function: ∇θlog⁡πθ(s,a)\nabla_\theta \log \pi_\theta(s,a).

Policy Gradient Theorem​

Policy Gradient = How policy changes ×\times How good the action is.

  • It generalizes the likelihood ratio approach to multi-step MDPs.
  • Replaces the instantaneous reward r(s,a)r(s,a) with the action value function Qπθ(s,a)Q^{\pi\theta}(s,a).
    • s1→a1s2→a2s3→a3Goals_1 \xrightarrow{a_1} s_2 \xrightarrow{a_2} s_3 \xrightarrow{a_3} \text{Goal}
 ∇θJ(θ)=Eπθ[∇θlog⁡πθ(s,a)⏟Score FunctionQπθ(s,a)⏟Action Value Function]\ \nabla_\theta J(\theta) = \mathbb{E}_{\pi\theta}[ \underbrace{\nabla_\theta \log \pi_\theta(s,a)}_{\text{Score Function}} \underbrace{Q^{\pi\theta}(s,a)}_{\text{Action Value Function}} ]
  • The theorem applies to start state objective, average reward, and average value objectives.
  • Qπθ(s,a)Q^{\pi_\theta}(s,a): the expected long-term reward starting from state ss, taking action aa and following policy πθ\pi_\theta
  • ∇θlog⁡πθ(s,a)\nabla_\theta \log \pi_\theta(s,a): How sensitive the policy is to changes in θ\theta.
  • Eπθ[⋅]\mathbb{E}{\pi\theta}[\cdot]: Average over all possible states and actions according to the policy πθ\pi_\theta.
  • ∇θJ(θ)\nabla_\theta J(\theta): The direction in which θ\theta should be changed to increase the objective J(θ)J(\theta).

Simplified Policy Gradient steps​

  1. Loop
  2. Collect trajectories for Policy πθ\pi_\theta
  3. Estimate advantage function AA
  4. Compute Policy Gradient g^\hat{g}
  5. Update Policy Parameter θnew=θold+αg^\theta_{\text{new}} = \theta_{\text{old}} + \alpha \hat{g}
  • g^\hat{g} is the estimated policy gradient.
    • Can be MC policy gradient, or Actor-Critic Policy Gradient.
  • if α\alpha is too big, data collected under bad policy and it cannot be recovered.
  • if α\alpha is too small, it is not efficient use of experience.

REINFORCE Algorithm​

  • Monte Carlo Policy Gradient: explore and learn from the environment and learn the optimal policy.
  • Update Parameters by Stochastic Gradient Ascent.
  • Using policy gradient theorem: find the partial derivatives to find the direction of the gradient.
  • Using return vtv_t as an unbiased sample of Qπθ(s,a)Q^{\pi\theta}(s,a).
    • Qπθ(st,at)=Eπθ[vt∣st,at]Q^{\pi\theta}(s_t,a_t) = \mathbb{E}_{\pi\theta}[v_t | s_t, a_t]

Δθ=α∇θlog⁡πθ(st,at)vt\Delta{\theta} = \alpha \nabla_\theta \log \pi_\theta(s_t,a_t) v_t

Function REINFORCEInitialize θ arbitrarilyfor each episode {s1,a1,r1,…,sT−1,aT−1,rT}∼πθ dofor t=1 to T−1 doθ←θ+α∇θlog⁡πθ(st,at)vtreturn θ\begin{array}{l} \textbf{Function REINFORCE} \\ \qquad \text{Initialize } \theta \text{ arbitrarily} \\ \qquad \textbf{for each episode } \{s_1,a_1,r_1,\ldots,s_{T-1},a_{T-1},r_T\} \sim \pi_\theta \textbf{ do} \\ \qquad\qquad \textbf{for } t=1 \textbf{ to } T-1 \textbf{ do} \\ \qquad\qquad\qquad \theta \leftarrow \theta + \alpha \nabla_\theta \log \pi_\theta(s_t,a_t) v_t \\ \qquad \textbf{return } \theta \\ \end{array}

REINFORCE: Sutton and Barto​

Input: a differentiable policy parameterization π(a∣s,θ)Algorithm parameter: step size α>0Initialize policy parameter θ∈Rd′ (e.g., to 0)Loop forever (for each episode):Generate an episode S0,A0,R1,…,ST−1,AT−1,RT, following π(⋅∣⋅,θ)Loop for each step of the episode t=0,1,…,T−1:G←∑k=t+1Tγk−t−1Rk(Gt)θ←θ+αγtG∇ln⁡π(At∣St,θ)\begin{array}{l} \textbf{Input: } \text{a differentiable policy parameterization } \pi(a \mid s,\theta) \\ \textbf{Algorithm parameter: } \text{step size } \alpha > 0 \\ \textbf{Initialize } \text{policy parameter } \theta \in \mathbb{R}^{d'} \text{ (e.g., to 0)} \\ \\ \textbf{Loop forever (for each episode):} \\ \qquad \text{Generate an episode } S_0,A_0,R_1,\ldots,S_{T-1},A_{T-1},R_T, \text{ following } \pi(\cdot \mid \cdot,\theta) \\ \qquad \textbf{Loop for each step of the episode } t=0,1,\ldots,T-1: \\ \qquad\qquad G \leftarrow \sum_{k=t+1}^{T} \gamma^{k-t-1}R_k \qquad (G_t) \\ \qquad\qquad \theta \leftarrow \theta + \alpha \gamma^t G \nabla \ln \pi(A_t \mid S_t,\theta) \end{array}
  • Slow to converge.
  • Going to have low bias but high variance.

Actor-Critic​

  • Actor has a supervisor (Critic) that tells it how good or bad the action actor took is.
  • Actor: Controls agent's behavior using Policy-based methods.
  • Critic: Measures how good the action taken by the agent is using Value-based methods.

Reducing Variance using a Critic​

Qw(s,a)≈Qπθ(s,a)Q_w(s,a) \approx Q^{\pi\theta}(s,a)

  • Monte Carlo policy gradient has high variance.
  • Use a Critic to estimate the action-value function.
  • Actor-Critic algorithms maintains two sets of parameters:
  • Critic: Updates action-value function parameters ww.
    • It is solving the problem of policy evaluation.
    • How good is the policy πθ\pi_\theta for current parameters θ\theta?
    • MC or TD methods to estimate the value function.
  • Actor: Updates policy parameters θ\theta in the direction advised by the Critic.
ΔθJ(θ)=Eπθ[∇θlog⁡πθ(s,a)Qw(s,a)]Δθ=α∇θlog⁡πθ(s,a)Qw(s,a)\Delta_{\theta} J(\theta) = \mathbb{E}_{\pi\theta}[ \nabla_\theta \log \pi_\theta(s,a) Q_w(s,a) ] \\ \Delta_{\theta} = \alpha \nabla_\theta \log \pi_\theta(s,a) Q_w(s,a)
  • It follows an approximate policy gradient.

Action-Value Actor-Critic​

  • Using Linear value function approximation: Qw(s,a)=ϕ(s,a)TwQ_w(s,a) = \phi(s,a)^T w
  • Critic: Use Linear TD(0) to update ww.
  • Actor: Use policy gradient to update θ\theta.
Function Actor-CriticInitialize θ,sSample a∼πθfor each step doSample reward r=RsaSample transition s′∼PsaSample action a′∼πθ(s′,a′)δ=r+γQw(s′,a′)−Qw(s,a)θ=θ+α∇θlog⁡πθ(s,a)Qw(s,a)w←w+βδϕ(s,a)a←a′,  s←s′\begin{array}{l} \textbf{Function Actor-Critic} \\ \qquad \text{Initialize } \theta, s \\ \qquad \text{Sample } a \sim \pi_\theta \\ \\ \qquad \textbf{for each step do} \\ \qquad\qquad \text{Sample reward } r = R_s^a \\ \qquad\qquad\text{Sample transition } s' \sim P_s^a \\ \qquad\qquad \text{Sample action } a' \sim \pi_\theta(s',a') \\ \\ \qquad\qquad \delta = r + \gamma Q_w(s',a') - Q_w(s,a) \\ \qquad\qquad \theta = \theta + \alpha \nabla_\theta \log \pi_\theta(s,a) Q_w(s,a) \\ \\ \qquad\qquad \mathbf{w} \leftarrow \mathbf{w} + \beta \delta \phi(s,a) \\ \qquad\qquad a \leftarrow a',\; s \leftarrow s' \end{array}
  • δ\delta is Critic.
  • θ\theta is Actor.
  • Update ww: Critic can provide a better advice.

Actor-Critic: Sutton and Barto​

Input: a differentiable policy parameterization π(a∣s,θ)Input: a differentiable state-value function parameterization v^(s,w)Parameters: step sizes αθ>0,  αw>0Initialize policy parameter θ∈Rd′ and state-value weights w∈Rd (e.g., to 0)Loop forever (for each episode):Initialize S (first state of episode)I←1Loop while S is not terminal (for each time step):A∼π(⋅∣S,θ)Take action A,  observe S′,Rδ←R+γv^(S′,w)−v^(S,w)(if S′ is terminal, then v^(S′,w)≐0)w←w+αwδ∇v^(S,w)θ←θ+αθIδ∇ln⁡π(A∣S,θ)I←γIS←S′\begin{array}{l} \textbf{Input: } \text{a differentiable policy parameterization } \pi(a \mid s,\theta) \\ \textbf{Input: } \text{a differentiable state-value function parameterization } \hat{v}(s,\mathbf{w}) \\ \textbf{Parameters: } \text{step sizes } \alpha^\theta > 0,\; \alpha^{\mathbf{w}} > 0 \\ \textbf{Initialize } \text{policy parameter } \theta \in \mathbb{R}^{d'} \text{ and state-value weights } \mathbf{w} \in \mathbb{R}^{d} \text{ (e.g., to 0)} \\ \textbf{Loop forever (for each episode):} \\ \qquad \text{Initialize } S \text{ (first state of episode)} \\ \qquad I \leftarrow 1 \\ \qquad \textbf{Loop while } S \textbf{ is not terminal (for each time step):} \\ \qquad\qquad A \sim \pi(\cdot \mid S,\theta) \\ \qquad\qquad \text{Take action } A,\; \text{observe } S',R \\ \qquad\qquad \delta \leftarrow R + \gamma \hat{v}(S',\mathbf{w}) - \hat{v}(S,\mathbf{w}) \qquad \left( \text{if } S' \text{ is terminal, then } \hat{v}(S',\mathbf{w}) \doteq 0 \right) \\ \qquad\qquad \mathbf{w} \leftarrow \mathbf{w} + \alpha^{\mathbf{w}} \delta \nabla \hat{v}(S,\mathbf{w}) \\ \qquad\qquad \theta \leftarrow \theta + \alpha^\theta I \delta \nabla \ln \pi(A \mid S,\theta) \\ \qquad\qquad I \leftarrow \gamma I \\ \qquad\qquad S \leftarrow S' \end{array}

TRPO, Trust Region Policy Optimization​

A(s,a)=Q(s,a)−V(s)A(s,a) = Q(s,a) - V(s)

  • Advantage: the difference between the Q and the V values.
    • How good is an action compared to the average action for a specific state.
  • Q(s,a)Q(s,a) = the expected long-term return when taking action aa in state ss
  • V(s)V(s) = the expected average long-term return when following the policy from state ss
  • Used in many Deep RL algorithms such as TRPO, PPO, GRP and etc.
  • Stationary Target: Fixed target during training.

Update the old policy to a new policy such that they are with in a "Trusted" distance apart.

  • Conservative policy update allows improvement instead of degradation of policy.
  • Improve training stability by avoiding parameter updates that changes the policy too much at one step.
  • By enforcing KL divergence constraint on size of the policy update at each iteration.

Kullback-Leibler Divergence​

KL divergence score

KL(P∣∣Q) KL(P || Q)

  • It quantifies how much one probability distribution differs from another probability distribution.
  • ∣∣|| indicates divergence or PP's divergence from QQ.

DKL(P∣∣Q)=∑x∈XP(x)log⁡P(x)Q(x)D_{KL}(P || Q) = \sum_{x \in X} P(x) \log \frac{P(x)}{Q(x)}

  • Given two probability distributions PP and QQ over a discrete random variable XX, the KL divergence is the expected value under PP of the log ratio between PP and QQ.
    • Multiplying by P(x)P(x) gives more weight to events that occur frequently under PP.
    • PP large, QQ small → large divergence
    • PP small, QQ large → effect is smaller
  • e.g. πold(a1∣s)=0.8\pi_{\text{old}}(a_1|s) = 0.8 and πold(a2∣s)=0.2\pi_{\text{old}}(a_2|s) = 0.2, while πnew(a1∣s)=0.1\pi_{\text{new}}(a_1|s) = 0.1 and πnew(a2∣s)=0.9\pi_{\text{new}}(a_2|s) = 0.9
    • The policy changed drastically in one update step.
  • TRPO prevents this by enforcing DKL(πold∥πnew)≤δD_{KL}(\pi_{\text{old}} \| \pi_{\text{new}}) \leq \delta.

TRPO vs Gradient Descent​

ComparisonGradient DescentTrust Region
Optimization approachPicks the steepest direction.Defines a region in which to search for the next point.
StepMoves forward by a step size.Determines the maximum step size to explore.
Next pointMoves directly in the selected direction.Locates the optimal point within the trust region.
Search processRepeats the directional step.Resumes the search from the selected point.
Main characteristicFast and simple for optimizing an objective function.Controls how far the optimization explores at each step.
In Reinforcement LearningMay not work well in reinforcement learning.Provides a restricted region for finding the next optimal point.

TRPO vs Gradient Descent

PPO, Proximal Policy Optimization​

  • TRPO is relatively complicated, every time we need to find trust region and solve the optimization problem, leading to high computational cost.
  • PPO simplifies it by using a Clipped Surrogate function
  • Based on a ratio of two policies
    • Current Policy πθ\pi_{\theta}
    • Baseline Policy (Old Policy) πθold\pi_{\theta_{\text{old}}}

Policy Ratio​

rt(θ)=πθ(at∣st)πθold(at∣st)r_t(\theta) = \frac{\pi_\theta(a_t|s_t)} {\pi_{\theta_{\text{old}}}(a_t|s_t)}
  • rt(θ)=1r_t(\theta)=1: no policy change
  • rt(θ)>1r_t(\theta)>1: the action becomes more likely
  • rt(θ)<1r_t(\theta)<1: the action becomes less likely

The surrogate objective is:

J(θ)=Et[rt(θ)A^t]J(\theta) = \mathbb{E}_t \left[ r_t(\theta)\hat A_t \right]
  • A^t>0\hat A_t>0: the action was better than expected → increase its probability.
  • A^t<0\hat A_t<0: the action was worse than expected → decrease its probability.
  • Without a restriction, the policy may change too much in a single update.

Clipped Surrogate Objective​

JCLIP(θ)=E^t[min⁡(rt(θ)A^t⏟Normal Policy Gradient objective,clip⁡(rt(θ),1−ϵ,1+ϵ)⏟Clipped Policy Gradient ObjectiveA^t)]J^{CLIP}(\theta) = \hat{\mathbb E}_t \left[ \min ( \underbrace{r_t(\theta)\hat A_t}_{\text{Normal Policy Gradient objective}}, \underbrace{\operatorname{clip} (r_t(\theta),1-\epsilon,1+\epsilon)}_{\text{Clipped Policy Gradient Objective}}\hat A_t ) \right]
  • rt(θ)=πθ(at∣st)πθold(at∣st)r_t(\theta) = \frac{\pi_\theta(a_t|s_t)}{\pi_{\theta_{\text{old}}}(a_t|s_t)} is the ratio of the new policy to the old policy.
  • A^t=Q(st,at)−V(st)\hat A_t = Q(s_t,a_t) - V(s_t) is the advantage function.
  • ϵ\epsilon is a hyperparameter, usually 0.10.1 or 0.20.2.
  • If ϵ=0.2\epsilon=0.2, the clipping range is [0.8,1.2][0.8,1.2].
  • For A^t>0\hat A_t>0, PPO removes the benefit of increasing rtr_t above 1+ϵ1+\epsilon.
  • For A^t<0\hat A_t<0, PPO removes the benefit of decreasing rtr_t below 1−ϵ1-\epsilon.
  • The policy ratio itself is not strictly forced to remain inside the clipping range.
  • Instead, clipping removes the incentive for excessively large beneficial policy updates.

Clipped Surrogate Objective

Algorithm: PPO with Clipped ObjectiveInput: θ0, ϵfor k=0,1,2,… doCollect set of partial trajectories Dk on policy πk=π(θk)Estimate advantages A^tπk using any advantage estimation algorithmCompute policy updateθk+1=arg⁡max⁡θLθkCLIP(θ)by taking K steps of minibatch SGD (via Adam), whereLθkCLIP(θ)=Eτ∼πk[∑t=0Tmin⁡(rt(θ)A^tπk,clip⁡(rt(θ),1−ϵ,1+ϵ)A^tπk)]\begin{array}{l} \textbf{Algorithm: PPO with Clipped Objective} \\ \textbf{Input: } \theta_0,\ \epsilon \\ \textbf{for } k=0,1,2,\ldots \textbf{ do} \\ \qquad \text{Collect set of partial trajectories } \mathcal{D}_k \text{ on policy } \pi_k=\pi(\theta_k) \\ \qquad \text{Estimate advantages } \hat{A}_t^{\pi_k} \text{ using any advantage estimation algorithm} \\ \\ \qquad \text{Compute policy update} \\ \qquad \theta_{k+1} = \arg\max_{\theta} \mathcal{L}_{\theta_k}^{CLIP}(\theta) \\ \\ \qquad \text{by taking } K \text{ steps of minibatch SGD (via Adam), where} \\ \qquad \mathcal{L}_{\theta_k}^{CLIP}(\theta) = \mathbb{E}_{\tau\sim\pi_k} \left[ \sum_{t=0}^{T} \min \left( r_t(\theta)\hat{A}_t^{\pi_k}, \operatorname{clip} \left( r_t(\theta),1-\epsilon,1+\epsilon \right) \hat{A}_t^{\pi_k} \right) \right] \\ \end{array}
  • θ0\theta_0: Initial policy parameters.
  • ϵ\epsilon: Clipping threshold.
  • A^tπk\hat{A}_t^{\pi_k}: Aπ(s,a)=Qπ(s,a)−Vπ(s)A_\pi(s,a)=Q_\pi(s,a)-V_\pi(s), where at∼π(at∣st),st+1∼P(st+1∣st,at)a_t\sim\pi(a_t\mid s_t),\quad s_{t+1}\sim P(s_{t+1}\mid s_t,a_t), for t≥0t\ge0.

RL 009

· 약 11분

Function Approximation​

v^(s,w)≈vπ(s)\hat{v}(s, \mathbf{w}) \approx v_\pi(s)

q^(s,a,w)≈qπ(s,a)\hat{q}(s, a, \mathbf{w}) \approx q_\pi(s, a)

  • Incremental methods for prediction
  • Model-free VFA: MC and TD targets

GPI, Generalized Policy Iteration​

  • Iterate between policy evaluation and policy improvement
  • Policy Evaluation: Approximate policy evaluation. q^(⋅,⋅,w)≈qπ\hat{q}(\cdot, \cdot, \mathbf{w}) \approx q_\pi
  • Policy Improvement: ϵ\epsilon-greedy policy improvement.

Types of Action-Value FA​

s→FA(w)→q^(s,w)s \to \text{FA}(\mathbf{w}) \to \hat{q}(s, \mathbf{w})
  • State Value Function Approximation
(s,a)→FA(w)→q^(s,a,w)(s, a) \to \text{FA}(\mathbf{w}) \to \hat{q}(s, a, \mathbf{w})
  • Action Value Function Approximation
    • q^(s,Left,w)=3.2\hat{q}(s, \text{Left}, \mathbf{w}) = 3.2
    • q^(s,Right,w)=8.7\hat{q}(s, \text{Right}, \mathbf{w}) = 8.7
s→FA(w)→q^(s,a1,w)⋯q^(s,an,w)s \to \text{FA}(\mathbf{w}) \to \hat{q}(s,a_1, \mathbf{w}) \cdots \hat{q}(s,a_n, \mathbf{w})
  • The network output is a vector of Q-values for each action.
  • More convenient to use discrete action spaces.
ActionQ-value
Left3.2
Right8.7
Jump5.3

Action VFA​

q^(s,a,w)≈qπ(s,a)\hat{q}(s, a, \mathbf{w}) \approx q_\pi(s, a)

  • Approximate the Action-value function.
  • Doing action aa at state ss, Approximate the Q-value of that action.

J=Eπ[(qπ(s,a)−q^(s,a,w))2]\mathcal{J} = \mathbb{E}_{\pi} \left[ (q_\pi(s, a) - \hat{q}(s, a, \mathbf{w}))^2 \right]

  • Minimize mean-squared error (MSE) between the approximate Q-value q^(s,a,w)\hat{q}(s, a, \mathbf{w}) and the true Q-value qπ(s,a)q_\pi(s, a).

Δw=α(qπ(s,a)−q^(s,a,w))∇wq^(s,a,w) \Delta \mathbf{w} = \alpha (q_{\pi}(s,a) - \hat{q}(s,a,\mathbf{w})) \nabla_{\mathbf{w}} \hat{q}(s,a,\mathbf{w})

  • Use SGD to find the local minimum.
  • qπ−q^q_{\pi} - \hat{q} tells us how much the prediction is off from the target.
  • ∇wq^(s,a,w)\nabla_{\mathbf{w}} \hat{q}(s,a,\mathbf{w}) tells us how each weight affects the predicted QQ-value.

Linear Action VFA​

x(s,a)=[x1(s,a)x2(s,a)⋮xn(s,a)]x(s, a) = \begin{bmatrix} x_1(s, a) \\ x_2(s, a) \\ \vdots \\ x_n(s, a) \end{bmatrix}
  • Feature vector is used to represent the state and action pair.

q^(s,a,w)≈x(s,a)Tw=∑jxj(s,a)wj\hat{q}(s, a, w) \approx x(s, a)^T w = \sum_j x_j (s, a) w_j

  • Predicted Q-value is a linear combination of the feature values. (sum of each feature value xjx_j multiplied by the weight wjw_j)
q^(s,a,w)=x(s,a)Twq^=x1w1+x2w2+⋯+xnwn\begin{aligned} \hat{q}(s, a, w) = x(s, a)^T w \\ \hat{q} = x_1w_1 + x_2w_2 + \cdots + x_n w_n \end{aligned}
  • x1,x2,⋯x_1, x_2, \cdots: features of the state and action pair.
  • w1,w2,⋯w_1, w_2, \cdots: weights that need to be learned.
  • derivative q^\hat{q} with respect to ww.
    • ∂q^∂w1=x1\frac{\partial \hat{q}}{\partial w_1} = x_1
    • ∂q^∂w2=x2\frac{\partial \hat{q}}{\partial w_2} = x_2
∇wq^=[x1x2⋮xn]=x(s,a)\nabla_w\hat{q} = \begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \end{bmatrix} = x(s, a)
  • e.g. q^=2w1+5w2\hat{q} = 2w_1 + 5w_2, then ∇wq^=[25]\nabla_w\hat{q} = \begin{bmatrix} 2 \\ 5 \end{bmatrix}
Δw=α(qπ−q^)∇wq^=α(qπ−q^)x(s,a)=α(qπ(s,a)−q^(s,a,w))x(s,a)\begin{aligned} \Delta w \\ &= \alpha (q_{\pi} - \hat{q}) \nabla_w\hat{q} \\ &= \alpha (q_{\pi} - \hat{q}) x(s, a) \\ &= \alpha (q_{\pi}(s, a) - \hat{q}(s, a, w)) x(s, a) \end{aligned}

Incremental Prediction Algorithm​

  • Assumption so far: qπ(s,a)q_{\pi}(s,a) is given.
  • But an actual RL agent does not know the true qπ(s,a)q_{\pi}(s,a).
  • Therefore, we need to estimate a target.
  • Monte Carlo (MC): the target is the return GtG_t.
    • Gt=Rt+1+γRt+2+⋯G_t = R_{t+1} + \gamma R_{t+2} + \cdots
    • Update: Δw=α(Gt−q^(st,at,w))∇wq^(st,at,w)\Delta w = \alpha \bigl(G_t - \hat q(s_t,a_t,w)\bigr)\nabla_w\hat q(s_t,a_t,w)
    • It compares the predicted Q-value with the actual return observed after the episode.
    • MC does not use another prediction inside the target.
  • Temporal Difference (TD): the target is Rt+1+γq^(st+1,at+1,w)R_{t+1} + \gamma \hat q(s_{t+1},a_{t+1},w).
    • Update: Δw=α(Rt+1+γq^(st+1,at+1,w)−q^(st,at,w))∇wq^(st,at,w)\Delta w = \alpha \bigl(R_{t+1} + \gamma\hat q(s_{t+1},a_{t+1},w) - \hat q(s_t,a_t,w)\bigr)\nabla_w\hat q(s_t,a_t,w)
    • It compares the current Q prediction with the current reward plus the discounted next Q prediction.
    • Bootstrapping: update the current prediction using another prediction.
    • Because the next prediction can also be wrong, we ask: can repeated updates converge to a stable value?
  • On-policy: behavior policy = target policy.
  • Off-policy: behavior policy ≠\ne target policy.
    • The policy that generates the experience is different from the policy that we want to evaluate or improve.
PolicyAlgorithmLookup TableLinearNon-linear
On-policyMC✓✓✓
On-policyTD(0)✓✓✗
Off-policyMC✓✓✓
Off-policyTD(0)✓✗✗
  • Deadly Triad: Function Approximation + Bootstrapping + Off-policy.
AlgorithmLookup TableLinearNon-linear
MC Control✓(✓)✕
SARSA✓(✓)✕
Q-Learning✓✕✕
  • SARSA learns the policy that it actually follows.
    • Target: Rt+1+γQ(st+1,at+1)R_{t+1} + \gamma Q(s_{t+1},a_{t+1}), On-policy TD
  • Q-Learning learns the optimal policy.
    • Target: max⁡a′Q(st+1,a′)\max_{a'} Q(s_{t+1},a'), Off-policy TD
  • (✓): Moved around the near-optimal value function.
    • Linear FA may not represent the exact Q∗Q^* because all state-action values share the same weight vector and must fit the same linear function.
  • x: Divergence

Batch Methods​

  • Incremental learning: an experience -> update the weights.
  • Batch methods: collect experiences -> store in D\mathcal{D} -> reuse D\mathcal{D} for training.
  • It seeks to find the best fitting value functions.

D={(s1,v1π),(s2,v2π),⋯ ,(sN,vNπ)} \mathcal{D} = \{(s_1, v^{\pi}_1), (s_2, v^{\pi}_2), \cdots, (s_N, v^{\pi}_N)\}

  • Which ww makes v^(s,w)\hat{v}(s, w) fit all stored data best?
    • Using the agents' experience or training data.
    • Training data: a fixed batch of previously collected data.

Least Squares Prediction​

  • Given a value function approximation: v^(s,w)≈vπ(s)\hat{v}(s,w) \approx v^\pi(s)
  • Given experience data: D={(s1,v1π),(s2,v2π),…,(sN,vNπ)}\mathcal{D} = \{(s_1,v_1^\pi),(s_2,v_2^\pi),\ldots,(s_N,v_N^\pi)\} consisting of state-value pairs.
LS(w)=∑t=1N(vtπ−v^(st,w))2LS(w)=\sum_{t=1}^{N}\left(v_t^\pi-\hat{v}(s_t,w)\right)^2
  • LS(w)LS(w) is the sum of all squared prediction errors.
  • The Least Squares method finds the parameter vector ww that minimizes the squared error between v^(s,w)\hat v(s,w) and vπ(s)v^\pi(s).
wπ=arg⁡min⁡wLS(w)w^\pi=\arg\min_w LS(w)
  • If we use the mean squared error instead:
ED[(vtπ−v^(st,w))2]=1N∑t=1N(vtπ−v^(st,w))2\mathbb{E}_{\mathcal D} \left[ \left(v_t^\pi-\hat v(s_t,w)\right)^2 \right] = \frac{1}{N} \sum_{t=1}^{N} \left(v_t^\pi-\hat v(s_t,w)\right)^2
  • The factor 1/N1/N does not change the minimizing ww.

SGD Procedure​

  1. Sample a {state,value}\{\text{state},\text{value}\} pair from D\mathcal D.
  2. Apply the SGD update:
Δw=α(vπ−v^(s,w))∇wv^(s,w)\Delta w = \alpha \left(v^\pi-\hat v(s,w)\right) \nabla_w\hat v(s,w)
  • Sample from D\mathcal D -> calculate the error -> update ww -> repeat.
  1. Under appropriate conditions, SGD converges toward the Least Squares solution.
  • Then, what model should represent v^(s,w)\hat v(s,w)?
    • Linear function approximator
    • ANN
    • CNN

DNN, Deep neural network​

  • Universal function approximator
    • Linear FA limited to linear combinations of features v^(s,w)=x(s)Tw\hat{v}(s, w) = x(s)^T w
    • DNN can represent non-linear mappings of features. s→DNN(w)→v^(s,w)s \rightarrow \text{DNN}(\mathbf{w}) \rightarrow \hat{v}(s, \mathbf{w})
  • Combination of both Linear and Non-Linear transformations
    • z=Wx+bz = Wx + b
    • h=ReLU(z)h = \text{ReLU}(z)
  • It may require exponentially less nodes or parameters to represent the sample Linear function.
  • SGD can be used to learn parameters
    • prediction -> loss -> gradient -> SGD -> ww update.
  • It can generalize from observed states to unseen states.
  • It can handle continuous state spaces, which are common in real world problems.
    • s=(x,y,velocity,angle)s = (x, y, \text{velocity}, \text{angle})
    • s=(2.371,5.826,0.43,⋯ )→DNN→v^(s,w)s = (2.371, 5.826, 0.43, \cdots) \rightarrow \text{DNN} \rightarrow \hat{v}(s, \mathbf{w})
  • E2E learning (learn feature representation and policy together) can be more effective.
  • Function approximation using images, environments with visual observations.
  • DNNs can directly process pixel data and learn from raw images.
  • DNNs can be used in environments with continuous action spaces for approximating policies (Robotics)
  • It can achieve SOTA performance in several complex tasks.

CNN, Convolutional neural network​

  • CONV is the first layer to extract features from an input image.
    • Core building block of a CNN
    • A number of filters such as Edge Detectors are applied to the input image.
  • Padding: add extra pixels around the image to handle edge cases.
    • Valid Padding: no padding, output size is smaller than input size.
      • p=0p = 0.
      • Output size: (n−f+1)×(n−f+1)(n - f + 1) \times (n - f + 1)
      • ff: filter size.
    • Same Padding: add padding so that output size is the same as input size.
      • p=f−12p = \frac{f-1}{2}
  • Stride: the number of pixels the filter moves across the input image.
    • S=1S = 1: Move the filter by one pixel horizontally and vertically.
    • S=2S = 2: Move the filter by two pixels horizontally and vertically.
  • POOL: down sampling operation which reduces the dimensionality of a matrix.
    • It reduces the number of parameters for large image but retain the valuable information.
    • Max pooling: Max(7, 8, 9, 10) = 10
    • Average pooling: Avg(7, 8, 9, 10) = 8.5
    • Sum pooling: Sum(7, 8, 9, 10) = 34
  • FC: The output matrix after convolution layer is flattened and feed into a fully connected layer similar to ANN.
    • It's a traditional Multi-layer Perceptron/Neural Network.
    • For multi-class classification, Softmax activation function is usually used.
    • Output of the CONV and POOL layers represent a high-level features of the Input image.
    • FC layer uses this feature to classify the input image into the desired class.

Deep Reinforcement Learning​

  • Use DNNs to represent
    • Value and Q-Value function (Action-value function)
    • Policy (Policy Gradient methods)
    • Model
  • Use SGD to optimize loss function.
  • RL makes the target, SGD trains DNN to fit the target.
  • In TD: Δw=learning rate×TD error×gradient\Delta w = \text{learning rate} \times \text{TD error} \times \text{gradient}
    • TD error: Rt+1+γq^(st+1,at+1,w)⏟Target−q^(st,at,w)⏟Current Prediction\underbrace{R_{t+1} + \gamma \hat{q}(s_{t+1},a_{t+1},w)}_{\text{Target}} - \underbrace{\hat{q}(s_t,a_t,w)}_{\text{Current Prediction}}
  • In Q-Learning: max⁡a′Q(st+1,a′,w)\max_{a'} Q(s_{t+1},a',w) is the target.

Q-Learning with VFA​

  • Original Q-Learning converges to the optimal Q∗(s,a)Q^*(s, a) using look-up table.
  • VFA Q-Learning minimizes MSD Loss by SGD using target Q estimates instead of true Q.
    • so it can diverge due to the correlation between samples or Non-stationary targets.

Experience Replay​

Environment
│
│ experience
▼
(s, a, r, s')
│
▼
Replay Buffer D
┌──────────────────────┐
│ old experience │
│ old experience │
│ old experience │
│ old experience │
└──────────────────────┘
│
│ random sample
▼
Mini-batch
│
├──────────────► Current Q Network
│ │
│ ▼
│ Q(s,a)
│
└──────────────► Target calculation
│
▼
r + γ max Q(s',a')
│
▼
Target − Prediction
│
▼
SGD
│
▼
Update weights
  • DQN stores past transitions (s,a,r,s′)(s,a,r,s') in a replay buffer and randomly samples them for training, which reduces correlation between consecutive samples and improves training stability.
    • Sample (s,a,r,s′)(s, a, r, s') from D\mathcal{D}
    • Compute the target value of the samples s:(r+γmax⁡a′q^(s′,a′,w))s: (r + \gamma \max_{a'} \hat{q}(s',a',w))
    • Use SGD to update the network weight: Δw=α(r+γmax⁡a′q^(s′,a′,w)−q^(s,a,w))∇wq^(s,a,w)\Delta w = \alpha (r + \gamma \max_{a'} \hat{q}(s',a',w) - \hat{q}(s,a,w))\nabla_w \hat{q}(s,a,w)

Fixed Q-Targets​

[Same structure of network 2]

Current state s Next state s'
│ │
▼ ▼
Online Q Network Target Network
weights = w weights = w⁻
│ │
▼ ▼
Q(s,a;w) max Q(s',a';w⁻)
│ │
└────────── compare ────────────────┘
│
▼
Loss
│
▼
update only w
  • Improve stability by fixing the target weights used in the target calculation for multiple updates.
  • Target network uses different set of weights that the weights being updated.
  • w−w^-: set of weights used in the target.
  • ww: set of weights being updated.

r+γmax⁡a′Q(s′,a′,w−)r + \gamma \max_{a'} Q(s',a',\color{red}w^-\color{black})

  • Sample (s,a,r,s′)(s, a, r, s') from D\mathcal{D}
  • Compute the target value of the samples s:(r+γmax⁡a′Q(s′,a′,w−))s: (r + \gamma \max_{a'} Q(s',a',w^-))
  • Use SGD to update the network weight: Δw=α(r+γmax⁡a′Q(s′,a′,w−)−Q(s,a,w))∇wQ(s,a,w)\Delta w = \alpha (r + \gamma \max_{a'} Q(s',a',w^-) - Q(s,a,w))\nabla_w Q(s,a,w)

DQN​

DQN algorithm

DQN in Atari​

  • E2E learning of Q(s,a)valuesfrompixelsQ(s,a) values from pixels s$
  • Input state ss is a stack or raw pixels from last 4 frames.
  • Output is Q(s,a)Q(s,a) for 18 joystick/button positions
  • Reward is chance in score for that step.
  • Network Architecture and hyper-parameters are fixed across all games.
  • 4x84x84 stack of 4 previous frames -> 16 8x8 filters CONV -> 32 4x4 filters CONV -> 256 hidden units FC -> Fully connected linear output layer.

DQN Atari

RL 008

· 약 9분

RL Taxonomy​

Drawbacks of previous methods​

  • Large state space:
    • Go: 1017010^{170}
    • Backgammon: 102010^{20}
    • Atari games: 109 to 101110^9 \text{ to } 10^{11}
  • Scale-up model-free based techniques for prediction and control is challenging.
  • Value function used look-up table representation
    • All states has an entry in V(s)V(s)
    • All state-action pair (s,a)(s,a) has an entry in Q(s,a)Q(s,a)
  • Too many state, and stat-action pair to store in memory
  • Slow learning process for each states, due to large space.
  • Each states needs to be explored sufficiently.
  • For large MDPs
    • Function approximation: Almost near optimal value.
    • Estimate value function with function approximation.
      • v^(s,w)≈vπ(s)\hat{v}(s,w) \approx v_\pi(s)
      • q^(s,a,w)≈qπ(s,a)\hat{q}(s,a,w) \approx q_\pi(s,a)
    • Generalize from seen states to unseen states.
    • Using MC or TD learning techniques: Update parameter ww.

Function Approximation​

  • A technique for estimating unknown underlying function using historical or available observations.
  • Assumption: an underlying mapping function exists
    • f(x)≈f^(x)f(x) \approx \hat{f}(x)
  • Function: x→fyx \xrightarrow{f} y

Types of Value Function Approximation​

State-value: state ss → scalar v^(s,w)\hat{v}(s,w)

Action-value (s, a input): state ss and action aa → scalar q^(s,a,w)\hat{q}(s,a,w)

Action-value (s input, all actions out): state ss → q^(s,a1,w),…,q^(s,am,w)\hat{q}(s,a_1,w),\ldots,\hat{q}(s,a_m,w)

  • ww is the parameter vector of the function approximator.
    • e.g. Neural Network weights

Types of Function Approximator​

  • Tabular
    • V-Table: s→v(s)s \rightarrow v(s)
    • Q-Table: (s,a)→q(s,a)(s,a) \rightarrow q(s,a)
  • Decision Trees, Nearest Neighbors
    • s=[speed=49,distance=10]s = [\text{speed} = 49, \text{distance} = 10]
    • s→Decision Tree / KNN→v^(s)s \rightarrow \text{Decision Tree / KNN} \rightarrow \hat{v}(s)
  • Linear Function approximation
    • Linear Combination of Features
    • Values are linear function for features v^(s,w)=wTx(s)\hat{v}(s,w) = w^Tx(s)
    • x(s)=[speeddistancefuel]x(s) = \begin{bmatrix} \text{speed} \\ \text{distance} \\ \text{fuel} \end{bmatrix}
    • v^(s,w)=wTx(s)\hat{v}(s,w) = w^Tx(s)
    • v^(s,w)=w1x1(s)+⋯+wnxn(s)\hat{v}(s,w) = w_1x_1(s) + \cdots + w_n x_n(s)
  • Differentiable function approximation
    • v^(s,w)\hat{v}(s,w) is a differentiable function of ww, can be non-linear in ss
    • e.g. Neural Network, or CNN
      • ∂v^(s,w)∂w\frac{\partial \hat{v}(s,w)}{\partial w}
      • w←w−α∇wLw \leftarrow w - \alpha \nabla_wL
      • Pixels→CNNv^(s)\text{Pixels} \xrightarrow{CNN} \hat{v}(s)

Which FA to use?​

In principle, any FA that fits the RL framework can be used.

FANotes
TabularEasy; not scalable; does not generalise
LinearRequires good features
Differentiable (better choice)Scalable; not always well understood
Neural NetworksPerforms well
Deep Neural NetworksPopular choice; performs well
  • Need training methods that are suitable for non-stationary data.

ANN​

Logistic Regression​

L(a,y)=−ylog⁡(a)−(1−y)log⁡(1−a)\mathcal{L}(a, y) = -y \log(a) - (1-y) \log(1-a)

  • Loss function for Logistic Regression

Gradient Descent​

Goal: Find ww tht minimize J(w)J(w) or find a local minimum of J(w)J(w).

  • An iterative approach for error correction.
  • For one sample, L(a,y)=−ylog⁡(a)−(1−y)log⁡(1−a)\mathcal{L}(a, y) = -y \log(a) - (1-y) \log(1-a)
  • For mm samples,

J(w,b)=1m∑i=1mL(a(i),y(i))J(w, b) = \frac{1}{m} \sum_{i=1}^m \mathcal{L}(a^{(i)}, y^{(i)})

  • Find ww and bb that will minimize J(w,b)J(w, b)
    • min⁡w,bJ(w,b)\min_{w, b} J(w, b)
    • J(w)J(w) is loss function.

w←w−α∂J(w,b)∂w,b←b−α∂J(w,b)∂bw \leftarrow w - \alpha \frac{\partial J(w, b)}{\partial w}, \quad b \leftarrow b - \alpha \frac{\partial J(w, b)}{\partial b}

ΔwJ(w)=(∂J(w)∂w1,…,∂J(w)∂wn)\Delta w J(w) = \big(\frac{\partial J(w)}{\partial w_1}, \ldots, \frac{\partial J(w)}{\partial w_n}\big)

  • Adjust the ww in the direction of the -ve gradient.
    • w=w−αΔw,b=b−αΔbw = w - \alpha \Delta w, \quad b = b - \alpha \Delta b
    • where α\alpha is the learning rate.
    • and, Δw=∂J(w,b)∂w,Δb=∂J(w,b)∂b\Delta w = \frac{\partial J(w, b)}{\partial w}, \quad \Delta b = \frac{\partial J(w, b)}{\partial b}

ANN as a Function Approximator​

  • Need a method to estimate: Δw\Delta w
  • Method to incrementally adjust and update: ww
  • Representation of some aspects of RL environments as feature vector x(s)x(s)
  • Aspects can be approximated: V(s) or Q(s,a)V(s) \text{ or } Q(s, a)
    • Estimate value functions with function approximation.
    • V^(s,w)≈V(s)\hat{V}(s, \color{red}{w}\color{black}) \approx V(s)
    • Q^(s,a,w)≈Q(s,a)\hat{Q}(s, a, \color{red}{w}\color{black}) \approx Q(s, a)
  • A mechanism to plugin MC and TD for function approximation.

Value Function Approximation for policy evaluation​

VFA: Value Function Approximation

  • vπ(s)v_\pi(s) is given, so making it supervised.
  • v^(s,w)\hat{v}(s, w) is estimated value if it follows the policy π\pi by using ANN.
  • x→y^vsyx \rightarrow \hat{y} \quad \text{vs} \quad y (supervised learning)
  • s→v^(s,w)vsvπ(s)s \rightarrow \hat{v}(s, w) \quad \text{vs} \quad v_\pi(s) (Reinforcement learning)

J(w)=Eπ[(vπ(s)−v^(s,w))2] J(w) = \mathbb{E}_\pi[\big(v_\pi(s) - \hat{v}(s, w)\big)^2]

  • Find ww that minimizes J(w)J(w)
    • J(w)J(w): Loss function.
    • v^(s,w)\hat{v}(s, w): Guess from the value function approximation.
    • vπ(s)−v^(s,w)v_\pi(s) - \hat{v}(s, w): Error between the true value and the estimated value.
    • Eπ[⋅]\mathbb{E}_\pi[\cdot]: Expected average over all states ss according to the policy π\pi.
Δw=−12α∇wJ(w)Δw=αEπ[(vπ(s)−v^(s,w))⏟Error∇wv^(s,w)⏟Gradient]\begin{aligned} & \Delta w = -\frac{1}{2} \alpha \nabla_w J(w) \\ & \Delta w = \alpha \mathbb{E}_\pi[\underbrace{\big(v_\pi(s) - \hat{v}(s, w)\big)}_{Error} \underbrace{\nabla_w \hat{v}(s, w)}_{Gradient}] \end{aligned}
  • Δw=\Delta w = Step size X Error X Gradient

VFA with SGD​

Δw=α(vπ(s)−v^(s,w))∇wv^(s,w) \Delta w = \alpha (v_\pi(s) - \hat{v}(s, w)) \nabla_w \hat{v}(s, w)

  • Stochastic Gradient Descent sample the gradient
  • Sample a state randomly, find what vπ(s)v_\pi(s) is, and find the estimate
    • Δw=α[Error at s×Gradient at s]\Delta w = \alpha [\text{Error at } s \times \text{Gradient at } s]
    • Sample sts_t from π\pi, and update ww
  • Expected value update using SGD update is same as full gradient update
    • Random sampling will be eventually the same as full gradient update

Linear Value Function Approximation​

  • Represent Value function (state or action) by a linear combination of features
    • v^(s,w)=x(s)Tw=∑j=0nxj(s)wj\hat{v}(s, w) = x(s)^Tw = \sum_{j=0}^n x_j(s) w_j
  • Loss function: J(w)=Eπ[(vπ(s)−v^(s,w))2]J(w) = \mathbb{E}_\pi[\big(v_\pi(s) - \hat{v}(s, w)\big)^2]

Δw=α(vπ(s)−v^(s,w))⏟Errorx(s)⏟Feature\Delta w = \alpha \underbrace{\big(v_\pi(s) - \hat{v}(s, w)\big)}_{Error} \underbrace{x(s)}_{Feature}

  • Weight update: step size X Error X Feature value
  • SGD converges to global mininum

Incremental methods for prediction​

  • Real-world RL is not supervised, instead, it is guided by rewards.
  • No vπ(s)v_\pi(s) is given.
  • Instead, substitute a target for vπ(s)v_\pi(s)

Δw=α(Gt−v^(st,w))∇wv^(st,w) \Delta w = \alpha(G_t - \hat{v}(s_t, w)) \nabla_w \hat{v}(s_t, w)

  • Monte Carlo updates: target is the return GtG_t

Δw=α(Rt+1+γv^(st+1,w)⏟TD Target−v^(st,w))∇wv^(st,w) \Delta w = \alpha(\underbrace{R_{t+1} + \gamma \hat{v}(s_{t+1}, w)}_{\text{TD Target}} - \hat{v}(s_t, w)) \nabla_w \hat{v}(s_t, w)

  • TD updates: use TD Target

VFA for Monte Carlo​

  • MC return GtG_t is an unbiased, noisy sample of true value vπ(st)v_\pi(s_t)
    • if Gt=3,7,4,6,5,⋯G_t = 3, 7, 4, 6, 5, \cdots
    • but in average, 1N∑i=1NGt(i)≈vπ(s)\frac{1}{N} \sum_{i=1}^N G_t^{(i)} \approx v_\pi(s)
  • ⟨S1,G1⟩,⟨S2,G2⟩,⋯ ,⟨SN,GN⟩\langle S_1, G_1 \rangle, \langle S_2, G_2 \rangle, \cdots, \langle S_N, G_N \rangle is an estimate of vπ(s)v_\pi(s)
    • x→yx \rightarrow y (supervised learning)
    • st→Gts_t \rightarrow G_t (Reinforcement learning)
  • so it learns to v^(s,w)≈Gt\hat{v}(s, w) \approx G_t
Δw=α(Gt−v^(s,w))∇wv^(s,w)Δw=α(Gt−v^(s,w))x(s)\begin{aligned} & \Delta w = \alpha(G_t - \hat{v}(s, w)) \nabla_w \hat{v}(s, w) \\ & \Delta w = \alpha \big(G_t - \hat{v}(s, w)\big) x(s) \end{aligned}
  • In Linear VFA, v^(s,w)=wTx(s)\hat{v}(s,w) = w^Tx(s)
    • x(s)x(s) is the feature vector of state ss
    • ww is the weight vector
    • so ∇wv^(s,w)=∇w(wTx(s))=x(s)\nabla_w \hat{v}(s, w) = \nabla_w (w^Tx(s)) = x(s)
  • Update = Learning rate X Error X state features
Initialize w=0,k=1Loop:Sample k-th episode (sk1,ak1,rk1,...,SkLk) using policy πFor t=1,...Lk:if First Visit to (s) in episode k,thenGt(s)=∑j=tLkγk,jWeight update: w←w−α(Gt−v^(s,w))x(s)k=k+1\begin{aligned} & \text{Initialize } w = 0, k = 1 \\ & Loop: \\ & \quad \text{Sample k-th episode } (s_{k1}, a_{k1}, r_{k1}, ..., S_{kL_k}) \text{ using policy } \pi \\ & \quad \text{For } t = 1, ... L_k: \\ & \quad \quad \text{if First Visit to } (s) \text{ in episode } k, then \\ & \quad \quad \quad G_t(s) = \sum_{j=t}^{L_k} \gamma_{k,j} \\ & \quad \quad \quad \text{Weight update: } \quad w \leftarrow w - \alpha(G_t - \hat{v}(s,w))x(s) \\ & \quad \quad k = k + 1 \\ & \end{aligned}
  • Gt=Rt+1+γRt+2+γ2Rt+3+⋯+γLk−tRLkG_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots + \gamma^{L_k-t} R_{L_k}

VFA for TD Learning​

  • Use bootstrapping and sampling to approximate the target vπv_\pi
    • Sampling: Use a sampled transition St,At,Rt+1,St+1S_t, A_t, R_{t+1}, S_{t+1} instead of computing the full expectation over possible transitions.
    • Bootstrapping: Construct the TD target using the current estimate v^(St+1,w)\hat{v}(S_{t+1}, w), instead of waiting for the complete episodic return.

Rt+1+γv^(St+1,w)R_{t+1} + \gamma \hat{v}(S_{t+1}, w)

  • TD Target is a biased sample of true value vπ(St)v_\pi(S_t)
  • Can use supervised learning on a training set of ⟨S,R⟩\langle S, R \rangle paris
    • ⟨S1,R2+γv^(S2,w)⟩,⟨S2,R3+γv^(S3,w)⟩,⋯ ,⟨ST−1,RT⟩\langle S_1, R_2 + \gamma \hat{v}(S_2, w) \rangle, \langle S_2, R_3 + \gamma \hat{v}(S_3, w) \rangle, \cdots, \langle S_{T-1}, R_T \rangle

Δw=α(R+γv^(s′,w)−v^(s,w))∇wv^(s,w) \Delta w = \alpha(R + \gamma \hat{v}(s', w) - \hat{v}(s, w)) \nabla_w \hat{v}(s, w)

  • Linear VFA + TD(0) for prediction and policy evaluation
  • TD Error: δt=Rt+1+γv^(St+1,w)−v^(St,w)\delta_t = R_{t+1} + \gamma \hat{v}(S_{t+1}, w) - \hat{v}(S_t, w)
  • Δw=αδt∇wv^(St,w)\Delta w = \alpha \delta_t \nabla_w \hat{v}(S_t, w)
    • ∇wv^(s,w)=x(s)\nabla_w \hat{v}(s, w) = x(s)
    • Δw=αδtx(s)\Delta w = \alpha \delta_t x(s)
    • w←w−αδtx(s)w \leftarrow w - \alpha \delta_t x(s)
Initialize w=0Loop:Initialize sSample transition (s,a,r,s′) using policy πWeight update: w←w−α(R+γv^(s′,w)−v^(s,w))x(s)\begin{aligned} & \text{Initialize } w = 0 \\ & Loop: \\ & \quad \text{Initialize } s \\ & \quad \text{Sample transition } (s, a, r, s') \text{ using policy } \pi \\ & \quad \text{Weight update: } \quad w \leftarrow w - \alpha(R + \gamma \hat{v}(s', w) - \hat{v}(s, w))x(s) \\ & \end{aligned}

Overall​

  • Linear VFA: v^(s,w)=wTx(s)\hat{v}(s, w) = w^Tx(s)
  • MC Target = GtG_t
  • TD Target = Rt+1+γv^(s′,w)R_{t+1} + \gamma \hat{v}(s', w)
  • MC: w←w+α(Gt−v^(s,w))x(s)w \leftarrow w + \alpha(G_t - \hat{v}(s, w)) x(s)
  • TD: w←w+α(Rt+1+γv^(s′,w)−v^(s,w))x(s)w \leftarrow w + \alpha(R_{t+1} + \gamma \hat{v}(s', w) - \hat{v}(s, w))x(s)

IPPR 003

· 약 10분

Feature Detection​

  1. Detect invariant features of the image.
  2. Describe the local area around each feature.
  3. Match patterns of the feature descriptions.

Moravec conner detector​

E(u,v)=∑x,y[I(x,y)−I(x+u,y+v)]2E(u, v) = \sum_{x, y} [I(x, y) - I(x + u, y + v)]^2

  • One of the earliest corner detectors (1980)
  • Moravec detects a corner by shifting a small window in different directions and checking whether the image changes significantly in every direction.
    • Shifting a window in any direction should give a large change in intensity, measured in terms of Sum of Squared Differences (SSD).
  • (u,v)(u, v) is how much the window is shifted.
  • Larger EE indicates the image changes more after the shift.

Moravec corner detection

  • Flat: E≈0E \approx 0, No change in any direction
  • Edge: E≈1E \approx 1, Change in some direction
  • Corner: E≈40E \approx 40, Large change in every direction

Harris corner detector​

E(x,y)=∑u∑vW(u,v)⏟Window function[I(u+x,v+y)⏟Shifted Intensity−I(u,v)⏟Intensity]2 E(x, y) = \sum_{u}\sum_{v} \underbrace{W(u, v)}_{\text{Window function}} [\underbrace{I(u + x, v + y)}_{\text{Shifted Intensity}} - \underbrace{I(u, v)}_{\text{Intensity}}]^2

  • Improvement over Moravec change of intensify for a shifted windoe centered at (u,v)(u, v)

Harris corner detection

  • (x,y)=(1,0)→(x, y) = (1, 0) \rightarrow move 1px to the right.
  • (x,y)=(0,1)→(x, y) = (0, 1) \rightarrow move down 1px.
  • (x,y)=(2,1)→(x, y) = (2, 1) \rightarrow move 2px to the right and 1px down.
  • I(u,v)I(u, v): Pixel intensity of the original point.
  • I(u+x,v+y)I(u + x, v + y): Pixel intensity of the shifted point.
  • SSD: if I(u,v)=65I(u,v) = 65, and I(u+x,v+y)=124I(u + x, v+ y) = 124, then the SSD is (124−65)2=3481(124 - 65)^2 = 3481.
  • w(u,v)w(u, v): window function, usually apply gaussian weighting to the pixels around the center.
    • if we calculate all the (x,y)(x, y) step by step, it will be computationally expensive.
    • so we use Taylor Expansion to approximate the intensity change.

Taylor Expansion​

I(u+x,v+y)≈I(u,v)+Ix(u,v)x+Iy(u,v)yI(u + x, v + y) \approx I(u, v) + I_x(u, v)x + I_y(u, v)y

  • Let IxI_x and IyI_y be the partial derivatives of II
  • Approximates the intensity of the slightly shifted point, using the current intensity and gradient information.
  • Ix=∂I∂xI_x = \frac{\partial I}{\partial x}: How much the intensity changes when moving to the right or left a little bit.
  • Iy=∂I∂yI_y = \frac{\partial I}{\partial y}: How much the intensity changes when moving up or down a little bit.

E(x,y)≈∑u∑vw(u,v)[Ix(u,v)x+Iy(u,v)y]2E(x, y) \approx \sum_{u}\sum_{v} w(u, v) [I_x(u, v)x + I_y(u, v)y]^2

  • because I(u+x,v+y)≈I(u,v)+Ix(u,v)x+Iy(u,v)yI(u + x, v + y) \approx I(u, v) + I_x(u, v)x + I_y(u, v)y.
  • we can calculate intensity change by x/y gradient and the window shift.
  • (ax+by)2=a2x2+2abxy+b2y2=[x,y][a2ababb2][xy](ax + by)^2 = a^2x^2 + 2abxy + b^2y^2 = [x, y] \begin{bmatrix} a^2 & ab \\ ab & b^2 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix}

E(x,y)=[x,y][∑u∑vw(u,v)Ix2∑u∑vw(u,v)IxIy∑u∑vw(u,v)IxIy∑u∑vw(u,v)Iy2]⏟A[xy]E(x,y) = [x, y] \underbrace{\begin{bmatrix} \sum_{u}\sum_{v} w(u, v) I_x^2 & \sum_{u}\sum_{v} w(u, v) I_xI_y \\ \sum_{u}\sum_{v} w(u, v) I_xI_y & \sum_{u}\sum_{v} w(u, v) I_y^2 \end{bmatrix}}_{A} \begin{bmatrix} x \\ y \end{bmatrix}

  • Eigenvector = direction of the change
  • Eigenvalue = magnitude of the change
  • if both λ1 and λ2≈0\lambda_1 \text{ and } \lambda_2 \approx 0, the point is flat.
  • if either λ1 or λ2≫0\lambda_1 \text{ or } \lambda_2 \gg 0 the point is an edge.
  • if both λ1 and λ2≪0\lambda_1 \text{ and } \lambda_2 \ll 0 the point is a corner.

R=det⁡(A)−k(trace(A))2R = \det(A) - k(\text{trace}(A))^2

  • det⁡(A)=λ1λ2\det(A) = \lambda_1 \lambda_2
    • it can check if the point is a corner by checking if λ1 and λ2\lambda_1 \text{ and } \lambda_2 are both large.
  • trace(A)=λ1+λ2\text{trace}(A) = \lambda_1 + \lambda_2
    • it can penalizes edge-like responses where one eigenvalue is large but the other is small.
  • R=λ1λ2−k(λ1+λ2)2R = \lambda_1 \lambda_2 - k(\lambda_1 + \lambda_2)^2
    • kk is an empirical constant, typically set 0.04≤k≤0.060.04 \leq k \leq 0.06.
    • A threshold is applied an corners detected, non-maxima are suppressed.
    • RR can be derived from eigenvalues of the matrix AA.
    • R≈0R \approx 0 the point is flat.
    • R<0R < 0 the point is an edge.
    • R≫0R \gg 0 the point is a corner.

Harris corner detection pipeline​

  • Compute the Harris response RR for every pixel.
  • Large positive RR indicates a strong corner response.
  • Apply a threshold to remove weak responses.
  • Apply non-maximum suppression to keep only local maxima.
  • Overlay the remaining points on the original image as detected corners.

Detector vs descriptor​

  • Detector: detect the location of the features in an image or video (WHERE).
  • Descriptor: descriptors summarize the appearance of the neighborhood (WHAT IT LOOKS LIKE).
  • A good feature detector should be:
    • make similar descriptors for similar features of the same object.
    • Invariance: the descriptor should be invariant to translation, rotation, scale, and illumination.

SIFT​

Scale-Invariant Feature Transform

  • It was proposed by Lowe in 1999, includes both a detector and a descriptor.
  • A method to detect and match local features despite changes in scale and rotation.
  • Core idea: build multiple blurred versions of the image, compute their differences, and find points that stand out across scales.
  1. Build a scale-space pyramid of Differences of Gaussians (DoG) and detect minima/maxima.
  2. Localize keypoints.
  3. Assign them an orientation.
  4. Compute the SIFT descriptor.

DoG pyramid

  • L(x,y,σ)=G(x,y,σ)∗I(x,y)L(x, y, \sigma) = G(x, y, \sigma) * I(x, y): Blurred image at scale σ\sigma.
  • D(x,y,σ)=L(x,y,kσ)−L(x,y,σ)D(x, y, \sigma) = L(x, y, k\sigma) - L(x, y, \sigma): Difference of Gaussians at scale σ\sigma.
  • Octave: a group of scale-space images at the same resolution.
  • After each octave, the image is typically downsampled by a factor of 2.

DoG octave

Key point localization​

Image→Gaussian scale space→DoG→DoG extrema→Filter low-contrast and edge responses→Keypoints\text{Image} \rightarrow \text{Gaussian scale space} \rightarrow \text{DoG} \rightarrow \text{DoG extrema} \rightarrow \text{Filter low-contrast and edge responses} \rightarrow \text{Keypoints}

  • Detect local maxima and minima in DoG scale space.
  • Remove low-contrast points because they are unstable and sensitive to noise.
  • Remove edge responses because their locations are poorly localized.
  • Use the ratio of principal curvatures to distinguish edges from stable corner/blob-like features.
  • Example: 832→729→536832 \rightarrow 729 \rightarrow 536

DoG Keypoints

  • (a): Original image (233x189)
  • (b): 832 DoG extrema
  • (c): 729 left after peak-value threshold
  • (d): left after testing the ratio of principal curvatures.

Orientation assignment​

  • For every keypoint, compute the gradient at each location in its local neighborhood.
  • The gradients are computed on the Gaussian-blurred image at the keypoint's scale, σ\sigma.
  • Gradient directions are quantized into 36 bins over 360∘360^\circ.
  • Each gradient contributes to the histogram according to its magnitude.
  • The dominant histogram bin is assigned as the keypoint's orientation.
    • [10,20,20,30,20]→20[10, 20, 20, 30, 20] \rightarrow 20
    • This orientation becomes the anchor direction for the SIFT descriptor.

SIFT descriptor​

SIFT descriptor = 128-dimensional vector

  • A 16x16 grid of locations of the gradient at σ\sigma scale around the keypoint.
  • The grid is divided into 4x4 sub-grids of 4x4 locations each.
  • For each sub-grid, an 8-bin histogram of the magnitude weighted gradient orientation is computed.
    • All 8 bins are retained.
  • The histogram from all the sub-grids are concatenated into the SIFT descriptor.
    • The dimensionality is given by 8 bins x 16 histograms = 128.

Image→Gaussian scale space→DoG→DoG extrema→Filter low-contrast and edge responses→Keypoints→Assign orientation→Build 128-D descriptor\text{Image} \rightarrow \text{Gaussian scale space} \rightarrow \text{DoG} \rightarrow \text{DoG extrema} \rightarrow \text{Filter low-contrast and edge responses} \rightarrow \text{Keypoints} \rightarrow \text{Assign orientation} \rightarrow \text{Build 128-D descriptor}

SIFT descriptor

  • SIFT Features encode information about at 16x16 area around the feature point at the appropriate scale.
  • It is scale, rotation, and translation invariant.
  • Similar features give similar SIFT values regardless of orientation, scale, and translation.

SIFT wolf

Applications of SIFT​

  • Object recognition: SIFT descriptors are extracted from an input image and matched to the SIFT descriptors of known objects in a database.
  • Stereo vision: SIFT descriptors from the left and right images are matched to create the disparity map.
  • Tracking: SIFT descriptors from successive frames are matched to track a target.
  • Object and action classification: histograms of SIFT descriptors are computed over single frames or whole videos and used as input for a classifier.

Object classification​

  • Object classification uses histograms of SIFT descriptors to characterize the class of an object.
  • A popular histogram representation is called Bag of Features (BoF).
    • BoF first requires creating a dictionary, also called a codebook, from the training set.
    • Once the dictionary is computed, a Bag of Features can be computed for any image.
    • The resulting Bag of Features is then used for classification.
# Example SIFT descriptors from training images
descriptors = [
[1.0, 1.2],
[0.9, 1.1],
[1.1, 0.8],

[5.0, 5.1],
[4.8, 5.2],
[5.2, 4.9],

[9.0, 1.0],
[8.8, 1.2],
]

# Representative descriptors after clustering
codebook = [
[1.0, 1.0], # codeword 1
[5.0, 5.0], # codeword 2
[9.0, 1.0], # codeword 3
]

# SIFT descriptors from a new image
new_image_descriptors = [
[1.2, 0.9],
[0.8, 1.1],
[5.1, 4.9],
[9.2, 1.1],
[8.9, 0.8],
]

# Nearest codeword assignments
assignments = [
0, # -> codeword 1
0, # -> codeword 1
1, # -> codeword 2
2, # -> codeword 3
2, # -> codeword 3
]

# Bag of Features histogram
bof = [2, 1, 2]

Dictionary creation​

  • Extract all SIFT descriptors from the training images.
  • Use a clustering algorithm, typically k-means, to group the descriptors into kk clusters.
  • The descriptor space is partitioned into kk regions.
    • Example: k=1000k=1000.
  • The resulting clusters form the dictionary/codebook.

Detection creation

Bag of Features​

  • Map all SIFT descriptors of an image to clusters in the dictionary.
  • Count the number of descriptors assigned to each cluster.
  • Form a histogram with kk bins.
  • Use this histogram as a measurement vector for a classifier.
  • Possible classifiers include Bayes, SVM, KNN, and neural networks.

Other Local Features​

  • SURF (Speeded Up Robust Features): another local feature method designed to provide robust features with faster computation.
  • GLOH (Gradient Location and Orientation Histogram): describes local image structure using gradient location and orientation histograms.
  • HOG (Histogram of Oriented Gradients): represents local regions using histograms of gradient orientations.
  • For classification, descriptors can be extracted either from detected interest points or from a regular grid.
  • Descriptors extracted from a regular grid are called dense features.

Spatio-temporal local features​

  • In video, local features can be extracted from each frame separately or as 3D local features.
  • Here, “3D” means x,y,tx, y, t, where tt is time.
  • These are called spatio-temporal features.
  • They describe the appearance of local cuboids across space and time.

Cuboids

Other Spatio-temporal local features​

  • HOG/HOF: Histogram of Optical Flow.
  • HOG3D: a spatio-temporal extension of HOG.
  • ESURF: Extended SURF.
  • MBH: Motion Boundary Histograms.
  • DTF: Dense Trajectory Features.
  • For classification, these descriptors can be computed either at detected points or over a regular grid.

Object Classification FLow​

Object Classification Flow

  • Local descriptors: An image is represented by many local feature descriptors such as SIFT or HOG. The result is a set of descriptors, not a single vector.
  • Encoding: Since different images can produce different numbers of descriptors, the set of descriptors is converted into one fixed-length vector. Bag of Features, VLAD, and Fisher Vector are different encoding methods for this purpose.
    • Bag of Features: Each descriptor is assigned to the nearest representative feature, and the number of descriptors assigned to each representative feature is counted.
    • VLAD: Instead of only counting assignments, VLAD stores how each descriptor differs from its nearest representative feature.
    • Fisher Vector: It represents how the descriptors differ from a learned feature distribution, capturing more detailed statistical information.
  • Classifier: The encoded fixed-length vector is given to a classifier, which outputs a class label such as car, person, or dog.
  • Main idea: SIFT describes many local regions, while BoF, VLAD, and Fisher Vector combine those local descriptions into one image-level vector for classification.

RL 007

· 약 7분

Temporal-Difference Learning​

Updates a guess towards a guess.

  • Model-free: No MDP Dynamics or Rewards
  • Learns directly from episodes of experience.
  • Bootstrapping: Estimate value function using estimated value from incomplete episodes.
    • Update estimate using another estimate.
  • Updates the estimate of VV immediately after each step.
  • Combines Monte Carlo and Dynamic Programming (Bootstrapping idea).

MC​

V(St)=V(St)+α[Gt⏟Goal−V(St)⏟Previous estimate]V(S_t) = V(S_t) + \alpha [\underbrace{G_t}_{\text{Goal}} - \underbrace{V(S_t)}_{\text{Previous estimate}} ]

  • Update V(St)V(S_t) towards the actual return.
  • α=1n\alpha = \frac{1}{n}: Every-visit MC.
    • gives equal weight to all past samples in the arithmetic mean.
  • Fixed α>1n\alpha > \frac{1}{n}: gives more weight to recent experience and reduces the influence of older episodes faster.
    • α=0.1,V(S)=10\alpha = 0.1, \quad V(S) = 10
    • V(S)←10+0.1(20−10)=11V(S) \leftarrow 10 + 0.1 (20 - 10) = 11
    • V(S)←11+0.1(30−11)=12.9V(S) \leftarrow 11 + 0.1 (30 - 11) = 12.9
    • Move 10% of the way towards the new value.

One-Step Bootstrapping​

TD(0)→TD(λ)→TD(1)≈MC\text{TD}(0) \rightarrow \text{TD}(\lambda) \rightarrow \text{TD}(1) \approx \text{MC}

  • λ\lambda controls how much longer-term return information is used in the TD update.
    • It controls how far into the future TD learns from.
  • λ=0\lambda = 0: uses one-step bootstrapping, corresponding to TD(0).
  • As λ\lambda increases, rewards further into the future have more influence on the update.
  • λ=1\lambda = 1: approaches the Monte Carlo return in episodic tasks.

V(St)=V(St)+α[Rt+1+γV(St+1)⏟TD target−V(St)⏟TD Error]V(S_t) = V(S_t) + \alpha [\underbrace{\underbrace{R_{t+1} + \gamma V(S_{t+1})}_{\text{TD target}} - V(S_t)}_{\text{TD Error}} ]

  • Only one immediate reward is used Rt+1R_{t+1}.
  • Everything after that is replaced by the current guess V(St+1)V(S_{t+1}) instead of actual future rewards.
  • It uses actual reward for the first step and the estimated value/guess for the rest.
MC
Sₜ ──Rₜ₊₁──> Sₜ₊₁ ──Rₜ₊₂──> ... ──> Terminal
│ │
└────────── episode 끝까지 기다림 ────────┘
↓
actual Gₜ
↓
V(Sₜ) update


TD(0)
Sₜ ──Rₜ₊₁──> Sₜ₊₁ ── ? ──> ...
│ │
│ └─ current V(Sₜ₊₁)
│
└── Rₜ₊₁ + γV(Sₜ₊₁)로 즉시 V(Sₜ) update

TD(0) Algorithm​

Loop for each episode:InitializeSLoop for each step of the episode:A←action given by policyπTake actionA,observeR,S′V(S)←V(S)+α[R+γV(S′)−V(S)]S←S′UntilS is terminal\begin{aligned} &\text{Loop for each episode:} \\ &\quad \text{Initialize} \quad S \\ &\quad \text{Loop for each step of the episode:} \\ &\quad \quad A \leftarrow \text{action given by policy} \quad \pi \\ &\quad \quad \text{Take action} \quad A, \quad \text{observe} \quad R, \quad S' \\ &\quad \quad V(S) \leftarrow V(S) + \alpha [R + \gamma V(S') - V(S)] \\ &\quad \quad S \leftarrow S' \\ &\quad \text{Until} \quad S \text{ is terminal} \\ \end{aligned}
  • No need to wait until the end of the episode to update the value function.

MC vs. TD​

AspectMonte Carlo (MC)Temporal-Difference (TD)
Learning sequenceLearns from complete episodesLearns from incomplete episodes
TargetActual return GtG_tEstimated return using bootstrapping
Update timingAfter the episode endsBefore the episode ends / step by step
Future informationUses actual future rewardsUses observed reward(s) + estimated future value
BootstrappingNoYes
BiasUnbiasedBiased
VarianceHighLow
EnvironmentEpisodic / terminating environmentsAlso works in continuing / non-terminating environments
Practical speedSlower updatesFaster updates in practice

RMS Error Comparison between MC and TD

  • In practice, TD is faster than MC because it can learn from incomplete episodes.

MC, TD, and DP

  • MC: Full sampled path to the end.
  • TD: Just one real step.
  • DP: Every branch, weighted by probability, no sampling.

Backup Methods

SARSA​

St,At,Rt+1,St+1,At+1S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}

  • Follows generalized Policy Iteration.
    • Policy Evaluation: TD Policy Evaluation Q≈qπQ \approx q_\pi
    • Policy Improvement: ϵ\epsilon-greedy policy improvement, allowing exploration.
    • Update happens after every time step.
  • Use TD methods for evaluation. Q(S,A)Q(S, A)
  • TD Evaluation + ϵ\epsilon-greedy Policy Improvement = SARSA

Q(St,At)=Q(St,At)+α[Rt+1+γQ(St+1,At+1)⏟TD target−Q(St,At)]Q(S_t, A_t) = Q(S_t, A_t) + \alpha [\underbrace{R_{t+1} + \gamma Q(S_{t+1}, A_{t+1})}_{\text{TD target}} - Q(S_t, A_t)]

  • (St,At,Rt+1,St+1,At+1)(S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}): transition from one state-action pair to the next.
  • The process repeatedly alternates between improving QQ and improving the policy.
  • The estimates gradually move toward the optimal action-value function q∗q_* and the optimal policy π∗\pi_*.
  • Unlike classical policy iteration, SARSA does not need to complete policy evaluation before improving the policy.

SARSA Example​

  • Q(St,At)=10Q(S_t,A_t)=10
  • Rt+1=2R_{t+1}=2
  • γ=0.9\gamma=0.9
  • α=0.5\alpha=0.5
  • Q(St+1,At+1)=8Q(S_{t+1},A_{t+1})=8
  • TD Target =2+0.9(8)=9.2=2+0.9(8)=9.2
  • TD Error =9.2−10=−0.8=9.2-10=-0.8
  • Updated Q(St,At)=10+0.5(−0.8)=9.6Q(S_t,A_t)=10+0.5(-0.8)=9.6

SARSA Algorithm​

Loop for each episode:InitializeSChooseAt from St using policy π derived from QLoop for each step of the episode:Take actionAt+1,observeRt+1,St+1Q(St,At)←Q(St,At)+α[Rt+1+γQ(St+1,At+1)−Q(St,At)]St←St+1At←At+1UntilS is terminal\begin{aligned} &\text{Loop for each episode:} \\ &\quad \text{Initialize} \quad S \\ &\quad \text{Choose} A_t \text{ from } S_t \text{ using policy } \pi \text{ derived from } Q\\ &\quad \text{Loop for each step of the episode:} \\ &\quad \quad \text{Take action} \quad A_{t+1}, \quad \text{observe} \quad R_{t+1}, \quad S_{t+1} \\ &\quad \quad Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha [R_{t+1} + \gamma Q(S_{t+1}, A_{t+1}) - Q(S_t, A_t)] \\ &\quad \quad S_t \leftarrow S_{t+1} \\ &\quad \quad A_t \leftarrow A_{t+1} \\ &\quad \text{Until} \quad S \text{ is terminal} \\ \end{aligned}
  • As SARSA learns, each episode is completed faster.
  • As the Q-values improve, the agent learns better actions for each state and reaches the goal using fewer steps.

Q-Learning​

  • On-policy: SARSA, behavior policy is the same as the target policy.
  • Off-policy: Q-Learning, behavior policy is different from the target policy. Q(S,A)Q(S, A)
  • Update Q(St,At)Q(S_t, A_t) toward the value of the alternative, best action.

Q(St,At)=Q(St,At)+α[Rt+1+γmax⁡aQ(St+1,a)⏟TD target−Q(St,At)] Q(S_t, A_t) = Q(S_t, A_t) + \alpha [\underbrace{R_{t+1} + \gamma \max_{a} Q(S_{t+1}, a)}_{\text{TD target}} - Q(S_t, A_t)]

  • The Actual next action is replaced by the Best possible action.
  • Q(St,At)=10Q(S_t, A_t)=10
  • Rt+1=2R_{t+1}=2
  • γ=0.9\gamma=0.9
  • α=0.5\alpha=0.5
  • Q(St+1,a1)=8Q(S_{t+1}, a_1)=8
  • Q(St+1,a2)=11Q(S_{t+1}, a_2)=11
  • Q(St+1,a3)=5Q(S_{t+1}, a_3)=5
  • TD Target =2+0.9(11)=11.9=2+0.9(11)=11.9
  • TD Error =11.9−10=1.9=11.9-10=1.9
  • Updated Q(St,At)=10+0.5(1.9)=10.95Q(S_t, A_t)=10+0.5(1.9)=10.95

Q-Learning Algorithm​

Loop for each episode:InitializeSLoop for each step of the episode:At fromSt using policy π derived from QTake actionAt+1,observeRt+1,St+1Q(St,At)←Q(St,At)+α[Rt+1+γmax⁡aQ(St+1,a)−Q(St,At)]St←St+1UntilS is terminal\begin{aligned} &\text{Loop for each episode:} \\ &\quad \text{Initialize} \quad S \\ &\quad \text{Loop for each step of the episode:} \\ &\quad \quad A_t \text{ from} S_t \text{ using policy } \pi \text{ derived from } Q\\ &\quad \quad \text{Take action} \quad A_{t+1}, \quad \text{observe} \quad R_{t+1}, \quad S_{t+1} \\ &\quad \quad Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha [R_{t+1} + \gamma \max_{a} Q(S_{t+1}, a) - Q(S_t, A_t)] \\ &\quad \quad S_t \leftarrow S_{t+1} \\ &\quad \text{Until} \quad S \text{ is terminal} \\ \end{aligned}

Cliff Walking​

Cliff Walking

  • SARSA (on-policy) accounts for ε-greedy exploration near the cliff and learns the safer route.
  • Q-Learning (off-policy) learns the optimal route.
    • but occasionally falls off the cliff during exploration, hurting its online performance

Cliff Walking Rewards

AspectSARSAQ-Learning
Policy typeOn-policyOff-policy
Bootstrap targetQ(St+1,At+1)Q(S_{t+1},A_{t+1})max⁡aQ(St+1,a)\max_a Q(S_{t+1},a)
Next action usedAction actually takenBest possible action
LearnsValue of the behavior policy being followedOptimal policy π∗\pi_*
Cliff WalkingSafer pathOptimal but riskier path

RL 006

· 약 12분

Known MDP vs Unknown MDP​

AspectKnown MDPUnknown MDP
Environment Knowledge (P,RP, R)Full knowledge of state transition dynamics PP and reward function RRPP and RR are unknown; agent must explore the environment
Problem ApproachWell-defined optimization problem →\rightarrow Pure planning via computationTrial-and-error interaction →\rightarrow Must learn and optimize simultaneously
Primary GoalDirectly compute the optimal policy (π∗\pi_*)Learn and optimize policies without prior model knowledge
Representative MethodsValue Iteration, Policy Iteration (Dynamic Programming)Monte Carlo, Q-Learning, SARSA (Reinforcement Learning)
ParadigmModel-based (Planning)Model-free (Reinforcement Learning)

Model-based vs Model-free​

AspectModel-Based LearningModel-Free Learning
Model Access (P,RP, R)Has full access to transition dynamics PP and reward function RRNo access to environment dynamics (PP and RR are unknown)
Optimization ApproachDirect mathematical computation and planning using the known modelDirect learning and trial-and-error optimization through interaction
Estimation SourceComputes values and optimal policy π∗\pi_* via dynamic programming equationsEstimates vπ,qπv_\pi, q_\pi, and π∗\pi_* directly from sampled experience
Computation vs. SamplingPure computation / Planning (requires no real-time environment sampling)Sample-based learning (requires trajectories / episodic experience)
Typical MethodsPolicy Iteration, Value Iteration (DP)Monte Carlo Methods, TD Learning, Q-Learning, SARSA

Monte Carlo Methods​

  • A Computational technique that uses random sampling and statistical methods to solve complex problems and estimate numerical results.
    • Named after the Monte Carlo Casino in Monaco.
    • It means Estimate an unknown quantity by sampling, and averaging what you observe.
  • Used fo any estimation method whose operation involves a significant random component.
  • Used in mathematics, physics, engineering, finance, computer science, etc.
  • It is particularly valuable when an analytical solution is difficult or impossible to obtain.

Estimating π\pi by Sampling (Monte Carlo Simulation)​

  • Mechanism:
    • Generate uniform random points (x,y)∈[−1,1]×[−1,1](x, y) \in [-1, 1] \times [-1, 1].
    • Count points falling inside the unit circle (x2+y2≤1x^2 + y^2 \le 1).
    • Estimate π\pi via area proportions:
AreacircleAreasquare=π4π≈4×#points inside circle#total points\begin{aligned} \frac{\text{Area}_{circle}}{\text{Area}_{square}} = \frac{\pi}{4} \\ & \pi \approx 4 \times \frac{\text{\#points inside circle}}{\text{\#total points}} \end{aligned}
  • Empirical Validation:
    • Total samples (nn): 30003000 points
    • Estimated value: π=3.1386666666666665\pi = 3.1386666666666665
    • Relative error: −0.0931%-0.0931\% from true value (≈3.14159265\approx 3.14159265)

Monte Carlo

Monte Carlo Prediction​

vπ(s)=Eπ[Gt∣St=s]≈1N∑i=1N(s)G(i)v_\pi(s) = \mathbb{E}_{\pi}[G_t | S_t = s] \approx \frac{1}{N} \sum_{i=1}^{N(s)} G^{(i)}

  • 1N∑i=1N(s)G(i)\frac{1}{N} \sum_{i=1}^{N(s)} G^{(i)}: Mean of the returns/rewards
  • Model-Free Learning: Operates without prior knowledge of transition dynamics PP or reward function RR.
  • Learning from Complete Episodes: Learns state-value functions vπv_\pi exclusively from full trajectories under policy π\pi. Only works for episodic tasks where termination at step TT is guaranteed.
  • No Bootstrapping: Does not update estimates using other value estimates v(s′)v(s'); instead, updates rely solely on actual empirical returns observed at the end of the episode.
  • Empirical Mean Returns: The value of state ss is estimated by the sample average of all observed returns starting from ss:

An Episode of Experience & Return Formulation​

  • Trajectory Structure: S0→A0,R1S1→A1,R2S2⋯→AT−1,RTSTS_0 \xrightarrow{A_0, R_1} S_1 \xrightarrow{A_1, R_2} S_2 \dots \xrightarrow{A_{T-1}, R_T} S_T
  • Discounted Return (GtG_t): Gt=Rt+1+γRt+2+γ2Rt+3+⋯+γT−t−1RTG_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \dots + \gamma^{T-t-1} R_T
  • Discount Factor (γ=1\gamma = 1): For episodic tasks with terminal-only rewards (such as Blackjack), setting γ=1\gamma = 1 is standard practice because the episode length is finite.

First-Visit Monte Carlo​

  • First-Visit MC estimates the value function V(s)V(s) by averaging returns following only the first occurrence of state ss within each sampled episode.
  • Algorithmic Flow:
    • Initialize counters N(s)←0N(s) \leftarrow 0 and accumulate returns: G(s)←0∀s∈SG(s) \leftarrow 0 \quad \forall s \in S
    • Sample a complete episode i={Si,0,Ai,1,Ri,2,…,Si,Ti}i = \{S_{i,0}, A_{i,1}, R_{i,2}, \dots, S_{i,T_i}\} generated under policy π\pi
    • Compute return Gi,t=∑k=t+1Tiγk−t−1Ri,kG_{i,t} = \sum_{k=t+1}^{T_i} \gamma^{k-t-1} R_{i,k} from step tt to termination.
    • Only for the first time step tt where state ss appears in episode ii:
      • N(s)←N(s)+1N(s) \leftarrow N(s) + 1 (Increment counter for total first visits)
      • G(s)←G(s)+Gi,tG(s) \leftarrow G(s) + G_{i,t} (Increment total return)
      • V(s)←G(s)N(s)V(s) \leftarrow \frac{G(s)}{N(s)} (Update the value by mean return)

A→R1=1B→R2=2A→R3=1C→R4=1terminalA \xrightarrow{R_1=1} B \xrightarrow{R_2=2} A \xrightarrow{R_3 = 1} C \xrightarrow{R_4 = 1} \text{terminal}

State sN(s)N(s)G(s)G(s)V(s)=G(s)N(s)V(s) = \frac{G(s)}{N(s)}
A199.00
B188.00
C155.00

Every-Visit Monte Carlo​

  • Every-Visit MC treats every single occurrence of state ss within an episode as a valid data sample, accumulating its corresponding return into the empirical mean.
  • Algorithmic Flow:
    • Initialize counters N(s)←0N(s) \leftarrow 0 and accumulate returns: G(s)←0∀s∈SG(s) \leftarrow 0 \quad \forall s \in S
    • Sample a complete episode i={Si,0,Ai,1,Ri,2,…,Si,Ti}i = \{S_{i,0}, A_{i,1}, R_{i,2}, \dots, S_{i,T_i}\} generated under policy π\pi
    • Compute return Gi,t=∑k=t+1Tiγk−t−1Ri,kG_{i,t} = \sum_{k=t+1}^{T_i} \gamma^{k-t-1} R_{i,k} from step tt to termination.
    • For each time step tt where state ss appears in episode ii:
      • N(s)←N(s)+1N(s) \leftarrow N(s) + 1 (Increment counter for total visits)
      • G(s)←G(s)+Gi,tG(s) \leftarrow G(s) + G_{i,t} (Increment total return)
      • V(s)←G(s)N(s)V(s) \leftarrow \frac{G(s)}{N(s)} (Update the value by mean return)

A→R1=1B→R2=2A→R3=1C→R4=1terminalA \xrightarrow{R_1=1} B \xrightarrow{R_2=2} A \xrightarrow{R_3 = 1} C \xrightarrow{R_4 = 1} \text{terminal}

State sN(s)N(s)G(s)G(s)V(s)=G(s)N(s)V(s) = \frac{G(s)}{N(s)}
A29+6=157.50
B188.00
C155.00
DimensionFirst-Visit MCEvery-Visit MC
Returns used per episodeOnly the first occurrenceEvery occurrence
Sample independenceIndependent across episodes (i.i.d.)Correlated within an episode (mitigated by sampling)
Bias (finite samples)UnbiasedBiased, but bias→0\text{bias} \to 0
ConvergenceConsistent (Law of Large Numbers)Consistent (as episodes→∞\text{episodes} \to \infty)
ImplementationRequires a "seen this episode?" checkSimpler — no check needed
Practical UseStandard theoretical baselineFrequently preferred (uses all available data)

Incremental Mean​

μk=1k∑j=1kxj\mu_k = \frac{1}{k} \sum_{j=1}^{k} x_j

μk+1=1k+1∑j=1k+1xj=1k+1(∑j=1kxj+xk+1)=1k+1(kμk+xk+1)=μk+1k+1(xk+1−μk)\begin{aligned} \mu_{k+1} &= \frac{1}{k+1} \sum_{j=1}^{k+1} x_j \\ &= \frac{1}{k+1} \left( \sum_{j=1}^{k} x_j + x_{k+1} \right) \\ &= \frac{1}{k+1} \left( k \mu_k + x_{k+1} \right) \\ &= \mu_k + \frac{1}{k+1} (x_{k+1} - \mu_k) \end{aligned}
  • New estimate = Old estimate + step-size * (new sample - old estimate).
  • Memory efficient: Only need to store the old estimate (μk\mu_k) and the number of visits (kk).

Incremental Monte Carlo​

  • Updates the value function V(s)V(s) incrementally after each trajectory without requiring memory to store individual past returns.
  • Algorithmic Flow:
    • Initialize N(s)←0N(s) \leftarrow 0 and V(s)←0V(s) \leftarrow 0 for all s∈Ss \in S.
    • Episode sampling: Execute episode ii under policy π\pi and compute returns Gi,t=∑k=t+1Tiγk−t−1RkG_{i,t} = \sum_{k=t+1}^{T_i} \gamma^{k-t-1} R_{k}.
    • Incremental update: For each visited state ss at time step tt:
      • N(s)←N(s)+1N(s) \leftarrow N(s) + 1 (Increment counter for total visits)
      • V(s)←V(s)+α(Gi,t−V(s))V(s) \leftarrow V(s) + \alpha (G_{i,t} - V(s)) (Update the value by mean return)
      • Where Gi,t−V(s)G_{i,t} - V(s) represents the temporal difference (TD) error between the sampled return target and the current estimate.
  • Choice step size α\alpha
    • α=1N(s)\alpha = \frac{1}{N(s)}: Replicates the exact empirical sample-average of Every-Visit MC where all observed samples receive equal weight.
    • α=constant\alpha = \text{constant}: Implements an exponential recency-weighted running average that decays outdated experience, making it suited for non-stationary environments where MDP dynamics change over time.
  • Cons:
    • Requires a significant number of episodes to converge to the true value function.
    • Requires to terminate the episode.

Model-free Control​

  • The MDP model is unknown, or too large/complex to use directly.
  • But experience can be sampled.
  • Applications:
    • Robo soccer
    • Autonomous vehicles
    • Robotics
    • Game playing
    • Recommender systems
    • Finance & portfolio management

On-Policy vs Off-Policy​

DimensionOn-Policy LearningOff-Policy Learning
DefinitionEvaluates and improves the exact same policy currently used to generate action decisionsEvaluates/improves a target policy (π\pi) while behaving via a different behavior policy (bb)
Data GenerationTrajectories must be generated by the current active policy π\piTrajectories can come from exploratory policies, historical logs, or human demonstrations
Exploration Trade-offMust balance exploration directly within the target policy (e.g., ϵ\epsilon-greedy)Separates exploration (behavior policy) from exploitation/optimality (target policy)
Representative AlgorithmsGLIE Monte Carlo Control, SARSAQ-Learning, Deep Q-Networks (DQN)

General Policy Iteration​

  • Alternates between Policy Evaluation (V≈vπV \approx v_\pi or Q≈qπQ \approx q_\pi) and Policy Improvement (π←greedy\pi \leftarrow \text{greedy}).
  • This interplay drives the system asymptotically toward the optimal pair (v∗,π∗)(v_*, \pi_*) or (q∗,π∗)(q_*, \pi_*).

π′(s)=argmaxa∈A(R(s,a)+γ∑s′∈SP(s′∣s,a)V(s′))\pi'(s) = \text{argmax}_{a \in A} \big( \mathcal{R}(s, a) + \gamma \sum_{s' \in S} \mathcal{P}(s' | s, a) V(s') \big)

  • Why V(s)V(s) Fails in Model-Free Settings:
    • Finding the maximizing action over V(s)V(s) strictly requires the transition model P(s′∣s,a)P(s' \mid s, a) and reward function R(s,a)R(s, a).
    • In Model-Free RL, these dynamics are unavailable; hence, V(s)V(s) alone cannot guide policy updates without an explicit environment model.

GPI

π′(s)=argmaxa∈AQ(s,a)\pi'(s) = \text{argmax}_{a \in A}Q(s,a)

  • Model-Free Advantage:
    • By estimating Q(s,a)Q(s, a) directly through sample episodes, policy improvement requires no knowledge of PP or RR.
    • This fundamental shift makes Q(s,a)Q(s, a) estimation the standard paradigm for Model-Free Control (Monte Carlo Control, SARSA, Q-Learning).
V(s)V(s)Q(s,a)Q(s, a)
QuestionHow good is this state?How good is this action in this state?
Includes Action?NoYes
Policy EvaluationVery suitableSlightly more difficult
Policy ImprovementRequires a modelDirectly possible
Model-Free ControlInconvenientVery suitable

GPI with Q

  • This is why MC Control estimates qπ(s,a)q_\pi(s,a), not vπ(s)v_\pi(s).

Exploration Problem​

a=arg⁡max⁡aQ(s,a)a = \arg\max_a Q(s,a)
  • A greedy agent always chooses the action with the highest current estimated value.
  • But what if the current Q(s,a)Q(s,a) estimates are inaccurate?

Mystery Box Example​

Initially,

Q(red)=0,Q(blue)=0Q(\text{red}) = 0, \qquad Q(\text{blue}) = 0
  1. Open the red box:
    R=0→Q(red)=0R = 0 \rightarrow Q(\text{red}) = 0

  2. Open the blue box:
    R=+1→Q(blue)=1R = +1 \rightarrow Q(\text{blue}) = 1

  3. Keep opening the blue box:
    R=+1,+3,+2,…→Q(blue)≈2R = +1, +3, +2, \ldots \rightarrow Q(\text{blue}) \approx 2

  4. A purely greedy agent now keeps choosing the blue box because
    Q(blue)>Q(red)Q(\text{blue}) > Q(\text{red}).

  5. However, the red box may actually be better. For example,
    E[R∣red]=5\mathbb{E}[R \mid \text{red}] = 5.

    The agent does not know this because it sampled the red box only once.

Exploitation vs. Exploration​

  • Exploitation: Choose the action that currently has the highest estimated value.
  • Exploration: Try less-sampled or unfamiliar actions to discover whether they may actually be better.
  • In this example, the agent should occasionally explore the red box because it has not been sampled enough to confidently conclude that it is worse.

ϵ\epsilon-Greedy Exploration​

π(a∣s)={greedy action with high probabilityrandom action with probability ϵ\pi(a|s) = \begin{cases} \text{greedy action \quad with high probability} \\ \text{random action \quad with probability $\epsilon$} \\ \end{cases}
  • if ϵ=0.1\epsilon = 0.1, then the agent will choose the greedy action with probability 0.90.9 (Exploitation)
  • And the random action with probability 0.10.1 (Exploration).
  • Policy Improvement Theorem:
    • for any ϵ\epsilon-greedy policy π\pi
    • The ϵ\epsilon-greedy policy π′\pi' is as good or better than the original policy π\pi: vπ′(s)≥vπ(s)v_{\pi'}(s) \geq v_{\pi}(s)

Monte Carlo Control​

  • Traditional Policy Iteration:
    • Fix the policy π\pi.
    • Evaluate the current policy until QQ is sufficiently close to qπ(s,a)q_\pi(s,a).
    • Improve the policy using the estimated action values.
    • Repeat policy evaluation and policy improvement.
  • Monte Carlo Control:
    • Perform MC Policy Evaluation after every episode.
    • Improve the policy using ϵ\epsilon-greedy after every episode.
    • Q1→π1=ϵ-greedy(Q1)Q_1 \rightarrow \pi_1 = \epsilon\text{-greedy}(Q_1)
    • Q2→π2=ϵ-greedy(Q2)Q_2 \rightarrow \pi_2 = \epsilon\text{-greedy}(Q_2)
    • ⋯\cdots
    • Eventually approaches (q∗,π∗)(q_*, \pi_*) under appropriate convergence conditions.

MC Control

Evaluate a little→Improve→Evaluate a little→Improve→⋯\text{Evaluate a little} \rightarrow \text{Improve} \rightarrow \text{Evaluate a little} \rightarrow \text{Improve} \rightarrow \cdots

GLIE​

Greedy in the Limit with Infinite Exploration

  1. lim⁡k→∞Nk(s,a)=∞\lim_{k \to \infty} N_k(s,a) = \infty
  2. lim⁡k→∞πk(a∣s)=1(a=arg max⁡a′∈AQk(s,a′))\lim_{k \to \infty} \pi_k(a|s) = 1(a = \argmax_{a' \in A} Q_k(s,a'))
  • Explore enough early -> Explore less over time -> Eventually greedy.
    • Nk(s,a)N_k(s,a): How many times the state-action pair (s,a)(s,a) has been visited in the kk-th episode.
    • πk→greedy(Qk)\pi_k \rightarrow \text{greedy}(Q_k)
  • Infinite exploration first, greedy behavior in the limit.

GILE Monte Carlo Control​

  • Algorithm flow:
    • Run episode k={S0,A0,R1,…,ST}k = \{S_0, A_0, R_1, \dots, S_{T}\} with policy πk\pi_k.
    • For each state-action pair (s,a)(s,a) in the episode:
      • Nk(s,a)←Nk(s,a)+1N_k(s,a) \leftarrow N_k(s,a) + 1
      • Qk(s,a)←Qk(s,a)+1Nk(s,a)(Gk−Qk(s,a))Q_k(s,a) \leftarrow Q_k(s,a) + \frac{1}{N_k(s,a)} (G_k - Q_k(s,a))
    • Improve the policy based on the new QQ value.
      • ϵ←1k\epsilon \leftarrow \frac{1}{k}
      • π←ϵ-greedy(Q)\pi \leftarrow \epsilon\text{-greedy}(Q)
    • Repeat until convergence.
  • old estimate + step-size * (new sample - old estimate).
    • old estimate = Q(St,At)Q(S_t, A_t)
    • new sample = GtG_t
    • step-size = 1Nk(s,a)\frac{1}{N_k(s,a)}
  • Run Episode → Update Q → Reduce ϵ\epsilon → Improve Policy

DP vs MC​

  • Dynamic Programming:
    • Model-based
    • Bootstrapping: Updating a value estimate using another estimated value instead of waiting for the final outcome.
    • Lower variance
  • Monte Carlo:
    • Model-free
    • No bootstrapping: It uses rewards that actually occurred, not an estimated value of the next state.
    • Uses complete sampled returns
    • Requires episodic tasks
    • Higher variance

RL 005

· 약 7분

MDP​

(S,A,P,R,γ)(\mathcal{S}, \mathcal{A}, \mathcal{P}, \mathcal{R}, \gamma)

  • At each time step tt, the agent observes state St∈SS_t \in \mathcal{S} and chooses action At∈AA_t \in \mathcal{A}
  • Receives reward Rt+1∈RR_{t+1} \in \mathcal{R}
  • Transitions to a new state St+1S_{t+1}

Transition Dynamics​

Transition Probability

  • How the environment responds to an action, independent of the agent's policy
  • Policy: Whether to brake or accelerate when the traffic light is yellow.
  • Transition Dynamics: How much the car decelerates after braking, and what the resulting next state is.

P(s′∣s,a)=P(St+1=s′∣St=s,At=a)P(s'|s,a) = P(S_{t+1} = s'|S_t = s, A_t = a)

Policy​

  • A policy is the agent’s rule for choosing actions.
  • It tells the agent what action to take in a given state.
  • It defines agent's behavior.

Deterministic Policy:π(s)=a\text{Deterministic Policy}: \pi(s) = a

  • Direct mapping, and no randomness
  • All probability on one action

Stochastic Policy:π(a∣s)=P(At=a∣St=s)\text{Stochastic Policy}: \pi(a|s) = P(A_t = a | S_t = s)

  • A probability distribution over actions.
  • More general, all four Bellman Equations are stochastic, use π(a∣s)\pi(a|s) to represent the policy.
  • Policy is what the agent controls.

Value Functions​

vπ(s)=Eπ[Rt+1+γvπ(St+1)∣St=s]v_\pi(s) = \mathbb{E}_\pi[R_{t+1} + \gamma v_\pi(S_{t+1}) | S_t = s]

  • How good is this state?
  • Eπ[Gt∣St=s]\mathbb{E}_\pi[G_t | S_t = s]

qπ(s,a)=Eπ[Rt+1+γvπ(St+1)∣St=s,At=a]q_\pi(s,a) = \mathbb{E}_\pi[R_{t+1} + \gamma v_\pi(S_{t+1}) | S_t = s, A_t = a]

  • How good is this action in this state?
  • Eπ[Gt∣St=s,At=a]\mathbb{E}_\pi[G_t | S_t = s, A_t = a]

vπ(s)=∑a∈Aπ(a∣s)qπ(s,a)v_\pi(s) = \sum_{a \in \mathcal{A}} \pi(a|s) q_\pi(s,a)

  • The average value of the actions, weighted by the probability of choosing each action.
    • a1a_1 is brake
    • a2a_2 is accelerate
    • vπ(s)=0.8∗10+0.2∗20=10v_\pi(s) = 0.8 * 10 + 0.2 * 20 = 10
qπ(s,a)=R(s,a)+γ∑s′∈SP(s′∣s,a)vπ(s′)q_\pi(s,a) = \mathcal{R}(s,a) + \gamma \sum_{s' \in \mathcal{S}} P(s'|s,a) v_\pi(s')
  • The value of taking action aa in state ss: the immediate reward plus the discounted expected value of the possible next states.

Four Types of Bellman Equations​

vπ(s)=∑aπ(a∣s)qπ(s,a)qπ(s,a)=R(s,a)+γ∑s′P(s′∣s,a)vπ(s′)vπ(s)=∑aπ(a∣s)[R(s,a)+γ∑s′P(s′∣s,a)vπ(s′)]qπ(s,a)=R(s,a)+γ∑s′P(s′∣s,a)∑a′π(a′∣s′)qπ(s′,a′)\begin{aligned} &v_\pi(s) = \sum_{a} \pi(a|s) q_\pi(s,a) \\ &q_\pi(s,a) = \mathcal{R}(s,a) + \gamma \sum_{s'} P(s'|s,a) v_\pi(s') \\ &v_\pi(s) = \sum_{a} \pi(a|s) \left[ \mathcal{R}(s,a) + \gamma \sum_{s'} P(s'|s,a) v_\pi(s') \right] \\ &q_\pi(s,a) = \mathcal{R}(s,a) + \gamma \sum_{s'} P(s'|s,a) \sum_{a'} \pi(a'|s') q_\pi(s',a') \end{aligned}
  • Evaluate a state: vπ(s)v_\pi(s)
  • Evaluate an action: qπ(s,a)q_\pi(s,a)
  • Calculate Bellman by only vv: Third equation
  • Calculate Bellman by only qq: Fourth equation

Dynamic Programming​

Optimization method for sequential problem

  • Dynamic: Sequential or Temporal component
  • Programming: Optimizing a program or policy
  • Sub Problem
  • Optimal Solution

Prediction and Control​

  • Prediction: Evaluate a given policy vπ(s)v_\pi(s)
  • Control: Find the optimal policy π∗\pi_*

Policy Improvement​

  • π→vπ→π′\pi \to v_\pi \to \pi'
  • π′=greedy(vπ)\pi' = \text{greedy}(v_\pi)
  • Evaluate current policy, Improve it greedily, then get a better policy

Policy Improvement

Modified Policy Iteration​

  • Policy iteration can be computationally expensive
  • MPI: cut off the policy evaluation after a few iterations kk then step to policy improvement.
    • k=1⇒Value iterationk = 1 \Rightarrow \text{Value iteration}
    • k=3,4⇒Modified Policy iterationk = 3,4 \Rightarrow \text{Modified Policy iteration}
    • kis large enough⇒Policy iterationk \quad \text{is large enough} \Rightarrow \text{Policy iteration}

Poisson Distribution Formulation​

P(X=n)=λne−λn!P(X = n) = \frac{\lambda^n e^{-\lambda}}{n!}

  • How many times an event occurs within a fixed interval of time (or space) when we only know the long-term average rate (λ\lambda).
  • nn: The actual number of requests or returns (n∈{0,1,2,…}n \in \{0, 1, 2, \ldots\})
  • λ\lambda: The expected/average number of requests or returns
  • ee: Euler's number (2.71828)
  • n!n!: Factorial of nn

Deterministic Value Iteration​

v∗(s)=max⁡a(R(s,a)+γ∑s′P(s′∣s,a)v∗(s′))v_*(s) = \max_{a} \left( \mathcal{R}(s,a) + \gamma \sum_{s'} P(s'|s,a) v_*(s') \right)

  • If solutions to sub-problems v∗(s′)v_*(s') are known, the optimal value v∗(s)v_*(s) for the current state can be computed directly.
  • Value signals propagate backwards across the state space from states with terminal rewards.

Value Iteration​

vk+1(s)=max⁡a(R(s,a)+γ∑s′P(s′∣s,a)vk(s′))v_{k+1}(s) = \max_{a} \left( \mathcal{R}(s,a) + \gamma \sum_{s'} P(s'|s,a) v_k(s') \right)

  • Infinite (∞\infty) iterations are required to converge exactly to v∗v_*.
  • In practical implementations, iteration terminates when the maximum value change between iterations is less than a small threshold θ\theta.

Dynamic Programming ALgorithms​

ProblemBellman EquationAlgorithm
PredictionBellman Expectation:
vk+1(s)=∑a∈Aπ(a∣s)(R(s,a)+γ∑s′∈SP(s′∣s,a)vk(s′))v_{k+1}(s) = \sum_{a \in A} \pi(a \mid s) \left( R(s, a) + \gamma \sum_{s' \in S} P(s' \mid s, a) v_k(s') \right)
Iterative Policy Evaluation
ControlBellman Expectation + Greedy Policy Improvement:
vk+1(s)=∑a∈Aπ(a∣s)(R(s,a)+γ∑s′∈SP(s′∣s,a)vk(s′))v_{k+1}(s) = \sum_{a \in A} \pi(a \mid s) \left( R(s, a) + \gamma \sum_{s' \in S} P(s' \mid s, a) v_k(s') \right)
π′=greedy(Vπ)\pi' = \text{greedy}(V_\pi)
Policy Iteration
ControlBellman Optimality:
vk+1(s)=max⁡a(R(s,a)+γ∑s′∈SP(s′∣s,a)vk(s′))v_{k+1}(s) = \max_a \left( R(s, a) + \gamma \sum_{s' \in S} P(s' \mid s, a) v_k(s') \right)
Value Iteration

Efficiency of DP​

  • Strengths:
    • A foundational and efficient framework widely used for solving MDPs.
    • Mathematically guaranteed to converge to an optimal policy in polynomial time in terms of the number of states and actions.
    • Exponentially faster than exhaustive direct search across the policy space (∣A∣∣S∣|A|^{|S|}).
  • Limitations:
    • Can become computationally impractical for extremely large or complex environments.
    • Curse of Dimensionality: As the number of state variables (dimensions) increases, the total state space size (∣S∣|S|) expands exponentially, leading to severe computational and memory bottlenecks.

Asynchronous Dynamic Programming​

  • Comparison with Synchronous Methods: Standard DP methods sweep through the entire state space systematically in every iteration. Asynchronous DP backs up individual states independently in arbitrary order.
  • In-place Value Updates: Directly overwrites values in a single memory array, allowing immediate propagation of newly updated state values to subsequent calculations.
  • Computational Gain & Convergence:
    • Significantly reduces computation by avoiding exhaustive full-state sweeps.
    • Guaranteed to converge to the optimal value function v∗v_*, provided that all states continue to be selected and updated indefinitely.

Real-Time Dynamic Programming (RTDP)​

  • Interaction-Driven Online Updates: Solves sub-problems on-the-fly by focusing updates specifically on states that are directly relevant to the agent's current trajectory.
  • Target Applications: Large-scale environments where full state-space iteration is intractable (e.g., robotics, autonomous control systems, game AI).
  • Core Characteristics:
    • Online Decision Making: Makes and refines decisions while operating directly in the environment.
    • Lazy Evaluation: Computes values only for visited or critical state subsets rather than unvisited distant states.
    • Adaptive Exploration: Guides search toward high-reward trajectories through active interaction.
    • Approximate MDP Solution: Yields near-optimal policies for relevant regions without solving the global MDP.

Approximate Dynamic Programming (ADP)​

  • Motivation: Addresses the curse of dimensionality where tabular representation of states and exact value computation become computationally infeasible.
  • Function Approximation Methods: Parameterizes and estimates the value function using scalable statistical and machine learning models:
    • Linear models, deep neural networks, decision trees, and general regression techniques.
  • Error Management Mechanisms:
    • Eligibility Traces: Accelerates credit assignment and temporal consistency across multi-step transitions.
    • Experience Replay: Stores transition tuples in a replay buffer and samples them randomly to break data correlation and stabilize value approximation.