15 min total

Reinforcement Learning

Q-Learning

Q-Learning

Qlearning

off policy, value based RL
goal is to find optimal policy indirectly by learning Q function
does TD update after each step
has a Q function Q(s, a) - quality of taking action a in state s
Q stands for quality

  1. initialize Q table
  2. choose action using epsilon greedy strategy
  3. take action, recieve reward and move to S_t+1
  4. update Q value (TD update)

Internally stored as a Q-table

  • Rows → states
  • Columns → actions
  • Cells → Q-values

this works well only for small discrete state spaces
not scalable to continous state spaces/large state spaces
also har cell ki Q value ko calculate krna parta he beforehand


off-policy: using a different policy for accting (inference) and different for updating (training)

on-policy: using the same policy for acting and updating


acting policy: which action do i take in the real environment at this moment

updating policy: when updating Q-values, which future action do i assume ill take
future action could be exploratory or a optimal value


Deep Q learning (DQN)

use a deep neural network to approximate Q values
Q(s, a)
input state
output Q values for all possible actions

loss function in DQN


instability (training doesnt reliabily converge to a good policy) is deep Q learning is caused by:

  • updating one state action pair affects only one table cell
    in DQN updating weights affects many states at once, a small gradient step can change Q values everywhere
  • you update Q to chase a target, but the target itself moves after every update


stabilization techniques:

  1. experience replay:
    in test time, agent sees data like in very sequenced mannerthese experiences are highly correlated, training samples independent and identically distributed. with replay each experience is reused many times
  2. Fixed Q target network:cowboy = Q(s, a)
    cow = TD target
    everytime the cowboy steps forward
    the cow runs forward too
    you never catch itonline (main) network
    target network (frozen)create online Q network - randomize weightscreate target Q network - copy weights from online networkonline network predicts Q values
    sample a batch from replay buffer
python
(s₁, a₁, r₁, s₂)
(s₂, a₂, r₂, s₃)
(s₃, a₃, r₃, s₄)

Trajectories

trajectory is a sequence of states and actions in the world, also referred to as episodes or rollouts.

jsx
\tau = (s_0, a_0, s_1, a_1, ...).

Deep Deterministic Policy Gradient

is a off-policy algorithm, even if an experience was collected by an older version of the policy, DDPG can sample it again and use it to train its critic.

DDPG was an improvement over DQN/Q-learning, they used to work well with discrete actions but had no option to generate continuous action space.

replay buffer:
(current state, action taken, reward received, next state, episode ended <bool>)

uses bellman equation (Q function) to learn the policy
since it always outputs a single action, its called deterministic policy.

Action Model

Actor is a neural network that inputs state and outputs action

objective function:

Critic Model

uses bellman equation to calculate value of taking an action right now
eqA

we derive eqB by substituting action equation into eqA:

r: reward received now
: discount factor
d: whether the episode terminated
s′: next state
Target Actor: produces next action
Target Critic: evaluates next action

general bellman target is: - eqN
DDPG has an actor that generates actions - eqM
substitute eqM into eqN

we also add a terminal-state condition
therefore;

How is the Whole Architecture trained?

for current state
a. main actor produces an action
b. add exploration noise
c. execute action in the environment, env returns r, s’, d
d. store the transition in the replay buffer
e. sample a batch of n size from replay buffer
f. calculate target Q values
a. target actor network predicts next action
b. target critic network evaluates next action
c. calculate bellman target
d. calculate mean squared error
g. calculate gradients for the whole mini replay batch
h. update main critic parameters using gradient descent
i. update main actor network
j. update the target actor and target critic using polyak averaging
k. repeat

Why were Target Networks introduced?

a target actor produces the next action used in target calculation
a target critic outputs rewards for that next action

actor picks the next action ,
critic evaluates it later on
and our training target is:

since our error function is this:

if we make our main critic and actor networks predicted the next action and reward as well
it will update the main critic and actor weights midst each replay buffer update
and will lead to training instability
The Critic update tries to reduce the error between its current prediction and the target.
That same update changes the network's predictions at other states, including the next states used to calculate future targets.
Those new targets can cause subsequent gradient updates to push the network in different directions.

