This is a great question about reinforcement learning theory. Let me derive the policy gradient theorem using the log-derivative trick and explain the intuition behind it.
Policy Gradient Theorem Derivation
Starting with the Performance Objective
Let's define the performance measure (expected return) as:
J(θ)=Eτ∼pθ(τ)[R(τ)]
where:
- θ are the policy parameters
- τ is a trajectory
- pθ(τ) is the probability of trajectory τ under policy
We can write this as:
J(θ)=∫τpθ(τ)R(τ
The Log-Derivative Trick (Score Function)
The key insight is the log-derivative trick:
∇θpθ(τ)=p
This comes from the chain rule:
∇θlogpθ(τ)=
Therefore:
∇θpθ(τ)=p
Applying to the Performance Gradient
Now let's compute the gradient of J(θ):
∇θJ(θ)=∇θ∫
Assuming we can swap the gradient and integral (regularity conditions):
∇θJ(θ)=∫τ∇
∇θJ(θ)=Eτ∼
This expectation form reveals the core result: the policy gradient is the expected return weighted by the score function (log-derivative of the policy). The trajectory probability factorizes as a product of environment dynamics and policy terms, where only the policy terms depend on θ.
When I take the gradient of the log trajectory probability, the initial state distribution and transition dynamics vanish since they're independent of the parameters. What remains is just the sum of policy score functions across timesteps. Substituting this back into the expectation gives the policy gradient theorem: the gradient of the objective equals the expected sum of returns times policy score functions.
This can be reformulated more elegantly by recognizing that the return R(τ) can be expressed as the action-value function Qπ(st,a representing cumulative discounted rewards from each state-action pair. So the gradient becomes an expectation over state-action pairs of the policy score weighted by their Q-values. For infinite horizons with discounting, this form holds directly. I can further reduce variance by subtracting a baseline function that depends only on the state, which doesn't bias the gradient but decreases its variance.
The advantage function Aπ(st,at captures exactly this—it measures how much better an action is compared to the state's average value. This formulation is powerful because the return signal itself never needs to be differentiable with respect to the policy parameters. The gradient flows only through the policy's log-probability, while the return can be any scalar value—discrete rewards like win/loss signals, non-differentiable functions, or even human feedback all work equally well.
The mechanism is elegant: the log-derivative trick transforms the gradient into a form where the reward multiplies the policy gradient rather than being differentiated through. This means the policy learns to increase the probability of actions that produced high returns, regardless of whether those returns came from a smooth function or a black-box simulator. The policy parameters shift probability mass toward successful actions purely through the log-probability term, leaving the reward signal untouched. discontinuous) or entirely determined by simulation/evaluation
Concrete Example
Suppose the reward is:
R(τ)={10if trajectory achieves goal
This is completely non-differentiable. But:
∇θJ(θ)=E[1goal achieved
The indicator function doesn't need to be differentiable. The gradient only propagates through ∇θlogπθ(at∣, which is always differentiable (for continuous policies).
Implementation
In practice, I sample a trajectory from the policy, compute its return using whatever non-differentiable operations are needed, then backpropagate only through the policy's log probabilities weighted by that return value. The key insight is that automatic differentiation handles the policy term seamlessly even when the reward computation itself involves discontinuous functions.
The core mechanism works through probability redistribution: actions get sampled from the current policy, evaluated in the environment, and then the policy is adjusted to increase the probability of trajectories that achieved higher returns.
Policy Gradient Theorem & Log-Derivative Trick
Formal Derivation
1. Starting with the Performance Objective
We want to optimize expected return:
J(θ)=Eτ∼pθ
where θ parameterizes the policy, τ is a trajectory, and R(τ) is the cumulative reward.
2. The Log-Derivative Trick
The critical identity is:
∇θpθ(τ)=p
Proof: Using the chain rule on logpθ(τ)=p:
3. Computing the Policy Gradient
∇θJ(θ)=∇θ∫
Swap gradient and integral (regularity conditions):
=∫τ∇θpθ
Apply log-derivative trick:
=∫τpθ(τ)∇
Rewrite as expectation:
=Eτ∼pθ(τ)
4. Decomposing Trajectory Log-Probability
logpθ
The crucial simplification:
∇θlogpθ(τ)=
Environment dynamics don't depend on θ—they cancel out!
5. Policy Gradient Theorem
∇θJ(θ
Common alternative forms:
With advantage functions:
∇θJ(θ)=E
With baselines (variance reduction):
∇θJ(θ)=E[∇
Why Non-Differentiable Rewards Are Possible
The Key Insight: Reward ≠ Differentiable Path
The policy gradient depends on:
(differentiable policy terms)×(arbitrary numerical reward)
∇J = E[∇_θ log π(a|s) × R(τ)]
└─────────────┬──────────┘ └─────┬────┘
Differentiable through Can be ANY
backprop (policy only) function
1. Probability Redistribution, Not Direct Optimization
Instead of differentiating rewards, we redistribute probability mass:
| Traditional Gradient | Policy Gradient |
|---|
| ∇θR → broken if R non-differentiable | ∇θ → always works |
2. Concrete Example: Binary Reward
Suppose R(τ)={10if goal reachedotherwise (completely non-differentiable)
∇θJ=E[step function
- The indicator function doesn't need to be differentiable
- Only logπθ(a∣s) must be differentiable
- Gradient only passes through policy parameters, not reward evaluation
3. Mechanism: Likelihood Ratio Weighting
The log-derivative trick creates a weighted sampling estimator:
dθdE[R]=E[
dθdE[R]=E[R
This swaps the chain rule for a weight, which can be constant/discrete.
4. Why the Shift in Density Works
For a Gaussian policy πθ(a∣s)=N(μθ(s),σ:
∇θlogπθ(a∣s)
When we apply gradient update: θ←θ+α⋅R(τ)⋅∇θlogπ
- If R(τ)>0: mean μθ shifts toward sampled action a
- If : mean shifts
This creates natural credit assignment without explicit reward derivatives.
Practical Implementation
def policy_gradient_update(trajectory, policy, optimizer, baseline=None):
states, actions, rewards = trajectory
returns = compute_returns(rewards) # ← Can use ANY function
# Initialize gradient accumulator
policy_loss = 0
for t in range(len(trajectory)):
# Compute log probability (differentiable)
log_prob = policy.log_prob(actions[t], states[t])
# Compute advantage
advantage = returns[t]
if baseline:
advantage = returns[t] - baseline(states[t]) # Optional
# Policy gradient: reward weights the log-prob gradient
policy_loss += -log_prob * advantage # negative for gradient ascent
# Backprop only through policy, not reward computation
optimizer.zero_grad()
policy_loss.backward() # ← Works even if returns[] used non-diff ops
optimizer.step()
Key properties:
compute_returns() can use black-box simulator, if-statements, etc.
- Backprop only differentiates through
policy.log_prob()
- Gradient exists even with discontinuous, discrete, or stochastic rewards
Summary Table
| Aspect | Why Log-Derivative Works |
|---|
| Reward Differentiability | Not needed—only policy gradients computed |
| Mechanism | Rewrites ∇θE[R] as E[R⋅∇ |
This is why REINFORCE, actor-critic, and PPO can optimize arbitrary objectives—they exploit the mathematical decoupling between policy differentiation and reward evaluation.