Skip to content

Trust regions and clipping: TRPO and PPO

Reuse a batch for several updates without wrecking the policy. TRPO limits each step's KL divergence; PPO clips the probability ratio. Read PPO's approximate KL and clip fraction to judge an update.

Advanced ~15 min9 steps

What runs in CodeSplash

You will be able to

  • Write the surrogate objective with the probability ratio
  • Explain TRPO's KL constraint and why it is expensive to enforce
  • Compute PPO's clipped surrogate for positive and negative advantages
  • Read approximate KL and clip fraction in a CodeSplash PPO run

Read first

01

Reusing a batch is risky

Read

A plain policy gradient uses each batch once. To squeeze more from it, optimize a surrogate built from the probability ratio between the new policy and the one that collected the data:

L(θ)=E[ρt A^t],ρt=πθ(at∣st)πold(at∣st).L(\theta) = \mathbb{E}\big[\rho_t\, \hat A_t\big], \qquad \rho_t = \frac{\pi_\theta(a_t \mid s_t)}{\pi_{\text{old}}(a_t \mid s_t)} .

The surrogate only matches the true objective near the old policy. Push it far and the estimate is fiction: the policy can collapse in one update.

02

TRPO: a hard limit on the step

Read

TRPOTrust region policy optimization (TRPO)Improve the policy's surrogate objective subject to a hard limit on the average KL divergence from the old policy. maximizes the surrogate subject to an average KL divergenceKullback–Leibler divergenceHow many extra nats it costs to describe draws from one distribution with a code built for another; 0 when they match. between old and new policy of at most δ:

max⁡θ  E[ρtA^t]s.t.E[KL(πold∥πθ)]≤δ.\max_\theta\; \mathbb{E}[\rho_t \hat A_t] \quad \text{s.t.} \quad \mathbb{E}\big[\mathrm{KL}(\pi_{\text{old}} \Vert \pi_\theta)\big] \le \delta .

It solves this with conjugate gradients on second-order information and a line search that backs off until the limit holds. In the reference's example a candidate policy improves the surrogate to 0.427 with an average KL of 0.0059, inside a limit of a hundredth, so the step is accepted. Reliable, but expensive and awkward with shared networks.

03

PPO: clip the ratio

Read

PPOProximal policy optimization (PPO)Improves a stochastic policy in small steps: the objective stops rewarding changes once an action's probability ratio leaves 1 ± ε. replaces the constraint with clipping:

Lclip=E[min⁡(ρtA^t,  clip(ρt,1−ϵ,1+ϵ) A^t)].L^{\text{clip}} = \mathbb{E}\big[\min\big(\rho_t \hat A_t,\; \mathrm{clip}(\rho_t, 1 - \epsilon, 1 + \epsilon)\, \hat A_t\big)\big].

For a positive advantage, gains stop once ρ\rho passes 1+ϵ1 + \epsilon; for a negative one, once it falls below 1−ϵ1 - \epsilon. The min makes the objective pessimistic: clipping never makes a change look better than it is. In the reference's example, ratios ρ=(1.3,0.7,1.1,0.9)\rho = (1.3, 0.7, 1.1, 0.9) with advantages (+1,+1,−1,−1)(+1, +1, -1, -1) and ϵ=0.2\epsilon = 0.2 give clipped terms 1.2, 0.7, −1.1 and −0.9.

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.

500

Trips from the start until the goal, the pit or 100 steps.

0.95

How much a reward one step later is worth now.

0.50

Step size of every update.

0.10

Q-learning only: share of steps that take a random action.

0.20

PPO only: how far the policy may move from the one that collected the batch.

0.10

Chance that a move turns 90° to either side.

Simulating…
Working…

Working…

04

Read the update diagnostics

In the app
Online policy learning (PPO)Recorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

PPO trained for 40,960 steps (1,365 episodes) in Admission control. Its most likely action in each state earns 3.269 per episode against 3.269 for the optimal policy and 1.651 for random actions (regret 0.000, discount 0.95); the stochastic policy itself earns 3.240.

Learned policy value (exact)
3.269
Optimal policy value
3.269
Regret
0
Share of the optimal gain
1

Plots

