AI Wiki中文/EN

Offline RL: learn a new policy from a fixed log

离线强化学习

Hold the dataset fixed and compare fitted Q-learning, supported-action constraints and conservative penalties, tracing how unseen actions change decisions.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The log shows what happened, not every available choice

Our original teaching task has two decisions. At the entrance, action 0 exits with 0.4 points; action 1 continues with no immediate reward. At the second decision, action 0 earns 1 point and action 1 earns −2, then the episode ends. With discount 0.9, continuing and choosing action 0 is worth 0.9. Merely copying the most frequent entrance action can instead earn 0.4.

Suppose an old policy usually exited, and seldom tried the second action at the second decision. Its log can contain enough pieces to assemble the better route. It may also leave a tempting action completely unmeasured. A large predicted Q-value for that action is not an observation of success.

Offline reinforcement learning learns from an already collected dataset without adding environment interactions during training. “Offline” does not mean that the computer lacks an internet connection. Ordinary off-policy learning can reuse old transitions while continuing to collect new ones; a fixed offline dataset cannot correct a mistaken prediction by trying the proposed action. Problem definition and distribution shift

All-seed real returns expose unsupported-action failures and the cost of a stronger conservative penalty. Predictions and actual returns stay separate; tables show three significant digits.
All-seed real returns expose unsupported-action failures and the cost of a stronger conservative penalty. Predictions and actual returns stay separate; tables show three significant digits.

A Bellman target can ask about an action absent from the data

Let D\mathcal D contain logged transitions and let μ\mu denote the behavior that produced them. The desired policy still optimizes expected return in the actual environment:

