betaFeedback

WorksComputer Science

From Policy Evaluation to Off-Policy Control: Provable Emergence of In-Context Q-Learning

Abstract

Transformers can implement reinforcement-learning algorithms in context, yet how off-policy control emerges within Transformers remains poorly understood. We study Q-learning, a foundational model-free control algorithm that combines off-policy bootstrapping with greedy policy improvement. We prove that a two-layer attention-only Transformer can implement a finite-temperature form of Q-learning, where the temperature τ>0τ>0 controls the approximation to greedy action selection, recovering window Q-learning as τ→0τ\to0. We train the structured Transformer on randomly generated MDP tasks using output-only supervision. Experiments show that the theoretically predicted parameter structure emerges during training, including the internal greedy action-selection mechanism, and that the trained Transformer achieves performance comparable to Q-learning on unseen tasks. Our theoretical analysis further shows that the equivalent realizations form a solution manifold and that, under suitable task-diversity conditions, the training iterates converge locally to this manifold at an exponential rate. For the random-task model analyzed here, the local worst-case number of gradient steps needed to reduce the distance to the manifold by a factor εε is Θ(τ−5log⁡(1/ε))Θ\left(τ^{-5}\log(1/\varepsilon)\right), quantifying the increasing optimization cost as the learned update approaches window Q-learning.

Introduction

In-context reinforcement learning (ICRL) offers an alternative to the conventional paradigm of reinforcement learning. Rather than adapting to a new task through parameter updates, a pretrained agent can adjust its behavior directly from the interaction history provided in its context. This phenomenon has motivated an algorithmic interpretation of ICRL: a Transformer may not merely map a trajectory to a prediction, but may execute a reinforcement-learning algorithm within its forward pass. Recent theoretical work supports this view. Transformers have been shown to implement temporal-difference (TD) methods for policy evaluation, and more recent results extend this perspective to policy-improvement methods such as SARSA and actor-critic (Wang et al., 2024; 2025; Xie et al., 2026a;b; Liang & Lai, 2026).

A central regime remains largely unexplored: off-policy control. Existing policy-improvement constructions focus primarily on on-policy learning, where the behavior policy and the policy being improved are tightly coupled [10]. This coupling is restrictive in real applications where an agent must learn from previously collected, heterogeneous, or suboptimal experience rather than from trajectories generated by its current policy. Off-policy control asks whether useful policy improvement can still be carried out when these two roles are decoupled. Q-learning provides a canonical setting for studying this problem. Given a transition (s,a,r,s′)(s, a, r, s'), its target is r+γmax⁡a′Q(s′,a′)r + \gamma\max_{a'} Q(s', a'), which does not depend on the successor action selected by the behavior policy. Thus, subject to sufficient state-action coverage, Q-learning can use experience generated by a suboptimal behavior policy while improving toward a greedy target policy. This makes Q-learning a natural testbed for a more demanding form of in-context adaptation: whether a Transformer can use off-policy experience to carry out control, rather than merely evaluate or improve the policy that generated its context.

This transition is substantially more than a change of update rule. At a conceptual level, it marks the passage from Bellman evaluation to Bellman optimality. An in-context implementation of Q-learning must compare competing successor actions, resolve the resulting action selection, and then use that decision to construct the bootstrap target. We show that there exists a two-layer Transformer, combining masked softmax attention with linear attention, that jointly implements next-state action selection and the corresponding window semi-gradient Q-learning update in finite-temperature form, where the softmax temperature τ>0\tau> 0 controls the degree of approximation to greedy action selection, and standard window (hard-max) Q-learning is recovered in the limit τ→0\tau\to0. In this sense, the architecture of transformer does not merely reproduce the numerical output of Q-learning; its internal computation mirrors the decomposition of the algorithm itself.

What kind of pretraining can give rise to such a Transformer? We develop a gradient-based training algorithm in which a soft window-Q update serves as the teacher for each sampled context. Within the prescribed tokenization and attention mask, training supervises only the output update and imposes no numerical targets on the internal parameter blocks to implement either window Q-learning or action selection. Nevertheless, the constructed parameter structure emerges under training, recovering the underlying computation, including the internal action-selection mechanism. On unseen tasks, the trained Transformer achieves performance comparable to window Q-learning with the same step size.

