Policy gradients and actor–critic methods
Learn the action probabilities directly. Derive the REINFORCE update, cut its noise with a baseline, and combine an actor with a critic, as A2C and A3C do, with an entropy bonus to keep exploring.
What runs in CodeSplash
- DRL005Advantage actor–critic: A2C/A3C family Explained here
- Online policy learning with proximal policy optimization (PPO) Experimental
You will be able to
- Write the policy-gradient update and explain each factor
- Explain why subtracting a baseline keeps the gradient unbiased and lowers its variance
- Compute the actor, critic and entropy terms of an A2C loss
- Read a critic's explained variance in a CodeSplash PPO run
Read first
Push up what worked
ReadQ-learning learns values and acts greedily on them. Policy-gradient methods learn the policy itself, which handles stochastic policies and continuous actions naturally. The policy-gradient theoremPolicy-gradient theorem (REINFORCE)Raise the log-probability of each action in proportion to how good it turned out; subtracting a baseline cuts the noise. gives the direction that raises expected return:
Raise the log-probability of each action in proportion to the return that followed it. That's REINFORCE: unbiased, but noisy, because a whole episode's luck rides on each action.
DExplorable · Gridworld: Q-learning, policy gradients and PPO
How do value-based and policy-gradient learners find a good route, and what makes them fail?
Learner
Q-learning learns action values; REINFORCE and PPO adjust a policy's preferences directly.
Trips from the start until the goal, the pit or 100 steps.
How much a reward one step later is worth now.
Step size of every update.
Q-learning only: share of steps that take a random action.
PPO only: how far the policy may move from the one that collected the batch.
Chance that a move turns 90° to either side.
Working…
A baseline cuts the noise
ReadSubtract any baseline that doesn't depend on the action, and the expected gradient is unchanged, because is zero. Its variance can drop sharply. The natural baseline is , which turns the return into an advantageAdvantageHow much better an action did than the state's average: A(s, a) = Q(s, a) − V(s).:
Positive advantage: the action did better than usual from that state, so make it likelier. Negative: make it rarer.
Actor and critic
ReadAn actor–criticAdvantage actor–critic (A2C/A3C)An actor (the policy) follows the policy gradient using advantages from a critic (a value network) trained alongside it. method trains two heads: the actor (the policy) and the critic, a value network that supplies for the advantages. A2C's loss adds three terms:
The entropy bonusEntropy bonusRewards a policy for keeping its probability spread over actions, so it keeps exploring; entropy 0 means one action only. keeps the policy from collapsing onto one action too early. In the reference's example the actor term is 0.123, the critic error 0.625 and the entropy 0.556; with weights of a half and a hundredth the loss is 0.429. A3C ran many such learners in parallel without waiting for each other.
Is the critic any good?
In the appCodeSplash's PPO is an actor–critic: a policy head, a value head, advantages from GAEGeneralized advantage estimation (GAE)How much better an action did than the value network expected, blending one-step and whole-episode estimates with λ. and an entropy bonus. Its explained variance says how much of the returns' variation the critic predicts: near 1 is good, near 0 or below means the advantages are mostly noise.
PPO trained for 640 steps (21 episodes) in Admission control. Its most likely action in each state earns -0.092 per episode against 3.269 for the optimal policy and 1.651 for random actions (regret 3.361, discount 0.95); the stochastic policy itself earns 1.773.
- Learned policy value (exact)
- −0.0916
- Optimal policy value
- 3.269
- Regret
- 3.361
- Share of the optimal gain
- −1.077
Plots
View data
| Curve | Environment steps | Return per episode |
|---|---|---|
| Learned policy (exact) | 128 | −0.0916 |
| Learned policy (exact) | 256 | −0.0916 |
| Learned policy (exact) | 384 | −0.0916 |
| Learned policy (exact) | 512 | −0.0916 |
| Learned policy (exact) | 640 | −0.0916 |
| Training episodes | 128 | 1.467 |
| Training episodes | 256 | 2.020 |
| Training episodes | 384 | 0.9943 |
| Training episodes | 512 | 2.649 |
| Training episodes | 640 | 1.747 |
View data
| Action | Share of states | Policy |
|---|---|---|
| accept | 1 | Learned |
| reject | 0 | Learned |
| accept | 0.2857 | Optimal |
| reject | 0.7143 | Optimal |
Exact return per episode
| Policy | Return per episode | Regret |
|---|---|---|
| Learned policy (most likely action) | −0.0916 | 3.361 |
| Learned policy (sampled actions) | 1.773 | 1.496 |
| Optimal policy | 3.269 | 0 |
| Random actions | 1.651 | 1.618 |
Learned policy by state (7 states)
| state | queue | Learned action | Optimal action | P(accept) | P(reject) | State value (network) |
|---|---|---|---|---|---|---|
| queue 0 | 0 | accept | accept | 0.7640 | 0.2360 | 1.823 |
| queue 1 | 1 | accept | reject | 0.6082 | 0.3918 | 1.301 |
| queue 2 | 2 | accept | reject | 0.6848 | 0.3152 | 0.2798 |
| queue 3 | 3 | accept | reject | 0.5556 | 0.4444 | −0.3200 |
| queue 4 | 4 | accept | reject | 0.7313 | 0.2687 | −0.2712 |
| queue 5 | 5 | accept | reject | 0.6381 | 0.3619 | −0.0791 |
| queue 6 | 6 | accept | accept | 0.6788 | 0.3212 | −0.0834 |
Training by iteration
| Iteration | Environment steps | Episodes | Training return | Learned policy value (exact) | Network's start value | Loss | Entropy | Approximate KL | Clipped share | Explained variance |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 128 | 4 | 1.467 | −0.0916 | 0.6655 | 0.1206 | 0.6830 | 0.0002 | 100.0% | −1.721 |
| 2 | 256 | 8 | 2.020 | −0.0916 | 1.383 | 0.0980 | 0.6607 | 0.0089 | 92.2% | −0.2586 |
| 3 | 384 | 12 | 0.9943 | −0.0916 | 1.638 | 0.0612 | 0.6324 | 0.0146 | 39.1% | 0.4542 |
| 4 | 512 | 17 | 2.649 | −0.0916 | 1.738 | 0.0978 | 0.6079 | −0.0035 | 19.5% | 0.4611 |
| 5 | 640 | 21 | 1.747 | −0.0916 | 1.823 | 0.0879 | 0.5984 | 0.0136 | 10.2% | 0.6021 |
- The learned policy gets only -108% of the way from random actions to the optimal policy: train for more iterations or raise the entropy bonus.
- The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.
- Proximal policy optimization; Admission control (7 states, 2 actions, episodes of up to 30 steps, discount 0.95); 5 iterations × 128 steps, 4 epochs per iteration in batches of 32, hidden layers 32, learning rate 0.003, clip range 0.1, λ 0.8, value weight 1, entropy bonus 0.02; seed 42. Advantages are normalized over each rollout; rewards are divided by the environment's largest absolute reward while learning. Values are exact expected discounted returns per episode over the episode length from the start state (backward recursion over the environment's transition table); the optimal policy comes from value iteration on the same table. The diagnostics compare the policy after each iteration's update with the one that collected the rollout.
The exact R script · R R version 4.5.1 (2025-06-13)
# Online policy learning with proximal policy optimization (PPO)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.rl_ppo 2.0.0 · spec 2e88b600b9cfde6a
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_rl_*(): twins of codesplash.decide.online_rl (shared stream through the environment, exact evaluation)
# %% Inputs
# Environment "queue", discount 0.95: the app writes both into the environment files read below.
rounds <- as.integer(5)
steps <- as.integer(128)
epochs <- as.integer(4)
batch_size <- 32
hidden <- as.integer(unlist(c(32)))
lr <- as.numeric(0.003)
encoding <- "one_hot" # one_hot | features
clip <- as.numeric(0.1)
gae_lambda <- as.numeric(0.8)
vf_coef <- as.numeric(1)
ent_coef <- as.numeric(0.02)
seed <- 42
warnings <- list()
# %% Environment: written by the app before the run (mdp/transitions.parquet + mdp/mdp.json in the run folder)
env <- cs_rl_read_mdp("target/academy-parity/run-24905/decide.rl_ppo/queue-clip-lambda/out-r")
meta <- env$meta
S <- env$S; K <- env$K; gamma <- env$gamma
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-24905/decide.rl_ppo/queue-clip-lambda/out-r")
# %% Train online
fit <- cs_rl_ppo(env, encoding, hidden, rounds, steps, epochs, batch_size, lr, clip, gae_lambda, vf_coef, ent_coef, seed)
trace <- fit$trace
policy <- fit$policy
sc <- cs_rl_scores(env, policy)
stochastic_value <- cs_rl_evaluate(env, fit$probs)
greedy_values <- vapply(trace, function(t) t$greedy_value, numeric(1))
best <- which.max(greedy_values)
last <- trace[[length(trace)]]
if (K == 1L) {
warnings[[length(warnings) + 1L]] <- "The environment has one action, so every policy is the same and the share of the optimal gain is undefined."
}
if (fit$episodes == 0L) {
warnings[[length(warnings) + 1L]] <- "No episode finished during training: raise the steps per iteration or the number of iterations."
}
if (!is.null(sc$share) && sc$share < 0.5) {
warnings[[length(warnings) + 1L]] <- sprintf("The learned policy gets only %.0f%% of the way from random actions to the optimal policy: train for more iterations or raise the entropy bonus.", 100 * sc$share)
}
if (last$approx_kl > 0.1) {
warnings[[length(warnings) + 1L]] <- sprintf("The last update moved the policy a lot (approximate KL %.3f): lower the learning rate or the epochs per iteration.", last$approx_kl)
}
if (greedy_values[best] > sc$value + 1e-9 * max(1, abs(sc$value))) {
warnings[[length(warnings) + 1L]] <- sprintf("An earlier iteration's policy (iteration %d) was better (%s) than the final one; the result keeps the final policy.",
trace[[best]]$round, format(signif(greedy_values[best], 4)))
}
warnings[[length(warnings) + 1L]] <- "The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it."
# %% Result
opt_value <- as.numeric(meta$optimal_value)
uni_value <- as.numeric(meta$uniform_value)
labels <- env$labels
actions <- env$actions
live <- which(!env$terminal)
optimal <- as.integer(meta$optimal_policy) + 1L
fmt3 <- function(x) formatC(x, format = "f", digits = 3)
summary <- sprintf("PPO trained for %s steps (%s episodes) in %s. Its most likely action in each state earns %s per episode against %s for the optimal policy and %s for random actions (regret %s, discount %s); the stochastic policy itself earns %s.",
format(fit$env_steps, big.mark = ","), format(fit$episodes, big.mark = ","), meta$title, fmt3(sc$value), fmt3(opt_value),
fmt3(uni_value), fmt3(sc$regret), format(gamma, digits = 15), fmt3(stochastic_value))
values <- list(policy_value = sc$value, stochastic_value = stochastic_value, optimal_value = opt_value, uniform_value = uni_value,
regret = sc$regret, optimal_share = sc$share, optimal_actions = sc$optimal_actions, best_value = greedy_values[best],
best_round = trace[[best]]$round, final_return = last$train_return, estimated_value = last$estimated_value,
entropy = last$entropy, approx_kl = last$approx_kl, clip_fraction = last$clip_fraction,
explained_variance = last$explained_variance, n_episodes = fit$episodes, env_steps = fit$env_steps, rounds_run = length(trace),
final_loss = last$loss, n_states = S, n_actions = K, algorithm = "ppo")
fnames <- as.character(meta$feature_names)
pol_cols <- list(list(key = "s1", label = "state", type = "string"))
for (j in seq_along(fnames)) pol_cols[[length(pol_cols) + 1L]] <- list(key = sprintf("f%d", j), label = fnames[j], type = "number")
pol_cols[[length(pol_cols) + 1L]] <- list(key = "action", label = "Learned action", type = "string")
pol_cols[[length(pol_cols) + 1L]] <- list(key = "optimal", label = "Optimal action", type = "string")
for (j in seq_len(K)) pol_cols[[length(pol_cols) + 1L]] <- list(key = sprintf("v%d", j), label = sprintf("P(%s)", actions[j]), type = "number")
pol_cols[[length(pol_cols) + 1L]] <- list(key = "value", label = "State value (network)", type = "number")
pol_df <- data.frame(s1 = labels[live], stringsAsFactors = FALSE)
for (j in seq_along(fnames)) pol_df[[sprintf("f%d", j)]] <- as.numeric(env$features[live, j])
pol_df$action <- actions[policy[live]]
pol_df$optimal <- actions[optimal[live]]
for (j in seq_len(K)) pol_df[[sprintf("v%d", j)]] <- as.numeric(fit$probs[live, j])
pol_df$value <- as.numeric(fit$values[live])
eval_df <- data.frame(policy = c("Learned policy (most likely action)", "Learned policy (sampled actions)", "Optimal policy", "Random actions"),
value = c(sc$value, stochastic_value, opt_value, uni_value),
regret = c(sc$regret, opt_value - stochastic_value, 0, opt_value - uni_value))
share_df <- data.frame(action = actions,
learned = vapply(seq_len(K), function(j) if (length(live)) mean(policy[live] == j) else 0, numeric(1)),
optimal = vapply(seq_len(K), function(j) if (length(live)) mean(optimal[live] == j) else 0, numeric(1)))
num_or_na <- function(x) if (is.null(x)) NA_real_ else as.numeric(x)
train_df <- data.frame(round = vapply(trace, function(t) as.integer(t$round), integer(1)),
env_steps = vapply(trace, function(t) as.integer(t$env_steps), integer(1)),
episodes = vapply(trace, function(t) as.integer(t$episodes), integer(1)),
train_return = vapply(trace, function(t) num_or_na(t$train_return), numeric(1)),
greedy_value = greedy_values,
estimated_value = vapply(trace, function(t) as.numeric(t$estimated_value), numeric(1)),
loss = vapply(trace, function(t) as.numeric(t$loss), numeric(1)),
entropy = vapply(trace, function(t) as.numeric(t$entropy), numeric(1)),
approx_kl = vapply(trace, function(t) as.numeric(t$approx_kl), numeric(1)),
clip_fraction = vapply(trace, function(t) as.numeric(t$clip_fraction), numeric(1)),
explained_variance = vapply(trace, function(t) num_or_na(t$explained_variance), numeric(1)))
has_ret <- !is.na(train_df$train_return)
curve_x <- c(train_df$env_steps, train_df$env_steps[has_ret])
curve_y <- c(train_df$greedy_value, train_df$train_return[has_ret])
curve_s <- c(rep("Learned policy (exact)", nrow(train_df)), rep("Training episodes", sum(has_ret)))
charts <- list(
cs_chart("training", "return-curve", "Return per episode while training", list(
x = cs_col("Environment steps", curve_x),
y = cs_col("Return per episode", curve_y),
series = cs_col("Curve", curve_s, levels = c("Learned policy (exact)", "Training episodes"))
), controls = list(reference = opt_value), question = "Does the learned policy get closer to the best possible return as training goes on?"),
cs_chart("actions", "share-compare", "Actions by state: learned vs optimal", list(
level = cs_col("Action", c(actions, actions), levels = actions),
share = cs_col("Share of states", c(share_df$learned, share_df$optimal)),
source = cs_col("Policy", c(rep("Learned", K), rep("Optimal", K)), levels = c("Learned", "Optimal"))
), question = "How often does the learned policy choose each action, compared with the best policy?")
)
cs_publish(list(
method = "decide.rl_ppo",
methodVersion = "2.0.0",
title = "Online policy learning (PPO)",
engine = cs_engine_info("codesplashr", "torch"),
n = fit$env_steps,
summary = summary,
statistics = list(
list(key = "policy_value", label = "Learned policy value (exact)", value = sc$value),
list(key = "optimal_value", label = "Optimal policy value", value = opt_value),
list(key = "regret", label = "Regret", value = sc$regret),
list(key = "optimal_share", label = "Share of the optimal gain", value = sc$share)
),
tables = list(
list(key = "evaluation", title = "Exact return per episode",
columns = list(list(key = "policy", label = "Policy", type = "string"), list(key = "value", label = "Return per episode", type = "number"),
list(key = "regret", label = "Regret", type = "number")),
rows = eval_df),
list(key = "policy", title = sprintf("Learned policy by state (%d states)", length(live)), columns = pol_cols, rows = pol_df),
list(key = "training", title = "Training by iteration",
columns = list(list(key = "round", label = "Iteration", type = "integer"), list(key = "env_steps", label = "Environment steps", type = "integer"),
list(key = "episodes", label = "Episodes", type = "integer"), list(key = "train_return", label = "Training return", type = "number"),
list(key = "greedy_value", label = "Learned policy value (exact)", type = "number"),
list(key = "estimated_value", label = "Network's start value", type = "number"), list(key = "loss", label = "Loss", type = "number"),
list(key = "entropy", label = "Entropy", type = "number"), list(key = "approx_kl", label = "Approximate KL", type = "number"),
list(key = "clip_fraction", label = "Clipped share", type = "percent"),
list(key = "explained_variance", label = "Explained variance", type = "number")),
rows = train_df)
),
warnings = warnings,
notes = list(paste0(
sprintf("Proximal policy optimization; %s (%d states, %d actions, episodes of up to %d steps, discount %s); ", meta$title, S, K, env$horizon,
format(gamma, digits = 15)),
sprintf("%d iterations × %d steps, %d epochs per iteration in batches of %s, hidden layers %s, learning rate %s, clip range %s, λ %s, value weight %s, entropy bonus %s; seed %s. ",
rounds, steps, epochs, if (is.null(batch_size)) "the whole rollout" else as.character(batch_size), paste(hidden, collapse = ", "),
format(lr, digits = 15), format(clip, digits = 15), format(gae_lambda, digits = 15), format(vf_coef, digits = 15),
format(ent_coef, digits = 15), seed),
"Advantages are normalized over each rollout; rewards are divided by the environment's largest absolute reward while learning. ",
"Values are exact expected discounted returns per episode over the episode length from the start state (backward recursion over the ",
"environment's transition table); the optimal policy comes from value iteration on the same table. The diagnostics compare the policy ",
"after each iteration's update with the one that collected the rollout."
)),
values = values,
charts = charts
))
PPO trained for 640 steps (21 episodes) in Admission control. Its most likely action in each state earns -0.092 per episode against 3.269 for the optimal policy and 1.651 for random actions (regret 3.361, discount 0.95); the stochastic policy itself earns 1.773.
- Learned policy value (exact)
- −0.0916
- Optimal policy value
- 3.269
- Regret
- 3.361
- Share of the optimal gain
- −1.077
To keep this page light, the plots are shown once, under the R tab.
Exact return per episode
| Policy | Return per episode | Regret |
|---|---|---|
| Learned policy (most likely action) | −0.0916 | 3.361 |
| Learned policy (sampled actions) | 1.773 | 1.496 |
| Optimal policy | 3.269 | 0 |
| Random actions | 1.651 | 1.618 |
Learned policy by state (7 states)
| state | queue | Learned action | Optimal action | P(accept) | P(reject) | State value (network) |
|---|---|---|---|---|---|---|
| queue 0 | 0 | accept | accept | 0.7640 | 0.2360 | 1.823 |
| queue 1 | 1 | accept | reject | 0.6082 | 0.3918 | 1.301 |
| queue 2 | 2 | accept | reject | 0.6848 | 0.3152 | 0.2798 |
| queue 3 | 3 | accept | reject | 0.5556 | 0.4444 | −0.3200 |
| queue 4 | 4 | accept | reject | 0.7313 | 0.2687 | −0.2712 |
| queue 5 | 5 | accept | reject | 0.6381 | 0.3619 | −0.0791 |
| queue 6 | 6 | accept | accept | 0.6788 | 0.3212 | −0.0834 |
Training by iteration
| Iteration | Environment steps | Episodes | Training return | Learned policy value (exact) | Network's start value | Loss | Entropy | Approximate KL | Clipped share | Explained variance |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 128 | 4 | 1.467 | −0.0916 | 0.6655 | 0.1206 | 0.6830 | 0.0002 | 100.0% | −1.721 |
| 2 | 256 | 8 | 2.020 | −0.0916 | 1.383 | 0.0980 | 0.6607 | 0.0089 | 92.2% | −0.2586 |
| 3 | 384 | 12 | 0.9943 | −0.0916 | 1.638 | 0.0612 | 0.6324 | 0.0146 | 39.1% | 0.4542 |
| 4 | 512 | 17 | 2.649 | −0.0916 | 1.738 | 0.0978 | 0.6079 | −0.0035 | 19.5% | 0.4611 |
| 5 | 640 | 21 | 1.747 | −0.0916 | 1.823 | 0.0879 | 0.5984 | 0.0136 | 10.2% | 0.6021 |
- The learned policy gets only -108% of the way from random actions to the optimal policy: train for more iterations or raise the entropy bonus.
- The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.
- Proximal policy optimization; Admission control (7 states, 2 actions, episodes of up to 30 steps, discount 0.95); 5 iterations × 128 steps, 4 epochs per iteration in batches of 32, hidden layers 32, learning rate 0.003, clip range 0.1, λ 0.8, value weight 1, entropy bonus 0.02; seed 42. Advantages are normalized over each rollout; rewards are divided by the environment's largest absolute reward while learning. Values are exact expected discounted returns per episode over the episode length from the start state (backward recursion over the environment's transition table); the optimal policy comes from value iteration on the same table. The diagnostics compare the policy after each iteration's update with the one that collected the rollout.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Online policy learning with proximal policy optimization (PPO)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.rl_ppo 2.0.0 · spec 2e88b600b9cfde6a
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import codesplash as cs
from codesplash.decide import online_rl as rl # twin of codesplashr::cs_rl_* (shared stream through the environment, exact evaluation)
# %% Inputs
# Environment "queue", discount 0.95: the app writes both into the environment files read below.
rounds = int(5)
steps = int(128)
epochs = int(4)
batch_size = 32
hidden = [int(u) for u in [32]]
lr = float(0.003)
encoding = "one_hot" # one_hot | features
clip = float(0.1)
gae_lambda = float(0.8)
vf_coef = float(1)
ent_coef = float(0.02)
seed = 42
warnings = []
# %% Environment: written by the app before the run (mdp/transitions.parquet + mdp/mdp.json in the run folder)
env = rl.read_mdp("target/academy-parity/run-24905/decide.rl_ppo/queue-clip-lambda/out-python")
meta = env["meta"]
S, K, gamma = env["S"], env["K"], env["gamma"]
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-24905/decide.rl_ppo/queue-clip-lambda/out-python",
)
# %% Train online
fit = rl.ppo(env, encoding, hidden, rounds, steps, epochs, batch_size, lr, clip, gae_lambda, vf_coef, ent_coef, seed)
trace = fit["trace"]
policy = fit["policy"]
sc = rl.scores(env, policy)
stochastic_value = rl.evaluate(env, fit["probs"])
best = max(range(len(trace)), key=lambda i: (trace[i]["greedy_value"], -i))
last = trace[-1]
if K == 1:
warnings.append("The environment has one action, so every policy is the same and the share of the optimal gain is undefined.")
if fit["episodes"] == 0:
warnings.append("No episode finished during training: raise the steps per iteration or the number of iterations.")
if sc["share"] is not None and sc["share"] < 0.5:
warnings.append(f"The learned policy gets only {sc['share']:.0%} of the way from random actions to the optimal policy: train for more iterations or raise the entropy bonus.")
if last["approx_kl"] > 0.1:
warnings.append(f"The last update moved the policy a lot (approximate KL {last['approx_kl']:.3f}): lower the learning rate or the epochs per iteration.")
if trace[best]["greedy_value"] > sc["value"] + 1e-9 * max(1.0, abs(sc["value"])):
warnings.append(f"An earlier iteration's policy (iteration {trace[best]['round']}) was better ({trace[best]['greedy_value']:.4g}) than the final one; the result keeps the final policy.")
warnings.append("The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.")
# %% Result
opt_value, uni_value = float(meta["optimal_value"]), float(meta["uniform_value"])
labels, actions = env["labels"], env["actions"]
live = [s for s in range(S) if not env["terminal"][s]]
optimal = meta["optimal_policy"]
summary = (
f"PPO trained for {fit['env_steps']:,} steps ({fit['episodes']:,} episodes) in {meta['title']}. Its most likely action in each state earns "
f"{sc['value']:.3f} per episode against {opt_value:.3f} for the optimal policy and {uni_value:.3f} for random actions (regret "
f"{sc['regret']:.3f}, discount {gamma:g}); the stochastic policy itself earns {stochastic_value:.3f}."
)
values = {
"policy_value": sc["value"], "stochastic_value": stochastic_value, "optimal_value": opt_value, "uniform_value": uni_value,
"regret": sc["regret"], "optimal_share": sc["share"], "optimal_actions": sc["optimal_actions"], "best_value": trace[best]["greedy_value"],
"best_round": trace[best]["round"], "final_return": last["train_return"], "estimated_value": last["estimated_value"],
"entropy": last["entropy"], "approx_kl": last["approx_kl"], "clip_fraction": last["clip_fraction"],
"explained_variance": last["explained_variance"], "n_episodes": fit["episodes"], "env_steps": fit["env_steps"], "rounds_run": len(trace),
"final_loss": last["loss"], "n_states": S, "n_actions": K, "algorithm": "ppo",
}
pol_cols = [{"key": "s1", "label": "state", "type": "string"}]
pol_cols += [{"key": f"f{j + 1}", "label": f, "type": "number"} for j, f in enumerate(meta["feature_names"])]
pol_cols += [{"key": "action", "label": "Learned action", "type": "string"}, {"key": "optimal", "label": "Optimal action", "type": "string"}]
pol_cols += [{"key": f"v{j + 1}", "label": f"P({a})", "type": "number"} for j, a in enumerate(actions)]
pol_cols.append({"key": "value", "label": "State value (network)", "type": "number"})
pol_rows = []
for s in live:
r = {"s1": labels[s]}
r.update({f"f{j + 1}": float(x) for j, x in enumerate(env["features"][s])})
r["action"] = actions[int(policy[s])]
r["optimal"] = actions[int(optimal[s])]
r.update({f"v{j + 1}": float(fit["probs"][s, j]) for j in range(K)})
r["value"] = float(fit["values"][s])
pol_rows.append(r)
eval_rows = [
{"policy": "Learned policy (most likely action)", "value": sc["value"], "regret": sc["regret"]},
{"policy": "Learned policy (sampled actions)", "value": stochastic_value, "regret": opt_value - stochastic_value},
{"policy": "Optimal policy", "value": opt_value, "regret": 0.0},
{"policy": "Random actions", "value": uni_value, "regret": opt_value - uni_value},
]
share_rows = [{"action": a, "learned": float(np.mean([int(policy[s]) == j for s in live])) if live else 0.0,
"optimal": float(np.mean([int(optimal[s]) == j for s in live])) if live else 0.0} for j, a in enumerate(actions)]
curve_x = [t["env_steps"] for t in trace]
curve_rows = [(x, t["greedy_value"], "Learned policy (exact)") for x, t in zip(curve_x, trace)]
curve_rows += [(x, t["train_return"], "Training episodes") for x, t in zip(curve_x, trace) if t["train_return"] is not None]
charts = [
cs.chart("training", "return-curve", "Return per episode while training", {
"x": cs.col("Environment steps", [r[0] for r in curve_rows]),
"y": cs.col("Return per episode", [r[1] for r in curve_rows]),
"series": cs.col("Curve", [r[2] for r in curve_rows], levels=["Learned policy (exact)", "Training episodes"]),
}, controls={"reference": opt_value}, question="Does the learned policy get closer to the best possible return as training goes on?"),
cs.chart("actions", "share-compare", "Actions by state: learned vs optimal", {
"level": cs.col("Action", [r["action"] for r in share_rows] * 2, levels=actions),
"share": cs.col("Share of states", [r["learned"] for r in share_rows] + [r["optimal"] for r in share_rows]),
"source": cs.col("Policy", ["Learned"] * K + ["Optimal"] * K, levels=["Learned", "Optimal"]),
}, question="How often does the learned policy choose each action, compared with the best policy?"),
]
cs.publish({
"method": "decide.rl_ppo",
"methodVersion": "2.0.0",
"title": "Online policy learning (PPO)",
"engine": cs.engine_info("numpy", "pandas", "torch"),
"n": fit["env_steps"],
"summary": summary,
"statistics": [
{"key": "policy_value", "label": "Learned policy value (exact)", "value": sc["value"]},
{"key": "optimal_value", "label": "Optimal policy value", "value": opt_value},
{"key": "regret", "label": "Regret", "value": sc["regret"]},
{"key": "optimal_share", "label": "Share of the optimal gain", "value": sc["share"]},
],
"tables": [
{"key": "evaluation", "title": "Exact return per episode",
"columns": [{"key": "policy", "label": "Policy", "type": "string"}, {"key": "value", "label": "Return per episode", "type": "number"},
{"key": "regret", "label": "Regret", "type": "number"}],
"rows": eval_rows},
{"key": "policy", "title": f"Learned policy by state ({len(live)} states)", "columns": pol_cols, "rows": pol_rows},
{"key": "training", "title": "Training by iteration",
"columns": [{"key": "round", "label": "Iteration", "type": "integer"}, {"key": "env_steps", "label": "Environment steps", "type": "integer"},
{"key": "episodes", "label": "Episodes", "type": "integer"}, {"key": "train_return", "label": "Training return", "type": "number"},
{"key": "greedy_value", "label": "Learned policy value (exact)", "type": "number"},
{"key": "estimated_value", "label": "Network's start value", "type": "number"}, {"key": "loss", "label": "Loss", "type": "number"},
{"key": "entropy", "label": "Entropy", "type": "number"}, {"key": "approx_kl", "label": "Approximate KL", "type": "number"},
{"key": "clip_fraction", "label": "Clipped share", "type": "percent"},
{"key": "explained_variance", "label": "Explained variance", "type": "number"}],
"rows": trace},
],
"warnings": warnings,
"notes": [
f"Proximal policy optimization; {meta['title']} ({S} states, {K} actions, episodes of up to {env['horizon']} steps, discount {gamma:g}); "
f"{rounds} iterations × {steps} steps, {epochs} epochs per iteration in batches of {batch_size if batch_size is not None else 'the whole rollout'}, "
f"hidden layers {', '.join(str(h) for h in hidden)}, learning rate {lr:g}, clip range {clip:g}, λ {gae_lambda:g}, value weight {vf_coef:g}, "
f"entropy bonus {ent_coef:g}; seed {seed}. Advantages are normalized over each rollout; rewards are divided by the environment's largest "
"absolute reward while learning. Values are exact expected discounted returns per episode over the episode length from the start state "
"(backward recursion over the environment's transition table); the optimal policy comes from value iteration on the same table. The "
"diagnostics compare the policy after each iteration's update with the one that collected the rollout.",
],
"values": values,
"charts": charts,
})
PPO trained for 600 steps (50 episodes) in Inventory. Its most likely action in each state earns 28.238 per episode against 31.113 for the optimal policy and 24.166 for random actions (regret 2.875, discount 0.9); the stochastic policy itself earns 26.296.
- Learned policy value (exact)
- 28.238
- Optimal policy value
- 31.113
- Regret
- 2.875
- Share of the optimal gain
- 0.5862
Plots
View data
| Curve | Environment steps | Return per episode |
|---|---|---|
| Learned policy (exact) | 120 | 17.889 |
| Learned policy (exact) | 240 | 28.238 |
| Learned policy (exact) | 360 | 28.238 |
| Learned policy (exact) | 480 | 28.238 |
| Learned policy (exact) | 600 | 28.238 |
| Training episodes | 120 | 24.739 |
| Training episodes | 240 | 23.706 |
| Training episodes | 360 | 22.248 |
| Training episodes | 480 | 23.239 |
| Training episodes | 600 | 21.448 |
View data
| Action | Share of states | Policy |
|---|---|---|
| order 0 | 0 | Learned |
| order 2 | 1 | Learned |
| order 4 | 0 | Learned |
| order 0 | 0.5556 | Optimal |
| order 2 | 0.2222 | Optimal |
| order 4 | 0.2222 | Optimal |
Exact return per episode
| Policy | Return per episode | Regret |
|---|---|---|
| Learned policy (most likely action) | 28.238 | 2.875 |
| Learned policy (sampled actions) | 26.296 | 4.817 |
| Optimal policy | 31.113 | 0 |
| Random actions | 24.166 | 6.947 |
Learned policy by state (9 states)
| state | stock | Learned action | Optimal action | P(order 0) | P(order 2) | P(order 4) | State value (network) |
|---|---|---|---|---|---|---|---|
| stock 0 | 0 | order 2 | order 4 | 0.1609 | 0.5061 | 0.3330 | 21.434 |
| stock 1 | 1 | order 2 | order 4 | 0.1403 | 0.5292 | 0.3304 | 24.469 |
| stock 2 | 2 | order 2 | order 2 | 0.1493 | 0.5256 | 0.3251 | 25.815 |
| stock 3 | 3 | order 2 | order 2 | 0.1655 | 0.5175 | 0.3170 | 26.569 |
| stock 4 | 4 | order 2 | order 0 | 0.1836 | 0.5086 | 0.3078 | 27.322 |
| stock 5 | 5 | order 2 | order 0 | 0.2033 | 0.4986 | 0.2980 | 28.075 |
| stock 6 | 6 | order 2 | order 0 | 0.2245 | 0.4876 | 0.2879 | 28.829 |
| stock 7 | 7 | order 2 | order 0 | 0.2473 | 0.4755 | 0.2773 | 29.582 |
| stock 8 | 8 | order 2 | order 0 | 0.2631 | 0.4689 | 0.2680 | 30.335 |
Training by iteration
| Iteration | Environment steps | Episodes | Training return | Learned policy value (exact) | Network's start value | Loss | Entropy | Approximate KL | Clipped share | Explained variance |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 120 | 10 | 24.739 | 17.889 | 15.925 | 0.0477 | 1.089 | 0.0243 | 7.5% | −0.5517 |
| 2 | 240 | 20 | 23.706 | 28.238 | 19.741 | 0.0296 | 1.092 | 0.0246 | 20.8% | −0.5606 |
| 3 | 360 | 30 | 22.248 | 28.238 | 22.670 | 0.0249 | 1.071 | 0.0194 | 5.0% | −0.3583 |
| 4 | 480 | 40 | 23.239 | 28.238 | 25.080 | 0.0436 | 1.017 | 0.0211 | 37.5% | 0.0459 |
| 5 | 600 | 50 | 21.448 | 28.238 | 25.815 | 0.0024 | 1.006 | 0.0332 | 30.8% | 0.3099 |
- The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.
- Proximal policy optimization; Inventory (9 states, 3 actions, episodes of up to 12 steps, discount 0.9); 5 iterations × 120 steps, 6 epochs per iteration in batches of the whole rollout, hidden layers 16, 16, learning rate 0.01, clip range 0.2, λ 0.95, value weight 0.5, entropy bonus 0; seed 42. Advantages are normalized over each rollout; rewards are divided by the environment's largest absolute reward while learning. Values are exact expected discounted returns per episode over the episode length from the start state (backward recursion over the environment's transition table); the optimal policy comes from value iteration on the same table. The diagnostics compare the policy after each iteration's update with the one that collected the rollout.
The exact R script · R R version 4.5.1 (2025-06-13)
# Online policy learning with proximal policy optimization (PPO)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.rl_ppo 2.0.0 · spec 866a47228beb3b35
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_rl_*(): twins of codesplash.decide.online_rl (shared stream through the environment, exact evaluation)
# %% Inputs
# Environment "inventory", discount 0.9: the app writes both into the environment files read below.
rounds <- as.integer(5)
steps <- as.integer(120)
epochs <- as.integer(6)
batch_size <- NULL
hidden <- as.integer(unlist(c(16, 16)))
lr <- as.numeric(0.01)
encoding <- "features" # one_hot | features
clip <- as.numeric(0.2)
gae_lambda <- as.numeric(0.95)
vf_coef <- as.numeric(0.5)
ent_coef <- as.numeric(0)
seed <- 42
warnings <- list()
# %% Environment: written by the app before the run (mdp/transitions.parquet + mdp/mdp.json in the run folder)
env <- cs_rl_read_mdp("target/academy-parity/run-24905/decide.rl_ppo/inventory-features-full-batch/out-r")
meta <- env$meta
S <- env$S; K <- env$K; gamma <- env$gamma
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-24905/decide.rl_ppo/inventory-features-full-batch/out-r")
# %% Train online
fit <- cs_rl_ppo(env, encoding, hidden, rounds, steps, epochs, batch_size, lr, clip, gae_lambda, vf_coef, ent_coef, seed)
trace <- fit$trace
policy <- fit$policy
sc <- cs_rl_scores(env, policy)
stochastic_value <- cs_rl_evaluate(env, fit$probs)
greedy_values <- vapply(trace, function(t) t$greedy_value, numeric(1))
best <- which.max(greedy_values)
last <- trace[[length(trace)]]
if (K == 1L) {
warnings[[length(warnings) + 1L]] <- "The environment has one action, so every policy is the same and the share of the optimal gain is undefined."
}
if (fit$episodes == 0L) {
warnings[[length(warnings) + 1L]] <- "No episode finished during training: raise the steps per iteration or the number of iterations."
}
if (!is.null(sc$share) && sc$share < 0.5) {
warnings[[length(warnings) + 1L]] <- sprintf("The learned policy gets only %.0f%% of the way from random actions to the optimal policy: train for more iterations or raise the entropy bonus.", 100 * sc$share)
}
if (last$approx_kl > 0.1) {
warnings[[length(warnings) + 1L]] <- sprintf("The last update moved the policy a lot (approximate KL %.3f): lower the learning rate or the epochs per iteration.", last$approx_kl)
}
if (greedy_values[best] > sc$value + 1e-9 * max(1, abs(sc$value))) {
warnings[[length(warnings) + 1L]] <- sprintf("An earlier iteration's policy (iteration %d) was better (%s) than the final one; the result keeps the final policy.",
trace[[best]]$round, format(signif(greedy_values[best], 4)))
}
warnings[[length(warnings) + 1L]] <- "The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it."
# %% Result
opt_value <- as.numeric(meta$optimal_value)
uni_value <- as.numeric(meta$uniform_value)
labels <- env$labels
actions <- env$actions
live <- which(!env$terminal)
optimal <- as.integer(meta$optimal_policy) + 1L
fmt3 <- function(x) formatC(x, format = "f", digits = 3)
summary <- sprintf("PPO trained for %s steps (%s episodes) in %s. Its most likely action in each state earns %s per episode against %s for the optimal policy and %s for random actions (regret %s, discount %s); the stochastic policy itself earns %s.",
format(fit$env_steps, big.mark = ","), format(fit$episodes, big.mark = ","), meta$title, fmt3(sc$value), fmt3(opt_value),
fmt3(uni_value), fmt3(sc$regret), format(gamma, digits = 15), fmt3(stochastic_value))
values <- list(policy_value = sc$value, stochastic_value = stochastic_value, optimal_value = opt_value, uniform_value = uni_value,
regret = sc$regret, optimal_share = sc$share, optimal_actions = sc$optimal_actions, best_value = greedy_values[best],
best_round = trace[[best]]$round, final_return = last$train_return, estimated_value = last$estimated_value,
entropy = last$entropy, approx_kl = last$approx_kl, clip_fraction = last$clip_fraction,
explained_variance = last$explained_variance, n_episodes = fit$episodes, env_steps = fit$env_steps, rounds_run = length(trace),
final_loss = last$loss, n_states = S, n_actions = K, algorithm = "ppo")
fnames <- as.character(meta$feature_names)
pol_cols <- list(list(key = "s1", label = "state", type = "string"))
for (j in seq_along(fnames)) pol_cols[[length(pol_cols) + 1L]] <- list(key = sprintf("f%d", j), label = fnames[j], type = "number")
pol_cols[[length(pol_cols) + 1L]] <- list(key = "action", label = "Learned action", type = "string")
pol_cols[[length(pol_cols) + 1L]] <- list(key = "optimal", label = "Optimal action", type = "string")
for (j in seq_len(K)) pol_cols[[length(pol_cols) + 1L]] <- list(key = sprintf("v%d", j), label = sprintf("P(%s)", actions[j]), type = "number")
pol_cols[[length(pol_cols) + 1L]] <- list(key = "value", label = "State value (network)", type = "number")
pol_df <- data.frame(s1 = labels[live], stringsAsFactors = FALSE)
for (j in seq_along(fnames)) pol_df[[sprintf("f%d", j)]] <- as.numeric(env$features[live, j])
pol_df$action <- actions[policy[live]]
pol_df$optimal <- actions[optimal[live]]
for (j in seq_len(K)) pol_df[[sprintf("v%d", j)]] <- as.numeric(fit$probs[live, j])
pol_df$value <- as.numeric(fit$values[live])
eval_df <- data.frame(policy = c("Learned policy (most likely action)", "Learned policy (sampled actions)", "Optimal policy", "Random actions"),
value = c(sc$value, stochastic_value, opt_value, uni_value),
regret = c(sc$regret, opt_value - stochastic_value, 0, opt_value - uni_value))
share_df <- data.frame(action = actions,
learned = vapply(seq_len(K), function(j) if (length(live)) mean(policy[live] == j) else 0, numeric(1)),
optimal = vapply(seq_len(K), function(j) if (length(live)) mean(optimal[live] == j) else 0, numeric(1)))
num_or_na <- function(x) if (is.null(x)) NA_real_ else as.numeric(x)
train_df <- data.frame(round = vapply(trace, function(t) as.integer(t$round), integer(1)),
env_steps = vapply(trace, function(t) as.integer(t$env_steps), integer(1)),
episodes = vapply(trace, function(t) as.integer(t$episodes), integer(1)),
train_return = vapply(trace, function(t) num_or_na(t$train_return), numeric(1)),
greedy_value = greedy_values,
estimated_value = vapply(trace, function(t) as.numeric(t$estimated_value), numeric(1)),
loss = vapply(trace, function(t) as.numeric(t$loss), numeric(1)),
entropy = vapply(trace, function(t) as.numeric(t$entropy), numeric(1)),
approx_kl = vapply(trace, function(t) as.numeric(t$approx_kl), numeric(1)),
clip_fraction = vapply(trace, function(t) as.numeric(t$clip_fraction), numeric(1)),
explained_variance = vapply(trace, function(t) num_or_na(t$explained_variance), numeric(1)))
has_ret <- !is.na(train_df$train_return)
curve_x <- c(train_df$env_steps, train_df$env_steps[has_ret])
curve_y <- c(train_df$greedy_value, train_df$train_return[has_ret])
curve_s <- c(rep("Learned policy (exact)", nrow(train_df)), rep("Training episodes", sum(has_ret)))
charts <- list(
cs_chart("training", "return-curve", "Return per episode while training", list(
x = cs_col("Environment steps", curve_x),
y = cs_col("Return per episode", curve_y),
series = cs_col("Curve", curve_s, levels = c("Learned policy (exact)", "Training episodes"))
), controls = list(reference = opt_value), question = "Does the learned policy get closer to the best possible return as training goes on?"),
cs_chart("actions", "share-compare", "Actions by state: learned vs optimal", list(
level = cs_col("Action", c(actions, actions), levels = actions),
share = cs_col("Share of states", c(share_df$learned, share_df$optimal)),
source = cs_col("Policy", c(rep("Learned", K), rep("Optimal", K)), levels = c("Learned", "Optimal"))
), question = "How often does the learned policy choose each action, compared with the best policy?")
)
cs_publish(list(
method = "decide.rl_ppo",
methodVersion = "2.0.0",
title = "Online policy learning (PPO)",
engine = cs_engine_info("codesplashr", "torch"),
n = fit$env_steps,
summary = summary,
statistics = list(
list(key = "policy_value", label = "Learned policy value (exact)", value = sc$value),
list(key = "optimal_value", label = "Optimal policy value", value = opt_value),
list(key = "regret", label = "Regret", value = sc$regret),
list(key = "optimal_share", label = "Share of the optimal gain", value = sc$share)
),
tables = list(
list(key = "evaluation", title = "Exact return per episode",
columns = list(list(key = "policy", label = "Policy", type = "string"), list(key = "value", label = "Return per episode", type = "number"),
list(key = "regret", label = "Regret", type = "number")),
rows = eval_df),
list(key = "policy", title = sprintf("Learned policy by state (%d states)", length(live)), columns = pol_cols, rows = pol_df),
list(key = "training", title = "Training by iteration",
columns = list(list(key = "round", label = "Iteration", type = "integer"), list(key = "env_steps", label = "Environment steps", type = "integer"),
list(key = "episodes", label = "Episodes", type = "integer"), list(key = "train_return", label = "Training return", type = "number"),
list(key = "greedy_value", label = "Learned policy value (exact)", type = "number"),
list(key = "estimated_value", label = "Network's start value", type = "number"), list(key = "loss", label = "Loss", type = "number"),
list(key = "entropy", label = "Entropy", type = "number"), list(key = "approx_kl", label = "Approximate KL", type = "number"),
list(key = "clip_fraction", label = "Clipped share", type = "percent"),
list(key = "explained_variance", label = "Explained variance", type = "number")),
rows = train_df)
),
warnings = warnings,
notes = list(paste0(
sprintf("Proximal policy optimization; %s (%d states, %d actions, episodes of up to %d steps, discount %s); ", meta$title, S, K, env$horizon,
format(gamma, digits = 15)),
sprintf("%d iterations × %d steps, %d epochs per iteration in batches of %s, hidden layers %s, learning rate %s, clip range %s, λ %s, value weight %s, entropy bonus %s; seed %s. ",
rounds, steps, epochs, if (is.null(batch_size)) "the whole rollout" else as.character(batch_size), paste(hidden, collapse = ", "),
format(lr, digits = 15), format(clip, digits = 15), format(gae_lambda, digits = 15), format(vf_coef, digits = 15),
format(ent_coef, digits = 15), seed),
"Advantages are normalized over each rollout; rewards are divided by the environment's largest absolute reward while learning. ",
"Values are exact expected discounted returns per episode over the episode length from the start state (backward recursion over the ",
"environment's transition table); the optimal policy comes from value iteration on the same table. The diagnostics compare the policy ",
"after each iteration's update with the one that collected the rollout."
)),
values = values,
charts = charts
))
PPO trained for 600 steps (50 episodes) in Inventory. Its most likely action in each state earns 28.238 per episode against 31.113 for the optimal policy and 24.166 for random actions (regret 2.875, discount 0.9); the stochastic policy itself earns 26.296.
- Learned policy value (exact)
- 28.238
- Optimal policy value
- 31.113
- Regret
- 2.875
- Share of the optimal gain
- 0.5862
To keep this page light, the plots are shown once, under the R tab.
Exact return per episode
| Policy | Return per episode | Regret |
|---|---|---|
| Learned policy (most likely action) | 28.238 | 2.875 |
| Learned policy (sampled actions) | 26.296 | 4.817 |
| Optimal policy | 31.113 | 0 |
| Random actions | 24.166 | 6.947 |
Learned policy by state (9 states)
| state | stock | Learned action | Optimal action | P(order 0) | P(order 2) | P(order 4) | State value (network) |
|---|---|---|---|---|---|---|---|
| stock 0 | 0 | order 2 | order 4 | 0.1609 | 0.5061 | 0.3330 | 21.434 |
| stock 1 | 1 | order 2 | order 4 | 0.1403 | 0.5292 | 0.3304 | 24.469 |
| stock 2 | 2 | order 2 | order 2 | 0.1493 | 0.5256 | 0.3251 | 25.815 |
| stock 3 | 3 | order 2 | order 2 | 0.1655 | 0.5175 | 0.3170 | 26.569 |
| stock 4 | 4 | order 2 | order 0 | 0.1836 | 0.5086 | 0.3078 | 27.322 |
| stock 5 | 5 | order 2 | order 0 | 0.2033 | 0.4986 | 0.2980 | 28.075 |
| stock 6 | 6 | order 2 | order 0 | 0.2245 | 0.4876 | 0.2879 | 28.829 |
| stock 7 | 7 | order 2 | order 0 | 0.2473 | 0.4755 | 0.2773 | 29.582 |
| stock 8 | 8 | order 2 | order 0 | 0.2631 | 0.4689 | 0.2680 | 30.335 |
Training by iteration
| Iteration | Environment steps | Episodes | Training return | Learned policy value (exact) | Network's start value | Loss | Entropy | Approximate KL | Clipped share | Explained variance |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 120 | 10 | 24.739 | 17.889 | 15.925 | 0.0477 | 1.089 | 0.0243 | 7.5% | −0.5517 |
| 2 | 240 | 20 | 23.706 | 28.238 | 19.741 | 0.0296 | 1.092 | 0.0246 | 20.8% | −0.5606 |
| 3 | 360 | 30 | 22.248 | 28.238 | 22.670 | 0.0249 | 1.071 | 0.0194 | 5.0% | −0.3583 |
| 4 | 480 | 40 | 23.239 | 28.238 | 25.080 | 0.0436 | 1.017 | 0.0211 | 37.5% | 0.0459 |
| 5 | 600 | 50 | 21.448 | 28.238 | 25.815 | 0.0024 | 1.006 | 0.0332 | 30.8% | 0.3099 |
- The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.
- Proximal policy optimization; Inventory (9 states, 3 actions, episodes of up to 12 steps, discount 0.9); 5 iterations × 120 steps, 6 epochs per iteration in batches of the whole rollout, hidden layers 16, 16, learning rate 0.01, clip range 0.2, λ 0.95, value weight 0.5, entropy bonus 0; seed 42. Advantages are normalized over each rollout; rewards are divided by the environment's largest absolute reward while learning. Values are exact expected discounted returns per episode over the episode length from the start state (backward recursion over the environment's transition table); the optimal policy comes from value iteration on the same table. The diagnostics compare the policy after each iteration's update with the one that collected the rollout.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Online policy learning with proximal policy optimization (PPO)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.rl_ppo 2.0.0 · spec 866a47228beb3b35
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import codesplash as cs
from codesplash.decide import online_rl as rl # twin of codesplashr::cs_rl_* (shared stream through the environment, exact evaluation)
# %% Inputs
# Environment "inventory", discount 0.9: the app writes both into the environment files read below.
rounds = int(5)
steps = int(120)
epochs = int(6)
batch_size = None
hidden = [int(u) for u in [16, 16]]
lr = float(0.01)
encoding = "features" # one_hot | features
clip = float(0.2)
gae_lambda = float(0.95)
vf_coef = float(0.5)
ent_coef = float(0)
seed = 42
warnings = []
# %% Environment: written by the app before the run (mdp/transitions.parquet + mdp/mdp.json in the run folder)
env = rl.read_mdp("target/academy-parity/run-24905/decide.rl_ppo/inventory-features-full-batch/out-python")
meta = env["meta"]
S, K, gamma = env["S"], env["K"], env["gamma"]
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-24905/decide.rl_ppo/inventory-features-full-batch/out-python",
)
# %% Train online
fit = rl.ppo(env, encoding, hidden, rounds, steps, epochs, batch_size, lr, clip, gae_lambda, vf_coef, ent_coef, seed)
trace = fit["trace"]
policy = fit["policy"]
sc = rl.scores(env, policy)
stochastic_value = rl.evaluate(env, fit["probs"])
best = max(range(len(trace)), key=lambda i: (trace[i]["greedy_value"], -i))
last = trace[-1]
if K == 1:
warnings.append("The environment has one action, so every policy is the same and the share of the optimal gain is undefined.")
if fit["episodes"] == 0:
warnings.append("No episode finished during training: raise the steps per iteration or the number of iterations.")
if sc["share"] is not None and sc["share"] < 0.5:
warnings.append(f"The learned policy gets only {sc['share']:.0%} of the way from random actions to the optimal policy: train for more iterations or raise the entropy bonus.")
if last["approx_kl"] > 0.1:
warnings.append(f"The last update moved the policy a lot (approximate KL {last['approx_kl']:.3f}): lower the learning rate or the epochs per iteration.")
if trace[best]["greedy_value"] > sc["value"] + 1e-9 * max(1.0, abs(sc["value"])):
warnings.append(f"An earlier iteration's policy (iteration {trace[best]['round']}) was better ({trace[best]['greedy_value']:.4g}) than the final one; the result keeps the final policy.")
warnings.append("The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.")
# %% Result
opt_value, uni_value = float(meta["optimal_value"]), float(meta["uniform_value"])
labels, actions = env["labels"], env["actions"]
live = [s for s in range(S) if not env["terminal"][s]]
optimal = meta["optimal_policy"]
summary = (
f"PPO trained for {fit['env_steps']:,} steps ({fit['episodes']:,} episodes) in {meta['title']}. Its most likely action in each state earns "
f"{sc['value']:.3f} per episode against {opt_value:.3f} for the optimal policy and {uni_value:.3f} for random actions (regret "
f"{sc['regret']:.3f}, discount {gamma:g}); the stochastic policy itself earns {stochastic_value:.3f}."
)
values = {
"policy_value": sc["value"], "stochastic_value": stochastic_value, "optimal_value": opt_value, "uniform_value": uni_value,
"regret": sc["regret"], "optimal_share": sc["share"], "optimal_actions": sc["optimal_actions"], "best_value": trace[best]["greedy_value"],
"best_round": trace[best]["round"], "final_return": last["train_return"], "estimated_value": last["estimated_value"],
"entropy": last["entropy"], "approx_kl": last["approx_kl"], "clip_fraction": last["clip_fraction"],
"explained_variance": last["explained_variance"], "n_episodes": fit["episodes"], "env_steps": fit["env_steps"], "rounds_run": len(trace),
"final_loss": last["loss"], "n_states": S, "n_actions": K, "algorithm": "ppo",
}
pol_cols = [{"key": "s1", "label": "state", "type": "string"}]
pol_cols += [{"key": f"f{j + 1}", "label": f, "type": "number"} for j, f in enumerate(meta["feature_names"])]
pol_cols += [{"key": "action", "label": "Learned action", "type": "string"}, {"key": "optimal", "label": "Optimal action", "type": "string"}]
pol_cols += [{"key": f"v{j + 1}", "label": f"P({a})", "type": "number"} for j, a in enumerate(actions)]
pol_cols.append({"key": "value", "label": "State value (network)", "type": "number"})
pol_rows = []
for s in live:
r = {"s1": labels[s]}
r.update({f"f{j + 1}": float(x) for j, x in enumerate(env["features"][s])})
r["action"] = actions[int(policy[s])]
r["optimal"] = actions[int(optimal[s])]
r.update({f"v{j + 1}": float(fit["probs"][s, j]) for j in range(K)})
r["value"] = float(fit["values"][s])
pol_rows.append(r)
eval_rows = [
{"policy": "Learned policy (most likely action)", "value": sc["value"], "regret": sc["regret"]},
{"policy": "Learned policy (sampled actions)", "value": stochastic_value, "regret": opt_value - stochastic_value},
{"policy": "Optimal policy", "value": opt_value, "regret": 0.0},
{"policy": "Random actions", "value": uni_value, "regret": opt_value - uni_value},
]
share_rows = [{"action": a, "learned": float(np.mean([int(policy[s]) == j for s in live])) if live else 0.0,
"optimal": float(np.mean([int(optimal[s]) == j for s in live])) if live else 0.0} for j, a in enumerate(actions)]
curve_x = [t["env_steps"] for t in trace]
curve_rows = [(x, t["greedy_value"], "Learned policy (exact)") for x, t in zip(curve_x, trace)]
curve_rows += [(x, t["train_return"], "Training episodes") for x, t in zip(curve_x, trace) if t["train_return"] is not None]
charts = [
cs.chart("training", "return-curve", "Return per episode while training", {
"x": cs.col("Environment steps", [r[0] for r in curve_rows]),
"y": cs.col("Return per episode", [r[1] for r in curve_rows]),
"series": cs.col("Curve", [r[2] for r in curve_rows], levels=["Learned policy (exact)", "Training episodes"]),
}, controls={"reference": opt_value}, question="Does the learned policy get closer to the best possible return as training goes on?"),
cs.chart("actions", "share-compare", "Actions by state: learned vs optimal", {
"level": cs.col("Action", [r["action"] for r in share_rows] * 2, levels=actions),
"share": cs.col("Share of states", [r["learned"] for r in share_rows] + [r["optimal"] for r in share_rows]),
"source": cs.col("Policy", ["Learned"] * K + ["Optimal"] * K, levels=["Learned", "Optimal"]),
}, question="How often does the learned policy choose each action, compared with the best policy?"),
]
cs.publish({
"method": "decide.rl_ppo",
"methodVersion": "2.0.0",
"title": "Online policy learning (PPO)",
"engine": cs.engine_info("numpy", "pandas", "torch"),
"n": fit["env_steps"],
"summary": summary,
"statistics": [
{"key": "policy_value", "label": "Learned policy value (exact)", "value": sc["value"]},
{"key": "optimal_value", "label": "Optimal policy value", "value": opt_value},
{"key": "regret", "label": "Regret", "value": sc["regret"]},
{"key": "optimal_share", "label": "Share of the optimal gain", "value": sc["share"]},
],
"tables": [
{"key": "evaluation", "title": "Exact return per episode",
"columns": [{"key": "policy", "label": "Policy", "type": "string"}, {"key": "value", "label": "Return per episode", "type": "number"},
{"key": "regret", "label": "Regret", "type": "number"}],
"rows": eval_rows},
{"key": "policy", "title": f"Learned policy by state ({len(live)} states)", "columns": pol_cols, "rows": pol_rows},
{"key": "training", "title": "Training by iteration",
"columns": [{"key": "round", "label": "Iteration", "type": "integer"}, {"key": "env_steps", "label": "Environment steps", "type": "integer"},
{"key": "episodes", "label": "Episodes", "type": "integer"}, {"key": "train_return", "label": "Training return", "type": "number"},
{"key": "greedy_value", "label": "Learned policy value (exact)", "type": "number"},
{"key": "estimated_value", "label": "Network's start value", "type": "number"}, {"key": "loss", "label": "Loss", "type": "number"},
{"key": "entropy", "label": "Entropy", "type": "number"}, {"key": "approx_kl", "label": "Approximate KL", "type": "number"},
{"key": "clip_fraction", "label": "Clipped share", "type": "percent"},
{"key": "explained_variance", "label": "Explained variance", "type": "number"}],
"rows": trace},
],
"warnings": warnings,
"notes": [
f"Proximal policy optimization; {meta['title']} ({S} states, {K} actions, episodes of up to {env['horizon']} steps, discount {gamma:g}); "
f"{rounds} iterations × {steps} steps, {epochs} epochs per iteration in batches of {batch_size if batch_size is not None else 'the whole rollout'}, "
f"hidden layers {', '.join(str(h) for h in hidden)}, learning rate {lr:g}, clip range {clip:g}, λ {gae_lambda:g}, value weight {vf_coef:g}, "
f"entropy bonus {ent_coef:g}; seed {seed}. Advantages are normalized over each rollout; rewards are divided by the environment's largest "
"absolute reward while learning. Values are exact expected discounted returns per episode over the episode length from the start state "
"(backward recursion over the environment's transition table); the optimal policy comes from value iteration on the same table. The "
"diagnostics compare the policy after each iteration's update with the one that collected the rollout.",
],
"values": values,
"charts": charts,
})
The critic explains 60.2% of the variation in the queue and 31.0% in the inventory problem.
Predict: no baseline
PredictPredict first
You remove the baseline from REINFORCE and use the raw return. What happens to the gradient estimate?
Reveal
Unbiased but noisier. The baseline never changed the expectation; it only removed variance. Training needs more episodes for the same progress.
What runs here
ReadCommon mistakes
ReadCheck: policy gradients
CheckpointCheck yourself
An action's advantage estimate is negative. What does the actor update do?
Show the answer
Answer: a
The update scales ∇log π by the advantage; a negative advantage pushes the log-probability down.
Check yourself
What does the critic contribute in A2C?
Show the answer
Answer: a
The critic is trained on returns; the actor is trained on advantages computed with it.
Check yourself
Why does the A2C loss subtract an entropy term?
Show the answer
Answer: a
Without it, the policy can lock onto one action before it has seen enough of the others.
Check yourself
Which baseline would bias the policy gradient?
Show the answer
Answer: a
Action-independent baselines leave the expectation unchanged because E[∇log π(a∣s)] = 0 over actions.
Recap
Recap- Policy gradients raise the log-probability of actions in proportion to how well they turned out.
- A state-only baseline keeps the gradient unbiased and cuts its variance; with V(s) it gives advantages.
- Actor–critic methods train a policy and a value critic together, with an entropy bonus.
- CodeSplash's PPO is an actor–critic; read its critic's explained variance.
Concepts in this lesson