Skip to content

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.

Advanced ~15 min9 steps

What runs in CodeSplash

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

Read first

01

The max reaches where the logs never went

Read

Offline 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 max⁡a′Q(s′,a′)\max_{a'} Q(s', a'), and the network's guesses for actions the log never took in s′s' 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.

02

CQL: push down the unseen

Read

Conservative 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:

L=LBellman+α  Es[log⁡∑aeQ(s,a)−Q(s,alogged)].L = L_{\text{Bellman}} + \alpha\; \mathbb{E}_s\Big[\log \sum_a e^{Q(s, a)} - Q(s, a_{\text{logged}})\Big].

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.

03

IQL: never ask about unseen actions

Read

Implicit 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 V(s)V(s) to the logged actions' Q-values with an expectile loss that weights positive residuals by τ and negative ones by 1 − τ; with τ above a half, VV leans toward the better logged actions. Q is then trained toward r+γV(s′)r + \gamma V(s'), which uses only logged actions.

The policy is extracted by advantage-weighted imitation: copy logged actions with weight eβ(Q−V)e^{\beta (Q - V)}, capped. In the reference's example the weights come out as 20 (capped), 0.223 and 1.82.

04

Read a CQL run

In the app
Offline policy learning (Conservative Q-learning)Recorded · Python and R agreeRecorded 2026-11-25 · 19 values compared
R

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

Plots

Estimated return per episodeHow large are several estimates, how precise, and which exclude the null?
View data
ValueUpperPolicy and estimatorLower
0.51070.5289Conservative Q-learning · Fitted Q evaluation0.4940
0.53230.5866Conservative Q-learning · Weighted doubly robust0.4717
0.51850.6622Conservative Q-learning · Weighted per-decision IS−0.2262
0.51070.5289Behavior cloning (baseline) · Fitted Q evaluation0.4940
0.53230.5866Behavior cloning (baseline) · Weighted doubly robust0.4717
0.51850.6622Behavior cloning (baseline) · Weighted per-decision IS−0.2262
0.04870.1387Logged policy · Observed return−0.0376
Estimated start-state value by iterationHow does a policy's return change as training goes on, and does it beat the policy that logged the data?
View data
IterationEstimated value
10.4862
20.0208
30.5907
40.2081
Action shares: logged vs learnedHow often does the learned policy choose each action, compared with the logged policy?
View data
ActionSharePolicy
left0.1688Logged
stay0.1906Logged
right0.6406Logged
left0Learned
stay0Learned
right1Learned

Estimated return per episode

PolicyEstimatorEstimate95% CI low95% CI high
Conservative Q-learningFitted Q evaluation0.51070.49400.5289
Conservative Q-learningWeighted doubly robust0.53230.47170.5866
Conservative Q-learningWeighted per-decision IS0.5185−0.22620.6622
Behavior cloning (baseline)Fitted Q evaluation0.51070.49400.5289
Behavior cloning (baseline)Weighted doubly robust0.53230.47170.5866
Behavior cloning (baseline)Weighted per-decision IS0.5185−0.22620.6622
Logged policyObserved return0.0487−0.03760.1387

Learned policy by state (12 of 12 distinct states)

cellweather todayLearned actionQ(left)Q(stay)Q(right)
c1sunright−0.5433−0.39710.1158
c2sunright−0.9531−0.35480.3412
c3rainright−0.0943−0.37220.3326
c4rainright−0.04690.31150.7662
c5rainright−0.20870.01891.041
c1rainright−0.3203−0.83730.0391
c0sunright−0.8865−0.52330.3031
c3sunright−0.9514−0.31690.7796
c2rainright0.0251−0.65800.1797
c4sunright−0.41420.41921.025
c5sunright−0.42530.40501.216
c0rainright−0.1563−0.22900.2950

Actions: logged vs learned policy

actionLogged shareLearned share
left16.9%0.0%
stay19.1%0.0%
right64.1%100.0%

Training by iteration

IterationLossEstimated start-state value
10.96730.4862
20.97210.0208
30.97060.5907
40.95240.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
))
Python

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

PolicyEstimatorEstimate95% CI low95% CI high
Conservative Q-learningFitted Q evaluation0.51070.49400.5289
Conservative Q-learningWeighted doubly robust0.53230.47170.5866
Conservative Q-learningWeighted per-decision IS0.5185−0.22620.6622
Behavior cloning (baseline)Fitted Q evaluation0.51070.49400.5289
Behavior cloning (baseline)Weighted doubly robust0.53230.47170.5866
Behavior cloning (baseline)Weighted per-decision IS0.5185−0.22620.6622
Logged policyObserved return0.0487−0.03760.1387

Learned policy by state (12 of 12 distinct states)