Return per episode while trainingDoes the learned policy get closer to the best possible return as training goes on?
View data
CurveEnvironment stepsReturn per episode
Learned policy (exact)1,0240.6682
Learned policy (exact)2,0481.435
Learned policy (exact)3,0723.269
Learned policy (exact)4,0963.269
Learned policy (exact)5,1203.269
Learned policy (exact)6,1443.269
Learned policy (exact)7,1683.269
Learned policy (exact)8,1923.269
Learned policy (exact)9,2163.269
Learned policy (exact)10,2403.269
Learned policy (exact)11,2643.269
Learned policy (exact)12,2883.269
Learned policy (exact)13,3123.269
Learned policy (exact)14,3363.269
Learned policy (exact)15,3603.269
Learned policy (exact)16,3843.269
Learned policy (exact)17,4083.269
Learned policy (exact)18,4323.269
Learned policy (exact)19,4563.269
Learned policy (exact)20,4803.269
Learned policy (exact)21,5043.269
Learned policy (exact)22,5283.269
Learned policy (exact)23,5523.269
Learned policy (exact)24,5763.269
Learned policy (exact)25,6003.269
Learned policy (exact)26,6243.269
Learned policy (exact)27,6483.269
Learned policy (exact)28,6723.269
Learned policy (exact)29,6963.269
Learned policy (exact)30,7203.269
Learned policy (exact)31,7443.269
Learned policy (exact)32,7683.269
Learned policy (exact)33,7923.269
Learned policy (exact)34,8163.269
Learned policy (exact)35,8403.269
Learned policy (exact)36,8643.269
Learned policy (exact)37,8883.269
Learned policy (exact)38,9123.269
Learned policy (exact)39,9363.269
Learned policy (exact)40,9603.269
Training episodes1,0241.567
Training episodes2,0482.368
Training episodes3,0722.079
Training episodes4,0961.993
Training episodes5,1202.602
Training episodes6,1442.621
Training episodes7,1682.764
Training episodes8,1922.543
Training episodes9,2162.612
Training episodes10,2403.004
Training episodes11,2643.296
Training episodes12,2883.360
Training episodes13,3123.072
Training episodes14,3363.386
Training episodes15,3603.251
Training episodes16,3843.517
Training episodes17,4082.858
Training episodes18,4323.463
Training episodes19,4563.203
Training episodes20,4803.122

First 60 of 80 rows.

Actions by state: learned vs optimalHow often does the learned policy choose each action, compared with the best policy?
View data
ActionShare of statesPolicy
accept0.2857Learned
reject0.7143Learned
accept0.2857Optimal
reject0.7143Optimal

Exact return per episode

PolicyReturn per episodeRegret
Learned policy (most likely action)3.2690
Learned policy (sampled actions)3.2400.0294
Optimal policy3.2690
Random actions1.6511.618

Learned policy by state (7 states)

statequeueLearned actionOptimal actionP(accept)P(reject)State value (network)
queue 00acceptaccept0.99660.00344.102
queue 11rejectreject0.02780.97223.214
queue 22rejectreject0.07650.92352.088
queue 33rejectreject0.03260.9674−0.6559
queue 44rejectreject0.03540.9646−2.016
queue 55rejectreject0.06950.9305−0.8703
queue 66acceptaccept0.79820.2018−0.3915

Training by iteration