To understand why a Q-learning implementation can emerge under this training procedure, we provide a theoretical analysis of its convergence. The nonlinear dependence of softmax attention on the action-score parameters makes the analysis substantially more intricate than in linear-attention settings. Meanwhile, the Q-learning realization is inherently non-identifiable, with different parameter configurations implementing the same update. This makes the relevant optimization target a manifold of functionally equivalent Q-learning realizations rather than a single parameter vector. We characterize this realization manifold and show that, under verifiable conditions on the training distribution, the discrete-time training dynamics converge locally to this manifold at an exponential rate. The analysis further reveals a quantitative difficulty in approaching greedy Q-learning: for the random-task model considered here, the local worst-case number of gradient steps needed to reduce the distance to the manifold by a factor ϵ\epsilon is Θ(τ−5log⁡(1/ϵ))\Theta\left(\tau^{-5}\log(1/\epsilon)\right), quantifying the increasing optimization cost as the learned update approaches standard Q-learning.

Our results make three concrete advances. First, we give an explicit attention-only construction that jointly realizes successor-action comparison and the window Q-learning update. Second, we design a gradient-based training procedure and characterize a smooth manifold of functionally equivalent Q-learning realizations, showing local exponential convergence of the training dynamics to this manifold. Third, we quantify how the softmax temperature governs the tradeoff between approximating greedy action selection and optimization difficulty. Together, these results extend the mechanistic analysis of ICRL from policy evaluation and on-policy control to off-policy Q-learning.

Related work

Transformer-based agents have been studied extensively for sequential decision making. Decision Transformer and Trajectory Transformer formulate reinforcement learning as sequence modeling [2, 6], while Algorithm Distillation and related ICRL methods show that pretrained sequence models can adapt to unseen tasks through interaction histories without test-time parameter updates [7, 9, 5]. On the theoretical side, Lin et al. [11] establish provable ICRL under supervised pretraining and show that Transformers can approximate classical online decision-making algorithms.

Recent work has taken a mechanistic view of ICRL, asking which RL algorithms can be implemented by Transformer forward computation and whether the corresponding algorithmic parameters can emerge through pretraining. Wang et al. [16, 17] show that linear-attention Transformers can implement TD updates for policy evaluation, while Xie et al. [21] extend this result to standard softmax attention via a kernel-weighted TD construction. Beyond policy evaluation, Liang & Lai [10] show that Transformers can realize semi-gradient SARSA and actor-critic updates for policy improvement. However, analogous results for off-policy control, including classical Q-learning, where trajectory data are coupled with subsequent action selection, remain largely unexplored. We study the emergence of Q-learning updates within Transformers, including the Transformer construction, pretraining algorithm, and its convergence analysis. Unlike Liang & Lai [10], we focus on the effect of the action-selection mechanism on convergence, and our analysis accounts for discrete-time training iterates and provides verifiable convergence conditions.

Off-policy learning is particularly relevant to ICRL when context trajectories are offline, heterogeneous, or generated by suboptimal behavior policies. In such settings, the quality of the learned policy need not be tied to that of the behavior generating the trajectories, making off-policy value-based learning particularly relevant. Dong et al. [3] study ICRL from suboptimal historical trajectories and propose an advantage-weighted policy-learning framework to improve upon the behavior policies in the data. Scalable In-Context Q-Learning (Liu et al., [12]) combines context-conditioned value estimation, dynamic programming, and policy extraction to enable iterative improvement from suboptimal offline experience. In-Context Compositional Q-Learning (Xu et al., [22]) instead formulates QQ-function estimation as contextual inference and uses retrieved transitions to infer local QQ-functions for offline RL. Our work differs fundamentally from these studies by taking a mechanistic view of how Transformers realize QQ-learning in ICRL, characterizing both the forward-pass implementation of the QQ-learning update and the emergence of the corresponding parameter structure through training.

Background

Transformers and Self-Attention

All vectors are treated as column vectors. Let InI_n denote the n×nn \times n identity matrix, 0m×n0_{m \times n} the m×nm \times n zero matrix, and 0m0_m the mm-dimensional zero vector.

Let H=[h1,…,hn]∈RD×n\mathbf{H} = [h_1, \ldots, h_n] \in\mathbb{R}^{D \times n} denote a prompt representation, where each column hi∈RDh_i \in\mathbb{R}^{D} corresponds to one token. The standard single-head softmax self-attention (Vaswani et al., [15]) processes the prompt via SoftAttn⁡P,V(H)≜(VH)softmax⁡(HTPH)\operatorname{SoftAttn}_{P,V}(\mathbf{H}) \triangleq(V\mathbf{H})\operatorname{softmax}(\mathbf{H}^{\mathsf{T}}P\mathbf{H}), where V∈RD×DV \in\mathbb{R}^{D \times D} is the value projection matrix, P:=WKTWQ∈RD×DP := W_K^{\mathsf{T}}W_Q \in\mathbb{R}^{D \times D} collects the key and query projection parameters, the conventional scaling factor in scaled dot-product attention is absorbed into PP, and the softmax is applied independently to each query column, normalizing the attention scores over all key positions.