the updates are done collectively as a whole batch (lol dont assume these are sequential updartse inside a bathc) BUT even then the target moves its position leading to osicallions between replay buffer batches

Twin Delayed DDPG

DDPG has a Q value overestimation problem
suppose critic estimates:

ActionActual valueCritic estimate
A1012
B815
C67

actor tries to maximize the critics estimate
so it chooses B because critic says B has a value of 15
But B’s actual value is 8
actor is getting infuenced due to error in the critic
this is called Qvalue overestimation

so we did the following optimizations:
a. Clipped double Q learning - TD3 has two independent critics, both critic networks estimate value of the same state action pair, TD3 takes the smaller of their two estimates
b. delayed policy updates - TD3 updates two critics more frequently than the actor, adds a policy_delay param which delays actor updation until k = policy_delay iterations
c. target policy smoothing - if critic has learned an incorrect high estimate, target actor might select taht action because hte critic thinks it has an exceptionally high value, that high value might be approximation error. TD3 adds a little noise to target action

Results

EnvironmentWhen does the agent receive reward?DDPG returnTD3 return
HalfCheetahPositive reward for running forward faster; penalty for using excessive joint torque.3,3069,637
HopperReward for hopping forward and staying healthy; penalty for excessive control effort.2,0203,564
Walker2dReward for walking forward and staying upright; penalty for excessive control effort.1,8444,683
AntReward for moving forward while maintaining a healthy body posture; penalties for excessive control effort and undesirable body height.1,0054,372
ReacherReward (negative penalty) based on how close the robotic arm's endpoint is to its target; additional penalty for excessive actions.-6.51-3.60
InvertedPendulumReward for keeping the pole upright on the cart. Typically +1 per timestep it remains balanced.1,0001,000
InvertedDoublePendulumReward for keeping both connected poles upright, with penalties for distance from the ideal position and excessive velocity.9,3569,337

Training Recipe

a. Main Actor produces an action.
b. Add exploration noise to the action and clip it to valid action limits.
c. Execute the action in the environment. Environment returns reward r, next state s', and done flag d.
d. Store the transition in the replay buffer.
e. Sample a batch of N transitions from the replay buffer.
f. Calculate target Q-values:
a. Target Actor predicts the next action.
b. Add clipped Gaussian noise to the target action (target policy smoothing).
c. Both Target Critics evaluate the next action
d. Take the smaller of the two Q-values (clipped double-Q learning)
e. Calculate the Bellman target.
f. Calculate MSE losses for both Main Critics using the same target.
g. Calculate gradients for the entire minibatch for both Critics.
h. Update both Main Critics using gradient descent
i. Only every policy_delay Critic updates (usually every 2 updates)
a. Update Main Actor using Critic 1.
b. Update Target Actor using Polyak averaging.
c. Update both Target Critics using Polyak averaging.
j. Repeat.

Soft Actor-Critic

DDPG and TD3 learns a deterministic policy, where as SAC learns a stochastic policy
also introduces something called entropy regularization, encourages agent to maintain randomness in its actions and explore different possibilities.

has 1 actor, 2 crtiics, 2 target critics

in SAC, the actor produces mean and std
SAC also uses a entropy term in its bellman target

SAC also uses reparameterization trick to sample action from a distribution
this makes sampled action differentiable wtr to actors params

Training recipe

a. main actor produces probability distribution over possible actions
b. sample action from distribution
c. execute action in enviroment, environment returns reward, next sate and done flag
d. store transition in replay buffer
e. sample a batch of N transitions from replay buffer
i. current actor samples next action
ii. calculate log probability of each sampled action
iii. both target critics evaluate sampled next actions
iv. take smaller of two Q values
v. include entropy term in bellman target
vi. calcualte MSE losses for main critics using same target
f. calcaulte graditens for entire minibatch for both critics
g. update main actor
i. sample actions from current actor using reparameterization trick
ii. both main critics evalute those actions
iii. take smaller Q value
iv. calculate the actor objective using Q value and entropy term
v. update actor using gradient ascent
j. update both target critics using polyak averging
k. repeat