cellweather todayLearned actionQ(left)Q(stay)Q(right)
c1sunright−0.5433−0.39710.1158
c2sunright−0.9531−0.35480.3412
c3rainright−0.0943−0.37220.3326
c4rainright−0.04690.31150.7662
c5rainright−0.20870.01891.041
c1rainright−0.3203−0.83730.0391
c0sunright−0.8865−0.52330.3031
c3sunright−0.9514−0.31690.7796
c2rainright0.0251−0.65800.1797
c4sunright−0.41420.41921.025
c5sunright−0.42530.40501.216
c0rainright−0.1563−0.22900.2950

Actions: logged vs learned policy

actionLogged shareLearned share
left16.9%0.0%
stay19.1%0.0%
right64.1%100.0%

Training by iteration

IterationLossEstimated start-state value
10.96730.4862
20.97210.0208
30.97060.5907
40.95240.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.

05

Read an IQL run

In the app
Offline policy learning (Implicit Q-learning)Recorded · Python and R agreeRecorded 2026-11-25 · 21 values compared
R

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

Plots

Estimated return per episodeHow large are several estimates, how precise, and which exclude the null?
View data
ValueUpperPolicy and estimatorLower
20.19720.476Implicit Q-learning · Fitted Q evaluation19.924
25.66829.117Implicit Q-learning · Weighted doubly robust22.670
11.90914.420Implicit Q-learning · Weighted per-decision IS8.280
17.38217.781Behavior cloning (baseline) · Fitted Q evaluation17.016
28.59033.079Behavior cloning (baseline) · Weighted doubly robust22.151
19.67024.716Behavior cloning (baseline) · Weighted per-decision IS11.179
19.88522.061Logged policy · Observed return18.000
Estimated start-state value by iterationHow does a policy's return change as training goes on, and does it beat the policy that logged the data?
View data
IterationEstimated value
1−0.5128
20.1109
30.8400
Action shares: logged vs learnedHow often does the learned policy choose each action, compared with the logged policy?
View data
ActionSharePolicy
order 00.3275Logged
order 20.3450Logged
order 40.3275Logged
order 00.5450Learned
order 20.4550Learned
order 40Learned

Estimated return per episode

PolicyEstimatorEstimate95% CI low95% CI high
Implicit Q-learningFitted Q evaluation20.19719.92420.476
Implicit Q-learningWeighted doubly robust25.66822.67029.117
Implicit Q-learningWeighted per-decision IS11.9098.28014.420
Behavior cloning (baseline)Fitted Q evaluation17.38217.01617.781
Behavior cloning (baseline)Weighted doubly robust28.59022.15133.079
Behavior cloning (baseline)Weighted per-decision IS19.67011.17924.716
Logged policyObserved return19.88518.00022.061

Learned policy by state (7 of 7 distinct states)

stockLearned actionQ(order 0)Q(order 2)Q(order 4)
2order 01.4811.0101.290
3order 02.6291.6372.058
0order 22.0164.1821.544
1order 21.5242.1941.213
4order 04.2142.6083.290
5order 05.7953.5844.546
6order 07.3764.5615.802

Actions: logged vs learned policy

orderLogged shareLearned share
order 032.8%54.5%
order 234.5%45.5%
order 432.8%0.0%

Training by iteration

IterationLossEstimated start-state value
112.575−0.5128
210.8450.1109
39.6650.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
))
Python

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

PolicyEstimatorEstimate95% CI low95% CI high
Implicit Q-learningFitted Q evaluation20.19719.92420.476
Implicit Q-learningWeighted doubly robust25.66822.67029.117
Implicit Q-learningWeighted per-decision IS11.9098.28014.420
Behavior cloning (baseline)Fitted Q evaluation17.38217.01617.781
Behavior cloning (baseline)Weighted doubly robust28.59022.15133.079
Behavior cloning (baseline)Weighted per-decision IS19.67011.17924.716
Logged policyObserved return19.88518.00022.061

Learned policy by state (7 of 7 distinct states)

stockLearned actionQ(order 0)Q(order 2)Q(order 4)
2order 01.4811.0101.290
3order 02.6291.6372.058
0order 22.0164.1821.544
1order 21.5242.1941.213
4order 04.2142.6083.290
5order 05.7953.5844.546
6order 07.3764.5615.802

Actions: logged vs learned policy

orderLogged shareLearned share
order 032.8%54.5%
order 234.5%45.5%
order 432.8%0.0%

Training by iteration

IterationLossEstimated start-state value
112.575−0.5128
210.8450.1109
39.6650.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.

06

What runs here

Read
07

Common mistakes

Read
08

Check: CQL and IQL

Checkpoint

Check 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.

09

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