IterationEnvironment stepsEpisodesTraining returnLearned policy value (exact)Network's start valueLossEntropyApproximate KLClipped shareExplained variance
11,024341.5670.66821.0890.14530.68060.02020.0%−0.5517
22,048682.3681.4351.8000.09400.64840.013125.6%0.3907
33,0721022.0793.2692.0040.23220.61970.011915.2%0.4881
44,0961361.9933.2692.1790.22310.57620.016029.3%0.4912
55,1201702.6023.2692.5630.23650.52130.003810.2%0.4090
66,1442042.6213.2692.7560.25260.46100.013916.6%0.4006
77,1682382.7643.2693.1880.17740.43930.00221.5%0.3277
88,1922732.5433.2693.0610.21300.38800.00808.8%0.3888
99,2163072.6123.2693.1710.17650.34230.00300.0%0.2804
1010,2403413.0043.2693.3830.16760.29130.00495.3%0.3435
1111,2643753.2963.2693.6600.17470.24360.00374.8%0.2699
1212,2884093.3603.2693.8120.16360.22760.00110.1%0.1811
1313,3124433.0723.2693.9850.16590.20070.00374.5%0.2444
1414,3364773.3863.2694.0030.13870.1656−0.00131.9%0.2305
1515,3605123.2513.2694.0380.18420.19220.00160.0%0.2390
1616,3845463.5173.2694.1230.13330.18890.00283.0%0.2289
1717,4085802.8583.2693.9620.12820.19310.00161.5%0.2008
1818,4326143.4633.2694.1300.15630.18680.00191.1%0.2186
1919,4566483.2033.2693.9610.17440.18140.00825.2%0.2509
2020,4806823.1223.2694.1280.19540.13850.00405.3%0.3028
2121,5047162.9423.2693.9780.16300.12700.00140.0%0.2176
2222,5287503.4393.2694.0270.14710.13610.00170.5%0.2087
2323,5527853.3713.2694.0730.14370.1180−0.00072.9%0.2139
2424,5768193.0913.2693.9190.15270.09574.055e-52.6%0.2494
2525,6008533.3483.2693.8730.10580.19560.02480.2%0.2256
2626,6248872.8663.2693.7890.11520.17010.00060.1%0.3056
2727,6489213.4073.2693.8930.12960.15190.00130.0%0.2256
2828,6729552.9963.2693.9860.11360.1298−6.507e-52.1%0.1937
2929,6969893.1603.2694.0310.12440.10200.00232.2%0.2250
3030,7201,0242.8213.2693.9220.16110.08790.00190.0%0.2302
3131,7441,0583.2843.2693.9960.15000.0859−0.00041.1%0.2325
3232,7681,0923.1533.2693.9170.10590.09030.00050.0%0.1443
3333,7921,1262.8813.2693.9240.15800.08080.00220.0%0.2075
3434,8161,1603.1663.2694.0020.11500.06100.00131.9%0.2206
3535,8401,1943.3053.2694.1440.14350.0533−0.00030.5%0.2219
3636,8641,2283.0953.2694.0690.13800.04320.00020.9%0.2100
3737,8881,2623.3143.2693.9990.15340.03440.00020.2%0.2729
3838,9121,2973.5023.2694.1410.14450.06200.00230.6%0.1879
3939,9361,3312.8893.2694.0430.17580.0684−0.00130.7%0.2089
4040,9601,3653.5963.2694.1020.15470.0591−0.00070.1%0.2039
  • 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); 40 iterations × 1024 steps, 4 epochs per iteration in batches of 64, hidden layers 32, learning rate 0.003, clip range 0.2, λ 0.95, value weight 0.5, entropy bonus 0.01; 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 b9a54aac545aa1a4
# 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(40)
steps <- as.integer(1024)
epochs <- as.integer(4)
batch_size <- 64
hidden <- as.integer(unlist(c(32)))
lr <- as.numeric(0.003)
encoding <- "one_hot" # 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.01)
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-worked-example/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-worked-example/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
))
Python

PPO trained for 40,960 steps (1,365 episodes) in Admission control. Its most likely action in each state earns 3.269 per episode against 3.269 for the optimal policy and 1.651 for random actions (regret 0.000, discount 0.95); the stochastic policy itself earns 3.240.

Learned policy value (exact)
3.269
Optimal policy value
3.269
Regret
0
Share of the optimal gain
1

To keep this page light, the plots are shown once, under the R tab.

Exact return per episode

PolicyReturn per episodeRegret
Learned policy (most likely action)3.2690
Learned policy (sampled actions)3.2400.0294
Optimal policy3.2690
Random actions1.6511.618

Learned policy by state (7 states)

statequeueLearned actionOptimal actionP(accept)P(reject)State value (network)
queue 00acceptaccept0.99660.00344.102
queue 11rejectreject0.02780.97223.214
queue 22rejectreject0.07650.92352.088
queue 33rejectreject0.03260.9674−0.6559
queue 44rejectreject0.03540.9646−2.016
queue 55rejectreject0.06950.9305−0.8703
queue 66acceptaccept0.79820.2018−0.3915

Training by iteration

