v9.1.1
Menu

Log-Probability of a Softmax Policy

easyFREEPolicy Gradients and Advantage EstimationReinforcement LearningRL 1: Foundations

Problem Statement

Policy-gradient methods need log pi(a|s). Given action preferences (logits) logits and a chosen action index a, return the log-probability of that action under the softmax policy:

log⁡π(a)=ha−log⁡∑behb\log \pi(a) = h_a - \log \sum_b e^{h_b}

Implement log_prob(logits, a) using the log-sum-exp trick for stability.

Example

Input
log_prob([0.0, 0.0], 0)
Output
-0.6931
Reasoning
  • Identify the maximum logit mm to ensure numerical stability in the exponential calculations: m=max⁡(0.0,0.0)=0.0m = \max(0.0, 0.0) = 0.0.
  • Compute the shifted exponentials for each logit hbh_b by subtracting mm: e0.0−0.0=1.0e^{0.0 - 0.0} = 1.0 for both actions.
  • Sum these shifted values to get the unnormalized partition function: ∑=1.0+1.0=2.0\sum = 1.0 + 1.0 = 2.0.
  • Calculate the log-sum-exp (LSE) value by adding the max logit back to the log of the sum: LSE=0.0+ln⁡(2.0)≈0.6931\text{LSE} = 0.0 + \ln(2.0) \approx 0.6931.
  • Subtract the LSE from the logit of the chosen action a=0a=0 to obtain the log-probability: log⁡π(0)=0.0−0.6931=−0.6931\log \pi(0) = 0.0 - 0.6931 = -0.6931.
  • The final output is -0.6931

Constraints

  • 0 <= a < len(logits).
  • Return a float.

Learn this in

More from RL 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.