Learn a policy by acting in a simulator
Train a deep Q-network or PPO by acting in a small simulated environment, and judge the learned policy exactly against the best possible one.
What runs in CodeSplash
You will be able to
- Say how online learning differs from learning from logged episodes
- Compute a DQN target and a PPO probability ratio by hand
- Read regret and the share of the optimal gain, and why the exact value beats the training return as a measure
Read first
Learning by acting
ReadOnline reinforcement learningOnline reinforcement learningLearning a policy by acting in an environment and learning from what happens, instead of from logged episodes. learns a policy by trying actions and seeing what happens. Offline learning can only recombine what the logs show; online learning can try anything, which is why it belongs in a simulator, not on real customers.
The Policy learning studio's environments are small enough to solve exactly, so every policy a learner finds is scored against the best possible one with no simulation noise.
A deep Q-network
ReadA deep Q-networkDeep Q-network (DQN)A neural network that estimates each action's value Q(s, a); the policy takes the action with the highest value. estimates Q(s, a), the return of taking action a in state s and acting well afterwards. Each round it acts ε-greedilyε-greedy explorationTakes a random action with probability ε and the best-looking one otherwise; ε falls as training goes on., stores what happened in a replay bufferExperience replayKeeping recent transitions and training on random minibatches of them, so updates aren't dominated by the last few steps., and trains toward
with a target networkTarget network and double Q targetsTraining targets come from a lagged copy of the network; double targets pick the next action with one and value it with the other. that lags behind, so the targets don't chase themselves.
Compute a target
CheckpointCheck yourself
A step earned reward −0.04 and led to a state where the target network gives 1.2 for "down" and 1.5 for "right". With discount 0.95, what is the DQN target?
Show the answer
Answer: 1.385
y = −0.04 + 0.95 × max(1.2, 1.5) = −0.04 + 1.425 = 1.385. If the next state ended the episode, there would be no second term and y = −0.04.
Proximal policy optimization
ReadPPOProximal policy optimization (PPO)Improves a stochastic policy in small steps: the objective stops rewarding changes once an action's probability ratio leaves 1 ± ε. learns how likely each action should be. After a rollout it compares each taken action's new probability with the old one, the ratio ρ, and multiplies by the action's advantageGeneralized advantage estimation (GAE)How much better an action did than the value network expected, blending one-step and whole-episode estimates with λ. (how much better it did than expected). The objective stops rewarding changes once ρ leaves 1 ± ε, so one rollout can't push the policy too far.
Clip a ratio
CheckpointCheck yourself
With clip range 0.2, an action with a positive advantage had probability 0.30 when the rollout was collected; after some training it has 0.40. What happens in the next gradient step?
Show the answer
Answer: b
PPO doesn't pull the probability back; it just stops rewarding further increases for this rollout. The next rollout starts from the new policy.
Read a DQN result
In the appA deep Q-network trained for 4,000 steps (133 episodes) in Admission control earns 3.269 per episode against 3.269 for the optimal policy and 1.651 for random actions (regret 0.000, discount 0.95).
- Learned policy value (exact)
- 3.269
- Optimal policy value
- 3.269
- Regret
- 0
- Share of the optimal gain
- 1
Plots
View data
| Curve | Environment steps | Return per episode |
|---|---|---|
| Learned policy (exact) | 200 | −0.0916 |
| Learned policy (exact) | 400 | −0.0916 |
| Learned policy (exact) | 600 | −0.0916 |
| Learned policy (exact) | 800 | −0.0916 |
| Learned policy (exact) | 1,000 | −0.0916 |
| Learned policy (exact) | 1,200 | −0.0916 |
| Learned policy (exact) | 1,400 | −0.0916 |
| Learned policy (exact) | 1,600 | −0.0916 |
| Learned policy (exact) | 1,800 | −0.0916 |
| Learned policy (exact) | 2,000 | −0.0916 |
| Learned policy (exact) | 2,200 | −0.0916 |
| Learned policy (exact) | 2,400 | −0.0916 |
| Learned policy (exact) | 2,600 | 2.447 |
| Learned policy (exact) | 2,800 | 3.269 |
| Learned policy (exact) | 3,000 | 3.269 |
| Learned policy (exact) | 3,200 | 3.269 |
| Learned policy (exact) | 3,400 | 3.269 |
| Learned policy (exact) | 3,600 | 3.269 |
| Learned policy (exact) | 3,800 | 3.269 |
| Learned policy (exact) | 4,000 | 3.269 |
| Training episodes | 200 | 1.222 |
| Training episodes | 400 | 2.113 |
| Training episodes | 600 | 1.749 |
| Training episodes | 800 | 2.077 |
| Training episodes | 1,000 | −1.104 |
| Training episodes | 1,200 | 1.474 |
| Training episodes | 1,400 | 3.192 |
| Training episodes | 1,600 | 0.2773 |
| Training episodes | 1,800 | 0.5929 |
| Training episodes | 2,000 | 1.501 |
| Training episodes | 2,200 | 0.2483 |
| Training episodes | 2,400 | 0.8008 |
| Training episodes | 2,600 | 0.3695 |
| Training episodes | 2,800 | 2.736 |
| Training episodes | 3,000 | 2.776 |
| Training episodes | 3,200 | 3.126 |
| Training episodes | 3,400 | 3.334 |
| Training episodes | 3,600 | 3.417 |
| Training episodes | 3,800 | 2.962 |
| Training episodes | 4,000 | 3.278 |
View data
| Action | Share of states | Policy |
|---|---|---|
| accept | 0.1429 | Learned |
| reject | 0.8571 | Learned |
| accept | 0.2857 | Optimal |
| reject | 0.7143 | Optimal |
Exact return per episode
| Policy | Return per episode | Regret |
|---|---|---|
| Learned policy (DQN) | 3.269 | 0 |
| Optimal policy | 3.269 | 0 |
| Random actions | 1.651 | 1.618 |
Learned policy by state (7 states)
| state | queue | Learned action | Optimal action | Q(accept) | Q(reject) |
|---|---|---|---|---|---|
| queue 0 | 0 | accept | accept | 2.371 | 2.162 |
| queue 1 | 1 | reject | reject | 1.281 | 1.464 |
| queue 2 | 2 | reject | reject | −0.1823 | 0.0542 |
| queue 3 | 3 | reject | reject | −1.760 | −1.693 |
| queue 4 | 4 | reject | reject | −3.285 | −3.076 |
| queue 5 | 5 | reject | reject | −4.543 | −4.428 |
| queue 6 | 6 | reject | accept | −5.200 | −5.118 |
Training by round
| Round | Environment steps | Episodes | Exploration (ε) | Training return | Learned policy value (exact) | Network's start value | Loss |
|---|---|---|---|---|---|---|---|
| 1 | 200 | 6 | 1 | 1.222 | −0.0916 | 0.9454 | 0.0263 |
| 2 | 400 | 13 | 0.8417 | 2.113 | −0.0916 | 1.023 | 0.0173 |
| 3 | 600 | 20 | 0.6833 | 1.749 | −0.0916 | 1.264 | 0.0166 |
| 4 | 800 | 26 | 0.5250 | 2.077 | −0.0916 | 1.337 | 0.0191 |
| 5 | 1,000 | 33 | 0.3667 | −1.104 | −0.0916 | 1.557 | 0.0254 |
| 6 | 1,200 | 40 | 0.2083 | 1.474 | −0.0916 | 1.582 | 0.0244 |
| 7 | 1,400 | 46 | 0.0500 | 3.192 | −0.0916 | 1.772 | 0.0273 |
| 8 | 1,600 | 53 | 0.0500 | 0.2773 | −0.0916 | 1.744 | 0.0253 |
| 9 | 1,800 | 60 | 0.0500 | 0.5929 | −0.0916 | 1.893 | 0.0296 |
| 10 | 2,000 | 66 | 0.0500 | 1.501 | −0.0916 | 1.915 | 0.0270 |
| 11 | 2,200 | 73 | 0.0500 | 0.2483 | −0.0916 | 2.003 | 0.0306 |
| 12 | 2,400 | 80 | 0.0500 | 0.8008 | −0.0916 | 2.048 | 0.0318 |
| 13 | 2,600 | 86 | 0.0500 | 0.3695 | 2.447 | 2.114 | 0.0362 |
| 14 | 2,800 | 93 | 0.0500 | 2.736 | 3.269 | 2.171 | 0.0416 |
| 15 | 3,000 | 100 | 0.0500 | 2.776 | 3.269 | 2.179 | 0.0441 |
| 16 | 3,200 | 106 | 0.0500 | 3.126 | 3.269 | 2.244 | 0.0495 |
| 17 | 3,400 | 113 | 0.0500 | 3.334 | 3.269 | 2.239 | 0.0488 |
| 18 | 3,600 | 120 | 0.0500 | 3.417 | 3.269 | 2.269 | 0.0547 |
| 19 | 3,800 | 126 | 0.0500 | 2.962 | 3.269 | 2.336 | 0.0535 |
| 20 | 4,000 | 133 | 0.0500 | 3.278 | 3.269 | 2.371 | 0.0600 |
- The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.
- Deep Q-network; Admission control (7 states, 2 actions, episodes of up to 30 steps, discount 0.95); 20 rounds × 200 steps, 50 updates of 64 replayed transitions per round (buffer 10000), hidden layers 32, learning rate 0.001, ε 1 → 0.05 over 30% of the rounds, double targets, huber loss; seed 42. 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 training return is the observed average over the round's finished episodes.
The exact R script · R R version 4.5.1 (2025-06-13)
# Online policy learning with a deep Q-network (DQN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.rl_dqn 1.0.0 · spec ced53f94fa51c811
# 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(20)
steps <- as.integer(200)
updates <- as.integer(50)
batch_size <- as.integer(64)
buffer <- as.integer(10000)
hidden <- as.integer(unlist(c(32)))
lr <- as.numeric(0.001)
encoding <- "one_hot" # one_hot | features
eps_start <- as.numeric(1)
eps_end <- as.numeric(0.05)
explore <- as.numeric(0.3)
double <- TRUE
dueling <- FALSE
loss_kind <- "huber" # huber | squared
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-98732/decide.rl_dqn/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-98732/decide.rl_dqn/queue-worked-example/out-r")
# %% Train online
fit <- cs_rl_dqn(env, encoding, hidden, rounds, steps, updates, batch_size, buffer, lr, eps_start, eps_end, explore, double, dueling,
loss_kind, seed)
trace <- fit$trace
policy <- fit$policy
sc <- cs_rl_scores(env, policy)
greedy_values <- vapply(trace, function(t) t$greedy_value, numeric(1))
best <- which.max(greedy_values)
final_return <- trace[[length(trace)]]$train_return
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 round or the number of rounds."
}
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 rounds, explore longer or lower the learning rate.", 100 * sc$share)
}
if (greedy_values[best] > sc$value + 1e-9 * max(1, abs(sc$value))) {
warnings[[length(warnings) + 1L]] <- sprintf("An earlier round's policy (round %d) was better (%s) than the final one: deep Q-learning can drift; 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("A deep Q-network trained for %s steps (%s episodes) in %s earns %s per episode against %s for the optimal policy and %s for random actions (regret %s, discount %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))
values <- list(policy_value = sc$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 = final_return, estimated_value = trace[[length(trace)]]$estimated_value, n_episodes = fit$episodes,
env_steps = fit$env_steps, rounds_run = length(trace), final_loss = trace[[length(trace)]]$loss, n_states = S, n_actions = K,
algorithm = "dqn")
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("Q(%s)", actions[j]), 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$q[live, j])
eval_df <- data.frame(policy = c("Learned policy (DQN)", "Optimal policy", "Random actions"), value = c(sc$value, opt_value, uni_value),
regret = c(sc$regret, 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)),
epsilon = vapply(trace, function(t) as.numeric(t$epsilon), numeric(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)))
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_dqn",
methodVersion = "1.0.0",
title = "Online policy learning (DQN)",
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 round",
columns = list(list(key = "round", label = "Round", type = "integer"), list(key = "env_steps", label = "Environment steps", type = "integer"),
list(key = "episodes", label = "Episodes", type = "integer"), list(key = "epsilon", label = "Exploration (ε)", type = "number"),
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")),
rows = train_df)
),
warnings = warnings,
notes = list(paste0(
sprintf("Deep Q-network; %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 rounds × %d steps, %d updates of %d replayed transitions per round (buffer %d), hidden layers %s, learning rate %s, ", rounds, steps,
updates, batch_size, buffer, paste(hidden, collapse = ", "), format(lr, digits = 15)),
sprintf("ε %s → %s over %.0f%% of the rounds%s%s, %s loss; seed %s. ", format(eps_start, digits = 15), format(eps_end, digits = 15), 100 * explore,
if (isTRUE(double)) ", double targets" else "", if (isTRUE(dueling)) ", dueling head" else "", loss_kind, seed),
"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 training return is the observed average over the round's finished episodes."
)),
values = values,
charts = charts
))
A deep Q-network trained for 4,000 steps (133 episodes) in Admission control earns 3.269 per episode against 3.269 for the optimal policy and 1.651 for random actions (regret 0.000, discount 0.95).
- 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
| Policy | Return per episode | Regret |
|---|---|---|
| Learned policy (DQN) | 3.269 | 0 |
| Optimal policy | 3.269 | 0 |
| Random actions | 1.651 | 1.618 |
Learned policy by state (7 states)
| state | queue | Learned action | Optimal action | Q(accept) | Q(reject) |
|---|---|---|---|---|---|
| queue 0 | 0 | accept | accept | 2.371 | 2.162 |
| queue 1 | 1 | reject | reject | 1.281 | 1.464 |
| queue 2 | 2 | reject | reject | −0.1823 | 0.0542 |
| queue 3 | 3 | reject | reject | −1.760 | −1.693 |
| queue 4 | 4 | reject | reject | −3.285 | −3.076 |
| queue 5 | 5 | reject | reject | −4.543 | −4.428 |
| queue 6 | 6 | reject | accept | −5.200 | −5.118 |
Training by round
| Round | Environment steps | Episodes | Exploration (ε) | Training return | Learned policy value (exact) | Network's start value | Loss |
|---|---|---|---|---|---|---|---|
| 1 | 200 | 6 | 1 | 1.222 | −0.0916 | 0.9454 | 0.0263 |
| 2 | 400 | 13 | 0.8417 | 2.113 | −0.0916 | 1.023 | 0.0173 |
| 3 | 600 | 20 | 0.6833 | 1.749 | −0.0916 | 1.264 | 0.0166 |
| 4 | 800 | 26 | 0.5250 | 2.077 | −0.0916 | 1.337 | 0.0191 |
| 5 | 1,000 | 33 | 0.3667 | −1.104 | −0.0916 | 1.557 | 0.0254 |
| 6 | 1,200 | 40 | 0.2083 | 1.474 | −0.0916 | 1.582 | 0.0244 |
| 7 | 1,400 | 46 | 0.0500 | 3.192 | −0.0916 | 1.772 | 0.0273 |
| 8 | 1,600 | 53 | 0.0500 | 0.2773 | −0.0916 | 1.744 | 0.0253 |
| 9 | 1,800 | 60 | 0.0500 | 0.5929 | −0.0916 | 1.893 | 0.0296 |
| 10 | 2,000 | 66 | 0.0500 | 1.501 | −0.0916 | 1.915 | 0.0270 |
| 11 | 2,200 | 73 | 0.0500 | 0.2483 | −0.0916 | 2.003 | 0.0306 |
| 12 | 2,400 | 80 | 0.0500 | 0.8008 | −0.0916 | 2.048 | 0.0318 |
| 13 | 2,600 | 86 | 0.0500 | 0.3695 | 2.447 | 2.114 | 0.0362 |
| 14 | 2,800 | 93 | 0.0500 | 2.736 | 3.269 | 2.171 | 0.0416 |
| 15 | 3,000 | 100 | 0.0500 | 2.776 | 3.269 | 2.179 | 0.0441 |
| 16 | 3,200 | 106 | 0.0500 | 3.126 | 3.269 | 2.244 | 0.0495 |
| 17 | 3,400 | 113 | 0.0500 | 3.334 | 3.269 | 2.239 | 0.0488 |
| 18 | 3,600 | 120 | 0.0500 | 3.417 | 3.269 | 2.269 | 0.0547 |
| 19 | 3,800 | 126 | 0.0500 | 2.962 | 3.269 | 2.336 | 0.0535 |
| 20 | 4,000 | 133 | 0.0500 | 3.278 | 3.269 | 2.371 | 0.0600 |
- The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.
- Deep Q-network; Admission control (7 states, 2 actions, episodes of up to 30 steps, discount 0.95); 20 rounds × 200 steps, 50 updates of 64 replayed transitions per round (buffer 10000), hidden layers 32, learning rate 0.001, ε 1 → 0.05 over 30% of the rounds, double targets, huber loss; seed 42. 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 training return is the observed average over the round's finished episodes.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Online policy learning with a deep Q-network (DQN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.rl_dqn 1.0.0 · spec ced53f94fa51c811
# 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(20)
steps = int(200)
updates = int(50)
batch_size = int(64)
buffer = int(10000)
hidden = [int(u) for u in [32]]
lr = float(0.001)
encoding = "one_hot" # one_hot | features
eps_start = float(1)
eps_end = float(0.05)
explore = float(0.3)
double = True
dueling = False
loss_kind = "huber" # huber | squared
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-98732/decide.rl_dqn/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-98732/decide.rl_dqn/queue-worked-example/out-python",
)
# %% Train online
fit = rl.dqn(env, encoding, hidden, rounds, steps, updates, batch_size, buffer, lr, eps_start, eps_end, explore, double, dueling, loss_kind, seed)
trace = fit["trace"]
policy = fit["policy"]
sc = rl.scores(env, policy)
best = max(range(len(trace)), key=lambda i: (trace[i]["greedy_value"], -i))
final_return = trace[-1]["train_return"]
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 round or the number of rounds.")
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 rounds, explore longer or lower the learning rate.")
if trace[best]["greedy_value"] > sc["value"] + 1e-9 * max(1.0, abs(sc["value"])):
warnings.append(f"An earlier round's policy (round {trace[best]['round']}) was better ({trace[best]['greedy_value']:.4g}) than the final one: deep Q-learning can drift; 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"]
qs = rl.q_star(env)
live = [s for s in range(S) if not env["terminal"][s]]
optimal = meta["optimal_policy"]
summary = (
f"A deep Q-network trained for {fit['env_steps']:,} steps ({fit['episodes']:,} episodes) in {meta['title']} earns {sc['value']:.3f} per episode "
f"against {opt_value:.3f} for the optimal policy and {uni_value:.3f} for random actions (regret {sc['regret']:.3f}, discount {gamma:g})."
)
values = {
"policy_value": sc["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": final_return,
"estimated_value": trace[-1]["estimated_value"], "n_episodes": fit["episodes"], "env_steps": fit["env_steps"], "rounds_run": len(trace),
"final_loss": trace[-1]["loss"], "n_states": S, "n_actions": K, "algorithm": "dqn",
}
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"Q({a})", "type": "number"} for j, a in enumerate(actions)]
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["q"][s, j]) for j in range(K)})
pol_rows.append(r)
eval_rows = [
{"policy": "Learned policy (DQN)", "value": sc["value"], "regret": sc["regret"]},
{"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_dqn",
"methodVersion": "1.0.0",
"title": "Online policy learning (DQN)",
"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 round",
"columns": [{"key": "round", "label": "Round", "type": "integer"}, {"key": "env_steps", "label": "Environment steps", "type": "integer"},
{"key": "episodes", "label": "Episodes", "type": "integer"}, {"key": "epsilon", "label": "Exploration (ε)", "type": "number"},
{"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"}],
"rows": trace},
],
"warnings": warnings,
"notes": [
f"Deep Q-network; {meta['title']} ({S} states, {K} actions, episodes of up to {env['horizon']} steps, discount {gamma:g}); "
f"{rounds} rounds × {steps} steps, {updates} updates of {batch_size} replayed transitions per round (buffer {buffer}), hidden layers "
f"{', '.join(str(h) for h in hidden)}, learning rate {lr:g}, ε {eps_start:g} → {eps_end:g} over {explore:.0%} of the rounds"
f"{', double targets' if double else ''}{', dueling head' if dueling else ''}, {loss_kind} loss; seed {seed}. "
"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 training return is the observed average over the round's finished episodes.",
],
"values": values,
"charts": charts,
})
After 4,000 steps in the admission-control queue, the learned policy earns 3.269 per episode; the optimal policy earns 3.269 and random actions 1.651. Its regretPolicy regretHow much return per episode the learned policy gives up against the optimal one: optimal value minus its value. is 0.000: it gets 100.0% of the optimal gainShare of the optimal gainHow far a policy gets from random actions (0) to the optimal policy (1); undefined when random actions are already optimal., and takes an optimal action in 100.0% of the states.
A shorter gridworld run, 1,200 steps, gets only 16.9% of the way: online learners need many episodes.
Read a PPO result
In the appPPO 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
View data
| Curve | Environment steps | Return per episode |
|---|---|---|
| Learned policy (exact) | 1,024 | 0.6682 |
| Learned policy (exact) | 2,048 | 1.435 |
| Learned policy (exact) | 3,072 | 3.269 |
| Learned policy (exact) | 4,096 | 3.269 |
| Learned policy (exact) | 5,120 | 3.269 |
| Learned policy (exact) | 6,144 | 3.269 |
| Learned policy (exact) | 7,168 | 3.269 |
| Learned policy (exact) | 8,192 | 3.269 |
| Learned policy (exact) | 9,216 | 3.269 |
| Learned policy (exact) | 10,240 | 3.269 |
| Learned policy (exact) | 11,264 | 3.269 |
| Learned policy (exact) | 12,288 | 3.269 |
| Learned policy (exact) | 13,312 | 3.269 |
| Learned policy (exact) | 14,336 | 3.269 |
| Learned policy (exact) | 15,360 | 3.269 |
| Learned policy (exact) | 16,384 | 3.269 |
| Learned policy (exact) | 17,408 | 3.269 |
| Learned policy (exact) | 18,432 | 3.269 |
| Learned policy (exact) | 19,456 | 3.269 |
| Learned policy (exact) | 20,480 | 3.269 |
| Learned policy (exact) | 21,504 | 3.269 |
| Learned policy (exact) | 22,528 | 3.269 |
| Learned policy (exact) | 23,552 | 3.269 |
| Learned policy (exact) | 24,576 | 3.269 |
| Learned policy (exact) | 25,600 | 3.269 |
| Learned policy (exact) | 26,624 | 3.269 |
| Learned policy (exact) | 27,648 | 3.269 |
| Learned policy (exact) | 28,672 | 3.269 |
| Learned policy (exact) | 29,696 | 3.269 |
| Learned policy (exact) | 30,720 | 3.269 |
| Learned policy (exact) | 31,744 | 3.269 |
| Learned policy (exact) | 32,768 | 3.269 |
| Learned policy (exact) | 33,792 | 3.269 |
| Learned policy (exact) | 34,816 | 3.269 |
| Learned policy (exact) | 35,840 | 3.269 |
| Learned policy (exact) | 36,864 | 3.269 |
| Learned policy (exact) | 37,888 | 3.269 |
| Learned policy (exact) | 38,912 | 3.269 |
| Learned policy (exact) | 39,936 | 3.269 |
| Learned policy (exact) | 40,960 | 3.269 |
| Training episodes | 1,024 | 1.567 |
| Training episodes | 2,048 | 2.368 |
| Training episodes | 3,072 | 2.079 |
| Training episodes | 4,096 | 1.993 |
| Training episodes | 5,120 | 2.602 |
| Training episodes | 6,144 | 2.621 |
| Training episodes | 7,168 | 2.764 |
| Training episodes | 8,192 | 2.543 |
| Training episodes | 9,216 | 2.612 |
| Training episodes | 10,240 | 3.004 |
| Training episodes | 11,264 | 3.296 |
| Training episodes | 12,288 | 3.360 |
| Training episodes | 13,312 | 3.072 |
| Training episodes | 14,336 | 3.386 |
| Training episodes | 15,360 | 3.251 |
| Training episodes | 16,384 | 3.517 |
| Training episodes | 17,408 | 2.858 |
| Training episodes | 18,432 | 3.463 |
| Training episodes | 19,456 | 3.203 |
| Training episodes | 20,480 | 3.122 |
First 60 of 80 rows.
View data
| Action | Share of states | Policy |
|---|---|---|
| accept | 0.2857 | Learned |
| reject | 0.7143 | Learned |
| accept | 0.2857 | Optimal |
| reject | 0.7143 | Optimal |
Exact return per episode
| Policy | Return per episode | Regret |
|---|---|---|
| Learned policy (most likely action) | 3.269 | 0 |
| Learned policy (sampled actions) | 3.240 | 0.0294 |
| Optimal policy | 3.269 | 0 |
| Random actions | 1.651 | 1.618 |
Learned policy by state (7 states)
| state | queue | Learned action | Optimal action | P(accept) | P(reject) | State value (network) |
|---|---|---|---|---|---|---|
| queue 0 | 0 | accept | accept | 0.9966 | 0.0034 | 4.102 |
| queue 1 | 1 | reject | reject | 0.0278 | 0.9722 | 3.214 |
| queue 2 | 2 | reject | reject | 0.0765 | 0.9235 | 2.088 |
| queue 3 | 3 | reject | reject | 0.0326 | 0.9674 | −0.6559 |
| queue 4 | 4 | reject | reject | 0.0354 | 0.9646 | −2.016 |
| queue 5 | 5 | reject | reject | 0.0695 | 0.9305 | −0.8703 |
| queue 6 | 6 | accept | accept | 0.7982 | 0.2018 | −0.3915 |
Training by iteration
| Iteration | Environment steps | Episodes | Training return | Learned policy value (exact) | Network's start value | Loss | Entropy | Approximate KL | Clipped share | Explained variance |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 1,024 | 34 | 1.567 | 0.6682 | 1.089 | 0.1453 | 0.6806 | 0.0202 | 0.0% | −0.5517 |
| 2 | 2,048 | 68 | 2.368 | 1.435 | 1.800 | 0.0940 | 0.6484 | 0.0131 | 25.6% | 0.3907 |
| 3 | 3,072 | 102 | 2.079 | 3.269 | 2.004 | 0.2322 | 0.6197 | 0.0119 | 15.2% | 0.4881 |
| 4 | 4,096 | 136 | 1.993 | 3.269 | 2.179 | 0.2231 | 0.5762 | 0.0160 | 29.3% | 0.4912 |
| 5 | 5,120 | 170 | 2.602 | 3.269 | 2.563 | 0.2365 | 0.5213 | 0.0038 | 10.2% | 0.4090 |
| 6 | 6,144 | 204 | 2.621 | 3.269 | 2.756 | 0.2526 | 0.4610 | 0.0139 | 16.6% | 0.4006 |
| 7 | 7,168 | 238 | 2.764 | 3.269 | 3.188 | 0.1774 | 0.4393 | 0.0022 | 1.5% | 0.3277 |
| 8 | 8,192 | 273 | 2.543 | 3.269 | 3.061 | 0.2130 | 0.3880 | 0.0080 | 8.8% | 0.3888 |
| 9 | 9,216 | 307 | 2.612 | 3.269 | 3.171 | 0.1765 | 0.3423 | 0.0030 | 0.0% | 0.2804 |
| 10 | 10,240 | 341 | 3.004 | 3.269 | 3.383 | 0.1676 | 0.2913 | 0.0049 | 5.3% | 0.3435 |
| 11 | 11,264 | 375 | 3.296 | 3.269 | 3.660 | 0.1747 | 0.2436 | 0.0037 | 4.8% | 0.2699 |
| 12 | 12,288 | 409 | 3.360 | 3.269 | 3.812 | 0.1636 | 0.2276 | 0.0011 | 0.1% | 0.1811 |
| 13 | 13,312 | 443 | 3.072 | 3.269 | 3.985 | 0.1659 | 0.2007 | 0.0037 | 4.5% | 0.2444 |
| 14 | 14,336 | 477 | 3.386 | 3.269 | 4.003 | 0.1387 | 0.1656 | −0.0013 | 1.9% | 0.2305 |
| 15 | 15,360 | 512 | 3.251 | 3.269 | 4.038 | 0.1842 | 0.1922 | 0.0016 | 0.0% | 0.2390 |
| 16 | 16,384 | 546 | 3.517 | 3.269 | 4.123 | 0.1333 | 0.1889 | 0.0028 | 3.0% | 0.2289 |
| 17 | 17,408 | 580 | 2.858 | 3.269 | 3.962 | 0.1282 | 0.1931 | 0.0016 | 1.5% | 0.2008 |
| 18 | 18,432 | 614 | 3.463 | 3.269 | 4.130 | 0.1563 | 0.1868 | 0.0019 | 1.1% | 0.2186 |
| 19 | 19,456 | 648 | 3.203 | 3.269 | 3.961 | 0.1744 | 0.1814 | 0.0082 | 5.2% | 0.2509 |
| 20 | 20,480 | 682 | 3.122 | 3.269 | 4.128 | 0.1954 | 0.1385 | 0.0040 | 5.3% | 0.3028 |
| 21 | 21,504 | 716 | 2.942 | 3.269 | 3.978 | 0.1630 | 0.1270 | 0.0014 | 0.0% | 0.2176 |
| 22 | 22,528 | 750 | 3.439 | 3.269 | 4.027 | 0.1471 | 0.1361 | 0.0017 | 0.5% | 0.2087 |
| 23 | 23,552 | 785 | 3.371 | 3.269 | 4.073 | 0.1437 | 0.1180 | −0.0007 | 2.9% | 0.2139 |
| 24 | 24,576 | 819 | 3.091 | 3.269 | 3.919 | 0.1527 | 0.0957 | 4.055e-5 | 2.6% | 0.2494 |
| 25 | 25,600 | 853 | 3.348 | 3.269 | 3.873 | 0.1058 | 0.1956 | 0.0248 | 0.2% | 0.2256 |
| 26 | 26,624 | 887 | 2.866 | 3.269 | 3.789 | 0.1152 | 0.1701 | 0.0006 | 0.1% | 0.3056 |
| 27 | 27,648 | 921 | 3.407 | 3.269 | 3.893 | 0.1296 | 0.1519 | 0.0013 | 0.0% | 0.2256 |
| 28 | 28,672 | 955 | 2.996 | 3.269 | 3.986 | 0.1136 | 0.1298 | −6.507e-5 | 2.1% | 0.1937 |
| 29 | 29,696 | 989 | 3.160 | 3.269 | 4.031 | 0.1244 | 0.1020 | 0.0023 | 2.2% | 0.2250 |
| 30 | 30,720 | 1,024 | 2.821 | 3.269 | 3.922 | 0.1611 | 0.0879 | 0.0019 | 0.0% | 0.2302 |
| 31 | 31,744 | 1,058 | 3.284 | 3.269 | 3.996 | 0.1500 | 0.0859 | −0.0004 | 1.1% | 0.2325 |
| 32 | 32,768 | 1,092 | 3.153 | 3.269 | 3.917 | 0.1059 | 0.0903 | 0.0005 | 0.0% | 0.1443 |
| 33 | 33,792 | 1,126 | 2.881 | 3.269 | 3.924 | 0.1580 | 0.0808 | 0.0022 | 0.0% | 0.2075 |
| 34 | 34,816 | 1,160 | 3.166 | 3.269 | 4.002 | 0.1150 | 0.0610 | 0.0013 | 1.9% | 0.2206 |
| 35 | 35,840 | 1,194 | 3.305 | 3.269 | 4.144 | 0.1435 | 0.0533 | −0.0003 | 0.5% | 0.2219 |
| 36 | 36,864 | 1,228 | 3.095 | 3.269 | 4.069 | 0.1380 | 0.0432 | 0.0002 | 0.9% | 0.2100 |
| 37 | 37,888 | 1,262 | 3.314 | 3.269 | 3.999 | 0.1534 | 0.0344 | 0.0002 | 0.2% | 0.2729 |
| 38 | 38,912 | 1,297 | 3.502 | 3.269 | 4.141 | 0.1445 | 0.0620 | 0.0023 | 0.6% | 0.1879 |
| 39 | 39,936 | 1,331 | 2.889 | 3.269 | 4.043 | 0.1758 | 0.0684 | −0.0013 | 0.7% | 0.2089 |
| 40 | 40,960 | 1,365 | 3.596 | 3.269 | 4.102 | 0.1547 | 0.0591 | −0.0007 | 0.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
))
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
| Policy | Return per episode | Regret |
|---|---|---|
| Learned policy (most likely action) | 3.269 | 0 |
| Learned policy (sampled actions) | 3.240 | 0.0294 |
| Optimal policy | 3.269 | 0 |
| Random actions | 1.651 | 1.618 |
Learned policy by state (7 states)
| state | queue | Learned action | Optimal action | P(accept) | P(reject) | State value (network) |
|---|---|---|---|---|---|---|
| queue 0 | 0 | accept | accept | 0.9966 | 0.0034 | 4.102 |
| queue 1 | 1 | reject | reject | 0.0278 | 0.9722 | 3.214 |
| queue 2 | 2 | reject | reject | 0.0765 | 0.9235 | 2.088 |
| queue 3 | 3 | reject | reject | 0.0326 | 0.9674 | −0.6559 |
| queue 4 | 4 | reject | reject | 0.0354 | 0.9646 | −2.016 |
| queue 5 | 5 | reject | reject | 0.0695 | 0.9305 | −0.8703 |
| queue 6 | 6 | accept | accept | 0.7982 | 0.2018 | −0.3915 |
Training by iteration
| Iteration | Environment steps | Episodes | Training return | Learned policy value (exact) | Network's start value | Loss | Entropy | Approximate KL | Clipped share | Explained variance |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 1,024 | 34 | 1.567 | 0.6682 | 1.089 | 0.1453 | 0.6806 | 0.0202 | 0.0% | −0.5517 |
| 2 | 2,048 | 68 | 2.368 | 1.435 | 1.800 | 0.0940 | 0.6484 | 0.0131 | 25.6% | 0.3907 |
| 3 | 3,072 | 102 | 2.079 | 3.269 | 2.004 | 0.2322 | 0.6197 | 0.0119 | 15.2% | 0.4881 |
| 4 | 4,096 | 136 | 1.993 | 3.269 | 2.179 | 0.2231 | 0.5762 | 0.0160 | 29.3% | 0.4912 |
| 5 | 5,120 | 170 | 2.602 | 3.269 | 2.563 | 0.2365 | 0.5213 | 0.0038 | 10.2% | 0.4090 |
| 6 | 6,144 | 204 | 2.621 | 3.269 | 2.756 | 0.2526 | 0.4610 | 0.0139 | 16.6% | 0.4006 |
| 7 | 7,168 | 238 | 2.764 | 3.269 | 3.188 | 0.1774 | 0.4393 | 0.0022 | 1.5% | 0.3277 |
| 8 | 8,192 | 273 | 2.543 | 3.269 | 3.061 | 0.2130 | 0.3880 | 0.0080 | 8.8% | 0.3888 |
| 9 | 9,216 | 307 | 2.612 | 3.269 | 3.171 | 0.1765 | 0.3423 | 0.0030 | 0.0% | 0.2804 |
| 10 | 10,240 | 341 | 3.004 | 3.269 | 3.383 | 0.1676 | 0.2913 | 0.0049 | 5.3% | 0.3435 |
| 11 | 11,264 | 375 | 3.296 | 3.269 | 3.660 | 0.1747 | 0.2436 | 0.0037 | 4.8% | 0.2699 |
| 12 | 12,288 | 409 | 3.360 | 3.269 | 3.812 | 0.1636 | 0.2276 | 0.0011 | 0.1% | 0.1811 |
| 13 | 13,312 | 443 | 3.072 | 3.269 | 3.985 | 0.1659 | 0.2007 | 0.0037 | 4.5% | 0.2444 |
| 14 | 14,336 | 477 | 3.386 | 3.269 | 4.003 | 0.1387 | 0.1656 | −0.0013 | 1.9% | 0.2305 |
| 15 | 15,360 | 512 | 3.251 | 3.269 | 4.038 | 0.1842 | 0.1922 | 0.0016 | 0.0% | 0.2390 |
| 16 | 16,384 | 546 | 3.517 | 3.269 | 4.123 | 0.1333 | 0.1889 | 0.0028 | 3.0% | 0.2289 |
| 17 | 17,408 | 580 | 2.858 | 3.269 | 3.962 | 0.1282 | 0.1931 | 0.0016 | 1.5% | 0.2008 |
| 18 | 18,432 | 614 | 3.463 | 3.269 | 4.130 | 0.1563 | 0.1868 | 0.0019 | 1.1% | 0.2186 |
| 19 | 19,456 | 648 | 3.203 | 3.269 | 3.961 | 0.1744 | 0.1814 | 0.0082 | 5.2% | 0.2509 |
| 20 | 20,480 | 682 | 3.122 | 3.269 | 4.128 | 0.1954 | 0.1385 | 0.0040 | 5.3% | 0.3028 |
| 21 | 21,504 | 716 | 2.942 | 3.269 | 3.978 | 0.1630 | 0.1270 | 0.0014 | 0.0% | 0.2176 |
| 22 | 22,528 | 750 | 3.439 | 3.269 | 4.027 | 0.1471 | 0.1361 | 0.0017 | 0.5% | 0.2087 |
| 23 | 23,552 | 785 | 3.371 | 3.269 | 4.073 | 0.1437 | 0.1180 | −0.0007 | 2.9% | 0.2139 |
| 24 | 24,576 | 819 | 3.091 | 3.269 | 3.919 | 0.1527 | 0.0957 | 4.055e-5 | 2.6% | 0.2494 |
| 25 | 25,600 | 853 | 3.348 | 3.269 | 3.873 | 0.1058 | 0.1956 | 0.0248 | 0.2% | 0.2256 |
| 26 | 26,624 | 887 | 2.866 | 3.269 | 3.789 | 0.1152 | 0.1701 | 0.0006 | 0.1% | 0.3056 |
| 27 | 27,648 | 921 | 3.407 | 3.269 | 3.893 | 0.1296 | 0.1519 | 0.0013 | 0.0% | 0.2256 |
| 28 | 28,672 | 955 | 2.996 | 3.269 | 3.986 | 0.1136 | 0.1298 | −6.507e-5 | 2.1% | 0.1937 |
| 29 | 29,696 | 989 | 3.160 | 3.269 | 4.031 | 0.1244 | 0.1020 | 0.0023 | 2.2% | 0.2250 |
| 30 | 30,720 | 1,024 | 2.821 | 3.269 | 3.922 | 0.1611 | 0.0879 | 0.0019 | 0.0% | 0.2302 |
| 31 | 31,744 | 1,058 | 3.284 | 3.269 | 3.996 | 0.1500 | 0.0859 | −0.0004 | 1.1% | 0.2325 |
| 32 | 32,768 | 1,092 | 3.153 | 3.269 | 3.917 | 0.1059 | 0.0903 | 0.0005 | 0.0% | 0.1443 |
| 33 | 33,792 | 1,126 | 2.881 | 3.269 | 3.924 | 0.1580 | 0.0808 | 0.0022 | 0.0% | 0.2075 |
| 34 | 34,816 | 1,160 | 3.166 | 3.269 | 4.002 | 0.1150 | 0.0610 | 0.0013 | 1.9% | 0.2206 |
| 35 | 35,840 | 1,194 | 3.305 | 3.269 | 4.144 | 0.1435 | 0.0533 | −0.0003 | 0.5% | 0.2219 |
| 36 | 36,864 | 1,228 | 3.095 | 3.269 | 4.069 | 0.1380 | 0.0432 | 0.0002 | 0.9% | 0.2100 |
| 37 | 37,888 | 1,262 | 3.314 | 3.269 | 3.999 | 0.1534 | 0.0344 | 0.0002 | 0.2% | 0.2729 |
| 38 | 38,912 | 1,297 | 3.502 | 3.269 | 4.141 | 0.1445 | 0.0620 | 0.0023 | 0.6% | 0.1879 |
| 39 | 39,936 | 1,331 | 2.889 | 3.269 | 4.043 | 0.1758 | 0.0684 | −0.0013 | 0.7% | 0.2089 |
| 40 | 40,960 | 1,365 | 3.596 | 3.269 | 4.102 | 0.1547 | 0.0591 | −0.0007 | 0.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,
})
PPO in the same queue: 3.269 per episode for its most likely action in each state, 3.240 for the sampled policy itself. Its policy entropyEntropy bonusRewards a policy for keeping its probability spread over actions, so it keeps exploring; entropy 0 means one action only. is 0.06: close to zero, it has nearly settled on one action per state.
Check your understanding
CheckpointCheck yourself
The training return of the last round is well below the learned policy's exact value. Which explanation fits?
Show the answer
Answer: a
The exact value is computed from the environment's transition table, so there is nothing to be optimistic about; the training return mixes in exploration and chance.
Check yourself
Random actions earn 2 per episode, the optimal policy 10, and the learned policy 8. What share of the optimal gain does the learned policy reach?
Show the answer
Answer: 0.75
(8 − 2) / (10 − 2) = 6 / 8 = 0.75. Its regret is 10 − 8 = 2.
Check yourself
A DQN run warns that an earlier round's policy was better than the final one. What is a sensible next step?
Show the answer
Answer: b
Deep Q-learning can drift after it finds a good policy. Picking the best round by its exact value only works because this environment can be solved exactly; with a real process you couldn't.
Try it
In the appIn the Policy learning studio, choose a built-in environment in Data, then open Train online. Pick DQN or PPO and run; the return curve climbs while the network trains. In Compare, each run sits below the offline policies with its exact value only, labeled apart from the off-policy estimates.
import numpy as np
# Tabular Q-learning on a corridor: states 0..5, actions left/right, reward 1 for reaching state 5.
rng = np.random.default_rng(1)
n, gamma, alpha, eps = 6, 0.9, 0.5, 0.2
Q = np.zeros((n, 2))
for episode in range(300):
s = 0
while s != n - 1:
a = int(rng.integers(2)) if rng.random() < eps else int(np.argmax(Q[s]))
s2 = max(s - 1, 0) if a == 0 else s + 1
r = 1.0 if s2 == n - 1 else 0.0
target = r + (0.0 if s2 == n - 1 else gamma * Q[s2].max())
Q[s, a] += alpha * (target - Q[s, a])
s = s2
print(["right" if q[1] > q[0] else "left" for q in Q[:-1]])set.seed(1)
n <- 6; gamma <- 0.9; alpha <- 0.5; eps <- 0.2
Q <- matrix(0, nrow = n, ncol = 2)
for (episode in 1:300) {
s <- 1
while (s != n) {
a <- if (runif(1) < eps) sample(1:2, 1) else which.max(Q[s, ])
s2 <- if (a == 1) max(s - 1, 1) else s + 1
r <- if (s2 == n) 1 else 0
target <- r + if (s2 == n) 0 else gamma * max(Q[s2, ])
Q[s, a] <- Q[s, a] + alpha * (target - Q[s, a])
s <- s2
}
}
ifelse(Q[-n, 2] > Q[-n, 1], "right", "left")Recap
Recap- Online learning tries actions and learns from what happens; keep it in a simulator.
- DQN learns action values with replay and a lagging target network; PPO learns action probabilities with a clipped objective.
- In a small environment the learned policy is scored exactly: regret and the share of the optimal gain say how close it got.
- The training return is noisy and includes exploration; judge the policy by its exact value.
Concepts in this lesson