REINFORCE with baseline for continuous actions
Implement a Gaussian policy with network-produced mean and learned log deviation, and REINFORCE with discounted returns and a baseline; solve InvertedPendulum and measure the baseline’s effect on gradient variance.
After this lesson you can
- Implement a Gaussian policy with correct log probability and entropy.
- Implement REINFORCE with discounted returns and normalization.
- Measure gradient-estimator variance with and without a baseline.
- Solve InvertedPendulum consistently across seeds.
Before you start
A force that learns from its consequences
An inverted pendulum falls if the cart does not correct its tilt. MuJoCo calculates motion, but learning a policy does not require differentiating its physics engine: we can try forces, observe how long balance lasts and increase the probability of decisions contributing to a good result. That is REINFORCE. The challenge is distinguishing a learning signal from variation caused by random actions and initial states.
In the previous lesson you fixed the evaluation protocol. Here each independent training run produces a different policy, evaluated with separate episodes using its mean action. Raw evaluation return is not necessarily the discounted objective used for training. Identify both, together with seeds, budget and versions; reaching a score in one run does not demonstrate consistency.
The policy will be Gaussian, with mean produced by a network and learned deviation. First derive its gradient, then construct an estimator with complete returns and a baseline. Finally measure both control achieved on the pendulum and dispersion of gradient estimates. Do not confuse the experiment with the figure’s toy model: the latter has a known exact answer and clarifies what is measured.
The gradient without differentiating the simulator
Let be a differentiable density whose support is independent of . Initial distribution and environment transitions do not directly depend on . Consider finite horizon , or an equivalent representation with absorbing states after the end, and integrable reward. Assume differentiation and integration can be interchanged and the following expectations are finite. These assumptions matter: the likelihood-ratio identity does not permit differentiating arbitrary integrals without conditions.
A trajectory has a density factored into initial distribution, policies and transitions. Differentiating its logarithm removes environment factors because they do not directly depend on the parameters. If and , then
The central equality uses where density is positive. The term is called the score: it measures how the log probability of an action changes as parameters move. An action accompanied by favorable return pushes toward parameters assigning it more density. This is a local interpretation of the update, not a guarantee that every action in a successful trajectory was good.
The formula uses total return for every step. Rewards before an action cannot depend on that future action. Conditional on history through , expected score of the next action is zero: integrating yields the derivative of the density integral, which is one. Past terms thus have zero expectation and can be removed. If return from is defined as
The outer factor is needed for the initial-state discounted objective above. Another formulation may absorb it into a discounted state distribution, but must say so. When , the finite-horizon estimator does not need that factor. The derivation matches the policy gradient principle and REINFORCE estimator; Spinning Up develops the undiscounted episodic version.
In practice expectation is approximated by a trajectory average. More independent trajectories reduce sampling noise under usual assumptions, but do not guarantee a finite update improves return. Monte Carlo error depends on variance of the full contribution, not reward variance alone. If an external limit cuts a trajectory, a return simply ending there estimates the truncated objective; the continuing objective needs a future correction, for example an approximate value, with its own assumptions and error.
A multidimensional Gaussian policy
The sum appears because joint density is the product of independent-dimensional densities. Averaging instead of summing changes gradient and entropy scale with ; it does not compute joint log density. The logarithmic parameter prevents negative deviations and allows learning a multiplicative scale; it does not prevent arbitrarily small or large deviations. A multivariate Gaussian permits full covariances; we choose a diagonal matrix for simplicity, not because every optimal policy has independent actions. For a Gaussian, uncorrelatedness and independence coincide, but not for arbitrary distributions.
Differential entropy can be negative and depends on unit scale; it is not a probability or a performance measure by itself. Adding a positive entropy coefficient to the objective favors exploration but changes the objective optimized. An explicit bound on log_std limits numerical extremes but does not replace exploration diagnostics. Record deviation, return and fraction of saturated actions; a policy can have high pre-clipping deviation and produce many identical boundary actions.
What pushes each parameter
For one dimension write and . Treating the observed action as fixed when differentiating, the density formula gives
The first derivative has the sign of displacement from the mean. With positive advantage, an ascent update moves the mean toward that sample; with negative advantage it moves away. Magnitude also depends on deviation: the same physical difference has greater score for a narrow distribution. That sensitivity does not make very small deviation always better, because actions far from the mean become rare and weights can be unstable.
The second derivative compares squared standardized distance with one. If and advantage is positive, the contribution pushes deviation wider; if , it pushes it narrower. One sample does not determine the final trend: sum contributions over actions, states and episodes. When a network produces the mean, the chain rule multiplies the first score by the network Jacobian with respect to parameters. If log_std is shared across states, all transitions contribute to that same vector.
This decomposition is a useful sanity check. If code always gives zero mean gradient although return depends on action, check that the sample is not connected through the reparameterization path when computing log_prob. If output shape retains the action dimension and the wrong batch dimension is summed, inspect dimensions first. For a batch of states and actions, component density has shape , while joint action log density has shape . Only after summing action dimensions do you aggregate over transitions and episodes according to the chosen estimator.
import math
def gaussian_log_prob(mu, log_std, action):
return -0.5 * sum(((x-m)/math.exp(l))**2 + 2*l + math.log(2*math.pi)
for m, l, x in zip(mu, log_std, action))
def gaussian_entropy(log_std):
return sum(l + 0.5*math.log(2*math.pi*math.e) for l in log_std)
mu = [0.1, 0.2]
log_std = [math.log(1.0), math.log(0.5)]
action = [0.3, -0.1]
print("log densidad:", round(gaussian_log_prob(mu, log_std, action), 6))
print("entropía:", round(gaussian_entropy(log_std), 6))Log density can be positive because density is not bounded by one. Nor is it the probability of obtaining exactly one real action, which is zero under a continuous distribution. The formula evaluates density with respect to Lebesgue measure; interval probability requires integration.
Latent action, clipping and score
A Gaussian is unbounded, but an environment may require actions in a finite interval. One simple choice here is to sample and apply to the environment. Clipping then belongs to the effective transition mechanism: the random trajectory includes latent sample . The score estimator uses , retaining the sample before clipping. Evaluating Gaussian density at as if it were the original sample is incorrect: the clipped distribution accumulates mass at the bounds and does not have only an ordinary continuous density there.
Another approach transforms the Gaussian with tanh and corrects log density with the Jacobian. This is a different policy, studied with SAC. Do not mix the tanh correction with simple clipping. For deterministic evaluation apply the same action transformation to the mean; recording the fraction clipped shows when latent distribution and executed action differ substantially.
In PyTorch, the score estimator treats the sample as fixed data when differentiating log_prob. Normal.sample() does this; if using rsample(), detach the sample for this calculation. Backpropagating through the sample itself when differentiating its log density computes a different derivative and can cancel or change the score signal. PyTorch distribution documentation distinguishes sampling, log probability and multivariate events.
A baseline that does not bias the gradient
For a fixed baseline and conditions allowing differentiation and integration to be interchanged,
Expected update is unchanged, although each sample’s contribution changes. If shares parameters with the actor or is learned, this equality concerns score multiplied by a baseline value treated as fixed when constructing the policy gradient. In code, use detach to separate its graph for actor loss and train the critic with its own loss. detach alone does not fix statistical dependence: a mean or critic fitted using the same return of the action being weighted can depend on that action. Freezing a previously fitted baseline, using independent data or designing cross-fitting makes the argument’s condition explicit.
A baseline does not necessarily reduce variance for every choice. A constant far from return can increase it. Even is useful and interpretable but does not always minimize the trace of the covariance of all score components. The best constant for a particular variance notion depends on weights given by score norm. The correct question is empirical and precise: with the same frozen policy, how does variance of the chosen estimator change when subtracting a baseline defined before collecting trajectories?
The optimal constant depends on the score
Consider one contribution , where , fixing state and policy. Assume finite second moments and . Since , expected contribution does not depend on constant . Covariance trace is its second squared moment minus squared norm of that expectation. Only the first term depends on :
The derivative with respect to vanishes at
The quadratic coefficient is positive by assumption, making this point the unique minimum. If score norm is constant or uncorrelated with , equals ; generally it does not. The result concerns one conditional contribution and the sum of variances of its components. A full trajectory gradient has cross-step covariances, so its global optimal baseline may differ. Thus a local formula does not prove that an experiment’s trained critic minimizes variance of the entire update.
Changing units or parameterization also changes score norm and thus the constant minimizing that trace. The zero-expectation property does not depend on choosing the optimal baseline; the variance-reduction claim does depend on baseline and measure used. If the denominator were zero, score would be almost surely zero for the considered components and the expression would not define a unique constant.
In this model, and . Parameters are mean and log deviation at , with score . Gaussian moments give true gradient . For one sample, covariance trace of the no-baseline estimator is ; with it is . For the average of independent samples both traces divide by . The calculations use , and : reduction in this model follows verifiably from its definition, not from an invented MuJoCo laboratory result.
Batch size reduces dispersion of the mean but does not change each estimator’s expectation. Baseline and batch act differently: the former changes per-sample contributions, the latter averages them. Here, if , subtracting changes nothing. In a real environment gradient components can have different scales and correlations; trace summarizes the sum of variances, not each direction. Also inspect means and components when comparing estimators.
The pendulum and measurement design
According to the InvertedPendulum-v5 documentation, the environment receives a scalar force in [-3, 3] and returns four observations in order: cart position, pendulum angle, cart velocity and pendulum angular velocity. The episode terminates when state is nonfinite or angle leaves its healthy range; the default external limit is 1000 steps. Reward is one per healthy step and zero on an unhealthy step: undiscounted return counts healthy steps, not necessarily all transitions after a fall. Evaluation also reports termination and truncation, as in the previous lesson.
REINFORCE training collects episodes under the current policy, computes returns backward and updates the network using a loss whose sign turns ascent into descent. To estimate a discounted objective gradient from the start, each score is weighted by . Keep the policy fixed while collecting the batch attributed to that update. A baseline trained after batch collection is used in the next iteration, not to claim independence afterward with those same actions. An inaccurate critic does not introduce bias merely by being inaccurate if independence holds; it can still leave high variance or increase it.
Normalizing returns or advantages can improve numerical update scale, but normalization by the same batch’s mean and deviation makes each sample weight depend on the others and generally changes the finite estimator. Do not present it as exactly unbiased. If the lab normalizes, record the rule and compare with an unnormalized estimator measurement to study the theoretical property. If it uses an entropy coefficient, distinguish its gradient from return gradient.
An algebraic example shows why same-batch dependence matters. Let independent pairs satisfy and . If you subtract the same batch mean , then
Terms with vanish by independence, but the term retains . This example contracts expectation; it does not prove every normalization has exactly that effect. If each baseline is the mean of the other returns, for , it is independent of its own action under the iid design and cancellation is recovered. Also dividing by a deviation estimated in the same batch adds another dependence; detach prevents an accidental derivative but does not remove statistical dependence.
The practical update below divides by a batch scale and clips norm after summing. This can prevent excessively large steps, but neither the direction nor length of the normalized update is generally an unbiased estimator of . The variance experiment separates such practical decisions from the mathematical identity. A useful algorithm can use a biased estimator without contradiction; claiming an unproved guarantee would be the problem.
Lab: train and measure
The following local cells use PyTorch, NumPy, Gymnasium and MuJoCo on CPU. They train five policies from independent initializations and then measure the first frozen policy’s gradient. Selection is fixed before final evaluation: after the first update and every ten thereafter, evaluate on five validation seeds; stop if all five reach 1000, or at 160 updates. Five different test seeds are held out for the final result. Training seed 0 was also used in a pilot to tune this configuration, so it must not be presented as a fully blind hyperparameter selection test.
The training objective here is explicitly discounted return until termination or the finite 1000-step horizon. No value is added at the limit because this is a truncated-horizon objective, not the return of an underlying continuing task. The policy does not observe time remaining; that restricts the policy family but the score estimator still applies to the finite-horizon trajectory distribution. Test metric is undiscounted sum. Early-stopping interaction counts can differ between seeds and are printed so future method comparisons can control budget.
The first cell builds actor, critic, returns and collection. A value network produces the baseline frozen during actor update. Latent action is stored separately from clipped force. Collection advances several active environments in one inference batch; this does not imply equal trajectory lengths.
import platform
import gymnasium as gym
import mujoco
import numpy as np
import torch
from torch import nn
from torch.distributions import Normal
torch.set_num_threads(1)
GAMMA = 0.99
BATCH = 12
VALIDATION_SEEDS = [100000 + i for i in range(5)]
TEST_SEEDS = [200000 + i for i in range(5)]
print("Versiones:", platform.python_version(), torch.__version__, gym.__version__, mujoco.__version__, np.__version__)
class Actor(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(nn.Linear(4, 32), nn.Tanh(), nn.Linear(32, 32), nn.Tanh(), nn.Linear(32, 1))
self.log_std = nn.Parameter(torch.tensor([-0.7]))
def forward(self, obs):
return self.net(obs), self.log_std.clamp(-3.0, 0.5).exp()
class Critic(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(nn.Linear(4, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, 1))
def forward(self, obs):
return self.net(obs).squeeze(-1)
def sample_episodes(actor, envs, rng, count):
obs = []
for env in envs[:count]:
state, _ = env.reset(seed=int(rng.integers(1000000, 2**31 - 1)))
obs.append(state)
obs = np.array(obs, dtype=np.float32)
active = np.ones(count, dtype=bool)
trajectories = [{"obs": [], "latent": [], "rewards": [], "terminated": False, "truncated": False} for _ in range(count)]
low, high = envs[0].action_space.low, envs[0].action_space.high
while active.any():
ids = np.flatnonzero(active)
with torch.no_grad():
mu, std = actor(torch.from_numpy(obs[ids]))
latent = mu.numpy() + std.numpy() * rng.standard_normal(mu.shape).astype(np.float32)
actions = np.clip(latent, low, high)
for j, idx in enumerate(ids):
state = obs[idx].copy()
nxt, reward, term, trunc, _ = envs[idx].step(actions[j])
traj = trajectories[idx]
traj["obs"].append(state)
traj["latent"].append(latent[j].copy())
traj["rewards"].append(float(reward))
traj["terminated"], traj["truncated"] = bool(term), bool(trunc)
obs[idx] = nxt
active[idx] = not (term or trunc)
return trajectories
def trajectory_tensors(trajectories):
states, actions, returns, weights, lengths = [], [], [], [], []
for tr in trajectories:
g, ret = 0.0, []
for r in tr["rewards"][::-1]:
g = r + GAMMA * g
ret.append(g)
ret.reverse()
n = len(ret)
lengths.append(n)
states.extend(tr["obs"])
actions.extend(tr["latent"])
returns.extend(ret)
weights.extend(GAMMA ** np.arange(n))
return (torch.tensor(np.asarray(states), dtype=torch.float32),
torch.tensor(np.asarray(actions), dtype=torch.float32),
torch.tensor(returns, dtype=torch.float32),
torch.tensor(np.asarray(weights), dtype=torch.float32), lengths)npm run lab and open the connection link.Check recursion on a short sequence before trusting a training curve. For rewards and discount 0.5, returns from each step are ; the discounted gradient’s second outer factor is 0.5. This differs from using only immediate reward.
toy = [{"obs": [np.zeros(4)]*3, "latent": [np.zeros(1)]*3, "rewards": [1.0, 2.0, 3.0]}]
old_gamma = GAMMA
GAMMA = 0.5
_, _, toy_returns, toy_weights, _ = trajectory_tensors(toy)
print("Retornos:", toy_returns.tolist(), "pesos:", toy_weights.tolist())
GAMMA = old_gammanpm run lab and open the connection link.The evaluation harness reproduces the previous lesson’s run_episode interface: reset(seed), return accumulation and closure on either flag. The deterministic policy applies the same clipping to the mean; actor and critic are not updated during test. Every call creates and closes its own environment.
def evaluate(actor, seeds):
env = gym.make("InvertedPendulum-v5")
out = []
try:
for seed in seeds:
obs, _ = env.reset(seed=seed)
total, steps = 0.0, 0
while True:
with torch.no_grad():
mu, _ = actor(torch.tensor(obs[None, :], dtype=torch.float32))
action = np.clip(mu.numpy()[0], env.action_space.low, env.action_space.high)
obs, reward, terminated, truncated, _ = env.step(action)
total += float(reward)
steps += 1
if terminated or truncated:
out.append({"seed": seed, "return": total, "steps": steps,
"terminated": bool(terminated), "truncated": bool(truncated)})
break
finally:
env.close()
return outnpm run lab and open the connection link.The training cell computes advantages with the critic before its update. It divides by same-batch standard deviation and clips gradient norm to stabilize optimization; both are practical decisions that change the finite-sample update. No claim of exact unbiasedness is made for that normalized update. Later variance comparison uses an unnormalized, unclipped estimator and a frozen policy.
def train(seed, use_baseline=True):
torch.manual_seed(seed)
rng = np.random.default_rng(seed)
actor, critic = Actor(), Critic()
actor_opt = torch.optim.Adam(actor.parameters(), lr=0.003)
critic_opt = torch.optim.Adam(critic.parameters(), lr=0.003)
envs = [gym.make("InvertedPendulum-v5") for _ in range(BATCH)]
training_steps = 0
try:
for update in range(160):
trajectories = sample_episodes(actor, envs, rng, BATCH)
states, actions, returns, weights, lengths = trajectory_tensors(trajectories)
training_steps += sum(lengths)
with torch.no_grad():
advantage = returns - critic(states) if use_baseline else returns
scale = advantage.std().clamp_min(1.0)
mu, std = actor(states)
logp = Normal(mu, std).log_prob(actions).sum(-1)
actor_loss = -(weights * logp * advantage / scale).sum() / BATCH
actor_opt.zero_grad()
actor_loss.backward()
torch.nn.utils.clip_grad_norm_(actor.parameters(), 10.0)
actor_opt.step()
if use_baseline:
for _ in range(4):
loss_v = ((critic(states) - returns) ** 2).mean()
critic_opt.zero_grad()
loss_v.backward()
critic_opt.step()
if (update + 1) % 10 == 0 or update == 0:
validation = evaluate(actor, VALIDATION_SEEDS)
if all(e["return"] == 1000 for e in validation):
break
finally:
for env in envs:
env.close()
test = evaluate(actor, TEST_SEEDS)
result = {"seed": seed, "updates": update + 1, "steps": training_steps, "test": test}
return result, actor, critic
runs, models = [], []
for seed in range(5):
result, actor, critic = train(seed)
runs.append(result)
models.append((actor, critic))
print("semilla", seed, "actualizaciones", result["updates"], "pasos", result["steps"],
"retornos", [e["return"] for e in result["test"]],
"truncamientos", sum(e["truncated"] for e in result["test"]))npm run lab and open the connection link.With Python 3.13.1, PyTorch 2.11.0+cu128 on CPU, Gymnasium 1.4.0, MuJoCo 3.17.0 and NumPy 2.5.2, the reference run obtained 1000 in all five test episodes for each of five training seeds. Seeds 0 through 4 stopped at updates 80, 60, 80, 40 and 110 respectively. The cell prints actual steps and flags: retaining them avoids confusing early stopping with equal budget across runs. This establishes what was observed under these conditions and seeds, not a universal success probability or fair PPO/SAC comparison at a different budget.
Now run a control without subtracting a baseline with the same seed 0, stopping rule, batch scale and norm clipping. The function initializes a critic in both branches to retain initialization order, but neither uses nor trains it in the control. Generators start with the same seed, although trajectory lengths diverge and thereafter need not consume the same random numbers.
control, _, _ = train(0, use_baseline=False)
print("Sin baseline: actualizaciones", control["updates"], "pasos", control["steps"],
"retornos", [e["return"] for e in control["test"]],
"truncamientos", sum(e["truncated"] for e in control["test"]))npm run lab and open the connection link.In the reference run, the no-baseline control reached five test returns of 1000 after 100 updates and 136838 training steps; with critic, the same seed stopped after 80 updates and 156173 steps. One variant needed fewer updates and the other fewer steps in this pair. One seed cannot establish which is more efficient or equate an update with a fixed interaction budget. The next measurement isolates another question: estimator variance for one frozen policy.
Measure variance without moving the policy
A training curve does not directly measure estimator variance: policy and data change each update. Now freeze seed 0 actor and critic. An independent pilot of 64 episodes fixes a constant baseline as mean return from each step. Then collect 128 new episodes and calculate each full gradient vector three times: without baseline, with that constant and with the frozen critic. All three calculations use exactly the same trajectory and latent actions. No batch normalization or gradient clipping is used in this measurement.
For each variant stack parameter vectors and sum their sample variances: the covariance matrix trace. The paired comparison subtracts vectors calculated from the same episode; the norm of the mean difference is accompanied by the square root of summed variances of that difference divided by episode count. This standard error summarizes a multivariate scale, not a hypothesis test or simultaneous componentwise interval.
def measure_variance(actor, critic, pilot_episodes=64, measured_episodes=128, seed=987654321):
actor.eval()
critic.eval()
rng = np.random.default_rng(seed)
envs = [gym.make("InvertedPendulum-v5") for _ in range(16)]
def collect(n):
result = []
while len(result) < n:
result.extend(sample_episodes(actor, envs, rng, min(16, n - len(result))))
return result
try:
pilot = collect(pilot_episodes)
_, _, pilot_returns, _, _ = trajectory_tensors(pilot)
constant = float(pilot_returns.mean())
measured = collect(measured_episodes)
finally:
for env in envs:
env.close()
vectors = {"ninguna": [], "constante": [], "critico": []}
for episode in measured:
states, actions, returns, weights, _ = trajectory_tensors([episode])
with torch.no_grad():
values = critic(states)
for name, baseline in [("ninguna", 0.0), ("constante", constant), ("critico", values)]:
mu, std = actor(states)
logp = Normal(mu, std).log_prob(actions).sum(-1)
objective = (weights * logp * (returns - baseline)).sum()
gradient = torch.autograd.grad(objective, actor.parameters())
vectors[name].append(torch.cat([x.reshape(-1) for x in gradient]).detach().numpy())
stats = {}
for name, data in vectors.items():
values = np.array(data)
stats[name] = {"traza": float(values.var(axis=0, ddof=1).sum()),
"norma_media": float(np.linalg.norm(values.mean(axis=0)))}
for name in ["constante", "critico"]:
diff = np.array(vectors[name]) - np.array(vectors["ninguna"])
stats[name]["diferencia_medias"] = float(np.linalg.norm(diff.mean(axis=0)))
stats[name]["error_tipico_rms"] = float(np.sqrt(diff.var(axis=0, ddof=1).sum() / len(diff)))
stats[name]["cociente"] = stats["ninguna"]["traza"] / stats[name]["traza"]
return constant, stats
constant, stats = measure_variance(*models[0])
print("Baseline del piloto:", round(constant, 3))
for name, values in stats.items():
print(name, {k: round(v, 3) for k, v in values.items()})npm run lab and open the connection link.In the reference run, trace was 27612492.0 without baseline, 1410508.125 with constant and 2385135.5 with critic. Ratios were approximately 19.58 and 11.58 respectively for this policy and measurement. Norm of the paired mean difference with the constant was 306.397 versus RMS standard error 374.995. The observed difference is compatible with sampling noise at that scale but does not prove exact equality of expectations. The unbiasedness proof follows from conditional independence and identity assumptions, not a finite empirical test.
The constant outperforming the critic here does not prove general superiority. The constant was estimated from a pilot of this same policy; the critic was trained during a sequence of changing policies and may poorly approximate the frozen policy’s return. That describes what was measured and a possible critic limitation, not a demonstrated causal explanation of the difference. Identifying cause needs extra controls, such as comparing value error and variance with critics trained under the frozen policy on separate data.
Trace depends on network parameterization and parameter units. Compare all three methods on the same actor; do not directly compare its absolute number with another architecture. The ratio within this measurement answers a specific question. If repeating with other policies, seeds or pilot sizes, also report ratio dispersion and do not select only the most favorable.
Extending the comparison without changing the question
A generalization test can freeze multiple policies chosen by a prior rule: for example, initial and final actor from each training run, without selecting those with greatest reduction. For each, reserve a separate pilot to fit the constant baseline and collect new episodes for paired comparison. Record pilot seed, measurement seed, each trajectory length and sample count. If refitting the critic with frozen-policy data, hold out yet another set to evaluate gradients. This avoids using one return both to fit the baseline and justify cancellation of its own contribution.
Mean gradient and variance answer different questions. An independent constant baseline preserves expected gradient under the assumptions, even if estimated with error from an independent pilot: condition on the obtained value and apply the zero-score argument. However, if the constant varies between experiments, conditional variance also varies, so state whether variation is summarized within each pilot or also across pilots. This lesson fixes one pilot and then compares new episodes; it does not quantify variation from choosing another pilot.
Paired comparison is often more informative than two independent collections because each episode supplies two estimates of the same signal and allows analyzing their difference. This does not make steps within an episode independent samples. A trajectory’s rewards, states and scores are related through dynamics and prior decisions. Thus the variance cell’s unit is the summed vector from a complete episode. A mean of independent episodes has per-episode covariance divided by their count, provided policy and baseline are frozen and independence holds. This can fail if the actor updates between episodes or shared randomness makes them dependent.
When interpreting a training curve, also separate estimator noise from other changes. Reduced variance alone does not determine steps to solve the task: optimizer, advantage scale, norm clipping, state distribution and stopping rule affect the result. In the single-seed comparison just run, the critic changed both the update and the subsequent data trajectory. The frozen experiment isolates dispersion of three formulas on the same trajectories but does not by itself identify what caused the difference between the two training runs.
If reproduction misses the criterion on another installation, keep returns and versions instead of substituting the reference table. First check use of the same latent actions for log density, environment version, evaluation mean and separate test seeds. Then inspect episode length, learned deviation, advantage scale and norms before and after clipping. Different behavior may come from a version or implementation difference, but measure it before assigning cause. Lab output is part of the evidence, not a promise of bit-for-bit training reproduction on every machine.
Exercises
Step 1 of 3. Which property does the argument use?
gaussian_log_prob(mu, log_std, a) and gaussian_entropy(log_std). Arguments are PyTorch tensors with the last dimension representing actions and earlier dimensions broadcast. Return the sum over the last dimension, not the mean. Do not construct a PyTorch distribution in your solution: tests use one as a reference.import torch
def gaussian_log_prob(mu, log_std, a):
pass
def gaussian_entropy(log_std):
passREINFORCE converts observed returns to a log-density gradient without differentiating the simulator. Summing log probabilities respects dimensions; a baseline independent of the current action preserves expectation and can reduce dispersion. Learning evidence and evidence of variance reduction require different, reproducible measurements.