As a widely studied alternative to softmax self-attention, linear self-attention replaces the softmax-normalized attention weights with unnormalized bilinear attention scores (Ahn et al. [1], Gatmiry et al. [4], Zhang et al. [23]). Its formulation is given by LinAttn⁡P,V(H)≜1n(VH)(HTPH)\operatorname{LinAttn}_{P,V}(\mathbf{H}) \triangleq\frac{1}{n}(V\mathbf{H})(\mathbf{H}^{\mathsf{T}}P\mathbf{H}), where the factor 1n\frac{1}{n} normalizes the aggregation with respect to the prompt length.

To model a multi-layer Transformer structure, we stack LL attention layers with residual connections. Let H(0)=H∈RD×n\mathbf{H}^{(0)} = \mathbf{H} \in\mathbb{R}^{D \times n} denote the initial input prompt representation. For each layer ℓ∈{1,2,…,L}\ell\in\{1,2,\ldots,L\}, the layer-wise update rule reads

H(ℓ):=H(ℓ−1)+Attn⁡P(ℓ),V(ℓ)(H(ℓ−1))∈RD×n,(1)\mathbf{H}^{(\ell)} := \mathbf{H}^{(\ell-1)} + \operatorname{Attn}_{P^{(\ell)},V^{(\ell)}}\left(\mathbf{H}^{(\ell-1)}\right) \in\mathbb{R}^{D \times n}, \tag*{(1)}

where Attn⁡\operatorname{Attn} denotes either SoftAttn⁡\operatorname{SoftAttn} or LinAttn⁡\operatorname{LinAttn}, and {P(ℓ),V(ℓ)}\{P^{(\ell)}, V^{(\ell)}\} are the layer-specific projection parameters at layer ℓ\ell. After stacking LL attention layers, the final Transformer output is defined as

TF⁡L(H;{P(ℓ),V(ℓ)}ℓ=1L):=fread(H(L)),(2)\operatorname{TF}_L\left(\mathbf{H}; \{P^{(\ell)}, V^{(\ell)}\}_{\ell=1}^{L}\right) := f_{\mathrm{read}}\left(\mathbf{H}^{(L)}\right), \tag*{(2)}

where fread:RD×n→RDoutf_{\mathrm{read}}: \mathbb{R}^{D \times n} \to\mathbb{R}^{D_{\mathrm{out}}} denotes a fixed readout map. Equation (2) establishes the notation convention we adopt for defining the output of an LL-layer Transformer. Specifically, the attention mechanism produces a matrix, while we require a vector output for policy improvement. Following prior works (Xie et al. [21], Liang & Lai [10], Wang et al. [16]), we use the bottom-right dd-dimensional vector of the output matrix as this vector.

Reinforcement Learning and Q-learning

We consider an infinite-horizon discounted Markov decision process (MDP) E=(S,A,P,R,γ)\mathcal{E} = (\mathcal{S}, \mathcal{A}, P, R, \gamma), where S\mathcal{S} is the state space, A\mathcal{A} is the action space, P(⋅∣s,a)∈P(S)P(\cdot\mid s,a) \in\mathcal{P}(\mathcal{S}) is the transition kernel, R:S×A×S→RR : \mathcal{S} \times\mathcal{A} \times\mathcal{S} \to\mathbb{R} is the reward function, and γ∈[0,1)\gamma\in[0,1) is the discount factor. Here, P(X)\mathcal{P}(\mathcal{X}) denotes the set of probability distributions over X\mathcal{X}. At time tt, an agent in state StS_t selects an action At∼π(⋅∣St)A_t \sim\pi(\cdot\mid S_t) according to a policy π:P(A)\pi: \mathcal{P}(\mathcal{A}), receives a reward Rt+1=R(St,At,St+1)R_{t+1} = R(S_t, A_t, S_{t+1}), and transitions to a successor state St+1∼P(⋅∣St,At)S_{t+1} \sim P(\cdot\mid S_t, A_t). The discounted return from time tt is defined as Gt:=∑k=0∞γkRt+k+1G_t := \sum_{k=0}^{\infty} \gamma^k R_{t+k+1}. The state-value and action-value functions associated with a policy π\pi are respectively defined as vπ(s):=Eπ[Gt∣St=s]v_\pi(s) := \mathbb{E}_\pi[G_t \mid S_t = s], qπ(s,a):=Eπ[Gt∣St=s,At=a]q_\pi(s,a) := \mathbb{E}_\pi[G_t \mid S_t = s, A_t = a]. The objective of RL is to find a policy that maximizes the expected discounted return.