D={(si,ai,ri,si′,di)}i=1N,J(π)=Eτ∼π[∑t=0H−1γtrt].\mathcal D=\{(s_i,a_i,r_i,s'_i,d_i)\}_{i=1}^N,\qquad J(\pi)=\mathbb E_{\tau\sim\pi}\left[\sum_{t=0}^{H-1}\gamma^t r_t\right].

Here did_i marks true termination, not an arbitrary time limit. A policy that improves on the log need not reproduce its action frequencies. But it also induces different state and action distributions. We assume the recorded state is sufficient for this finite Markov task and that the environment law stays fixed; those assumptions are not established just by counting rows.

Fitted Q iteration constructs targets using the previous Q-function, then fits those targets on recorded state–action pairs. For a greedy backup:

yi(k)=ri+γ(1−di)max⁡bQk(si′,b),Qk+1≈arg min⁡Q12N∑i(Q(si,ai)−yi(k))2.y_i^{(k)}=r_i+\gamma(1-d_i)\max_b Q_k(s'_i,b),\qquad Q_{k+1}\approx\operatorname*{arg\,min}_Q \frac1{2N}\sum_i\big(Q(s_i,a_i)-y_i^{(k)}\big)^2.

The approximation sign allows incomplete numerical optimization. The loss only constrains logged actions, whereas the maximum queries every candidate action at a logged successor state. An unsupported large value can therefore enter the target for an earlier, frequently observed transition. In our zero-coverage experiment, initialization at 2 survives for the unseen second-stage action and makes the wrong route look attractive. This is more specific than saying that the network “overfits.” Unseen-action backup problem

One response constrains the policy to supported actions. Another changes value fitting. The discrete CQL(H) objective adds a contrast between a soft maximum over actions and the Q-values of dataset actions:

LCQL(Q)=12N∑i(Q(si,ai)−yi)2+αN∑i[log⁡∑beQ(si,b)−Q(si,ai)],α≥0.\mathcal L_{\mathrm{CQL}}(Q)= \frac1{2N}\sum_i(Q(s_i,a_i)-y_i)^2 +\frac\alpha N\sum_i\left[ \log\sum_b e^{Q(s_i,b)}-Q(s_i,a_i) \right],\qquad\alpha\ge0.

This expression uses a finite discrete action set and a stated temperature of one. Continuous actions need a different treatment of the action integral; the referenced code samples actions and corrects densities. Its Atari implementation adds the discrete regularizer to QR-DQN, while our experiment uses a scalar table. CQL Equation 4 Fixed implementations

Let d^(s)=ns/N\widehat d(s)=n_s/N, μ^(a∣s)=nsa/ns\widehat\mu(a\mid s)=n_{sa}/n_s, and yˉsa\bar y_{sa} be the mean fixed target at an observed pair. Differentiating the tabular objective gives:

∂L∂Q(s,a)=d^(s)[μ^(a∣s)(Q(s,a)−yˉsa)+α(softmax⁡(Q(s,⋅))a−μ^(a∣s))].\frac{\partial\mathcal L}{\partial Q(s,a)}= \widehat d(s)\left[ \widehat\mu(a\mid s)(Q(s,a)-\bar y_{sa}) +\alpha\left(\operatorname{softmax}(Q(s,\cdot))_a-\widehat\mu(a\mid s)\right) \right].

Use this formula only for ns>0n_s>0; at nsa=0n_{sa}=0, omit the data-residual term rather than computing an undefined mean. For an unseen action with a large softmax share, the regularizer produces a positive gradient, so gradient descent lowers its value. Data actions can be pushed upward relative to other actions. The regularizer is not a calibrated uncertainty interval.

For any scalar cc, the regularizer at a state is unchanged when all of that state’s action values move together:

Rs(Q)=log⁡∑aeQ(s,a)−∑aμ^(a∣s)Q(s,a),Rs(Q+c1)=Rs(Q).\mathcal R_s(Q)=\log\sum_a e^{Q(s,a)}-\sum_a\widehat\mu(a\mid s)Q(s,a), \qquad \mathcal R_s(Q+c\mathbf1)=\mathcal R_s(Q).

The Bellman loss supplies a value anchor. With an entirely unobserved action, repeated penalization can keep lowering that cell without fitting any observed reward there; a finite number of updates is not a posterior estimate of its true reward.

Read “lower bound” with its conditions. The CQL paper distinguishes a pointwise result for one objective from a tighter policy-average result for another. Its analysis depends on the target distribution, coverage, estimation error and regularization conditions. A finite max-backup optimization followed by a greedy recommendation does not inherit a universal lower-bound certificate. The default run below even has a predicted maximum near 0.61343 for the alpha-1 controller whose real return is 0.4. That is a warning against applying a different theorem to this implementation, not a refutation of the paper. CQL, Section 3.1

A simpler comparison restricts both backups and final recommendations to observed actions:

AD(s)={a:nsa>0},yi=ri+γ(1−di)max⁡b∈AD(si′)Q(si′,b),π(s)∈arg max⁡a∈AD(s)Q(s,a).\mathcal A_{\mathcal D}(s)=\{a:n_{sa}>0\},\qquad y_i=r_i+\gamma(1-d_i)\max_{b\in\mathcal A_{\mathcal D}(s'_i)}Q(s'_i,b), \qquad \pi(s)\in\operatorname*{arg\,max}_{a\in\mathcal A_{\mathcal D}(s)}Q(s,a).

The program raises an error if a required nonterminal successor has no supported action. A single observation is enough to enter this simple support set; it is not enough for statistical confidence in a noisy problem. Restrictions can also exclude a genuinely excellent action that was never logged.

Freeze the data before fitting any policy

The behavior continues from the entrance with probability 0.3. At the second decision, the probability of choosing action 1 is a parameter rare. Each experiment collects 64 complete episodes and then freezes them. We compare three scalar-table fits with alpha 0, 0.1 and 1; a supported-action fit; and a behavior-cloning baseline that chooses each state’s most frequent action.

For each alpha, 24 outer rounds recompute targets. Each round runs 80 full-batch gradient steps at learning rate 0.2 with the targets held fixed. Both nonterminal Q rows start at 2; the terminal row is zero. This is 1,920 gradient steps, each reading all NN transitions, plus 24N24N target calculations. The reported target count does not include all gradient work. The supported method uses four target-and-average rounds; cloning only counts actions. Fitting collects no new real transitions.

For SS states, AA actions, KK outer rounds and LL inner steps, the tabular full-batch work is on the order of KL(N+SA)KL(N+SA) with O(N+SA)O(N+SA) storage. These are teaching-operation counts, not wall-clock claims about large neural implementations. real_value uses the known simulator only for independent evaluation after fitting.

The following Python/NumPy program runs end to end. The source implementation is original; no upstream training code is executed.

"""Original fixed-data tabular FQI/CQL(H) teaching example; NumPy only.
No new interactions during fitting; not the paper's QR-DQN or SAC experiments.
"""
import json
import numpy as np
GAMMA = .9


def positive_int(n):
    if isinstance(n, bool) or not isinstance(n, (int, np.integer)) or n < 1:
        raise ValueError('Expected a positive integer')
    return int(n)


def step(state, action, unknown_reward=-2.):
    if state not in (0, 1) or action not in (0, 1): raise ValueError('Invalid nonterminal decision')
    if state == 0: return (2, .4, True) if action == 0 else (1, 0., False)
    return 2, (1. if action == 0 else float(unknown_reward)), True


def collect(seed, episodes=64, rare=.05):
    if not np.isfinite(rare) or not 0 <= rare <= 1: raise ValueError('Invalid probability')
    rng = np.random.default_rng(seed); rows=[]
    for _ in range(positive_int(episodes)):
        state=0
        while state != 2:
            probability = .3 if state == 0 else rare
            action = int(rng.random() < probability)
            nxt,reward,done = step(state,action)
            rows.append((state,action,reward,nxt,done));state=nxt
    return np.asarray(rows,dtype=float)


def validate(data):
    d=np.asarray(data,dtype=float)
    if d.ndim != 2 or d.shape[1] != 5 or len(d) == 0 or not np.isfinite(d).all():
        raise ValueError('Nonempty finite transition table required')
    if not np.isin(d[:,0],[0,1]).all() or not np.isin(d[:,1],[0,1]).all() or not np.isin(d[:,3],[1,2]).all():
        raise ValueError('Invalid states or actions')
    if not np.isin(d[:,4],[0,1]).all() or not np.array_equal(d[:,4] == 1,d[:,3] == 2):
        raise ValueError('Explicit true terminal mask required')
    expected=np.where((d[:,0]==0)&(d[:,1]==1),1,2)
    if not np.array_equal(d[:,3],expected):raise ValueError('Transition violates the two-stage task')
    return d


def statistics(data):
    d=validate(data);counts=np.zeros((2,2),dtype=int)
    np.add.at(counts,(d[:,0].astype(int),d[:,1].astype(int)),1)
    return counts


def targets(data, q, supported=False):
    d=validate(data);nxt=d[:,3].astype(int);done=d[:,4].astype(bool)
    values=q.max(1).copy()
    if supported:
        counts=statistics(d)
        for state in (0,1):
            mask=counts[state]>0
            if np.any((nxt==state)&~done) and not mask.any():
                raise ValueError('No supported successor action for this backup')
            values[state]=float(q[state,mask].max()) if mask.any() else 0.
    values[2]=0.
    return d[:,2]+GAMMA*np.where(done,0.,values[nxt])


def loss_gradient(q, data, target, alpha):
    d=validate(data);target=np.asarray(target,dtype=float)
    if q.shape != (3,2) or target.shape != (len(d),) or not np.isfinite(q).all() or not np.isfinite(target).all():
        raise ValueError('Finite table and target required')
    if not np.isfinite(alpha) or alpha<0: raise ValueError('Nonnegative alpha required')
    counts=statistics(d);frequency=counts/len(d);state_frequency=frequency.sum(1)
    s,a=d[:,0].astype(int),d[:,1].astype(int);residual=q[s,a]-target
    gradient=np.zeros_like(q);np.add.at(gradient,(s,a),residual/len(d))
    maximum=q[:2].max(1,keepdims=True);e=np.exp(q[:2]-maximum);prob=e/e.sum(1,keepdims=True)
    logsum=maximum[:,0]+np.log(e.sum(1))
    penalty=float(state_frequency@logsum-np.sum(frequency*q[:2]))
    gradient[:2]+=alpha*(state_frequency[:,None]*prob-frequency)
    return float(.5*np.mean(residual**2)+alpha*penalty),gradient


def fit(data, alpha=0., outer=24, inner=80, learning_rate=.2, initial=2.):
    d=validate(data)
    if not np.isfinite(learning_rate) or learning_rate<=0 or not np.isfinite(initial): raise ValueError('Invalid optimizer')
    q=np.full((3,2),float(initial));q[2]=0.
    for _ in range(positive_int(outer)):
        y=targets(d,q)  # Fixed target throughout the inner optimization.
        for _ in range(positive_int(inner)):
            _,gradient=loss_gradient(q,d,y,alpha);q-=learning_rate*gradient
    return q


def supported_fqi(data, rounds=4):
    d=validate(data);counts=statistics(d);q=np.zeros((3,2))
    for _ in range(positive_int(rounds)):
        y=targets(d,q,supported=True)
        for state in (0,1):
            for action in (0,1):
                mask=(d[:,0]==state)&(d[:,1]==action)
                if mask.any():q[state,action]=y[mask].mean()
    policy=[]
    for state in (0,1):
        mask=counts[state]>0
        policy.append(int(np.argmax(np.where(mask,q[state],-np.inf))) if mask.any() else None)
    return q,policy


def real_value(policy, unknown_reward=-2.):
    state=0;value=0.;discount=1.
    while state!=2:
        action=policy[state]
        if action is None:raise ValueError('Policy abstains at a reached state')
        state,reward,_=step(state,action,unknown_reward);value+=discount*reward;discount*=GAMMA
    return value


def experiment(seed=0, rare=.05):
    d=collect(seed,rare=rare);counts=statistics(d);methods=[]
    for alpha in (0.,.1,1.):
        q=fit(d,alpha);policy=q[:2].argmax(1).tolist()
        methods.append(dict(method='fqi' if alpha==0 else 'cql',alpha=alpha,q=q[:2].tolist(),
            policy=policy,predicted_start=float(q[0].max()),real_return=real_value(policy),
            gradient_steps=24*80,transition_targets=24*len(d)))
    q,policy=supported_fqi(d)
    methods.append(dict(method='supported',q=q[:2].tolist(),policy=policy,real_return=real_value(policy)))
    policy=counts.argmax(1).tolist()
    methods.append(dict(method='behavior-cloning',policy=policy,real_return=real_value(policy)))
    return dict(seed=seed,rare_probability=rare,episodes=64,real_transitions=len(d),counts=counts.tolist(),
        methods=methods,optimal_real_return=max(real_value([a,b]) for a in (0,1) for b in (0,1)))


if __name__=='__main__':
    print(json.dumps(experiment(),indent=2))
Inspect the recorded summary
{
  "seed": 0,
  "rare_probability": 0.05,
  "episodes": 64,
  "real_transitions": 82,
  "counts": [
    [
      46,
      18
    ],
    [
      17,
      1
    ]
  ],
  "methods": [
    {
      "method": "fqi",
      "alpha": 0.0,
      "q": [
        [
          0.40000000000000024,
          0.9000000000000037
        ],
        [
          1.0000000000000027,
          -1.9632035040665075
        ]
      ],
      "policy": [
        1,
        0
      ],
      "predicted_start": 0.9000000000000037,
      "real_return": 0.9,
      "gradient_steps": 1920,
      "transition_targets": 1968
    },
    {
      "method": "cql",
      "alpha": 0.1,
      "q": [
        [
          0.44243618011938973,
          0.7909615945150398
        ],
        [
          0.9993172095153531,
          -1.9655070222322186
        ]
      ],
      "policy": [
        1,
        0
      ],
      "predicted_start": 0.7909615945150398,
      "real_return": 0.9,
      "gradient_steps": 1920,
      "transition_targets": 1968
    },
    {
      "method": "cql",
      "alpha": 1.0,
      "q": [
        [
          0.61342500592268,
          0.350517920816353
        ],
        [
          0.99547638199504,
          -1.9223159592142167
        ]
      ],
      "policy": [
        0,
        0
      ],
      "predicted_start": 0.61342500592268,
      "real_return": 0.4,
      "gradient_steps": 1920,
      "transition_targets": 1968
    },
    {
      "method": "supported",
      "q": [
        [
          0.3999999999999998,
          0.8999999999999999
        ],
        [
          1.0,
          -2.0
        ]
      ],
      "policy": [
        1,
        0
      ],
      "real_return": 0.9
    },
    {
      "method": "behavior-cloning",
      "policy": [
        0,
        0
      ],
      "real_return": 0.4
    }
  ],
  "optimal_real_return": 0.9
}

All eight seeds are retained for each of three coverage settings. Returns below are exact values of the resulting deterministic policies in the teaching environment, not estimates made by their Q-tables.

Probability of the rare actionSeedsOrdinary fit, alpha 0CQL alpha 0.1CQL alpha 1Supported fitCloning
00–7All −1.8All 0.9All 0.4All 0.9All 0.4
0.050–7Six 0.9; seeds 4 and 6: −1.8All 0.9All 0.4All 0.9All 0.4
0.50–7All 0.9All 0.9All 0.4All 0.9All 0.4

At probability 0.05, the eight rare-action counts are 1, 1, 1, 1, 0, 2, 0 and 2. In default seed 0 there are 82 real transitions, with counts 46/18 at the entrance and 17/1 at the second decision. The ordinary fit already succeeds because it saw the harmful action. The alpha-1 penalty instead selects the frequent exit and forgoes the supported 0.9 route. More conservatism is not automatically more useful.

The zero-coverage failure can be interpreted without any optimizer. Construct a second environment identical on every logged pair but change the unobserved reward from −2 to +2. The same behavior produces exactly the same data in both worlds. Their optimal returns are 0.9 and 1.8. No method can identify which world it is in from this log alone; a preference for the supported route is an explicit conservative choice.

Coverage is not the same as a large file

The example uses deterministic rewards, exact state identities and a short known graph. It has no hidden state, learned representation or dataset contamination. In a large problem, noisy rewards, incomplete state information and distribution shift can invalidate conclusions that looked clear from this table.

Offline RL is not synonymous with cloning, but improving on cloning requires evidence that supports useful deviations. Dataset size alone does not show that evidence. A held-out Bellman loss can remain small while a policy exploits values at actions absent from both training and validation. Reward scaling also changes the balance between the squared fit term and a fixed conservative coefficient.

Finally, selecting alpha by repeatedly checking the true simulator return uses information that a strictly offline practitioner may not possess. Here the fixed coefficients are an openly reported teaching comparison. Actual policy selection needs an explicit validation protocol and off-policy evaluation, with that estimator’s own support and uncertainty limits. The fixed CQL repository also notes dataset-version changes and parameter differences; its old README scores are not current benchmark guarantees. Versioned implementation notes

What would the missing row tell you?

  1. All recorded samples at a state use action 0 with terminal reward 1. Both Q-values start at zero. For alpha 1, what are the two gradients and the result of one gradient step with learning rate 0.2?

    Answer: The data residual contributes −1 to action 0 and zero to action 1. The softmax term contributes −0.5 and +0.5, yielding gradients −1.5 and +0.5. The updated values are 0.3 and −0.1. Lowering the unseen value does not reveal its true reward.

  2. Why can the supported fit earn 0.9 when behavior cloning earns 0.4 in this task?

    Answer: Cloning chooses the frequent entrance exit. The log also contains transitions that continue and then choose the rewarding second-stage action. Supported backups can connect those observed pieces into the 0.9 route without copying their original frequencies.

  3. A zero-coverage log is consistent with an unobserved reward of either −2 or +2. What experiment-free argument rules out a guarantee of choosing the true optimum in both worlds?

    Answer: An algorithm receives identical data in the two worlds, so that data cannot determine which unobserved outcome holds. Their best routes differ. The uncertainty cannot be removed by more gradient steps on the same log; new evidence or an additional assumption is needed.

  4. The alpha-1 default run predicts about 0.61343 but its greedy controller earns 0.4. Does this disprove CQL’s theorem? How should you account for its training cost?

    Answer: No. This finite max-backup/CQL(H)/greedy implementation is not the fixed-policy estimator under all conditions of the cited bound. Its fit uses 1,920 full-batch gradient steps and 24N24N target entries for that alpha, with zero new real interactions. The other coefficients and baselines add their own computation; evaluation is separate.

Separate the dataset, the optimizer and the claim

The selected tutorial explains why reusing data and forbidding new collection are different settings. CQL gives a family of conservative objectives rather than a single unconditional promise. The fixed source code distinguishes the discrete QR-DQN and continuous SAC-based variants. Tutorial CQL paper Fixed code

Compare Q-learning and experience replay for the online learning context, and world models for another way to use learned predictions. Neither a conservative value fit nor a realistic model makes unsupported actions identifiable from a fixed log.

Make a prediction, then check

Must a stronger conservative penalty in offline Q-learning yield a higher real policy return?

Choose one answer

Learning objectives

  • Fit from a fixed dataset without new interaction and explain how unseen-action values enter Bellman targets.
  • Compute a discrete CQL objective and gradient, separating empirical behavior, coverage assumptions and conditional value bounds.

Prerequisites & connections

Explore related knowledge →

References

  1. Offline Reinforcement Learning: Tutorial, Review, and Perspectives on Open Problems — arXiv v3
    Sergey Levine; Aviral Kumar; George Tucker; Justin Fu · 2020
  2. Conservative Q-Learning for Offline Reinforcement Learning — scoped conference paper
    Aviral Kumar; Aurick Zhou; George Tucker; Sergey Levine · 2020
  3. CQL author implementation — fixed discrete and continuous method reading
    Aviral Kumar; CQL contributors · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: Selected v3 dated2020-11-01, first submitted2020-05-04. Read pages7/9/10/18/19 of43 and650 identity characters on page1. Fixed data, distribution shifts, IS/WIS and unseen-action backups; neither the2020 sufficiency footnote nor unverified original imitation bounds are current universal conclusions. Not a full-paper audit. Official13-page NeurIPS33 PDF; read3–4 and650 identity characters on page1, viewed4. Pointwise versus policy-average bounds, sampling/coverage/alpha conditions and discrete CQL(H) Equation4. No full appendix-proof or benchmark audit; finite teaching optimization is not certified by those theorems. Fixed2020-09-14 commit; full54-line README, discrete141–174/219–243, continuous cql.py194–282. QR-DQN regularization differs from continuous sampling corrections; data Q mean is not the comment’s log likelihood. README notes D4RL/version changes. Atari Apache identity only; all21 D4RL MIT lines read. No copying/execution. 6 paired equations and four explained exercises. Fixed targets, terminal masks, full tabular CQL(H) gradients, regularizer shift invariance and supported backups independently checked.24 seed/coverage settings retain ordinary-fit failures, stronger-penalty opportunity cost and predicted/real value differences. Two indistinguishable logged worlds have different optimal values. No new interaction in fitting or unconditional lower-bound claim.

  • Fixed targets, terminal masks, full tabular CQL(H) gradients, regularizer shift invariance and supported backups independently checked.24 seed/coverage settings retain ordinary-fit failures, stronger-penalty opportunity cost and predicted/real value differences. Two indistinguishable logged worlds have different optimal values. No new interaction in fitting or unconditional lower-bound claim.
  • Four computed SVG variants per topic;9 numeric/geometry tests and12 current responsive cases passed. All six selected current captures directly viewed; no figure failure or post-capture asset edit in this group. Actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.