Compute a REINFORCE policy-gradient update with a baseline

REINFORCE pushes up the log-probability of actions in proportion to the return that followed them. Subtracting a baseline (an estimate of the state value) keeps the gradient unbiased while cutting its variance a lot. The same idea appears in policy-gradient fine-tuning of LLMs.

The policy is a tabular softmax: theta has shape (S, A) and pi(a | s) = softmax(theta[s])[a].

Write reinforce_update(theta, episode, baseline, gamma, lr).
- episode: list of (s, a, r) steps in time order.
- baseline: length S array, b[s].
- G_t = r_t + gamma * G_{t+1} is the discounted return from step t.
- The gradient of log pi(a | s) with respect to theta[s] is onehot(a) - pi(. | s), and zero for other rows. Use pi from the ORIGINAL theta for every step.
- grad = sum over t of (G_t - b[s_t]) * grad log pi(a_t | s_t).
Return theta + lr * grad as a NumPy array (gradient ascent). Do not modify the input.

Signaturedef reinforce_update(theta, episode, baseline, gamma, lr)

Example

theta = [[0, 0]], episode [(0, 1, 1.0)], baseline [0.5], gamma 1, lr 1. pi = [0.5, 0.5], G = 1, weight 0.5, grad = 0.5 * [-0.5, 0.5], result [[-0.25, 0.25]].

Understand the idea

REINFORCE nudges up the probability of actions that were followed by good returns and nudges down the others. Subtracting a baseline, a guess of how good the state usually is, keeps the update unbiased but much less noisy, because only better-than-expected returns push up. For a softmax policy, the gradient of log pi(a | s) is one_hot(a) minus the action probabilities. Worked example: theta = [[0, 0]], one state, baseline [1], gamma = 0.5, lr = 1, episode [(0, 0, 0), (0, 1, 2)]. Returns: G_1 = 2, G_0 = 0 + 0.5 * 2 = 1. pi = [0.5, 0.5]. Step 0 weight = 1 - 1 = 0, contributes nothing. Step 1 weight = 2 - 1 = 1, gradient [0, 1] - [0.5, 0.5] = [-0.5, 0.5]. New theta = [[-0.5, 0.5]]. Rule: compute G_t backwards as r_t + gamma * G_(t+1); grad[s_t] += (G_t - b[s_t]) * (one_hot(a_t) - pi(. | s_t)) using the original theta for every step; return theta + lr * grad as a new array. The same policy-gradient idea underlies RL fine-tuning of LLMs.

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

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: worked examplereinforce_update([[0.0, 0.0]], [(0, 1, 1.0)], [0.5], 1.0, 1.0)
  • Sample 2: two statesreinforce_update(_th, _ep, _b, 0.9, 0.1)