IterationEnvironment stepsEpisodesTraining returnLearned policy value (exact)Network's start valueLossEntropyApproximate KLClipped shareExplained variance
11,024341.5670.66821.0890.14530.68060.02020.0%−0.5517
22,048682.3681.4351.8000.09400.64840.013125.6%0.3907
33,0721022.0793.2692.0040.23220.61970.011915.2%0.4881
44,0961361.9933.2692.1790.22310.57620.016029.3%0.4912
55,1201702.6023.2692.5630.23650.52130.003810.2%0.4090
66,1442042.6213.2692.7560.25260.46100.013916.6%0.4006
77,1682382.7643.2693.1880.17740.43930.00221.5%0.3277
88,1922732.5433.2693.0610.21300.38800.00808.8%0.3888
99,2163072.6123.2693.1710.17650.34230.00300.0%0.2804
1010,2403413.0043.2693.3830.16760.29130.00495.3%0.3435
1111,2643753.2963.2693.6600.17470.24360.00374.8%0.2699
1212,2884093.3603.2693.8120.16360.22760.00110.1%0.1811
1313,3124433.0723.2693.9850.16590.20070.00374.5%0.2444
1414,3364773.3863.2694.0030.13870.1656−0.00131.9%0.2305
1515,3605123.2513.2694.0380.18420.19220.00160.0%0.2390
1616,3845463.5173.2694.1230.13330.18890.00283.0%0.2289
1717,4085802.8583.2693.9620.12820.19310.00161.5%0.2008
1818,4326143.4633.2694.1300.15630.18680.00191.1%0.2186
1919,4566483.2033.2693.9610.17440.18140.00825.2%0.2509
2020,4806823.1223.2694.1280.19540.13850.00405.3%0.3028
2121,5047162.9423.2693.9780.16300.12700.00140.0%0.2176
2222,5287503.4393.2694.0270.14710.13610.00170.5%0.2087
2323,5527853.3713.2694.0730.14370.1180−0.00072.9%0.2139
2424,5768193.0913.2693.9190.15270.09574.055e-52.6%0.2494
2525,6008533.3483.2693.8730.10580.19560.02480.2%0.2256
2626,6248872.8663.2693.7890.11520.17010.00060.1%0.3056
2727,6489213.4073.2693.8930.12960.15190.00130.0%0.2256
2828,6729552.9963.2693.9860.11360.1298−6.507e-52.1%0.1937
2929,6969893.1603.2694.0310.12440.10200.00232.2%0.2250
3030,7201,0242.8213.2693.9220.16110.08790.00190.0%0.2302
3131,7441,0583.2843.2693.9960.15000.0859−0.00041.1%0.2325
3232,7681,0923.1533.2693.9170.10590.09030.00050.0%0.1443
3333,7921,1262.8813.2693.9240.15800.08080.00220.0%0.2075
3434,8161,1603.1663.2694.0020.11500.06100.00131.9%0.2206
3535,8401,1943.3053.2694.1440.14350.0533−0.00030.5%0.2219
3636,8641,2283.0953.2694.0690.13800.04320.00020.9%0.2100
3737,8881,2623.3143.2693.9990.15340.03440.00020.2%0.2729
3838,9121,2973.5023.2694.1410.14450.06200.00230.6%0.1879
3939,9361,3312.8893.2694.0430.17580.0684−0.00130.7%0.2089
4040,9601,3653.5963.2694.1020.15470.0591−0.00070.1%0.2039
  • 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); 40 iterations × 1024 steps, 4 epochs per iteration in batches of 64, hidden layers 32, learning rate 0.003, clip range 0.2, λ 0.95, value weight 0.5, entropy bonus 0.01; 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 b9a54aac545aa1a4
# 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(40)
steps = int(1024)
epochs = int(4)
batch_size = 64
hidden = [int(u) for u in [32]]
lr = float(0.003)
encoding = "one_hot"  # one_hot | features
clip = float(0.2)
gae_lambda = float(0.95)
vf_coef = float(0.5)
ent_coef = float(0.01)
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-worked-example/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-worked-example/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,
})

