Module contents
Lesson 33 of 37Advanced 110 min

Offline RL: learning from fixed data without interaction

Study why naive off-policy learning fails on fixed logs, then compare policy constraints, conservative value regularization, IQL expectiles, sequential off-policy evaluation, and return-conditioned sequence models.

After this lesson you can

  • Explain extrapolation error and reproduce it with fixed data.
  • Implement TD3+BC, CQL, and IQL on a common core and compare them with behavior cloning.
  • Derive the CQL lower bound in the tabular case.
  • Evaluate policies with FQE, importance sampling, and sequential doubly robust estimators.
  • Discuss the capabilities and limits of Decision Transformer.

Before you start

Learning without requesting another transition

Imagine teaching a robot using only recorded trajectories. A new policy must not try actions on the robot while it is being fitted: a fall, a mistaken clinical intervention, or a change to a service can incur costs missing from the training file. In offline RL, the dataset D={(s,a,r,s′)}D=\{(s,a,r,s')\} is fixed before learning. Evaluation in a separate simulator helps investigate a method, but repeated use to choose hyperparameters is no longer purely offline selection.

The distinction from off-policy learning is subtle. Off-policy Q-learning can learn from actions different from those of the target policy, but in interactive use new experience can correct predictions. Offline, an action absent from the data brings no correction of its own. If the critic mistakenly assigns that action a high value and policy improvement maximizes the critic, the actor can select exactly the region where the critic is least reliable. The extrapolation error then enters the Bellman target and can propagate to states present in the dataset. Fujimoto and colleagues study this issue in batch learning.

For a driving task, suppose the records contain smooth maneuvers but no abrupt maneuver in a bend. The network can assign an arbitrary value to the abrupt maneuver because it has never received a contradictory label. Maximization selects it, and a recorded transition’s target then includes that value at the next state. Even when the Bellman fit has little error on recorded examples, the extracted policy may rely on actions unsupported by evidence. The same structure arises in continuous control, where the actor directly seeks high critic values.

“Outside support” is more than being far away in Euclidean distance. The distribution depends on state, history, and previous actions. An action common in one region may be unknown in another. With finite data, positive density in theory is insufficient: a region appearing only a few times can still carry high uncertainty. A diagnosis should examine joint coverage as well as marginal action histograms.

InteractiveA maximum outside the data
−11data

The initial curve is synthetic. Conservative mode numerically minimizes a discrete fitting objective with log-sum-exp; this is not full CQL training.

Treatment
60
Selected action0.78
Estimated value1.04
Within data regionno
Synthetic curve over discretized actions; the shaded region represents observed support. The illustrated regularizer is a particular convex objective, not an execution of full CQL.

The initial blue curve has a spurious peak far from the data. Conservative mode minimizes, over 101 actions, 12∑a(Q(a)−Q0(a))2+α[log⁡∑aeQ(a)−Ea∼bQ(a)]\frac12\sum_a(Q(a)-Q_0(a))^2+\alpha[\log\sum_a e^{Q(a)}-\mathbb E_{a\sim b}Q(a)], where bb is uniform over the shaded region and Q0Q_0 is the initial curve. The quadratic penalty over every action is an artificial prior chosen to give this problem a unique solution; it should not be mistaken for real data across the entire plot. Restricting the action keeps the curve and searches for its maximum only within observed support. Neither correction guarantees recovery of the true value when the representation or data fail.

Three ways to control distribution shift

Policy-constraint methods seek actions close to those of the behavior policy. BCQ generates candidates from a model fitted to the data and permits small perturbations. TD3+BC adds a penalty for deviating from recorded actions to the TD3 actor update and also normalizes states. This does not impose strict support: a network can interpolate or extrapolate outside the dataset even with low cloning loss. Fujimoto and Gu describe TD3+BC.

Conservative Q-Learning changes how the critic is fitted. In one discrete version, it adds a term that raises the cost of high values for all actions and lowers it for actions in the data:

LCQL=LBellman+α Es∼D ⁣[log⁡∑aeQ(s,a)−Ea∼bD(⋅∣s)Q(s,a)].\mathcal L_{\mathrm{CQL}}=\mathcal L_{\mathrm{Bellman}} +\alpha\,\mathbb E_{s\sim D}\!\left[\log\sum_a e^{Q(s,a)}-\mathbb E_{a\sim b_D(\cdot\mid s)}Q(s,a)\right].

In continuous spaces, an integral or its sample approximation replaces the sum, with appropriate treatment of proposal densities. Stronger regularization can reduce overestimation but can also make the critic too pessimistic. The theoretical results of Kumar and colleagues are conditional: adding an arbitrary conservative regularizer does not by itself establish a pointwise bound for every state-action pair.

In the discrete version, the derivative of the bracketed term with respect to Q(s,a)Q(s,a) is that action’s softmax probability minus its frequency in the data for that state. Descent tends to lower values where the former is greater and raise them where the latter dominates. Actions compete through normalization; the same constant is not subtracted from each. In continuous spaces, samples from a proposal distribution require density correction when approximating an integral. Too few samples or a poor proposal can leave important regions unexplored.

The parameter α\alpha controls a trade-off. A small value can leave out-of-distribution peaks in the critic; a large value can underestimate useful actions. Selecting it through repeated real-environment interactions adds online data. Strict offline evaluation requires a separate validation set and OPE tools, while recognizing that those tools can also fail when the candidate policy moves too far from the behavior policy. A simulation benchmark can finally assess performance, but must separate that assessment from tuning decisions.

For a checkable distinction, consider a one-step task with expected reward yay_a, data distribution b(a)>0b(a)>0, and fixed policy π\pi. Minimize 12∑ab(a)(Qa−ya)2+α∑a(π(a)−b(a))Qa\frac12\sum_a b(a)(Q_a-y_a)^2+\alpha\sum_a(\pi(a)-b(a))Q_a. The first-order condition gives Qa=ya−α(π(a)/b(a)−1)Q_a=y_a-\alpha(\pi(a)/b(a)-1). Averaging under π\pi,

∑aπ(a)(Qa−ya)=−α(∑aπ(a)2b(a)−1)≤0,\sum_a\pi(a)(Q_a-y_a) =-\alpha\left(\sum_a\frac{\pi(a)^2}{b(a)}-1\right)\leq0,

by Cauchy-Schwarz, since both distributions sum to one. This bounds the mean under π\pi in the idealized problem, without automatically guaranteeing a bound for a neural critic trained on finite data. In fact, b=(0.9,0.1)b=(0.9,0.1), π=(0.5,0.5)\pi=(0.5,0.5), y=(0,0)y=(0,0), and α=1\alpha=1 yield Q=(4/9,−4)Q=(4/9,-4): the first coordinate exceeds its true value even though the policy mean is negative.

Expectiles: improvement within the sample

Implicit Q-Learning avoids querying Q(s,a)Q(s,a) for new actions when building value targets. It first fits V(s)V(s) as an upper expectile of the values Q(s,a)Q(s,a) of actions recorded at that state. For u=Q(s,a)−V(s)u=Q(s,a)-V(s) the loss is

Lτ(u)=∣τ−1u<0∣u2.L_\tau(u)=|\tau-\mathbf1_{u<0}|u^2.

With τ=1/2\tau=1/2 the estimate is the mean; with τ>1/2\tau>1/2 positive residuals weigh more and the estimate moves toward the high observed values. The critic is updated with r+γV(s′)r+\gamma V(s') and a policy is extracted by cloning dataset actions, weighted by exp⁡(β[Q(s,a)−V(s)])\exp(\beta[Q(s,a)-V(s)]), commonly clipped for stability. Kostrikov and colleagues explain why the value step does not query out-of-data actions. The resulting parametric policy can still generalize beyond support, so the training objective is not an absolute guarantee about every produced action.

InteractiveMoving from the mean toward high observations
-2-1014expectile

The data are fixed. The line minimizes asymmetric squared loss without searching for a new action.

0.50
Expectile0.400
Mean0.40
Observed maximum4
Five fixed synthetic values: −2, −1, 0, 1, and 4. The expectile minimizes the loss in the preceding equation.

The first-order condition balances weighted positive and negative residuals. As τ\tau approaches one, the expectile of a finite sample approaches its maximum from below, but at τ<1\tau<1 need not equal it. An expectile differs from a quantile: it uses the magnitudes of all residuals, not just how many observations lie on each side.

For a sample z1,…,znz_1,\ldots,z_n and candidate vv, the condition is τ∑zi≥v(zi−v)=(1−τ)∑zi<v(v−zi)\tau\sum_{z_i\ge v}(z_i-v)=(1-\tau)\sum_{z_i<v}(v-z_i). At τ=0.5\tau=0.5 the weights coincide and give the arithmetic mean. At τ=0.9\tau=0.9 positive residuals receive nine times the weight of negative ones, but an extreme observation can move the result even when its frequency is small. In IQL the expectile concerns recorded action values conditional on state, not all future returns without conditioning.

Advantage-weighted extraction is not an exact search over a discrete set in the neural case either. A Gaussian policy can generalize between observed actions and produce actions absent from the file. Clipping exponential weights prevents one estimated advantage from dominating the fit, but introduces a further scale choice. Comparing implementations requires recording the expectile, temperature, clipping, and state normalization.

Evaluation without changing the logging policy

Sequential off-policy evaluation asks for the return of a target policy π\pi using behavior trajectories bb. Coverage requires b(a∣s)>0b(a\mid s)>0 wherever π(a∣s)>0\pi(a\mid s)>0 in relevant states. Even then, products ρ0:t=∏k=0tπ(ak∣sk)/b(ak∣sk)\rho_{0:t}=\prod_{k=0}^t\pi(a_k\mid s_k)/b(a_k\mid s_k) can have enormous variance. Per-decision importance sampling averages ∑tγtρ0:trt\sum_t\gamma^t\rho_{0:t}r_t; the weighted version normalizes by the sum of weights at each step, introduces finite-sample bias, and can be more stable. Effective sample size (∑iwi)2/∑iwi2(\sum_i w_i)^2/\sum_i w_i^2 reveals lost information when a few trajectories dominate.

Fitted Q Evaluation (FQE) fits a value function for a fixed policy using targets r+γEa′∼πQ(s′,a′)r+\gamma\mathbb E_{a'\sim\pi}Q(s',a') on recorded transitions. It depends on model quality and coverage even without new interaction. A sequential doubly robust estimator combines a fitted value and importance corrections; its robustness property requires assumptions about the model or behavior probabilities and does not eliminate variance or repair missing support. Jiang and Li develop this family; Le and colleagues study FQE in batch learning.

Weighted evaluation requires knowing or estimating the behavior probabilities that generated actions. If logs mix policy versions without identifying which acted, using one average probability can be wrong. When behavior is nearly deterministic, an action proposed by the target policy can have probability close to zero in the data: the product of ratios becomes unstable even when formally finite. Clipping weights reduces variance at the cost of bias; report the threshold and measure sensitivity.

To select among policies, compare both absolute value error and how often the method ranks candidates correctly. An estimator can have a common bias while preserving order, or low mean error while reversing two policies with similar returns. Holding out trajectories for evaluation and fitting FQE on others reduces data reuse, but cannot create coverage. In the next lab the environment model provides the true value so both properties can be measured without pretending it is known in a real application.

A sequence does not guarantee the requested return

Decision Transformer models sequences of desired returns, states, and actions with causal attention and learns to predict actions from history. At execution time the remaining return is updated using observed rewards. Chen and colleagues present it as conditional sequence modeling. Requesting a high return cannot create missing information: if high dataset returns arose from favorable luck, conditioning on them may select actions associated with luck without causing it. Combining trajectory fragments that never co-occurred in the data can also fail.

An extreme example is a lottery independent of the action: some recorded trajectories obtained high rewards by luck. A model conditioned on the reward can learn their associated actions, but repeating those actions does not alter the lottery probability. The condition is retrospective information correlated with the outcome, not an intervention compelling the environment to deliver it. Conditioning can be useful in deterministic tasks with adequate coverage, but should be evaluated using new seeds and initial states.

A benchmark is part of the experiment, not merely a name. D4RL groups datasets of different qualities; Minari specifies episode contracts and dataset versions. Record the identifier, version, normalization, and budget. Online fine-tuning after an offline stage can improve an agent, but its interactions must be counted and must not be described as exclusively offline learning.

Local lab: continuous control from our own logs

This lab generates its own data in HalfCheetah-v5 using Gymnasium and MuJoCo. To construct datasets of varied quality, twenty bounded linear controllers are sampled and ranked by two selection episodes of 400 steps. The collections use an intermediate-return controller, a mixture of controllers, random actions, and a public expert policy. Each dataset contains 20,000 transitions, is generated once with a fixed seed, and is reused across algorithms and their five fitting seeds.

For the expert dataset, only safetensors weights from a published SAC are downloaded, pinned to revision 48eeee298aa8e4b65770fd6f32b9c6caaac963a8, under MPL-2.0 with SHA-256 e9cf5c38b9e704f1bda8409a53a752c8d38e2ffbe6b2ac7484c05be31bfe1722. The code verifies the hash and reconstructs the network without executing remote code or loading arbitrary serialized objects. Across ten independently evaluated episodes with seeds 50000 to 50009, the deterministic policy achieved mean return 14157.66 and standard deviation 175.44. This is a measurement on this installation, not a guarantee across versions. Collection adds Gaussian noise with standard deviation 0.05 and clips actions to the valid range.

BC, TD3+BC, continuous CQL with uniform and policy samples, and IQL are implemented with shared small networks. The budget is 5000 updates per combination, with five new final evaluation episodes per seed. Parameters are fixed before evaluation returns are consulted: simulator evaluation compares methods experimentally rather than selecting hyperparameters for an exclusively offline application. The total is 80 fits; every finished combination is immediately saved to a JSONL file, allowing resumption after interruption. NumPy, PyTorch, Gymnasium, MuJoCo, and safetensors are required on CPU; the initial model download requires a connection.

Recorded runs use NumPy 2.5.4, PyTorch 2.11.0, Gymnasium 1.4.0, MuJoCo 4.0.1, and safetensors 0.8.0. Changing simulator version, collection seed, or episode limit can change data and results. If an existing results file belongs to another experiment, use another name: the code checks budget and size, but that does not completely identify a dataset.

The random collection shows what can be extracted from broad but poor behavior. The intermediate set uses the controller ranked in the middle of twenty candidates; it is not equivalent to a standard benchmark’s “medium” set. The mixed set selects one of those controllers at the beginning of each episode and combines different behaviors. The expert comes from an externally trained actor evaluated independently before collection. All four use the same simulator and number of transitions, but need not cover the same state-space regions.

The shared core computes state means and standard deviations only from the dataset used to fit a policy. Actions are bounded between −1 and 1. BC minimizes squared error against logged actions; TD3+BC combines critic value with that error. IQL fits an expectile value with τ=0.7\tau=0.7 and uses clipped exponential weights. CQL samples ten uniform actions and ten policy actions per state, correcting for density, in addition to temporal error. These are specific laboratory designs; their hyperparameters do not reconstruct every detail of official implementations.

The budget of 5000 batches of 256 transitions makes 1,280,000 draws with replacement, equivalent to 64 passes by dataset size, not 64 ordered passes or 1,280,000 distinct observations. Each method uses the same file for five fits, so variation across seeds measures fitting sensitivity on that fixed collection, not variation from collecting data again. The five episodes of each policy start with seeds reserved for evaluation. Their returns describe one fitted policy and must not be treated as five independent trainings.

The comparison holds dimensions and budget fixed, but not compute: a CQL update evaluates more actions and networks than a cloning update. The chosen hyperparameters are not guaranteed optimal for every dataset either. A better mean in this table applies to these policies, files, five seeds, and simulator versions; changing coverage or budget can change the ordering. Broader conclusions require new collections and tasks, with hyperparameter selection separate from final evaluation.

For value targets, true termination cancels continuation, whereas a time-limit truncation retains the next recorded state’s value. The collection loop stores the cases separately. If a dataset omitted the next observation on truncation or mixed reward versions, that choice would cease to be reproducible. The program prints results by combination and writes each row only after all five evaluation episodes complete; interruption can repeat an incomplete fit, but cannot present a partial record as a finished seed.

[ ]HalfCheetah algorithms and datasetsLocal GPU
"""BC, TD3+BC, IQL y CQL desde cero con datos propios de HalfCheetah.
No utiliza datos ni rutas ajenas. Para el estudio completo: python offline.py.
"""
import copy,json,random
import numpy as np
import gymnasium as gym
import torch
from torch import nn
from torch.distributions import Normal

torch.set_num_threads(1)
ENV='HalfCheetah-v5'
def mlp(n_in,n_out):
    return nn.Sequential(nn.Linear(n_in,128),nn.ReLU(),nn.Linear(128,128),nn.ReLU(),nn.Linear(128,n_out))

class Actor(nn.Module):
    def __init__(self,s,a,stochastic=False):
        super().__init__();self.net=mlp(s,a);self.logstd=nn.Parameter(torch.full((a,),-0.5));self.stochastic=stochastic
    def sample(self,s):
        mu=self.net(s);std=self.logstd.clamp(-5,2).exp().expand_as(mu);dist=Normal(mu,std)
        raw=dist.rsample();a=torch.tanh(raw);logp=(dist.log_prob(raw)-torch.log(1-a*a+1e-6)).sum(-1,keepdim=True)
        return a,logp
    def mean(self,s):return torch.tanh(self.net(s))
    def log_prob(self,s,a):
        a=a.clamp(-.999999,.999999);raw=torch.atanh(a);std=self.logstd.clamp(-5,2).exp().expand_as(raw)
        return (Normal(self.net(s),std).log_prob(raw)-torch.log(1-a*a+1e-6)).sum(-1,keepdim=True)

class Critic(nn.Module):
    def __init__(self,s,a):super().__init__();self.net=mlp(s+a,1)
    def forward(self,s,a):return self.net(torch.cat([s,a],dim=-1))

def controllers(seed=77,count=20):
    rng=np.random.default_rng(seed);env=gym.make(ENV);dim=env.observation_space.shape[0];adim=env.action_space.shape[0];rows=[]
    for i in range(count):
        # Proyección acotada sobre observaciones físicas, no entrenamiento en el conjunto offline.
        W=rng.normal(0,.2,(dim,adim));b=rng.normal(0,.2,adim);returns=[]
        for ep in range(2):
            s,_=env.reset(seed=9000+ep);score=0.
            for _ in range(400):
                action=np.tanh(np.clip(s,-5,5)@W+b);s,r,done,trunc,_=env.step(action);score+=r
                if done or trunc:break
            returns.append(score)
        rows.append((float(np.mean(returns)),W,b))
    env.close();rows.sort(key=lambda row:row[0]);return rows

def collect(rows,kind,n=20000,seed=111):
    rng=np.random.default_rng(seed);env=gym.make(ENV);samples=[];episode=0
    while len(samples)<n:
        s,_=env.reset(seed=seed+episode);episode+=1
        if kind=='mixed':controller=rows[int(rng.integers(len(rows)))]
        elif kind=='medium':controller=rows[len(rows)//2]
        elif kind=='best':controller=rows[-1]
        else:controller=None
        for _ in range(1000):
            if controller is None:a=rng.uniform(-1,1,env.action_space.shape)
            else:a=np.clip(np.tanh(np.clip(s,-5,5)@controller[1]+controller[2])+rng.normal(0,.1,env.action_space.shape),-1,1)
            ns,r,term,trunc,_=env.step(a);samples.append((s,a,r,ns,float(term)));s=ns
            if term or trunc or len(samples)>=n:break
    env.close();return tuple(np.asarray(x,dtype=np.float32) for x in zip(*samples))

def fit(data,method,seed,steps=5000,batch=256):
    random.seed(seed);np.random.seed(seed);torch.manual_seed(seed)
    s,a,r,ns,d=data;mean=s.mean(0);std=s.std(0)+1e-3
    x=torch.tensor((s-mean)/std);nx=torch.tensor((ns-mean)/std);actions=torch.tensor(a);rewards=torch.tensor(r[:,None]);done=torch.tensor(d[:,None])
    sd,ad=x.shape[1],actions.shape[1];actor=Actor(sd,ad);actor_t=copy.deepcopy(actor)
    q1,q2=Critic(sd,ad),Critic(sd,ad);t1,t2=copy.deepcopy(q1),copy.deepcopy(q2);v=mlp(sd,1)
    aopt=torch.optim.Adam(actor.parameters(),lr=3e-4);qopt=torch.optim.Adam(list(q1.parameters())+list(q2.parameters()),lr=3e-4);vopt=torch.optim.Adam(v.parameters(),lr=3e-4)
    for step in range(steps):
        ids=torch.randint(len(s),(batch,));st,act,rw,nst,terminal=x[ids],actions[ids],rewards[ids],nx[ids],done[ids]
        if method=='bc':
            loss=((actor.mean(st)-act)**2).mean();aopt.zero_grad();loss.backward();aopt.step();continue
        if method=='iql':
            with torch.no_grad():qt=torch.minimum(t1(st,act),t2(st,act))
            err=qt-v(st);vloss=(torch.where(err>=0,.7,.3)*err.square()).mean();vopt.zero_grad();vloss.backward();vopt.step()
            with torch.no_grad():target=rw+.99*(1-terminal)*v(nst)
        else:
            with torch.no_grad():
                if method=='td3bc':
                    next_action=(actor_t.mean(nst)+torch.randn_like(act).mul(.2).clamp(-.5,.5)).clamp(-1,1);entropy=0.
                else:next_action,logp=actor.sample(nst);entropy=.2*logp
                target=rw+.99*(1-terminal)*(torch.minimum(t1(nst,next_action),t2(nst,next_action))-entropy)
        loss=((q1(st,act)-target)**2+(q2(st,act)-target)**2).mean()
        if method=='cql':
            k=10;expanded=st[:,None,:].expand(-1,k,-1).reshape(batch*k,sd);uniform=torch.empty((batch*k,ad)).uniform_(-1,1)
            with torch.no_grad():sample,logp=actor.sample(expanded)
            # Densidad uniforme en [-1,1]^A: log p = -A log 2.
            for q in (q1,q2):
                random_q=q(expanded,uniform).reshape(batch,k)+ad*np.log(2)
                policy_q=q(expanded,sample).reshape(batch,k)-logp.reshape(batch,k)
                loss+=(torch.logsumexp(torch.cat([random_q,policy_q],1),1)-q(st,act).squeeze(-1)).mean()
        qopt.zero_grad();loss.backward();qopt.step()
        if method=='iql':
            with torch.no_grad():weight=torch.exp(3*(torch.minimum(t1(st,act),t2(st,act))-v(st))).clamp(max=100.)
            aloss=-(weight*actor.log_prob(st,act)).mean()
        elif method=='td3bc':
            pred=actor.mean(st);value=q1(st,pred);scale=2.5/(value.abs().mean().detach()+1e-6);aloss=-scale*value.mean()+((pred-act)**2).mean()
        else:
            pred,logp=actor.sample(st);aloss=(.2*logp-torch.minimum(q1(st,pred),q2(st,pred))).mean()
        if method!='td3bc' or step%2==0:
            aopt.zero_grad();aloss.backward();aopt.step()
        with torch.no_grad():
            for target_net,online in ((t1,q1),(t2,q2),(actor_t,actor)):
                for p,q in zip(target_net.parameters(),online.parameters()):p.lerp_(q,.005)
    return actor,mean,std

def evaluate(actor,mean,std,seed,episodes=5):
    env=gym.make(ENV);scores=[]
    for ep in range(episodes):
        state,_=env.reset(seed=seed+ep);total=0.
        for _ in range(1000):
            with torch.no_grad():action=actor.mean(torch.tensor(((state-mean)/std).astype(np.float32))[None]).numpy()[0]
            state,reward,done,trunc,_=env.step(action);total+=reward
            if done or trunc:break
        scores.append(total)
    env.close();return scores
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Verifiable expert datasetLocal GPU
import hashlib,urllib.request,os
from pathlib import Path
from safetensors.torch import load_file

def expert_weights(path='expert-model.safetensors'):
    path=Path(path);sha='e9cf5c38b9e704f1bda8409a53a752c8d38e2ffbe6b2ac7484c05be31bfe1722'
    url='https://huggingface.co/lucasschott/HalfCheetah-v5-SAC/resolve/48eeee298aa8e4b65770fd6f32b9c6caaac963a8/model.safetensors'
    if not path.exists():
        data=urllib.request.urlopen(url,timeout=90).read()
        if hashlib.sha256(data).hexdigest()!=sha:raise ValueError('Hash del modelo incorrecto')
        temp=path.with_suffix('.tmp');temp.write_bytes(data);os.replace(temp,path)
    if hashlib.sha256(path.read_bytes()).hexdigest()!=sha:raise ValueError('Hash del modelo incorrecto')
    return path

class Expert(nn.Module):
    def __init__(self,path):
        super().__init__();self.latent=nn.Sequential(nn.Linear(17,256),nn.ReLU(),nn.Linear(256,256),nn.ReLU());self.mu=nn.Linear(256,6)
        w=load_file(str(path))
        self.latent[0].weight.data.copy_(w['actor.latent_pi.0.weight']);self.latent[0].bias.data.copy_(w['actor.latent_pi.0.bias'])
        self.latent[2].weight.data.copy_(w['actor.latent_pi.2.weight']);self.latent[2].bias.data.copy_(w['actor.latent_pi.2.bias'])
        self.mu.weight.data.copy_(w['actor.mu.0.weight']);self.mu.bias.data.copy_(w['actor.mu.0.bias'])
    def forward(self,x):return torch.tanh(self.mu(self.latent(x)).clamp(-2,2))

def collect_expert(n=20000,seed=111):
    model=Expert(expert_weights()).eval();environment=gym.make(ENV);rng=np.random.default_rng(seed);samples=[];episode=0
    while len(samples)<n:
        state,_=environment.reset(seed=seed+episode);episode+=1
        for _ in range(1000):
            with torch.no_grad():base=model(torch.tensor(state,dtype=torch.float32)[None]).numpy()[0]
            action=np.clip(base+rng.normal(0,.05,base.shape),-1,1)
            nxt,reward,terminated,truncated,_=environment.step(action)
            samples.append((state,action,reward,nxt,float(terminated)));state=nxt
            if terminated or truncated or len(samples)>=n:break
    environment.close();return tuple(np.asarray(x,dtype=np.float32) for x in zip(*samples))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Compare four datasets and five seedsLocal GPU
from pathlib import Path
output=Path("offline-results.jsonl")
previous=[json.loads(line) for line in output.read_text(encoding="utf8").splitlines() if line.strip()] if output.exists() else []
assert all(x["steps"]==5000 and x["size"]==20000 and len(x["returns"])==5 for x in previous), "La configuración previa no coincide"
completed={(x["dataset"],x["method"],x["seed"]) for x in previous}
rows=controllers()
for kind in ("random","medium","expert","mixed"):
    dataset=collect_expert(20000,seed=111) if kind=="expert" else collect(rows,kind,20000,seed=111)
    for method in ("bc","td3bc","cql","iql"):
        for seed in range(5):
            if (kind,method,seed) in completed: continue
            actor,mean,std=fit(dataset,method,seed,5000)
            scores=evaluate(actor,mean,std,7000+seed*100,5)
            result={"dataset":kind,"method":method,"seed":seed,"steps":5000,"size":20000,"returns":scores,"mean":float(np.mean(scores))}
            with output.open("a",encoding="utf8") as stream: stream.write(json.dumps(result)+"\n");stream.flush()
            print(result,flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
InteractiveFour datasets and four methods
MethodRandomMediumExpertMixed
BC
TD3+BC
CQL
IQL

Five evaluation returns for the selected seed: −0.5, −0.8, 1.0, −0.7, −1.1. Means across seeds are not confidence intervals.

Mean of five seeds−1.0
Standard deviation across seeds0.6
Seed mean−0.4
Updates5000
Unnormalized returns in HalfCheetah-v5: 20,000 transitions per dataset, 5000 updates, and five seeds per method. Each seed is evaluated in five new episodes.

In this run, the random dataset gives mean returns of −1.0, −17.5, 9.3, and 260.4 for BC, TD3+BC, CQL, and IQL respectively. On the intermediate set, TD3+BC reaches a mean of 383.8 with standard deviation 385.6 across seeds. The table shows all 16 combinations and allows selection of any of the five fits to see its five returns. These values are not D4RL scores and should not be compared directly with that benchmark’s normalized tables.

On the mixed dataset BC reaches a mean of 529.5, but two seeds yield 1303.2 and 1401.9 and two others −85.5 and −54.8: a single mean hides very different results. With expert data, all four methods have negative means under this budget, although the data-generating actor obtained about 14157.7 in independent evaluation. Source quality does not guarantee that a small network and finite fitting reproduce its behavior on its own trajectories. Generalization and accumulated errors may contribute, but this experiment identifies no single cause and does not show that all offline methods fail on expert data.

Nor does the result universally rank methods: there is one fixed collection per category, five training seeds, and five episodes per policy. The displayed deviations summarize the five seed means and are not confidence intervals; episodes of one policy share the same training. Recollecting data, increasing budget, or changing coverage and hyperparameters might change the order. Simulator evaluation was reserved to measure the comparison, not to improve these configurations after viewing the table.

Lab: evaluation on a grid

The grid is 3 × 3, starting in the upper left with reward 1 for reaching the opposite corner. Transitions are deterministic and an absorbing state completes the seven-step horizon; discount is 0.95. The behavior policy selects uniformly among four actions. We evaluate three policies with increasing probabilities of moving toward the goal. For each, FQE is fitted with 256 trajectories and IS and DR are evaluated on another 256 independent trajectories; we repeat across 20 seeds. The exact value is calculated by dynamic programming only to measure error, not to fit FQE.

[ ]Grid, trajectories, and evaluatorsBrowser
import numpy as np
S,A,H,GAMMA=10,4,7,.95

def model():
    nxt=np.full((S,A),9,dtype=int);reward=np.zeros((S,A))
    for s in range(9):
        x,y=s%3,s//3
        for a,(dx,dy) in enumerate([(1,0),(0,1),(-1,0),(0,-1)]):
            t=max(0,min(2,y+dy))*3+max(0,min(2,x+dx))
            nxt[s,a]=9 if t==8 else t;reward[s,a]=float(t==8)
    return nxt,reward

NEXT,REWARD=model()
def policy(greed):
    p=np.full((S,A),(1-greed)/A)
    for s in range(8):
        x,y=s%3,s//3;choices=[]
        if x<2:choices.append(0)
        if y<2:choices.append(1)
        for a in choices:p[s,a]+=greed/len(choices)
    p[8]=.25;p[9]=.25
    return p

def trajectories(n,seed):
    rng=np.random.default_rng(seed);states=np.zeros((n,H),int);actions=rng.integers(A,size=(n,H));rewards=np.zeros((n,H));s=np.zeros(n,int)
    for t in range(H):
        states[:,t]=s;a=actions[:,t];rewards[:,t]=REWARD[s,a];s=NEXT[s,a]
    next_states=np.concatenate([states[:,1:],s[:,None]],axis=1)
    return states,actions,rewards,next_states

def truth(pi):
    v=np.zeros(S)
    for _ in range(H):v=np.sum(pi*(REWARD+GAMMA*v[NEXT]),axis=1)
    return float(v[0])

def fitted_q(data,pi):
    states,actions,rewards,next_states=data;q=np.zeros((H,S,A));v=np.zeros((H+1,S))
    for t in reversed(range(H)):
        s=states[:,t];a=actions[:,t];nxt=next_states[:,t]
        counts=np.bincount(s*A+a,minlength=S*A).reshape(S,A)
        sums=np.bincount(s*A+a,weights=rewards[:,t]+GAMMA*v[t+1,nxt],minlength=S*A).reshape(S,A)
        q[t]=np.divide(sums,counts,out=np.zeros_like(sums),where=counts>0);v[t]=(pi*q[t]).sum(axis=1)
    return q,v

def estimates(train,test,pi):
    q,v=fitted_q(train,pi);states,actions,rewards,next_states=test;n=len(states);weights=np.ones(n);pdis=wis=0.;dr=np.full(n,v[0,0]);ess=[]
    for t in range(H):
        s=states[:,t];a=actions[:,t];nxt=next_states[:,t];weights*=pi[s,a]/.25
        pdis+=GAMMA**t*np.mean(weights*rewards[:,t]);total=weights.sum()
        wis+=GAMMA**t*(weights@rewards[:,t]/total if total else 0.)
        dr+=GAMMA**t*weights*(rewards[:,t]+GAMMA*v[t+1,nxt]-q[t,s,a]);ess.append(total**2/(weights@weights) if weights@weights else 0.)
    return np.array([v[0,0],pdis,wis,dr.mean()]),np.array(ess)
[ ]Compare values and rankingsBrowser
policies=[policy(v) for v in (0.,.4,.8)]
targets=np.array([truth(p) for p in policies]);est=np.zeros((20,3,4));ess=[]
for seed in range(20):
    train=trajectories(256,seed*2);test=trajectories(256,seed*2+1)
    for j,p in enumerate(policies):
        est[seed,j],e=estimates(train,test,p);ess.append(e)
print('valores exactos',targets.round(4).tolist())
print('error absoluto medio FQE, PDIS, WIS, DR',np.mean(abs(est-targets[None,:,None]),axis=(0,1)).round(4).tolist())
print('orden correcto por método',np.sum((est[:,0,:]<est[:,1,:])&(est[:,1,:]<est[:,2,:]),axis=0).tolist())
print('ESS final mediana por política',np.median(np.array(ess).reshape(20,3,H)[:,:,-1],axis=0).round(2).tolist())

In the recorded run, exact values are 0.0939, 0.4286, and 0.7853. Mean absolute error across policies and seeds is 0.0118 for FQE, 0.0995 for per-decision IS, 0.0430 for weighted per-decision IS, and 0.0068 for DR; all four ranked the three policies correctly in all 20 repetitions. Median final-step ESS falls from 256 to 76.52 and 13.88 as the distance from behavior increases. The example uses a small environment and an easy tabular model: it cannot establish that DR or FQE dominate in continuous tasks or when support is absent. Unobserved state-action pairs receive zero value in FQE, an implementation decision that can introduce bias.

Exercises

ProofA bound on the mean, not on each coordinate
Prove: In the one-step problem described above, prove that the regularized critic has a mean under π no greater than the target mean, and explain why the bound need not hold pointwise.
0
Assume b(a) > 0, α ≥ 0, and normalized distributions b and π.

Step 1 of 3. Which value minimizes the loss for an action a?

NumericExpectile of five observations
For the five equally likely observations −2, −1, 0, 1, and 4, calculate the expectile τ = 0.9. Give at least three decimal places.
QuizNear-expert data
You have extensive data from an almost deterministic expert policy, without the ability to interact or validate hyperparameters in the real environment. What is a reasonable first baseline?
CodeExpectile loss and weighted cloning
Implement losses(q, v, logp, tau, beta, cap). The first three arguments are equal-length vectors, cap is positive, and all arguments are finite. Return two scalars: the mean of |τ − 1(q−v < 0)|(q−v)² and the negative mean of logp weighted by min(exp(beta·(q−v)), cap). Apply the cap to each weight, not to the mean. Do not modify the arguments.
import numpy as np
def losses(q, v, logp, tau, beta, cap):
  pass
Shift+Enter to run