Q-learning [18, 19] is a classical off-policy TD control algorithm for estimating the optimal action-value function. In the tabular setting, an estimate Qt(s,a)Q_t(s,a) is maintained explicitly for each state-action pair. Given a transition (St,At,Rt+1,St+1)(S_t,A_t,R_{t+1},S_{t+1}), Q-learning updates the value of the visited state-action pair according to

Qt+1(St,At)=(1−α)Qt(St,At)+α[Rt+1+γmax⁡a′∈AQt(St+1,a′)](3)Q_{t+1}(S_t,A_t)=(1-\alpha)Q_t(S_t,A_t)+\alpha\left[R_{t+1}+\gamma\max_{a'\in\mathcal{A}}Q_t(S_{t+1},a')\right] \tag*{(3)}

where α∈(0,1]\alpha\in(0,1] is the learning rate. All other state-action values remain unchanged. To handle large state-action spaces, we consider linear function approximation [14, 13]. Given a feature map ϕ:S×A→Rd\phi:\mathcal{S}\times\mathcal{A}\to\mathbb{R}^{d} and a parameter vector wt∈Rd\mathbf{w}_t\in\mathbb{R}^{d} at time tt, the action-value function is approximated by qwt(s,a):=wt⊤ϕ(s,a)q_{\mathbf{w}_t}(s,a):=\mathbf{w}_t^{\top}\phi(s,a). Given a transition (St,At,Rt+1,St+1)(S_t,A_t,R_{t+1},S_{t+1}), the semi-gradient Q-learning update is

wt+1=wt+α(Rt+1+γmax⁡a′∈Awt⊤ϕ(St+1,a′)−wt⊤ϕ(St,At))ϕ(St,At).(4)\mathbf{w}_{t+1}=\mathbf{w}_t+\alpha\left(R_{t+1}+\gamma\max_{a'\in\mathcal{A}}\mathbf{w}_t^{\top}\phi(S_{t+1},a')-\mathbf{w}_t^{\top}\phi(S_t,A_t)\right)\phi(S_t,A_t). \tag*{(4)}

The tabular setting is recovered as a special case when S\mathcal{S} and A\mathcal{A} are finite, d=∣S∣∣A∣d=|\mathcal{S}||\mathcal{A}|, and each state-action pair (s,a)(s,a) is assigned a distinct one-hot feature vector ϕ(s,a)=e(s,a)\phi(s,a)=e_{(s,a)}. In this case, each coordinate of wt\mathbf{w}_t corresponds to a single state-action value Qt(s,a)Q_t(s,a), and the above semi-gradient update reduces exactly to the standard tabular Q-learning update.

Transformer can implement In-context soft Q-learning