Every PPO run reports update diagnosticsPPO update diagnosticsHow far the last update moved the policy: the approximate KL divergence and the share of steps whose ratio left 1 ± ε. for its last iteration: the approximate KL between old and new policy, here −0.0007, and the clip fraction, the share of samples whose ratio hit the clip, here 0.1%. Both near zero: calm updates near convergence. The KL is estimated from the sampled actions, so when the policy barely moves it can dip slightly below zero.

Online policy learning (PPO)Recorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

PPO trained for 40 steps (40 episodes) in Custom gridworld. Its most likely action in each state earns 1.000 per episode against 1.000 for the optimal policy and 0.250 for random actions (regret 0.000, discount 0.95); the stochastic policy itself earns 0.593.

Learned policy value (exact)
1
Optimal policy value
1
Regret
0
Share of the optimal gain
1

Plots

Return per episode while trainingDoes the learned policy get closer to the best possible return as training goes on?
View data
CurveEnvironment stepsReturn per episode
Learned policy (exact)201
Learned policy (exact)401
Training episodes200.2500
Training episodes400.2500
Actions by state: learned vs optimalHow often does the learned policy choose each action, compared with the best policy?
View data
ActionShare of statesPolicy
up0Learned
down0Learned
left0Learned
right1Learned
up0Optimal
down0Optimal
left0Optimal
right1Optimal

Exact return per episode

PolicyReturn per episodeRegret
Learned policy (most likely action)10
Learned policy (sampled actions)0.59330.4067
Optimal policy10
Random actions0.25000.7500

Learned policy by state (1 states)

staterowcolLearned actionOptimal actionP(up)P(down)P(left)P(right)State value (network)
r1c111rightright0.14600.13550.12520.59330.4537

Training by iteration

IterationEnvironment stepsEpisodesTraining returnLearned policy value (exact)Network's start valueLossEntropyApproximate KLClipped shareExplained variance
120200.250010.1239−0.01831.3260.057880.0%0
240400.250010.4537−0.10321.1220.1957100.0%0
  • The last update moved the policy a lot (approximate KL 0.196): lower the learning rate or the epochs per iteration.
  • 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; Custom gridworld (2 states, 4 actions, episodes of up to 1 steps, discount 0.95); 2 iterations × 20 steps, 4 epochs per iteration in batches of 8, hidden layers 32, learning rate 0.003, clip range 0.2, λ 0.95, value weight 0.5, entropy bonus 0.01; 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 ef74235f5e862c9b
# 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 "gridworld", discount 0.95: the app writes both into the environment files read below.
rounds <- as.integer(2)
steps <- as.integer(20)
epochs <- as.integer(4)
batch_size <- 8
hidden <- as.integer(unlist(c(32)))
lr <- as.numeric(0.003)
encoding <- "one_hot" # 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.01)
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/degenerate-short-episodes/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/degenerate-short-episodes/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
))
Python

PPO trained for 40 steps (40 episodes) in Custom gridworld. Its most likely action in each state earns 1.000 per episode against 1.000 for the optimal policy and 0.250 for random actions (regret 0.000, discount 0.95); the stochastic policy itself earns 0.593.

Learned policy value (exact)
1
Optimal policy value
1
Regret
0
Share of the optimal gain
1

To keep this page light, the plots are shown once, under the R tab.

Exact return per episode

PolicyReturn per episodeRegret
Learned policy (most likely action)10
Learned policy (sampled actions)0.59330.4067
Optimal policy10
Random actions0.25000.7500

Learned policy by state (1 states)

staterowcolLearned actionOptimal actionP(up)P(down)P(left)P(right)State value (network)
r1c111rightright0.14600.13550.12520.59330.4537

Training by iteration

IterationEnvironment stepsEpisodesTraining returnLearned policy value (exact)Network's start valueLossEntropyApproximate KLClipped shareExplained variance
120200.250010.1239−0.01831.3260.057880.0%0
240400.250010.4537−0.10321.1220.1957100.0%0
  • The last update moved the policy a lot (approximate KL 0.196): lower the learning rate or the epochs per iteration.
  • 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; Custom gridworld (2 states, 4 actions, episodes of up to 1 steps, discount 0.95); 2 iterations × 20 steps, 4 epochs per iteration in batches of 8, hidden layers 32, learning rate 0.003, clip range 0.2, λ 0.95, value weight 0.5, entropy bonus 0.01; 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 ef74235f5e862c9b
