Offline RL in depth: conservative and implicit Q-learning
Learn a policy from logged episodes without trying anything new. CQL pushes down the values of actions the logs never took; IQL never evaluates them at all, using an expectile value and advantage-weighted imitation.
What runs in CodeSplash
- DRL011Conservative Q-learning (CQL) Runs in CodeSplash
- DRL012Implicit Q-learning (IQL) Runs in CodeSplash
- Offline policy learning from logged episodes Verified in Python and R
You will be able to
- Explain why the max in a Q-learning target goes wrong on logged data
- Write CQL's penalty and say what its weight α trades
- Explain IQL's expectile value loss and advantage-weighted policy extraction
- Read a CodeSplash offline run against the logged policy and behavior cloning
The max reaches where the logs never went
ReadOffline RLOffline policy learningLearns a decision policy from logged episodes only, without trying new actions; it can only be trusted where the logs tried them. learns from a fixed log of episodes. A Q-learning target takes , and the network's guesses for actions the log never took in are pure extrapolation. Some will be too high; the max picks them; the next targets inherit them. Online, trying the action would expose the error. Offline, nothing ever does.
Every offline method answers one question: how to stay where the logged data can vouch for the values.
CQL: push down the unseen
ReadConservative Q-learningConservative Q-learningA Q-network trained with a penalty that pushes down values of actions the logs rarely took, so the policy stays near logged behavior. adds a penalty to the usual Bellman error:
The log-sum-exp is a soft max over all actions; subtracting the logged action's value means only actions above the logged one are pushed down. In the reference's example the penalty is 2.055, and with α set to a half the total loss is 1.327. Larger α is more cautious: closer to imitating the log.
IQL: never ask about unseen actions
ReadImplicit Q-learningImplicit Q-learningLearns values only from logged actions (an expectile of their Q), then imitates logged actions weighted by exp(β × advantage). avoids the max altogether. It fits a value to the logged actions' Q-values with an expectile loss that weights positive residuals by τ and negative ones by 1 − τ; with τ above a half, leans toward the better logged actions. Q is then trained toward , which uses only logged actions.
The policy is extracted by advantage-weighted imitation: copy logged actions with weight , capped. In the reference's example the weights come out as 20 (capped), 0.223 and 1.82.
Read a CQL run
In the appConservative Q-learning learned a policy from 60 episodes (640 decisions). Fitted Q evaluation puts its return per episode at 0.511, 95% CI [0.494, 0.529], against 0.049 for the logged policy (discount 0.95). It agrees with the logged action at 64% of the logged states.
- Learned policy value (FQE)
- 0.5107
- 95% CI
- [0.4940, 0.5289]
- Logged policy value
- 0.0487
- Agreement with logged actions
- 0.6406
Plots
View data
| Value | Upper | Policy and estimator | Lower |
|---|---|---|---|
| 0.5107 | 0.5289 | Conservative Q-learning · Fitted Q evaluation | 0.4940 |
| 0.5323 | 0.5866 | Conservative Q-learning · Weighted doubly robust | 0.4717 |
| 0.5185 | 0.6622 | Conservative Q-learning · Weighted per-decision IS | −0.2262 |
| 0.5107 | 0.5289 | Behavior cloning (baseline) · Fitted Q evaluation | 0.4940 |
| 0.5323 | 0.5866 | Behavior cloning (baseline) · Weighted doubly robust | 0.4717 |
| 0.5185 | 0.6622 | Behavior cloning (baseline) · Weighted per-decision IS | −0.2262 |
| 0.0487 | 0.1387 | Logged policy · Observed return | −0.0376 |
View data
| Iteration | Estimated value |
|---|---|
| 1 | 0.4862 |
| 2 | 0.0208 |
| 3 | 0.5907 |
| 4 | 0.2081 |
View data
| Action | Share | Policy |
|---|---|---|
| left | 0.1688 | Logged |
| stay | 0.1906 | Logged |
| right | 0.6406 | Logged |
| left | 0 | Learned |
| stay | 0 | Learned |
| right | 1 | Learned |
Estimated return per episode
| Policy | Estimator | Estimate | 95% CI low | 95% CI high |
|---|---|---|---|---|
| Conservative Q-learning | Fitted Q evaluation | 0.5107 | 0.4940 | 0.5289 |
| Conservative Q-learning | Weighted doubly robust | 0.5323 | 0.4717 | 0.5866 |
| Conservative Q-learning | Weighted per-decision IS | 0.5185 | −0.2262 | 0.6622 |
| Behavior cloning (baseline) | Fitted Q evaluation | 0.5107 | 0.4940 | 0.5289 |
| Behavior cloning (baseline) | Weighted doubly robust | 0.5323 | 0.4717 | 0.5866 |
| Behavior cloning (baseline) | Weighted per-decision IS | 0.5185 | −0.2262 | 0.6622 |
| Logged policy | Observed return | 0.0487 | −0.0376 | 0.1387 |
Learned policy by state (12 of 12 distinct states)
| cell | weather today | Learned action | Q(left) | Q(stay) | Q(right) |
|---|---|---|---|---|---|
| c1 | sun | right | −0.5433 | −0.3971 | 0.1158 |
| c2 | sun | right | −0.9531 | −0.3548 | 0.3412 |
| c3 | rain | right | −0.0943 | −0.3722 | 0.3326 |
| c4 | rain | right | −0.0469 | 0.3115 | 0.7662 |
| c5 | rain | right | −0.2087 | 0.0189 | 1.041 |
| c1 | rain | right | −0.3203 | −0.8373 | 0.0391 |
| c0 | sun | right | −0.8865 | −0.5233 | 0.3031 |
| c3 | sun | right | −0.9514 | −0.3169 | 0.7796 |
| c2 | rain | right | 0.0251 | −0.6580 | 0.1797 |
| c4 | sun | right | −0.4142 | 0.4192 | 1.025 |
| c5 | sun | right | −0.4253 | 0.4050 | 1.216 |
| c0 | rain | right | −0.1563 | −0.2290 | 0.2950 |
Actions: logged vs learned policy
| action | Logged share | Learned share |
|---|---|---|
| left | 16.9% | 0.0% |
| stay | 19.1% | 0.0% |
| right | 64.1% | 100.0% |
Training by iteration
| Iteration | Loss | Estimated start-state value |
|---|---|---|
| 1 | 0.9673 | 0.4862 |
| 2 | 0.9721 | 0.0208 |
| 3 | 0.9706 | 0.5907 |
| 4 | 0.9524 | 0.2081 |
- 18 of 60 episodes end without done = true (cut short): their last step is left out of the Q-models because its next state is unknown.
- Effective sample size 2.5 of 60 episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.
- The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.
- Conservative Q-learning; discount 0.95; Q-models and evaluation use cell, weather today (networks: hidden layers 16, 4 rounds × 6 epochs, learning rate 0.005). Evaluation: fitted Q evaluation (linear per action, cross-fitted over 2 episode folds), weighted doubly robust and weighted per-decision IS with the logged propensities; 200 bootstrap resamples of episodes (seed 42). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.
The exact R script · R R version 4.5.1 (2025-06-13)
# Offline policy learning from logged episodes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.offline_rl 1.1.0 · spec baa2d85e8904e6c4
# Dataset: pol_corridor (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_bandit_design(), cs_seq_*(), cs_orl_*(): twins of codesplash.decide.ope / sequential / offline_rl
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/pol_corridor.parquet", col_select = c("episode", "step", "cell", "weather today", "action", "reward", "propensity", "done")))
n_input <- nrow(df)
df[["cell"]] <- factor(df[["cell"]], levels = c("c0", "c1", "c2", "c3", "c4", "c5")) # stored level order
df[["weather today"]] <- factor(df[["weather today"]], levels = c("rain", "sun")) # stored level order
df[["action"]] <- factor(df[["action"]], levels = c("left", "stay", "right")) # stored level order
df[["done"]] <- factor(df[["done"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("episode", "step", "cell", "weather today", "action", "reward", "propensity", "done")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("episode", "step", "cell", "weather today", "action", "reward", "propensity", "done")) # infinite values stop the run (registry/errors.yaml)
# %% Inputs
ep_col <- "episode"
step_col <- "step"
a_col <- "action"
r_col <- "reward"
p_col <- "propensity"
done_col <- "done"
features <- c("cell", "weather today")
algorithm <- "cql" # fqi | bc | cql | iql
gamma <- as.numeric(0.95)
iterations <- as.integer(300)
rounds <- as.integer(4)
hidden <- as.integer(unlist(c(16)))
epochs <- as.integer(6)
lr <- as.numeric(0.005)
batch_size <- 128
alpha <- as.numeric(1)
double <- TRUE
dueling <- FALSE
expectile <- as.numeric(0.7)
temperature <- as.numeric(3)
folds <- as.integer(2)
fqe_iterations <- as.integer(200)
n_boot <- as.integer(200)
conf <- 0.95
seed <- 42
# Yes/no columns count as 1/0.
as_flag <- function(v) if (is.factor(v)) as.character(v) == "true" else as.numeric(v) != 0
# Rows by episode (first appearance), then step.
ep_keys <- if (is.factor(df[[ep_col]])) as.character(df[[ep_col]]) else as.numeric(df[[ep_col]])
ord <- cs_seq_order(cs_seq_episode_codes(ep_keys), as.numeric(df[[step_col]]))
df <- df[ord, , drop = FALSE]
rownames(df) <- NULL
ep <- cs_seq_episode_codes(ep_keys[ord])
st <- cs_seq_structure(ep, as.numeric(df[[step_col]]), if (!is.null(done_col)) as_flag(df[[done_col]]) else NULL)
lv <- levels(df[[a_col]])
K <- length(lv)
action <- as.character(df[[a_col]])
reward <- if (is.factor(df[[r_col]])) as.numeric(as_flag(df[[r_col]])) else as.numeric(df[[r_col]])
propensity <- if (!is.null(p_col)) as.numeric(df[[p_col]]) else NULL
is_cat <- vapply(features, function(c) is.factor(df[[c]]), logical(1))
numeric_f <- features[!is_cat]
categorical_f <- lapply(stats::setNames(features[is_cat], features[is_cat]), function(c) levels(df[[c]]))
# %% Checks (same order in both engines)
if (st$duplicates > 0) cs_error("CS_E_INVALID_VALUES", column = step_col, requirement = "unique within each episode", count = st$duplicates)
if (!is.null(propensity)) {
bad <- sum(propensity <= 0 | propensity > 1)
if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = p_col, requirement = "a probability in (0, 1]", count = bad)
}
if (st$E < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = ep_col, min = 2, k = st$E)
present <- length(unique(action))
if (present < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = a_col, min = 2, k = present)
a_idx <- match(action, lv)
x <- cs_bandit_design(df, numeric_f, categorical_f)
starts <- st$starts
fit_rows <- st$fit_rows
# 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.offline_rl/corridor-cql/out-r")
# %% Learn
q_all <- NULL
probs_all <- NULL
bc <- cs_seq_behavior_cloning(x, a_idx, K)
bc_policy <- as.integer(apply(bc$probs, 1, which.max))
extra <- list()
if (algorithm == "fqi") {
fq <- cs_seq_fitted_q(x, a_idx, reward, st$nxt, K, gamma, fit_rows, iterations, starts = starts)
q_all <- x %*% t(fq$beta)
policy <- cs_seq_greedy(q_all, fq$support)
trace <- fq$trace
iters_run <- fq$iterations
if (!fq$converged) warnings <- c(warnings, sprintf("Fitted Q iteration did not settle within %d iterations; raise the limit or lower the discount.", iterations))
} else if (algorithm == "bc") {
probs_all <- bc$probs
policy <- bc_policy
trace <- bc$trace
iters_run <- bc$iterations
if (!bc$converged) warnings <- c(warnings, sprintf("Behavior cloning did not converge within %d Newton steps.", iters_run))
} else {
z <- cs_seq_nn_features(x, length(numeric_f))
if (algorithm == "cql") {
fit <- cs_orl_cql(z, a_idx, reward, st$nxt, fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, alpha, double, dueling, seed, starts)
q_all <- cs_orl_q_values(fit$params, z, dueling, K)
policy <- as.integer(apply(q_all, 1, which.max))
} else {
fit <- cs_orl_iql(z, a_idx, reward, st$nxt, fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, expectile, temperature, seed, starts)
q_all <- cs_orl_q_values(fit$params, z, FALSE, K)
policy <- as.integer(apply(cs_orl_policy_logits(fit$policy_params, z), 1, which.max))
extra <- list(weight_ess = fit$weight_ess, weight_capped = fit$weight_capped)
if (fit$weight_capped > 0.05) {
warnings <- c(warnings, sprintf("%.0f%% of the advantage weights hit the cap of 100: lower the temperature, or the policy imitates a few rows.", fit$weight_capped * 100))
}
}
trace <- fit$trace
iters_run <- rounds
}
# %% Evaluate (FQE always; weighted doubly robust when propensities are given)
ev <- cs_seq_evaluate(st, x, a_idx, policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep)
ev_bc <- if (algorithm != "bc") cs_seq_evaluate(st, x, a_idx, bc_policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep) else NULL
E <- ev$E
n <- ev$n
agreement <- mean(policy == a_idx)
low_support <- mean(bc$probs[cbind(seq_len(n), policy)] < 0.05)
if (st$truncated > 0) {
warnings <- c(warnings, sprintf("%d of %d episodes end without %s = true (cut short): their last step is left out of the Q-models because its next state is unknown.", st$truncated, E, done_col))
}
if (low_support > 0.2) {
warnings <- c(warnings, sprintf("At %.0f%% of the logged states the learned policy picks an action the logging policy rarely took (estimated probability under 5%%): its value there is extrapolated.", low_support * 100))
}
if (!ev$fqe_converged) warnings <- c(warnings, sprintf("Fitted Q evaluation of the learned policy did not settle within %d iterations.", fqe_iterations))
if (!is.null(propensity) && ev$ess < 0.1 * E) {
warnings <- c(warnings, sprintf("Effective sample size %.1f of %d episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.", ev$ess, E))
}
warnings <- c(warnings, "The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.")
# %% Result
alg_label <- c(fqi = "Fitted Q iteration", bc = "Behavior cloning", cql = "Conservative Q-learning", iql = "Implicit Q-learning")[[algorithm]]
pct <- sprintf("%.0f%%", conf * 100)
v_fqe <- ev$estimate$fqe
v_ci <- ev$ci$fqe
logged <- ev$logged
gfmt <- format(gamma, digits = 6)
summary <- sprintf(
"%s learned a policy from %s episodes (%s decisions). Fitted Q evaluation puts its return per episode at %.3f, %s CI [%.3f, %.3f], against %.3f for the logged policy (discount %s). It agrees with the logged action at %.0f%% of the logged states.",
alg_label, format(E, big.mark = ","), format(n, big.mark = ","), v_fqe, pct, v_ci[1], v_ci[2], logged, gfmt, agreement * 100
)
lab <- cs_seq_labels()
eval_rows <- list()
for (pair in list(list(alg_label, ev), list("Behavior cloning (baseline)", ev_bc))) {
res <- pair[[2]]
if (is.null(res)) next
for (e in intersect(c("fqe", "wdr", "wpdis"), names(res$estimate))) {
eval_rows[[length(eval_rows) + 1L]] <- data.frame(policy = pair[[1]], estimator = lab[[e]], estimate = res$estimate[[e]],
low = res$ci[[e]][1], high = res$ci[[e]][2])
}
}
eval_rows[[length(eval_rows) + 1L]] <- data.frame(policy = "Logged policy", estimator = "Observed return", estimate = logged,
low = ev$logged_ci[1], high = ev$logged_ci[2])
eval_df <- do.call(rbind, eval_rows)
values <- list(policy_value = v_fqe, policy_ci_low = v_ci[1], policy_ci_high = v_ci[2], logged_value = logged,
logged_ci_low = ev$logged_ci[1], logged_ci_high = ev$logged_ci[2], agreement = agreement, low_support_share = low_support,
n_episodes = E, n_steps = n, iterations_run = iters_run, final_loss = if (length(trace)) trace[[length(trace)]]$loss else NULL,
algorithm = algorithm)
if ("wdr" %in% names(ev$estimate)) {
values$policy_value_wdr <- ev$estimate$wdr
values$policy_wdr_ci_low <- ev$ci$wdr[1]
values$policy_wdr_ci_high <- ev$ci$wdr[2]
values$ess <- ev$ess
}
if (!is.null(ev_bc)) values$bc_value <- ev_bc$estimate$fqe
values <- c(values, extra)
# Policy table: one row per distinct state (first appearance).
ds <- cs_seq_distinct_states(x)
values$n_states <- ds$count
score <- if (!is.null(q_all)) q_all else probs_all
score_label <- if (!is.null(q_all)) "Q" else "P"
pol_cols <- lapply(seq_along(features), function(j) list(key = sprintf("s%d", j), label = features[j], type = if (is_cat[j]) "string" else "number"))
pol_cols[[length(pol_cols) + 1L]] <- list(key = "action", label = "Learned action", type = "string")
for (j in seq_len(K)) pol_cols[[length(pol_cols) + 1L]] <- list(key = sprintf("v%d", j), label = sprintf("%s(%s)", score_label, lv[j]), type = "number")
pol_df <- data.frame(row.names = seq_along(ds$rows))
for (j in seq_along(features)) {
c <- features[j]
pol_df[[sprintf("s%d", j)]] <- if (is_cat[j]) as.character(df[[c]][ds$rows]) else as.numeric(df[[c]][ds$rows])
}
pol_df$action <- lv[policy[ds$rows]]
for (j in seq_len(K)) pol_df[[sprintf("v%d", j)]] <- as.numeric(score[ds$rows, j])
rownames(pol_df) <- NULL
share_df <- data.frame(action = lv, logged = vapply(seq_len(K), function(j) mean(a_idx == j), numeric(1)),
learned = vapply(seq_len(K), function(j) mean(policy == j), numeric(1)))
train_value <- lapply(trace, function(t) t$value)
train_df <- data.frame(iteration = vapply(trace, function(t) as.integer(t$iteration), integer(1)),
loss = vapply(trace, function(t) as.numeric(t$loss), numeric(1)))
train_df$value <- if (length(trace) && !any(vapply(train_value, is.null, logical(1)))) unlist(train_value) else rep(NA_real_, nrow(train_df))
eval_labels <- paste(eval_df$policy, eval_df$estimator, sep = " · ")
charts <- list(
cs_chart("evaluation", "forest", "Estimated return per episode", list(
label = cs_col("Policy and estimator", eval_labels, levels = eval_labels),
estimate = cs_col("Value", eval_df$estimate),
low = cs_col("Lower", eval_df$low),
high = cs_col("Upper", eval_df$high)
), controls = list(reference = logged)),
cs_chart("actions", "share-compare", "Action shares: logged vs learned", list(
level = cs_col("Action", c(share_df$action, share_df$action), levels = lv),
share = cs_col("Share", c(share_df$logged, share_df$learned)),
source = cs_col("Policy", c(rep("Logged", K), rep("Learned", K)), levels = c("Logged", "Learned"))
), question = "How often does the learned policy choose each action, compared with the logged policy?")
)
if (length(trace) && !any(vapply(train_value, is.null, logical(1)))) {
charts <- append(charts, list(cs_chart("training", "return-curve", "Estimated start-state value by iteration", list(
x = cs_col("Iteration", train_df$iteration),
y = cs_col("Estimated value", train_df$value)
), controls = list(reference = logged))), after = 1L)
}
net_note <- if (algorithm %in% c("cql", "iql")) {
sprintf(" (networks: hidden layers %s, %d rounds × %d epochs, learning rate %s)", paste(hidden, collapse = ", "), rounds, epochs, format(lr, digits = 6))
} else ""
cs_publish(list(
method = "decide.offline_rl",
methodVersion = "1.1.0",
title = sprintf("Offline policy learning (%s)", alg_label),
engine = cs_engine_info("stats", "codesplashr", "torch"),
n = n,
summary = summary,
statistics = list(
list(key = "policy_value", label = "Learned policy value (FQE)", value = v_fqe),
list(key = "ci", label = paste(pct, "CI"), value = v_ci),
list(key = "logged", label = "Logged policy value", value = logged),
list(key = "agreement", label = "Agreement with logged actions", value = agreement)
),
tables = list(
list(key = "evaluation", title = "Estimated return per episode",
columns = list(list(key = "policy", label = "Policy", type = "string"), list(key = "estimator", label = "Estimator", type = "string"),
list(key = "estimate", label = "Estimate", type = "number"), list(key = "low", label = paste(pct, "CI low"), type = "number"),
list(key = "high", label = paste(pct, "CI high"), type = "number")),
rows = eval_df),
list(key = "policy", title = sprintf("Learned policy by state (%d of %d distinct states)", min(ds$count, 500L), ds$count), columns = pol_cols, rows = pol_df),
list(key = "actions", title = "Actions: logged vs learned policy",
columns = list(list(key = "action", label = a_col, type = "string"), list(key = "logged", label = "Logged share", type = "percent"),
list(key = "learned", label = "Learned share", type = "percent")),
rows = share_df),
list(key = "training", title = "Training by iteration",
columns = list(list(key = "iteration", label = "Iteration", type = "integer"), list(key = "loss", label = "Loss", type = "number"),
list(key = "value", label = "Estimated start-state value", type = "number")),
rows = train_df)
),
warnings = warnings,
notes = list(paste0(alg_label, "; discount ", gfmt, "; Q-models and evaluation use ", paste(features, collapse = ", "), net_note,
sprintf(". Evaluation: fitted Q evaluation (linear per action, cross-fitted over %d episode folds)", folds),
if (!is.null(propensity)) ", weighted doubly robust and weighted per-decision IS with the logged propensities" else "",
sprintf("; %d bootstrap resamples of episodes (seed %s). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.", n_boot, seed))),
values = values,
charts = charts
))
Conservative Q-learning learned a policy from 60 episodes (640 decisions). Fitted Q evaluation puts its return per episode at 0.511, 95% CI [0.494, 0.529], against 0.049 for the logged policy (discount 0.95). It agrees with the logged action at 64% of the logged states.
- Learned policy value (FQE)
- 0.5107
- 95% CI
- [0.4940, 0.5289]
- Logged policy value
- 0.0487
- Agreement with logged actions
- 0.6406
To keep this page light, the plots are shown once, under the R tab.
Estimated return per episode
| Policy | Estimator | Estimate | 95% CI low | 95% CI high |
|---|---|---|---|---|
| Conservative Q-learning | Fitted Q evaluation | 0.5107 | 0.4940 | 0.5289 |
| Conservative Q-learning | Weighted doubly robust | 0.5323 | 0.4717 | 0.5866 |
| Conservative Q-learning | Weighted per-decision IS | 0.5185 | −0.2262 | 0.6622 |
| Behavior cloning (baseline) | Fitted Q evaluation | 0.5107 | 0.4940 | 0.5289 |
| Behavior cloning (baseline) | Weighted doubly robust | 0.5323 | 0.4717 | 0.5866 |
| Behavior cloning (baseline) | Weighted per-decision IS | 0.5185 | −0.2262 | 0.6622 |
| Logged policy | Observed return | 0.0487 | −0.0376 | 0.1387 |
Learned policy by state (12 of 12 distinct states)
| cell | weather today | Learned action | Q(left) | Q(stay) | Q(right) |
|---|---|---|---|---|---|
| c1 | sun | right | −0.5433 | −0.3971 | 0.1158 |
| c2 | sun | right | −0.9531 | −0.3548 | 0.3412 |
| c3 | rain | right | −0.0943 | −0.3722 | 0.3326 |
| c4 | rain | right | −0.0469 | 0.3115 | 0.7662 |
| c5 | rain | right | −0.2087 | 0.0189 | 1.041 |
| c1 | rain | right | −0.3203 | −0.8373 | 0.0391 |
| c0 | sun | right | −0.8865 | −0.5233 | 0.3031 |
| c3 | sun | right | −0.9514 | −0.3169 | 0.7796 |
| c2 | rain | right | 0.0251 | −0.6580 | 0.1797 |
| c4 | sun | right | −0.4142 | 0.4192 | 1.025 |
| c5 | sun | right | −0.4253 | 0.4050 | 1.216 |
| c0 | rain | right | −0.1563 | −0.2290 | 0.2950 |
Actions: logged vs learned policy
| action | Logged share | Learned share |
|---|---|---|
| left | 16.9% | 0.0% |
| stay | 19.1% | 0.0% |
| right | 64.1% | 100.0% |
Training by iteration
| Iteration | Loss | Estimated start-state value |
|---|---|---|
| 1 | 0.9673 | 0.4862 |
| 2 | 0.9721 | 0.0208 |
| 3 | 0.9706 | 0.5907 |
| 4 | 0.9524 | 0.2081 |
- 18 of 60 episodes end without done = true (cut short): their last step is left out of the Q-models because its next state is unknown.
- Effective sample size 2.5 of 60 episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.
- The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.
- Conservative Q-learning; discount 0.95; Q-models and evaluation use cell, weather today (networks: hidden layers 16, 4 rounds × 6 epochs, learning rate 0.005). Evaluation: fitted Q evaluation (linear per action, cross-fitted over 2 episode folds), weighted doubly robust and weighted per-decision IS with the logged propensities; 200 bootstrap resamples of episodes (seed 42). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Offline policy learning from logged episodes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.offline_rl 1.1.0 · spec baa2d85e8904e6c4
# Dataset: pol_corridor (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.decide import ope, sequential as seq # twins of codesplashr::cs_bandit_design / cs_seq_* (shared-RNG folds and bootstrap)
from codesplash.decide import offline_rl as orl # twin of codesplashr::cs_orl_* (shared initial weights and batch order)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/pol_corridor.parquet", columns=["episode", "step", "cell", "weather today", "action", "reward", "propensity", "done"])
n_input = len(df)
df["cell"] = pd.Categorical(df["cell"], categories=["c0", "c1", "c2", "c3", "c4", "c5"]) # stored level order
df["weather today"] = pd.Categorical(df["weather today"], categories=["rain", "sun"]) # stored level order
df["action"] = pd.Categorical(df["action"], categories=["left", "stay", "right"]) # stored level order
df["done"] = pd.Categorical(df["done"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["episode", "step", "cell", "weather today", "action", "reward", "propensity", "done"]) # listwise deletion over the analysis columns
df["cell"] = df["cell"].cat.remove_unused_categories()
df["weather today"] = df["weather today"].cat.remove_unused_categories()
df["action"] = df["action"].cat.remove_unused_categories()
df["done"] = df["done"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["episode", "step", "cell", "weather today", "action", "reward", "propensity", "done"]) # infinite values stop the run (registry/errors.yaml)
# %% Inputs
ep_col, step_col, a_col, r_col = "episode", "step", "action", "reward"
p_col = "propensity"
done_col = "done"
features = ["cell", "weather today"]
algorithm = "cql" # fqi | bc | cql | iql
gamma = float(0.95)
iterations = int(300)
rounds = int(4)
hidden = [int(u) for u in [16]]
epochs = int(6)
lr = float(0.005)
batch_size = 128
alpha = float(1)
double = True
dueling = False
expectile = float(0.7)
temperature = float(3)
folds = int(2)
fqe_iterations = int(200)
n_boot = int(200)
conf = 0.95
seed = 42
def as_flag(s):
"""Yes/no columns count as 1/0."""
return (s.astype(str) == "true").to_numpy() if isinstance(s.dtype, pd.CategoricalDtype) else (s.to_numpy(dtype=float) != 0)
# Rows by episode (first appearance), then step.
ep_keys = df[ep_col].astype(str).tolist() if isinstance(df[ep_col].dtype, pd.CategoricalDtype) else df[ep_col].to_numpy(dtype=float).tolist()
order = seq.order_rows(seq.episode_codes(ep_keys), df[step_col].to_numpy(dtype=float))
df = df.iloc[order].reset_index(drop=True)
ep_keys = [ep_keys[i] for i in order]
ep = seq.episode_codes(ep_keys)
st = seq.structure(ep, df[step_col].to_numpy(dtype=float), as_flag(df[done_col]) if done_col else None)
levels = [str(x) for x in df[a_col].cat.categories]
K = len(levels)
action = df[a_col].astype(str).to_numpy()
reward = as_flag(df[r_col]).astype(float) if isinstance(df[r_col].dtype, pd.CategoricalDtype) else df[r_col].to_numpy(dtype=float)
propensity = df[p_col].to_numpy(dtype=float) if p_col else None
numeric = [c for c in features if not isinstance(df[c].dtype, pd.CategoricalDtype)]
categorical = {c: [str(x) for x in df[c].cat.categories] for c in features if isinstance(df[c].dtype, pd.CategoricalDtype)}
# %% Checks (same order in both engines)
if st["duplicates"]:
cs.cs_error("CS_E_INVALID_VALUES", column=step_col, requirement="unique within each episode", count=st["duplicates"])
if propensity is not None:
bad = int(np.sum((propensity <= 0) | (propensity > 1)))
if bad:
cs.cs_error("CS_E_INVALID_VALUES", column=p_col, requirement="a probability in (0, 1]", count=bad)
if st["E"] < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=ep_col, min=2, k=st["E"])
present = len(set(action.tolist()))
if present < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=a_col, min=2, k=present)
col_of = {lv: j for j, lv in enumerate(levels)}
a_idx = np.array([col_of[a] for a in action], dtype=np.int64)
x = ope.design(df, numeric, categorical)
starts = st["starts"]
fit_rows = st["fit_rows"]
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.offline_rl/corridor-cql/out-python",
)
# %% Learn
q_all = None
probs_all = None
bc = seq.behavior_cloning(x, a_idx, K)
bc_policy = np.argmax(bc["probs"], axis=1)
extra = {}
if algorithm == "fqi":
beta, support, iters_run, converged, trace = seq.fitted_q(x, a_idx, reward, st["next"], K, gamma, fit_rows, iterations, starts=starts)
q_all = seq.q_values(x, beta)
policy = seq.greedy(q_all, support)
if not converged:
warnings.append(f"Fitted Q iteration did not settle within {iterations} iterations; raise the limit or lower the discount.")
elif algorithm == "bc":
probs_all = bc["probs"]
policy = bc_policy
trace = bc["trace"]
iters_run, converged = bc["iterations"], bc["converged"]
if not converged:
warnings.append(f"Behavior cloning did not converge within {iters_run} Newton steps.")
else:
z = seq.nn_features(x, len(numeric))
if algorithm == "cql":
fit = orl.cql(z, a_idx, reward, st["next"], fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, alpha, double, dueling, seed, starts)
q_all = orl.q_numpy(orl.core.torch_init(), fit["params"], z, dueling, K)
policy = np.argmax(q_all, axis=1)
else:
fit = orl.iql(z, a_idx, reward, st["next"], fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, expectile, temperature, seed, starts)
q_all = orl.q_numpy(orl.core.torch_init(), fit["params"], z, False, K)
policy = np.argmax(orl.policy_logits(fit["policy_params"], z), axis=1)
extra = {"weight_ess": fit["weight_ess"], "weight_capped": fit["weight_capped"]}
if fit["weight_capped"] > 0.05:
warnings.append(f"{fit['weight_capped']:.0%} of the advantage weights hit the cap of 100: lower the temperature, or the policy imitates a few rows.")
trace = fit["trace"]
iters_run, converged = rounds, True
# %% Evaluate (FQE always; weighted doubly robust when propensities are given)
ev = seq.evaluate(st, x, a_idx, policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep)
ev_bc = seq.evaluate(st, x, a_idx, bc_policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep) if algorithm != "bc" else None
E, n = ev["E"], ev["n"]
agreement = float(np.mean(policy == a_idx))
low_support = float(np.mean(bc["probs"][np.arange(n), policy] < 0.05))
if st["truncated"]:
warnings.append(f"{st['truncated']} of {E} episodes end without {done_col} = true (cut short): their last step is left out of the Q-models because its next state is unknown.")
if low_support > 0.2:
warnings.append(f"At {low_support:.0%} of the logged states the learned policy picks an action the logging policy rarely took (estimated probability under 5%): its value there is extrapolated.")
if not ev["fqe_converged"]:
warnings.append(f"Fitted Q evaluation of the learned policy did not settle within {fqe_iterations} iterations.")
if propensity is not None and ev["ess"] < 0.1 * E:
warnings.append(f"Effective sample size {ev['ess']:.1f} of {E} episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.")
warnings.append("The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.")
# %% Result
alg_label = {"fqi": "Fitted Q iteration", "bc": "Behavior cloning", "cql": "Conservative Q-learning", "iql": "Implicit Q-learning"}[algorithm]
pct = f"{conf:.0%}"
v_fqe, (v_lo, v_hi) = ev["estimate"]["fqe"], ev["ci"]["fqe"]
logged = ev["logged"]
summary = (
f"{alg_label} learned a policy from {E:,} episodes ({n:,} decisions). Fitted Q evaluation puts its return per episode at {v_fqe:.3f}, "
f"{pct} CI [{v_lo:.3f}, {v_hi:.3f}], against {logged:.3f} for the logged policy (discount {gamma:g}). It agrees with the logged action at "
f"{agreement:.0%} of the logged states."
)
eval_rows = []
for name, res in [(alg_label, ev), ("Behavior cloning (baseline)", ev_bc)]:
if res is None:
continue
for e in [k for k in ("fqe", "wdr", "wpdis") if k in res["estimate"]]:
eval_rows.append({"policy": name, "estimator": seq.LABELS[e], "estimate": res["estimate"][e], "low": res["ci"][e][0], "high": res["ci"][e][1]})
eval_rows.append({"policy": "Logged policy", "estimator": "Observed return", "estimate": logged, "low": ev["logged_ci"][0], "high": ev["logged_ci"][1]})
values = {"policy_value": v_fqe, "policy_ci_low": v_lo, "policy_ci_high": v_hi, "logged_value": logged, "logged_ci_low": ev["logged_ci"][0],
"logged_ci_high": ev["logged_ci"][1], "agreement": agreement, "low_support_share": low_support, "n_episodes": E, "n_steps": n,
"iterations_run": iters_run, "final_loss": trace[-1]["loss"] if trace else None, "algorithm": algorithm}
if "wdr" in ev["estimate"]:
values.update({"policy_value_wdr": ev["estimate"]["wdr"], "policy_wdr_ci_low": ev["ci"]["wdr"][0], "policy_wdr_ci_high": ev["ci"]["wdr"][1], "ess": ev["ess"]})
if ev_bc is not None:
values["bc_value"] = ev_bc["estimate"]["fqe"]
values.update(extra)
# Policy table: one row per distinct state (first appearance).
first, n_states = seq.distinct_states(x)
values["n_states"] = n_states
pol_cols = [{"key": f"s{j + 1}", "label": c, "type": "string" if c in categorical else "number"} for j, c in enumerate(features)]
pol_cols.append({"key": "action", "label": "Learned action", "type": "string"})
score = q_all if q_all is not None else probs_all
score_label = "Q" if q_all is not None else "P"
for j, lv in enumerate(levels):
pol_cols.append({"key": f"v{j + 1}", "label": f"{score_label}({lv})", "type": "number"})
pol_rows = []
for i in first:
r = {f"s{j + 1}": (str(df[c].iloc[i]) if c in categorical else float(df[c].iloc[i])) for j, c in enumerate(features)}
r["action"] = levels[int(policy[i])]
for j in range(K):
r[f"v{j + 1}"] = float(score[i, j])
pol_rows.append(r)
share_rows = [{"action": lv, "logged": float(np.mean(a_idx == j)), "learned": float(np.mean(policy == j))} for j, lv in enumerate(levels)]
train_value = [t.get("value") for t in trace]
charts = [
cs.chart("evaluation", "forest", "Estimated return per episode", {
"label": cs.col("Policy and estimator", [f"{r['policy']} · {r['estimator']}" for r in eval_rows], levels=[f"{r['policy']} · {r['estimator']}" for r in eval_rows]),
"estimate": cs.col("Value", [r["estimate"] for r in eval_rows]),
"low": cs.col("Lower", [r["low"] for r in eval_rows]),
"high": cs.col("Upper", [r["high"] for r in eval_rows]),
}, controls={"reference": logged}),
cs.chart("actions", "share-compare", "Action shares: logged vs learned", {
"level": cs.col("Action", [r["action"] for r in share_rows] * 2, levels=levels),
"share": cs.col("Share", [r["logged"] for r in share_rows] + [r["learned"] for r in share_rows]),
"source": cs.col("Policy", ["Logged"] * K + ["Learned"] * K, levels=["Logged", "Learned"]),
}, question="How often does the learned policy choose each action, compared with the logged policy?"),
]
if all(v is not None for v in train_value) and train_value:
charts.insert(1, cs.chart("training", "return-curve", "Estimated start-state value by iteration", {
"x": cs.col("Iteration", [t["iteration"] for t in trace]),
"y": cs.col("Estimated value", train_value),
}, controls={"reference": logged}))
cs.publish({
"method": "decide.offline_rl",
"methodVersion": "1.1.0",
"title": f"Offline policy learning ({alg_label})",
"engine": cs.engine_info("numpy", "pandas", "torch"),
"n": n,
"summary": summary,
"statistics": [
{"key": "policy_value", "label": "Learned policy value (FQE)", "value": v_fqe},
{"key": "ci", "label": f"{pct} CI", "value": [v_lo, v_hi]},
{"key": "logged", "label": "Logged policy value", "value": logged},
{"key": "agreement", "label": "Agreement with logged actions", "value": agreement},
],
"tables": [
{"key": "evaluation", "title": "Estimated return per episode",
"columns": [{"key": "policy", "label": "Policy", "type": "string"}, {"key": "estimator", "label": "Estimator", "type": "string"},
{"key": "estimate", "label": "Estimate", "type": "number"}, {"key": "low", "label": f"{pct} CI low", "type": "number"},
{"key": "high", "label": f"{pct} CI high", "type": "number"}],
"rows": eval_rows},
{"key": "policy", "title": f"Learned policy by state ({min(n_states, 500)} of {n_states} distinct states)", "columns": pol_cols, "rows": pol_rows},
{"key": "actions", "title": "Actions: logged vs learned policy",
"columns": [{"key": "action", "label": a_col, "type": "string"}, {"key": "logged", "label": "Logged share", "type": "percent"},
{"key": "learned", "label": "Learned share", "type": "percent"}],
"rows": share_rows},
{"key": "training", "title": "Training by iteration",
"columns": [{"key": "iteration", "label": "Iteration", "type": "integer"}, {"key": "loss", "label": "Loss", "type": "number"},
{"key": "value", "label": "Estimated start-state value", "type": "number"}],
"rows": [{"iteration": t["iteration"], "loss": t["loss"], "value": t.get("value")} for t in trace]},
],
"warnings": warnings,
"notes": [
f"{alg_label}; discount {gamma:g}; Q-models and evaluation use {', '.join(features)}"
+ (f" (networks: hidden layers {', '.join(str(h) for h in hidden)}, {rounds} rounds × {epochs} epochs, learning rate {lr:g})" if algorithm in ("cql", "iql") else "")
+ f". Evaluation: fitted Q evaluation (linear per action, cross-fitted over {folds} episode folds)"
+ (", weighted doubly robust and weighted per-decision IS with the logged propensities" if propensity is not None else "")
+ f"; {n_boot} bootstrap resamples of episodes (seed {seed}). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.",
],
"values": values,
"charts": charts,
})
The learned policy's estimated value is 0.511, against 0.049 for the policy that produced the logs and 0.511 for behavior cloningBehavior cloningLearns to copy the logged actions from the states (here a multinomial logistic regression): a baseline every learned policy should beat.. The effective sample size is 2.5 of 60 episodes, so the weighted doubly robust check leans on the Q-model. And the policy was learned and scored on the same episodes: the result says so.
Read an IQL run
In the appImplicit Q-learning learned a policy from 40 episodes (400 decisions). Fitted Q evaluation puts its return per episode at 20.197, 95% CI [19.924, 20.476], against 19.885 for the logged policy (discount 0.9). It agrees with the logged action at 37% of the logged states.
- Learned policy value (FQE)
- 20.197
- 95% CI
- [19.924, 20.476]
- Logged policy value
- 19.885
- Agreement with logged actions
- 0.3725
Plots
View data
| Value | Upper | Policy and estimator | Lower |
|---|---|---|---|
| 20.197 | 20.476 | Implicit Q-learning · Fitted Q evaluation | 19.924 |
| 25.668 | 29.117 | Implicit Q-learning · Weighted doubly robust | 22.670 |
| 11.909 | 14.420 | Implicit Q-learning · Weighted per-decision IS | 8.280 |
| 17.382 | 17.781 | Behavior cloning (baseline) · Fitted Q evaluation | 17.016 |
| 28.590 | 33.079 | Behavior cloning (baseline) · Weighted doubly robust | 22.151 |
| 19.670 | 24.716 | Behavior cloning (baseline) · Weighted per-decision IS | 11.179 |
| 19.885 | 22.061 | Logged policy · Observed return | 18.000 |
View data
| Iteration | Estimated value |
|---|---|
| 1 | −0.5128 |
| 2 | 0.1109 |
| 3 | 0.8400 |
View data
| Action | Share | Policy |
|---|---|---|
| order 0 | 0.3275 | Logged |
| order 2 | 0.3450 | Logged |
| order 4 | 0.3275 | Logged |
| order 0 | 0.5450 | Learned |
| order 2 | 0.4550 | Learned |
| order 4 | 0 | Learned |
Estimated return per episode
| Policy | Estimator | Estimate | 95% CI low | 95% CI high |
|---|---|---|---|---|
| Implicit Q-learning | Fitted Q evaluation | 20.197 | 19.924 | 20.476 |
| Implicit Q-learning | Weighted doubly robust | 25.668 | 22.670 | 29.117 |
| Implicit Q-learning | Weighted per-decision IS | 11.909 | 8.280 | 14.420 |
| Behavior cloning (baseline) | Fitted Q evaluation | 17.382 | 17.016 | 17.781 |
| Behavior cloning (baseline) | Weighted doubly robust | 28.590 | 22.151 | 33.079 |
| Behavior cloning (baseline) | Weighted per-decision IS | 19.670 | 11.179 | 24.716 |
| Logged policy | Observed return | 19.885 | 18.000 | 22.061 |
Learned policy by state (7 of 7 distinct states)
| stock | Learned action | Q(order 0) | Q(order 2) | Q(order 4) |
|---|---|---|---|---|
| 2 | order 0 | 1.481 | 1.010 | 1.290 |
| 3 | order 0 | 2.629 | 1.637 | 2.058 |
| 0 | order 2 | 2.016 | 4.182 | 1.544 |
| 1 | order 2 | 1.524 | 2.194 | 1.213 |
| 4 | order 0 | 4.214 | 2.608 | 3.290 |
| 5 | order 0 | 5.795 | 3.584 | 4.546 |
| 6 | order 0 | 7.376 | 4.561 | 5.802 |
Actions: logged vs learned policy
| order | Logged share | Learned share |
|---|---|---|
| order 0 | 32.8% | 54.5% |
| order 2 | 34.5% | 45.5% |
| order 4 | 32.8% | 0.0% |
Training by iteration
| Iteration | Loss | Estimated start-state value |
|---|---|---|
| 1 | 12.575 | −0.5128 |
| 2 | 10.845 | 0.1109 |
| 3 | 9.665 | 0.8400 |
- 14% of the advantage weights hit the cap of 100: lower the temperature, or the policy imitates a few rows.
- Effective sample size 0.0 of 40 episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.
- The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.
- Implicit Q-learning; discount 0.9; Q-models and evaluation use stock (networks: hidden layers 16, 3 rounds × 6 epochs, learning rate 0.005). Evaluation: fitted Q evaluation (linear per action, cross-fitted over 2 episode folds), weighted doubly robust and weighted per-decision IS with the logged propensities; 200 bootstrap resamples of episodes (seed 42). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.
The exact R script · R R version 4.5.1 (2025-06-13)
# Offline policy learning from logged episodes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.offline_rl 1.1.0 · spec 880b853e6cd0ff74
# Dataset: pol_inventory (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_bandit_design(), cs_seq_*(), cs_orl_*(): twins of codesplash.decide.ope / sequential / offline_rl
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/pol_inventory.parquet", col_select = c("store week", "week", "stock", "order", "profit", "p_logged")))
n_input <- nrow(df)
df[["store week"]] <- factor(df[["store week"]], levels = sort(unique(df[["store week"]]), method = "radix"))
df[["order"]] <- factor(df[["order"]], levels = c("order 0", "order 2", "order 4")) # stored level order
df <- df[stats::complete.cases(df[c("store week", "week", "stock", "order", "profit", "p_logged")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("store week", "week", "stock", "order", "profit", "p_logged")) # infinite values stop the run (registry/errors.yaml)
# %% Inputs
ep_col <- "store week"
step_col <- "week"
a_col <- "order"
r_col <- "profit"
p_col <- "p_logged"
done_col <- NULL
features <- c("stock")
algorithm <- "iql" # fqi | bc | cql | iql
gamma <- as.numeric(0.9)
iterations <- as.integer(300)
rounds <- as.integer(3)
hidden <- as.integer(unlist(c(16)))
epochs <- as.integer(6)
lr <- as.numeric(0.005)
batch_size <- 100
alpha <- as.numeric(1)
double <- TRUE
dueling <- FALSE
expectile <- as.numeric(0.7)
temperature <- as.numeric(3)
folds <- as.integer(2)
fqe_iterations <- as.integer(200)
n_boot <- as.integer(200)
conf <- 0.95
seed <- 42
# Yes/no columns count as 1/0.
as_flag <- function(v) if (is.factor(v)) as.character(v) == "true" else as.numeric(v) != 0
# Rows by episode (first appearance), then step.
ep_keys <- if (is.factor(df[[ep_col]])) as.character(df[[ep_col]]) else as.numeric(df[[ep_col]])
ord <- cs_seq_order(cs_seq_episode_codes(ep_keys), as.numeric(df[[step_col]]))
df <- df[ord, , drop = FALSE]
rownames(df) <- NULL
ep <- cs_seq_episode_codes(ep_keys[ord])
st <- cs_seq_structure(ep, as.numeric(df[[step_col]]), if (!is.null(done_col)) as_flag(df[[done_col]]) else NULL)
lv <- levels(df[[a_col]])
K <- length(lv)
action <- as.character(df[[a_col]])
reward <- if (is.factor(df[[r_col]])) as.numeric(as_flag(df[[r_col]])) else as.numeric(df[[r_col]])
propensity <- if (!is.null(p_col)) as.numeric(df[[p_col]]) else NULL
is_cat <- vapply(features, function(c) is.factor(df[[c]]), logical(1))
numeric_f <- features[!is_cat]
categorical_f <- lapply(stats::setNames(features[is_cat], features[is_cat]), function(c) levels(df[[c]]))
# %% Checks (same order in both engines)
if (st$duplicates > 0) cs_error("CS_E_INVALID_VALUES", column = step_col, requirement = "unique within each episode", count = st$duplicates)
if (!is.null(propensity)) {
bad <- sum(propensity <= 0 | propensity > 1)
if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = p_col, requirement = "a probability in (0, 1]", count = bad)
}
if (st$E < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = ep_col, min = 2, k = st$E)
present <- length(unique(action))
if (present < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = a_col, min = 2, k = present)
a_idx <- match(action, lv)
x <- cs_bandit_design(df, numeric_f, categorical_f)
starts <- st$starts
fit_rows <- st$fit_rows
# 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.offline_rl/inventory-iql/out-r")
# %% Learn
q_all <- NULL
probs_all <- NULL
bc <- cs_seq_behavior_cloning(x, a_idx, K)
bc_policy <- as.integer(apply(bc$probs, 1, which.max))
extra <- list()
if (algorithm == "fqi") {
fq <- cs_seq_fitted_q(x, a_idx, reward, st$nxt, K, gamma, fit_rows, iterations, starts = starts)
q_all <- x %*% t(fq$beta)
policy <- cs_seq_greedy(q_all, fq$support)
trace <- fq$trace
iters_run <- fq$iterations
if (!fq$converged) warnings <- c(warnings, sprintf("Fitted Q iteration did not settle within %d iterations; raise the limit or lower the discount.", iterations))
} else if (algorithm == "bc") {
probs_all <- bc$probs
policy <- bc_policy
trace <- bc$trace
iters_run <- bc$iterations
if (!bc$converged) warnings <- c(warnings, sprintf("Behavior cloning did not converge within %d Newton steps.", iters_run))
} else {
z <- cs_seq_nn_features(x, length(numeric_f))
if (algorithm == "cql") {
fit <- cs_orl_cql(z, a_idx, reward, st$nxt, fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, alpha, double, dueling, seed, starts)
q_all <- cs_orl_q_values(fit$params, z, dueling, K)
policy <- as.integer(apply(q_all, 1, which.max))
} else {
fit <- cs_orl_iql(z, a_idx, reward, st$nxt, fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, expectile, temperature, seed, starts)
q_all <- cs_orl_q_values(fit$params, z, FALSE, K)
policy <- as.integer(apply(cs_orl_policy_logits(fit$policy_params, z), 1, which.max))
extra <- list(weight_ess = fit$weight_ess, weight_capped = fit$weight_capped)
if (fit$weight_capped > 0.05) {
warnings <- c(warnings, sprintf("%.0f%% of the advantage weights hit the cap of 100: lower the temperature, or the policy imitates a few rows.", fit$weight_capped * 100))
}
}
trace <- fit$trace
iters_run <- rounds
}
# %% Evaluate (FQE always; weighted doubly robust when propensities are given)
ev <- cs_seq_evaluate(st, x, a_idx, policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep)
ev_bc <- if (algorithm != "bc") cs_seq_evaluate(st, x, a_idx, bc_policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep) else NULL
E <- ev$E
n <- ev$n
agreement <- mean(policy == a_idx)
low_support <- mean(bc$probs[cbind(seq_len(n), policy)] < 0.05)
if (st$truncated > 0) {
warnings <- c(warnings, sprintf("%d of %d episodes end without %s = true (cut short): their last step is left out of the Q-models because its next state is unknown.", st$truncated, E, done_col))
}
if (low_support > 0.2) {
warnings <- c(warnings, sprintf("At %.0f%% of the logged states the learned policy picks an action the logging policy rarely took (estimated probability under 5%%): its value there is extrapolated.", low_support * 100))
}
if (!ev$fqe_converged) warnings <- c(warnings, sprintf("Fitted Q evaluation of the learned policy did not settle within %d iterations.", fqe_iterations))
if (!is.null(propensity) && ev$ess < 0.1 * E) {
warnings <- c(warnings, sprintf("Effective sample size %.1f of %d episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.", ev$ess, E))
}
warnings <- c(warnings, "The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.")
# %% Result
alg_label <- c(fqi = "Fitted Q iteration", bc = "Behavior cloning", cql = "Conservative Q-learning", iql = "Implicit Q-learning")[[algorithm]]
pct <- sprintf("%.0f%%", conf * 100)
v_fqe <- ev$estimate$fqe
v_ci <- ev$ci$fqe
logged <- ev$logged
gfmt <- format(gamma, digits = 6)
summary <- sprintf(
"%s learned a policy from %s episodes (%s decisions). Fitted Q evaluation puts its return per episode at %.3f, %s CI [%.3f, %.3f], against %.3f for the logged policy (discount %s). It agrees with the logged action at %.0f%% of the logged states.",
alg_label, format(E, big.mark = ","), format(n, big.mark = ","), v_fqe, pct, v_ci[1], v_ci[2], logged, gfmt, agreement * 100
)
lab <- cs_seq_labels()
eval_rows <- list()
for (pair in list(list(alg_label, ev), list("Behavior cloning (baseline)", ev_bc))) {
res <- pair[[2]]
if (is.null(res)) next
for (e in intersect(c("fqe", "wdr", "wpdis"), names(res$estimate))) {
eval_rows[[length(eval_rows) + 1L]] <- data.frame(policy = pair[[1]], estimator = lab[[e]], estimate = res$estimate[[e]],
low = res$ci[[e]][1], high = res$ci[[e]][2])
}
}
eval_rows[[length(eval_rows) + 1L]] <- data.frame(policy = "Logged policy", estimator = "Observed return", estimate = logged,
low = ev$logged_ci[1], high = ev$logged_ci[2])
eval_df <- do.call(rbind, eval_rows)
values <- list(policy_value = v_fqe, policy_ci_low = v_ci[1], policy_ci_high = v_ci[2], logged_value = logged,
logged_ci_low = ev$logged_ci[1], logged_ci_high = ev$logged_ci[2], agreement = agreement, low_support_share = low_support,
n_episodes = E, n_steps = n, iterations_run = iters_run, final_loss = if (length(trace)) trace[[length(trace)]]$loss else NULL,
algorithm = algorithm)
if ("wdr" %in% names(ev$estimate)) {
values$policy_value_wdr <- ev$estimate$wdr
values$policy_wdr_ci_low <- ev$ci$wdr[1]
values$policy_wdr_ci_high <- ev$ci$wdr[2]
values$ess <- ev$ess
}
if (!is.null(ev_bc)) values$bc_value <- ev_bc$estimate$fqe
values <- c(values, extra)
# Policy table: one row per distinct state (first appearance).
ds <- cs_seq_distinct_states(x)
values$n_states <- ds$count
score <- if (!is.null(q_all)) q_all else probs_all
score_label <- if (!is.null(q_all)) "Q" else "P"
pol_cols <- lapply(seq_along(features), function(j) list(key = sprintf("s%d", j), label = features[j], type = if (is_cat[j]) "string" else "number"))
pol_cols[[length(pol_cols) + 1L]] <- list(key = "action", label = "Learned action", type = "string")
for (j in seq_len(K)) pol_cols[[length(pol_cols) + 1L]] <- list(key = sprintf("v%d", j), label = sprintf("%s(%s)", score_label, lv[j]), type = "number")
pol_df <- data.frame(row.names = seq_along(ds$rows))
for (j in seq_along(features)) {
c <- features[j]
pol_df[[sprintf("s%d", j)]] <- if (is_cat[j]) as.character(df[[c]][ds$rows]) else as.numeric(df[[c]][ds$rows])
}
pol_df$action <- lv[policy[ds$rows]]
for (j in seq_len(K)) pol_df[[sprintf("v%d", j)]] <- as.numeric(score[ds$rows, j])
rownames(pol_df) <- NULL
share_df <- data.frame(action = lv, logged = vapply(seq_len(K), function(j) mean(a_idx == j), numeric(1)),
learned = vapply(seq_len(K), function(j) mean(policy == j), numeric(1)))
train_value <- lapply(trace, function(t) t$value)
train_df <- data.frame(iteration = vapply(trace, function(t) as.integer(t$iteration), integer(1)),
loss = vapply(trace, function(t) as.numeric(t$loss), numeric(1)))
train_df$value <- if (length(trace) && !any(vapply(train_value, is.null, logical(1)))) unlist(train_value) else rep(NA_real_, nrow(train_df))
eval_labels <- paste(eval_df$policy, eval_df$estimator, sep = " · ")
charts <- list(
cs_chart("evaluation", "forest", "Estimated return per episode", list(
label = cs_col("Policy and estimator", eval_labels, levels = eval_labels),
estimate = cs_col("Value", eval_df$estimate),
low = cs_col("Lower", eval_df$low),
high = cs_col("Upper", eval_df$high)
), controls = list(reference = logged)),
cs_chart("actions", "share-compare", "Action shares: logged vs learned", list(
level = cs_col("Action", c(share_df$action, share_df$action), levels = lv),
share = cs_col("Share", c(share_df$logged, share_df$learned)),
source = cs_col("Policy", c(rep("Logged", K), rep("Learned", K)), levels = c("Logged", "Learned"))
), question = "How often does the learned policy choose each action, compared with the logged policy?")
)
if (length(trace) && !any(vapply(train_value, is.null, logical(1)))) {
charts <- append(charts, list(cs_chart("training", "return-curve", "Estimated start-state value by iteration", list(
x = cs_col("Iteration", train_df$iteration),
y = cs_col("Estimated value", train_df$value)
), controls = list(reference = logged))), after = 1L)
}
net_note <- if (algorithm %in% c("cql", "iql")) {
sprintf(" (networks: hidden layers %s, %d rounds × %d epochs, learning rate %s)", paste(hidden, collapse = ", "), rounds, epochs, format(lr, digits = 6))
} else ""
cs_publish(list(
method = "decide.offline_rl",
methodVersion = "1.1.0",
title = sprintf("Offline policy learning (%s)", alg_label),
engine = cs_engine_info("stats", "codesplashr", "torch"),
n = n,
summary = summary,
statistics = list(
list(key = "policy_value", label = "Learned policy value (FQE)", value = v_fqe),
list(key = "ci", label = paste(pct, "CI"), value = v_ci),
list(key = "logged", label = "Logged policy value", value = logged),
list(key = "agreement", label = "Agreement with logged actions", value = agreement)
),
tables = list(
list(key = "evaluation", title = "Estimated return per episode",
columns = list(list(key = "policy", label = "Policy", type = "string"), list(key = "estimator", label = "Estimator", type = "string"),
list(key = "estimate", label = "Estimate", type = "number"), list(key = "low", label = paste(pct, "CI low"), type = "number"),
list(key = "high", label = paste(pct, "CI high"), type = "number")),
rows = eval_df),
list(key = "policy", title = sprintf("Learned policy by state (%d of %d distinct states)", min(ds$count, 500L), ds$count), columns = pol_cols, rows = pol_df),
list(key = "actions", title = "Actions: logged vs learned policy",
columns = list(list(key = "action", label = a_col, type = "string"), list(key = "logged", label = "Logged share", type = "percent"),
list(key = "learned", label = "Learned share", type = "percent")),
rows = share_df),
list(key = "training", title = "Training by iteration",
columns = list(list(key = "iteration", label = "Iteration", type = "integer"), list(key = "loss", label = "Loss", type = "number"),
list(key = "value", label = "Estimated start-state value", type = "number")),
rows = train_df)
),
warnings = warnings,
notes = list(paste0(alg_label, "; discount ", gfmt, "; Q-models and evaluation use ", paste(features, collapse = ", "), net_note,
sprintf(". Evaluation: fitted Q evaluation (linear per action, cross-fitted over %d episode folds)", folds),
if (!is.null(propensity)) ", weighted doubly robust and weighted per-decision IS with the logged propensities" else "",
sprintf("; %d bootstrap resamples of episodes (seed %s). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.", n_boot, seed))),
values = values,
charts = charts
))
Implicit Q-learning learned a policy from 40 episodes (400 decisions). Fitted Q evaluation puts its return per episode at 20.197, 95% CI [19.924, 20.476], against 19.885 for the logged policy (discount 0.9). It agrees with the logged action at 37% of the logged states.
- Learned policy value (FQE)
- 20.197
- 95% CI
- [19.924, 20.476]
- Logged policy value
- 19.885
- Agreement with logged actions
- 0.3725
To keep this page light, the plots are shown once, under the R tab.
Estimated return per episode
| Policy | Estimator | Estimate | 95% CI low | 95% CI high |
|---|---|---|---|---|
| Implicit Q-learning | Fitted Q evaluation | 20.197 | 19.924 | 20.476 |
| Implicit Q-learning | Weighted doubly robust | 25.668 | 22.670 | 29.117 |
| Implicit Q-learning | Weighted per-decision IS | 11.909 | 8.280 | 14.420 |
| Behavior cloning (baseline) | Fitted Q evaluation | 17.382 | 17.016 | 17.781 |
| Behavior cloning (baseline) | Weighted doubly robust | 28.590 | 22.151 | 33.079 |
| Behavior cloning (baseline) | Weighted per-decision IS | 19.670 | 11.179 | 24.716 |
| Logged policy | Observed return | 19.885 | 18.000 | 22.061 |
Learned policy by state (7 of 7 distinct states)
| stock | Learned action | Q(order 0) | Q(order 2) | Q(order 4) |
|---|---|---|---|---|
| 2 | order 0 | 1.481 | 1.010 | 1.290 |
| 3 | order 0 | 2.629 | 1.637 | 2.058 |
| 0 | order 2 | 2.016 | 4.182 | 1.544 |
| 1 | order 2 | 1.524 | 2.194 | 1.213 |
| 4 | order 0 | 4.214 | 2.608 | 3.290 |
| 5 | order 0 | 5.795 | 3.584 | 4.546 |
| 6 | order 0 | 7.376 | 4.561 | 5.802 |
Actions: logged vs learned policy
| order | Logged share | Learned share |
|---|---|---|
| order 0 | 32.8% | 54.5% |
| order 2 | 34.5% | 45.5% |
| order 4 | 32.8% | 0.0% |
Training by iteration
| Iteration | Loss | Estimated start-state value |
|---|---|---|
| 1 | 12.575 | −0.5128 |
| 2 | 10.845 | 0.1109 |
| 3 | 9.665 | 0.8400 |
- 14% of the advantage weights hit the cap of 100: lower the temperature, or the policy imitates a few rows.
- Effective sample size 0.0 of 40 episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.
- The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.
- Implicit Q-learning; discount 0.9; Q-models and evaluation use stock (networks: hidden layers 16, 3 rounds × 6 epochs, learning rate 0.005). Evaluation: fitted Q evaluation (linear per action, cross-fitted over 2 episode folds), weighted doubly robust and weighted per-decision IS with the logged propensities; 200 bootstrap resamples of episodes (seed 42). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Offline policy learning from logged episodes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.offline_rl 1.1.0 · spec 880b853e6cd0ff74
# Dataset: pol_inventory (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.decide import ope, sequential as seq # twins of codesplashr::cs_bandit_design / cs_seq_* (shared-RNG folds and bootstrap)
from codesplash.decide import offline_rl as orl # twin of codesplashr::cs_orl_* (shared initial weights and batch order)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/pol_inventory.parquet", columns=["store week", "week", "stock", "order", "profit", "p_logged"])
n_input = len(df)
df["store week"] = pd.Categorical(df["store week"], categories=sorted(df["store week"].dropna().unique()))
df["order"] = pd.Categorical(df["order"], categories=["order 0", "order 2", "order 4"]) # stored level order
df = df.dropna(subset=["store week", "week", "stock", "order", "profit", "p_logged"]) # listwise deletion over the analysis columns
df["store week"] = df["store week"].cat.remove_unused_categories()
df["order"] = df["order"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["store week", "week", "stock", "order", "profit", "p_logged"]) # infinite values stop the run (registry/errors.yaml)
# %% Inputs
ep_col, step_col, a_col, r_col = "store week", "week", "order", "profit"
p_col = "p_logged"
done_col = None
features = ["stock"]
algorithm = "iql" # fqi | bc | cql | iql
gamma = float(0.9)
iterations = int(300)
rounds = int(3)
hidden = [int(u) for u in [16]]
epochs = int(6)
lr = float(0.005)
batch_size = 100
alpha = float(1)
double = True
dueling = False
expectile = float(0.7)
temperature = float(3)
folds = int(2)
fqe_iterations = int(200)
n_boot = int(200)
conf = 0.95
seed = 42
def as_flag(s):
"""Yes/no columns count as 1/0."""
return (s.astype(str) == "true").to_numpy() if isinstance(s.dtype, pd.CategoricalDtype) else (s.to_numpy(dtype=float) != 0)
# Rows by episode (first appearance), then step.
ep_keys = df[ep_col].astype(str).tolist() if isinstance(df[ep_col].dtype, pd.CategoricalDtype) else df[ep_col].to_numpy(dtype=float).tolist()
order = seq.order_rows(seq.episode_codes(ep_keys), df[step_col].to_numpy(dtype=float))
df = df.iloc[order].reset_index(drop=True)
ep_keys = [ep_keys[i] for i in order]
ep = seq.episode_codes(ep_keys)
st = seq.structure(ep, df[step_col].to_numpy(dtype=float), as_flag(df[done_col]) if done_col else None)
levels = [str(x) for x in df[a_col].cat.categories]
K = len(levels)
action = df[a_col].astype(str).to_numpy()
reward = as_flag(df[r_col]).astype(float) if isinstance(df[r_col].dtype, pd.CategoricalDtype) else df[r_col].to_numpy(dtype=float)
propensity = df[p_col].to_numpy(dtype=float) if p_col else None
numeric = [c for c in features if not isinstance(df[c].dtype, pd.CategoricalDtype)]
categorical = {c: [str(x) for x in df[c].cat.categories] for c in features if isinstance(df[c].dtype, pd.CategoricalDtype)}
# %% Checks (same order in both engines)
if st["duplicates"]:
cs.cs_error("CS_E_INVALID_VALUES", column=step_col, requirement="unique within each episode", count=st["duplicates"])
if propensity is not None:
bad = int(np.sum((propensity <= 0) | (propensity > 1)))
if bad:
cs.cs_error("CS_E_INVALID_VALUES", column=p_col, requirement="a probability in (0, 1]", count=bad)
if st["E"] < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=ep_col, min=2, k=st["E"])
present = len(set(action.tolist()))
if present < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=a_col, min=2, k=present)
col_of = {lv: j for j, lv in enumerate(levels)}
a_idx = np.array([col_of[a] for a in action], dtype=np.int64)
x = ope.design(df, numeric, categorical)
starts = st["starts"]
fit_rows = st["fit_rows"]
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.offline_rl/inventory-iql/out-python",
)
# %% Learn
q_all = None
probs_all = None
bc = seq.behavior_cloning(x, a_idx, K)
bc_policy = np.argmax(bc["probs"], axis=1)
extra = {}
if algorithm == "fqi":
beta, support, iters_run, converged, trace = seq.fitted_q(x, a_idx, reward, st["next"], K, gamma, fit_rows, iterations, starts=starts)
q_all = seq.q_values(x, beta)
policy = seq.greedy(q_all, support)
if not converged:
warnings.append(f"Fitted Q iteration did not settle within {iterations} iterations; raise the limit or lower the discount.")
elif algorithm == "bc":
probs_all = bc["probs"]
policy = bc_policy
trace = bc["trace"]
iters_run, converged = bc["iterations"], bc["converged"]
if not converged:
warnings.append(f"Behavior cloning did not converge within {iters_run} Newton steps.")
else:
z = seq.nn_features(x, len(numeric))
if algorithm == "cql":
fit = orl.cql(z, a_idx, reward, st["next"], fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, alpha, double, dueling, seed, starts)
q_all = orl.q_numpy(orl.core.torch_init(), fit["params"], z, dueling, K)
policy = np.argmax(q_all, axis=1)
else:
fit = orl.iql(z, a_idx, reward, st["next"], fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, expectile, temperature, seed, starts)
q_all = orl.q_numpy(orl.core.torch_init(), fit["params"], z, False, K)
policy = np.argmax(orl.policy_logits(fit["policy_params"], z), axis=1)
extra = {"weight_ess": fit["weight_ess"], "weight_capped": fit["weight_capped"]}
if fit["weight_capped"] > 0.05:
warnings.append(f"{fit['weight_capped']:.0%} of the advantage weights hit the cap of 100: lower the temperature, or the policy imitates a few rows.")
trace = fit["trace"]
iters_run, converged = rounds, True
# %% Evaluate (FQE always; weighted doubly robust when propensities are given)
ev = seq.evaluate(st, x, a_idx, policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep)
ev_bc = seq.evaluate(st, x, a_idx, bc_policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep) if algorithm != "bc" else None
E, n = ev["E"], ev["n"]
agreement = float(np.mean(policy == a_idx))
low_support = float(np.mean(bc["probs"][np.arange(n), policy] < 0.05))
if st["truncated"]:
warnings.append(f"{st['truncated']} of {E} episodes end without {done_col} = true (cut short): their last step is left out of the Q-models because its next state is unknown.")
if low_support > 0.2:
warnings.append(f"At {low_support:.0%} of the logged states the learned policy picks an action the logging policy rarely took (estimated probability under 5%): its value there is extrapolated.")
if not ev["fqe_converged"]:
warnings.append(f"Fitted Q evaluation of the learned policy did not settle within {fqe_iterations} iterations.")
if propensity is not None and ev["ess"] < 0.1 * E:
warnings.append(f"Effective sample size {ev['ess']:.1f} of {E} episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.")
warnings.append("The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.")
# %% Result
alg_label = {"fqi": "Fitted Q iteration", "bc": "Behavior cloning", "cql": "Conservative Q-learning", "iql": "Implicit Q-learning"}[algorithm]
pct = f"{conf:.0%}"
v_fqe, (v_lo, v_hi) = ev["estimate"]["fqe"], ev["ci"]["fqe"]
logged = ev["logged"]
summary = (
f"{alg_label} learned a policy from {E:,} episodes ({n:,} decisions). Fitted Q evaluation puts its return per episode at {v_fqe:.3f}, "
f"{pct} CI [{v_lo:.3f}, {v_hi:.3f}], against {logged:.3f} for the logged policy (discount {gamma:g}). It agrees with the logged action at "
f"{agreement:.0%} of the logged states."
)
eval_rows = []
for name, res in [(alg_label, ev), ("Behavior cloning (baseline)", ev_bc)]:
if res is None:
continue
for e in [k for k in ("fqe", "wdr", "wpdis") if k in res["estimate"]]:
eval_rows.append({"policy": name, "estimator": seq.LABELS[e], "estimate": res["estimate"][e], "low": res["ci"][e][0], "high": res["ci"][e][1]})
eval_rows.append({"policy": "Logged policy", "estimator": "Observed return", "estimate": logged, "low": ev["logged_ci"][0], "high": ev["logged_ci"][1]})
values = {"policy_value": v_fqe, "policy_ci_low": v_lo, "policy_ci_high": v_hi, "logged_value": logged, "logged_ci_low": ev["logged_ci"][0],
"logged_ci_high": ev["logged_ci"][1], "agreement": agreement, "low_support_share": low_support, "n_episodes": E, "n_steps": n,
"iterations_run": iters_run, "final_loss": trace[-1]["loss"] if trace else None, "algorithm": algorithm}
if "wdr" in ev["estimate"]:
values.update({"policy_value_wdr": ev["estimate"]["wdr"], "policy_wdr_ci_low": ev["ci"]["wdr"][0], "policy_wdr_ci_high": ev["ci"]["wdr"][1], "ess": ev["ess"]})
if ev_bc is not None:
values["bc_value"] = ev_bc["estimate"]["fqe"]
values.update(extra)
# Policy table: one row per distinct state (first appearance).
first, n_states = seq.distinct_states(x)
values["n_states"] = n_states
pol_cols = [{"key": f"s{j + 1}", "label": c, "type": "string" if c in categorical else "number"} for j, c in enumerate(features)]
pol_cols.append({"key": "action", "label": "Learned action", "type": "string"})
score = q_all if q_all is not None else probs_all
score_label = "Q" if q_all is not None else "P"
for j, lv in enumerate(levels):
pol_cols.append({"key": f"v{j + 1}", "label": f"{score_label}({lv})", "type": "number"})
pol_rows = []
for i in first:
r = {f"s{j + 1}": (str(df[c].iloc[i]) if c in categorical else float(df[c].iloc[i])) for j, c in enumerate(features)}
r["action"] = levels[int(policy[i])]
for j in range(K):
r[f"v{j + 1}"] = float(score[i, j])
pol_rows.append(r)
share_rows = [{"action": lv, "logged": float(np.mean(a_idx == j)), "learned": float(np.mean(policy == j))} for j, lv in enumerate(levels)]
train_value = [t.get("value") for t in trace]
charts = [
cs.chart("evaluation", "forest", "Estimated return per episode", {
"label": cs.col("Policy and estimator", [f"{r['policy']} · {r['estimator']}" for r in eval_rows], levels=[f"{r['policy']} · {r['estimator']}" for r in eval_rows]),
"estimate": cs.col("Value", [r["estimate"] for r in eval_rows]),
"low": cs.col("Lower", [r["low"] for r in eval_rows]),
"high": cs.col("Upper", [r["high"] for r in eval_rows]),
}, controls={"reference": logged}),
cs.chart("actions", "share-compare", "Action shares: logged vs learned", {
"level": cs.col("Action", [r["action"] for r in share_rows] * 2, levels=levels),
"share": cs.col("Share", [r["logged"] for r in share_rows] + [r["learned"] for r in share_rows]),
"source": cs.col("Policy", ["Logged"] * K + ["Learned"] * K, levels=["Logged", "Learned"]),
}, question="How often does the learned policy choose each action, compared with the logged policy?"),
]
if all(v is not None for v in train_value) and train_value:
charts.insert(1, cs.chart("training", "return-curve", "Estimated start-state value by iteration", {
"x": cs.col("Iteration", [t["iteration"] for t in trace]),
"y": cs.col("Estimated value", train_value),
}, controls={"reference": logged}))
cs.publish({
"method": "decide.offline_rl",
"methodVersion": "1.1.0",
"title": f"Offline policy learning ({alg_label})",
"engine": cs.engine_info("numpy", "pandas", "torch"),
"n": n,
"summary": summary,
"statistics": [
{"key": "policy_value", "label": "Learned policy value (FQE)", "value": v_fqe},
{"key": "ci", "label": f"{pct} CI", "value": [v_lo, v_hi]},
{"key": "logged", "label": "Logged policy value", "value": logged},
{"key": "agreement", "label": "Agreement with logged actions", "value": agreement},
],
"tables": [
{"key": "evaluation", "title": "Estimated return per episode",
"columns": [{"key": "policy", "label": "Policy", "type": "string"}, {"key": "estimator", "label": "Estimator", "type": "string"},
{"key": "estimate", "label": "Estimate", "type": "number"}, {"key": "low", "label": f"{pct} CI low", "type": "number"},
{"key": "high", "label": f"{pct} CI high", "type": "number"}],
"rows": eval_rows},
{"key": "policy", "title": f"Learned policy by state ({min(n_states, 500)} of {n_states} distinct states)", "columns": pol_cols, "rows": pol_rows},
{"key": "actions", "title": "Actions: logged vs learned policy",
"columns": [{"key": "action", "label": a_col, "type": "string"}, {"key": "logged", "label": "Logged share", "type": "percent"},
{"key": "learned", "label": "Learned share", "type": "percent"}],
"rows": share_rows},
{"key": "training", "title": "Training by iteration",
"columns": [{"key": "iteration", "label": "Iteration", "type": "integer"}, {"key": "loss", "label": "Loss", "type": "number"},
{"key": "value", "label": "Estimated start-state value", "type": "number"}],
"rows": [{"iteration": t["iteration"], "loss": t["loss"], "value": t.get("value")} for t in trace]},
],
"warnings": warnings,
"notes": [
f"{alg_label}; discount {gamma:g}; Q-models and evaluation use {', '.join(features)}"
+ (f" (networks: hidden layers {', '.join(str(h) for h in hidden)}, {rounds} rounds × {epochs} epochs, learning rate {lr:g})" if algorithm in ("cql", "iql") else "")
+ f". Evaluation: fitted Q evaluation (linear per action, cross-fitted over {folds} episode folds)"
+ (", weighted doubly robust and weighted per-decision IS with the logged propensities" if propensity is not None else "")
+ f"; {n_boot} bootstrap resamples of episodes (seed {seed}). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.",
],
"values": values,
"charts": charts,
})
IQL's policy is valued at 20.20 against the logged 19.89. 14.0% of the advantage weights hit their cap: the policy then imitates a few rows heavily, and the run suggests a lower temperature.
What runs here
ReadCommon mistakes
ReadCheck: CQL and IQL
CheckpointCheck yourself
Which actions does CQL's penalty push down?
Show the answer
Answer: a
log Σ exp Q − Q(s, a_logged) is large when some other action looks much better than the logged one, which is where extrapolation errors live.
Check yourself
You raise CQL's α a lot. What does the learned policy tend toward?
Show the answer
Answer: a
A strong penalty keeps values of unlogged actions low, so the greedy policy rarely leaves the log's actions.
Check yourself
Why does IQL use an expectile with τ above a half to fit V(s)?
Show the answer
Answer: a
τ = 0.5 would give the mean; larger τ approaches a maximum over logged actions only.
Check yourself
Many of IQL's advantage weights hit their cap. What does that mean for the policy?
Show the answer
Answer: a
Capped weights mean exp(β·A) blew up for some rows, so those few dominate the imitation.
Check yourself
An offline policy's estimated value, learned and scored on the same 60 episodes, beats the logged policy's. What's the honest next step?
Show the answer
Answer: a
Selecting and scoring on the same data is optimistic. That's why the run carries that warning.
Recap
Recap- Offline, the max in Q targets reaches actions the log never took, and nothing corrects the errors.
- CQL pushes down values above the logged action's; α trades improvement for caution.
- IQL fits V with an expectile over logged actions and extracts the policy by capped advantage-weighted imitation.
- Read offline runs against the logged policy and behavior cloning, and check them on new episodes.
Concepts in this lesson