Compute prioritized replay sampling probabilities and importance weights

Why it matters Prioritized replay is part of Rainbow DQN and similar replay ideas are used to pick hard examples in LLM fine-tuning.

Prioritized experience replay samples transitions with large TD errors more often, then corrects the bias with importance-sampling weights.

Write per_weights(td_errors, alpha, beta, eps=1e-6). For N transitions:
- priority p_i = (|td_i| + eps) ** alpha
- probability P_i = p_i / sum p
- weight w_i = (N * P_i) ** (-beta), then divide all weights by their max so the largest is 1.
Return (P, w) as numpy arrays.

Signaturedef per_weights(td_errors, alpha, beta, eps=1e-6)

Example

per_weights([1, 3], 1.0, 1.0, 0.0) gives (array([0.25, 0.75]), array([1., 0.3333])).

Understand the idea

A replay buffer that samples uniformly wastes time on transitions the network already predicts well. Prioritized replay gives each transition a priority based on how wrong the network was (its TD error) and samples in proportion to it. But sampling non-uniformly biases the updates, so each sample's gradient is scaled down by an importance weight.

Example: TD errors 1 and 3 with alpha 1 give probabilities 0.25 and 0.75. With N = 2 and beta 1: weights are (2 * 0.25)^-1 = 2 and (2 * 0.75)^-1 = 0.667. Dividing by the max 2 gives 1 and 0.333, so the often-sampled transition gets a smaller step.

Rule: p = (|delta| + eps)^alpha, P = p / sum(p), w = (N * P)^(-beta) / max(w).

beta is usually annealed to 1 by the end of training so the correction becomes exact.

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

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

  • Sample 1: exampleper_weights([1, 3], 1.0, 1.0, 0.0)
  • Sample 2: negative errorsper_weights([-2, 0.5, 1, -0.1], 0.6, 0.4)