# 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 "gridworld", discount 0.95: the app writes both into the environment files read below.
rounds = int(2)
steps = int(20)
epochs = int(4)
batch_size = 8
hidden = [int(u) for u in [32]]
lr = float(0.003)
encoding = "one_hot"  # one_hot | features
clip = float(0.2)
gae_lambda = float(0.95)
vf_coef = float(0.5)
ent_coef = float(0.01)
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/degenerate-short-episodes/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/degenerate-short-episodes/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,
})

In this tiny two-state grid, the last update had an approximate KL of 0.196 and a clip fraction of 100.0%. The run warns: lower the learning rate or the epochs per iteration.

05

PPO on a custom environment

Read
Online policy learning (PPO)Recorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

PPO trained for 500 steps (33 episodes) in Custom formula. Its most likely action in each state earns 52.626 per episode against 52.691 for the optimal policy and 41.687 for random actions (regret 0.065, discount 0.9); the stochastic policy itself earns 46.141.

Learned policy value (exact)
52.626
Optimal policy value
52.691
Regret
0.0648
Share of the optimal gain
0.9941

Plots

Return per episode while trainingDoes the learned policy get closer to the best possible return as training goes on?
View data
CurveEnvironment stepsReturn per episode
Learned policy (exact)10043.903
Learned policy (exact)20052.626
Learned policy (exact)30043.903
Learned policy (exact)40050.042
Learned policy (exact)50052.626
Training episodes10038.651
Training episodes20043.654
Training episodes30046.438
Training episodes40047.687
Training episodes50047.932
Actions by state: learned vs optimalHow often does the learned policy choose each action, compared with the best policy?
View data
ActionShare of statesPolicy
wait0Learned
push0.2222Learned
pull0.7778Learned
wait0Optimal
push0.1111Optimal
pull0.8889Optimal

Exact return per episode

PolicyReturn per episodeRegret
Learned policy (most likely action)52.6260.0648
Learned policy (sampled actions)46.1416.550
Optimal policy52.6910
Random actions41.68711.004

Learned policy by state (9 states)

statesLearned actionOptimal actionP(wait)P(push)P(pull)State value (network)
s00pullpull0.21380.39050.39586.932
s11pullpull0.19830.38070.421010.444
s22pullpull0.22450.37620.39937.425
s33pullpull0.20090.34000.459214.310
s44pullpull0.19930.32600.474815.643
s55pullpull0.16060.39600.443413.682
s66pullpull0.18200.38100.437014.009
s77pushpull0.17660.43990.383519.613
s88pushpush0.27740.37440.348214.851

Training by iteration

IterationEnvironment stepsEpisodesTraining returnLearned policy value (exact)Network's start valueLossEntropyApproximate KLClipped shareExplained variance
1100638.65143.9031.4344.7381.095−0.00790.0%−0.0150
22001343.65452.6264.6425.4681.091−0.00033.0%−0.0219
33002046.43843.9037.7805.3321.081−0.01396.0%−0.0623
44002647.68750.04211.0765.2451.0690.00125.0%−0.1062
55003347.93252.62614.3104.2861.0670.00352.0%−0.0553
  • 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; Custom formula (9 states, 3 actions, episodes of up to 15 steps, discount 0.9); 5 iterations × 100 steps, 4 epochs per iteration in batches of 64, hidden layers 32, learning rate 0.003, clip range 0.2, λ 0.95, value weight 0.5, entropy bonus 0.01; 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 860409b6e1053de8
# 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 "formula", discount 0.9: the app writes both into the environment files read below.
rounds <- as.integer(5)
steps <- as.integer(100)
epochs <- as.integer(4)
batch_size <- 64
hidden <- as.integer(unlist(c(32)))
lr <- as.numeric(0.003)
encoding <- "one_hot" # 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.01)
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/formula-custom-settings/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/formula-custom-settings/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
))
Python

PPO trained for 500 steps (33 episodes) in Custom formula. Its most likely action in each state earns 52.626 per episode against 52.691 for the optimal policy and 41.687 for random actions (regret 0.065, discount 0.9); the stochastic policy itself earns 46.141.

