Compute one-step actor-critic advantages and losses

Why it matters A2C, A3C and the value head in PPO all train on this advantage and these two losses.

In a one-step actor-critic, the critic's TD error doubles as the advantage that tells the actor whether its action was better or worse than expected.

Write actor_critic_losses(logp, rewards, values, next_values, dones, gamma). All inputs are length B arrays: logp is log pi(a|s) of the taken actions, values is V(s), next_values is V(s_next).
- adv = rewards + gamma * next_values * (1 - dones) - values
- actor_loss = -mean(logp * adv), with adv treated as a constant
- critic_loss = mean(adv ** 2)
Return (adv as an array, actor_loss, critic_loss) with the losses as floats.

Signaturedef actor_critic_losses(logp, rewards, values, next_values, dones, gamma)

Example

actor_critic_losses([-1.0], [1.0], [0.5], [1.0], [0], 0.5) gives (array([1.]), 1.0, 1.0).

Understand the idea

An actor-critic has two parts: the actor (the policy) chooses actions, and the critic (a value function) predicts how good each state is. After a step, the critic checks its own prediction: reward plus discounted next value, minus what it predicted. That surprise is the advantage. Positive means "better than expected, do this more"; negative means "do it less".

Example: V(s) = 0.5, reward 1, gamma 0.5, V(s_next) = 1. Advantage = 1 + 0.5 * 1 - 0.5 = 1. With log pi(a|s) = -1, the actor loss is -(-1 * 1) = 1 and the critic loss is 1^2 = 1.

Rule: A = r + gamma * V(s') * (1 - done) - V(s); actor loss = -mean(log pi * A); critic loss = mean(A^2).

Modern policy gradient methods, including PPO for RLHF, are refinements of this pattern.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleactor_critic_losses([-1.0], [1.0], [0.5], [1.0], [0], 0.5)
  • Sample 2: terminalactor_critic_losses([-0.2, -2.0], [1.0, 0.0], [0.0, 3.0], [5.0, 5.0], [1, 0], 0.9)
  • Test 3: randomactor_critic_losses(_lp, _r, _v, _v2, _d, 0.99)