References

  1. [1]Kwangjun Ahn, Xiang Cheng, Hadi Daneshmand, and Suvrit Sra. Transformers learn to implement preconditioned gradient descent for in-context learning. Advances in Neural Information Processing Systems, 36:45614–45650, 2023.arxiv.org/abs/2306.00297
  2. [2]Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, and Igor Mordatch. Decision transformer: Reinforcement learning via sequence modeling. In Advances in Neural Information Processing Systems, volume 34, 2021.arxiv.org/abs/2106.01345
  3. [3]Juncheng Dong, Moyang Guo, Ethan X. Fang, Zhuoran Yang, and Vahid Tarokh. In-context reinforcement learning from suboptimal historical data. In Proceedings of the 42nd International Conference on Machine Learning, volume 267 of Proceedings of Machine Learning Research, pp. 14021–14039. PMLR, 2025.arxiv.org/abs/2601.20116
  4. [4]Khashayar Gatmiry, Nikunj Saunshi, Sashank J. Reddi, Stefanie Jegelka, and Sanjiv Kumar. Can looped transformers learn to implement multi-step gradient descent for in-context learning? In Forty-first International Conference on Machine Learning, 2024. URL https://openreview.net/forum?id=o8AaRKbP9K.arxiv.org/abs/2410.08292
  5. [5]Jake Grigsby, Linxi Fan, and Yuke Zhu. AMAGO: Scalable in-context reinforcement learning for adaptive agents. In International Conference on Learning Representations, 2024.arxiv.org/abs/2310.09971
  6. [6]Michael Janner, Qiyang Li, and Sergey Levine. Offline reinforcement learning as one big sequence modeling problem. In Advances in Neural Information Processing Systems, volume 34, pp. 1273–1286, 2021.arxiv.org/abs/2106.02039
  7. [7]Michael Laskin, Luyu Wang, Junhyuk Oh, Emilio Parisotto, Stephen Spencer, Richie Steigerwald, DJ Strouse, Steven Hansen, Angelos Filos, Ethan Brooks, Maxime Gazeau, Himanshu Sahni, Satinder Singh, and Volodymyr Mnih. In-context reinforcement learning with algorithm distillation. In International Conference on Learning Representations, 2023.arxiv.org/abs/2210.14215
  8. [8]John M. Lee. Introduction to Smooth Manifolds, volume 218 of Graduate Texts in Mathematics. Springer, New York, 2 edition, 2013. doi: 10.1007/978-1-4419-9982-5.DOI
  9. [9]Jonathan Lee, Annie Xie, Aldo Pacchiano, Yash Chandak, Chelsea Finn, Ofir Nachum, and Emma Brunskill. Supervised pretraining can learn in-context reinforcement learning. In Advances in Neural Information Processing Systems, volume 36, 2023.
  10. [10]Haodong Liang and Lifeng Lai. Transformers provably implement in-context reinforcement learning with policy improvement. arXiv preprint arXiv:2605.05755, 2026.
  11. [11]Licong Lin, Yu Bai, and Song Mei. Transformers as decision makers: Provable in-context reinforcement learning via supervised pretraining. In International Conference on Learning Representations, 2024.arxiv.org/abs/2310.08566
  12. [12]Jinmei Liu, Fuhong Liu, Zhenhong Sun, Jianye Hao, Huaxiong Li, Bo Wang, Daoyi Dong, Chunlin Chen, and Zhi Wang. Scalable in-context q-learning. In International Conference on Learning Representations, 2026.arxiv.org/abs/2506.01299
  13. [13]Francisco S. Melo, Sean P. Meyn, and M. Isabel Ribeiro. An analysis of reinforcement learning with function approximation. In Proceedings of the 25th International Conference on Machine Learning, pp. 664–671, 2008. doi: 10.1145/1390156.1390240.
  14. [14]John N. Tsitsiklis and Benjamin Van Roy. An analysis of temporal-difference learning with function approximation. IEEE Transactions on Automatic Control, 42(5):674–690, 1997.
  15. [15]Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, and Illia Polosukhin. Attention is all you need. In Advances in Neural Information Processing Systems, volume 30, 2017.arxiv.org/abs/1706.03762
  16. [16]Jiuqi Wang, Ethan H Blaser, Hadi Daneshmand, and Shangtong Zhang. Transformers learn temporal difference methods for in-context reinforcement learning. In ICML 2024 Workshop on In-Context Learning, 2024.
  17. [17]Jiuqi Wang, Rohan Chandra, and Shangtong Zhang. Towards provable emergence of in-context reinforcement learning. In Advances in Neural Information Processing Systems, volume 38, 2025.
  18. [18]Christopher J. C. H. Watkins. Learning from Delayed Rewards. PhD thesis, King’s College, University of Cambridge, 1989.DOI
  19. [19]Christopher J. C. H. Watkins and Peter Dayan. Q-learning. Machine Learning, 8(3–4):279–292, 1992. doi: 10.1007/BF00992698.DOI
  20. [21]Zixuan Xie, Xinyu Liu, Claire Chen, Shuze Daniel Liu, Rohan Chandra, and Shangtong Zhang. Beyond linear attention: Softmax transformers implement in-context reinforcement learning. arXiv preprint arXiv:2605.07333, 2026b.arxiv.org/abs/2605.07333
  21. [22]Qiushui Xu, Yuhao Huang, Yushu Jiang, Wenliang Zheng, Lei Song, Jinyu Wang, and Jiang Bian. In-context compositional q-learning for offline reinforcement learning. In International Conference on Learning Representations, 2026.arxiv.org/abs/2509.24067
  22. [23]Ruiqi Zhang, Spencer Frei, and Peter L Bartlett. Trained transformers learn linear models in-context. Journal of Machine Learning Research, 25(49):1–55, 2024.

Paper details

vlnc:W_6c23uhxe
Version
v1 · latest
Published
Fresh — added to the Hub within the last 30 days
Added
License
CC BY 4.0
Usage

views · 11

downloads · 0

A view counts once per browser per day, a download each time the PDF is requested.

  • Computer Science

AI tools

View statement
Looking for related papers…
Contents