Learned policy value (exact)
52.626
Optimal policy value
52.691
Regret
0.0648
Share of the optimal gain
0.9941

To keep this page light, the plots are shown once, under the R tab.

Exact return per episode

PolicyReturn per episodeRegret
Learned policy (most likely action)52.6260.0648
Learned policy (sampled actions)46.1416.550
Optimal policy52.6910
Random actions41.68711.004

Learned policy by state (9 states)

statesLearned actionOptimal actionP(wait)P(push)P(pull)State value (network)
s00pullpull0.21380.39050.39586.932
s11pullpull0.19830.38070.421010.444
s22pullpull0.22450.37620.39937.425
s33pullpull0.20090.34000.459214.310
s44pullpull0.19930.32600.474815.643
s55pullpull0.16060.39600.443413.682
s66pullpull0.18200.38100.437014.009
s77pushpull0.17660.43990.383519.613
s88pushpush0.27740.37440.348214.851

Training by iteration

IterationEnvironment stepsEpisodesTraining returnLearned policy value (exact)Network's start valueLossEntropyApproximate KLClipped shareExplained variance
1100638.65143.9031.4344.7381.095−0.00790.0%−0.0150
22001343.65452.6264.6425.4681.091−0.00033.0%−0.0219
33002046.43843.9037.7805.3321.081−0.01396.0%−0.0623
44002647.68750.04211.0765.2451.0690.00125.0%−0.1062
55003347.93252.62614.3104.2861.0670.00352.0%−0.0553
  • 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; Custom formula (9 states, 3 actions, episodes of up to 15 steps, discount 0.9); 5 iterations × 100 steps, 4 epochs per iteration in batches of 64, hidden layers 32, learning rate 0.003, clip range 0.2, λ 0.95, value weight 0.5, entropy bonus 0.01; 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 860409b6e1053de8
# 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 "formula", discount 0.9: the app writes both into the environment files read below.
rounds = int(5)
steps = int(100)
epochs = int(4)
batch_size = 64
hidden = [int(u) for u in [32]]
lr = float(0.003)
encoding = "one_hot"  # one_hot | features
clip = float(0.2)
gae_lambda = float(0.95)
vf_coef = float(0.5)
ent_coef = float(0.01)
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/formula-custom-settings/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/formula-custom-settings/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,
})

On a custom formula environment, PPO reaches 99.4% of the optimal gain in 500 steps. One run on one environment says little about the methods in general; the last lesson of this track is about comparing them properly.

06

What runs here

Read
07

Common mistakes

Read
08

Check: TRPO and PPO

Checkpoint

Check yourself

What does TRPO limit on each update?

Show the answer

Answer: a

A hard KL limit, enforced with conjugate gradients and a backtracking line search. PPO clips the ratio instead.

Check yourself

Why did PPO largely replace TRPO in practice?

Show the answer

Answer: a

TRPO's second-order solve and line search are costly and awkward with shared policy and value networks.

Check yourself

With ε = 0.2, a sample has advantage −1 and ratio 0.5. What is its clipped surrogate term, min(ρA, clip(ρ, 0.8, 1.2)·A)?

Show the answer

Answer: -0.8

ρA = −0.5; clip(0.5) = 0.8, so the clipped term is −0.8. The min picks −0.8: no reward for pushing a bad action's probability down further than 1 − ε.

Check yourself

What does taking the minimum of the clipped and unclipped terms guarantee?

Show the answer

Answer: a

The min is a lower bound. The ratio can still leave 1 ± ε; the objective just stops rewarding it.

Check yourself

A PPO run reports a large approximate KL and a clip fraction near 100% on its last update. What do you change first?

Show the answer

Answer: a

Big policy jumps per update are what clipping is meant to prevent; smaller steps or fewer passes over each batch calm them.

09

Recap

Recap
  • The ratio surrogate lets a batch be reused, but only near the old policy.
  • TRPO enforces a KL limit with a second-order solve; PPO clips the ratio with plain gradients.
  • PPO's min makes the objective pessimistic; ratios beyond 1 ± ε earn nothing more.
  • Read approximate KL and clip fraction: large values mean updates are too big.

Concepts in this lesson