Extracted main text — title through conclusion, appendix excluded. This is what our citation measures are computed over, published so the extraction can be checked by eye.
51,719 characters · 14 sections · 37 citation commands
Transformers Handle Endogeneity in In-Context Linear Regression
The transformer architecture vaswani has demonstrated remarkable in-context learning (ICL) capabilities across various domains, such as natural language processing Devlin2019BERTPO,radford2019language,brown2020language, computer vision dosovitskiy2021image, carion2020endtoend, and reinforcement learning lee2022multigame,parisotto2019stabilizing. Self-attention mechanism, a core component of transformers, allows these models to capture long-range dependencies in data, which is critical for success in these tasks. Despite their impressive performance, the theoretical understanding of transformers remains limited, leaving important questions unanswered about their true capabilities and the underlying mechanisms driving their exceptional results.
Recent efforts to theoretically understand transformers' ICL capabilities have focused on their performance in fundamental statistical tasks. Focusing on simple function classes, garg2023transformers highlighted that transformers, when trained on sufficiently large and diverse data from a specific function class, can generalize across most functions of that class without task-specific fine-tuning. Building on this, subsequent work by statistician established that attention layers enable transformers to perform gradient descent, implementing algorithms like linear regression, logistic regression, and LASSO; see also akyurek2023what,von2023transformers,li2023transformers,fu2023transformers,ahn2024transformers,jin2025incontextlearningmixturelinear. The learning dynamics of transformer trained via gradient descent for in-context learning linear function classes was analyzed in Huang:ICML:24. Furthermore zhang2023trained,zhang2024incontext showed that trained transformers’ ICL abilities for linear regression tasks are theoretically robust under certain distributional shifts and characterized the corresponding sample complexities.
Existing works on analyzing the ICL ability of transformers for linear regression tasks, however, ignore endogeneity and have mainly focused on the exogenous setup where the additive noise is uncorrelated with the explanatory variables. Ignoring endogeneity in linear regression leads to biased and inconsistent estimates, resulting from issues like omitted variable bias, simultaneity, and measurement error, which can distort causal inferences and lead to incorrect policy conclusions hausman2001mismeasured, wooldridge2015introductory, angrist2009mostly,greene2003econometric. Instrumental variable (IV) regression is a widely adopted method to handle endogeneity by utilizing instruments that are correlated with the endogenous variables but uncorrelated with the error term 10.1257/jep.15.4.69. A naturally intriguing question that therefore arises is:
In this work, we aim to answer this question and offer new insights on in-context linear regression tasks. Our key contributions include:
In-context Learning. Initial works by garg2023transformers and statistician adopted the standard multi-layer transformer architecture to conduct the experiments. Later, giannou2023loopedtransformersprogrammablecomputers and yang2024loopedtransformersbetterlearning showed that a looped architecture reduces the required depth of transformers and exhibits better efficiency in learning algorithms. gao2024expressivepowervariantlooped illustrated that the looped transformer architecture with extra pre-processing and post-processing layers can achieve higher expressive power than a standard transformer with the same number of parameters. Apart from works concerning the implementability of first-order gradient descent algorithms by transformers, other works have also examined higher-order and non-parametric optimization methods. Specifically, giannou2024transformersemulateincontextnewtons showed that transformers can emulate Newton's method for logistic regression. cheng2024transformersimplementfunctionalgradient showed that transformers can implement functional gradient descent and hence enable them to learn non-linear functions in-context. Relationship between in-context learning and Bayesian inference is also studied in ye2024pre,falck2024context.
nichani2024transformerslearncausalstructure illustrated how the transformers can learn the causal structure by encoding the latent causal graph in the first attention layer. goel2024can explored the representational power of transformer for learning linear dynamical systems. makkuva2024local,makkuva2024attention,rajaraman2024transformers,edelman2024evolution considered ICL Markov chains with transformers, including both landscape and training dynamics analyses. To the best of our knowledge, we are not aware of prior works on handling endogeniety with transformers.
Instrumental Variable Regression. IV regression has been widely studied in econometrics 10.1257/jep.15.4.69,angrist2009mostly. Recent works in machine learning explored the optimization based approaches for the IV regression problem. singh2020kernelinstrumentalvariableregression proposed the kernel IV regression to model non-linear relationship between variables. muandet2020dualinstrumentalvariableregression proposed that a non-linear IV regression problem can be formulated as a convex-concave saddle point problem. della2023stochastic,chen2024stochasticoptimizationalgorithmsinstrumental,peixoto2024nonparametric proposed a stochastic optimization algorithm for IV regression.
Notation:\quad Throughout this paper, unless otherwise specified, lower-case letters denote random variables or samples, while upper-case letters represent datasets (collections of samples). Bolded letters indicate vectors or matrices, whereas unbolded letters indicate scalars. The notation $\boldsymbol{X}_{:,i}$ refers to the $i$-th column, and $\boldsymbol{X}_{i,:}$ refers to the $i$-th row of matrix $\boldsymbol{X}$. $\lambda_{\min}(\cdot)$ denotes the minimum eigenvalue, and $\sigma_{\min}(\cdot)$ denotes the minimum singular value of a matrix. By default, $\|\cdot\|$ denotes the Euclidean norm for a vector, or the spectral norm for a matrix.
Suppose we are interested in estimating the relationship between response variable $y \in \mathbb{R}$ and predictor variable $\boldsymbol{x} \in \mathbb{R}^p$ with endogeneity. Given instruments $\boldsymbol{z} \in \mathbb{R}^q$, we consider the model
where $\boldsymbol{\beta}\in\mathbb{R}^{p}$, and $\boldsymbol{\Theta}\in\mathbb{R}^{q\times p}$ are the true model parameters, $\epsilon_1\in\mathbb{R}$ and $\boldsymbol{\epsilon}_2\in\mathbb{R}^{p}$ are (centered) random noise terms with variance $\sigma_1^2$ and covariance matrix $\boldsymbol{\Sigma}_2$, respectively. Further, $\boldsymbol{\epsilon}_2$ is an unobserved noise correlated with $\epsilon_1$, leading to the correlation between $\boldsymbol{x}$ and $\epsilon_1$, which introduces confounding in the model between $\boldsymbol{x}$ and $y$. Under this setting, the standard ordinary least squares (OLS) estimator is a biased and inconsistent estimator of $ \boldsymbol{\beta}$ (see wooldridge2015introductory, Chapter 9). To address this issue, instrumental variable (IV) regression is a widely used method to provide a consistent estimate for $\boldsymbol{\beta}$.
We introduce the standard assumptions required to show the convergence rate of the above estimator.
In particular, condition (i) above ensures the existence of unique solution for $\hat{\boldsymbol{\beta}}_{\textsf{2SLS}}$. We refer to stock2011introduction for additional elaborate discussions on the above conditions. To derive non-asymptotic convergence rates, we further assume the following regularity conditions.
The boundedness condition in (ii) is required to invoke matrix Bernstein inequalities tropp2015introductionmatrixconcentrationinequalities in the analysis. We anticipate that this condition may be relaxed to subgaussian or moment conditions by using more sophisticated matrix concentration results.
We note that although the consistency of the 2SLS estimator is a standard result in econometrics, most existing works focus on the asymptotic properties of the estimator. Theorem (ref) provides the first non-asymptotic bound for estimation error $\|\hat{\boldsymbol{\beta}}_{\textsf{2SLS}}-\boldsymbol{\beta}\|^2$, under random design. The detailed proof is provided in Appendix (ref).
Denote the input matrix as $\boldsymbol{H} = [\boldsymbol{h}_1,\ldots,\boldsymbol{h}_n]\in \mathbb{R}^{D\times n}$, where each column corresponds to one sample vector.
Previous works (e.g., statistician, zhang2023trained) have shown that transformers can perform in-context linear regression by emulating gradient descent (GD) with in-context pretraining. However, these studies have two key limitations. First, their analysis is based on single-level optimization algorithms, which is insufficient to demonstrate that transformers can efficiently learn more complex algorithms like 2SLS (Definition (ref)). Second, most ICL-related research focuses on the predictive performance of transformers, paying little attention to their ability to provide accurate coefficient estimates. We extend the current ICL framework by showing that transformers can implement a bi-level GD procedure (see Section (ref)) with looped transformer architecture (Definition (ref)), allowing them to efficiently emulate 2SLS and provide coefficient estimates that are at least as accurate as 2SLS in the presence of endogeneity (as in (ref)).
We first introduce a gradient-based bi-level optimization procedure to obtain the 2SLS estimator in (ref). Given the dataset $(\boldsymbol{Z},\boldsymbol{X},\boldsymbol{Y})=\{(\boldsymbol{z}_i,\boldsymbol{x}_i, y_i)\}_{i=1}^n$, the objective function of IV regression can be formulated as the following bi-level optimization problem:
Consider the following gradient updates with learning rates $\alpha,\eta$:
Note that the GD-2SLS updates in (ref) are designed to solve (ref). We now show that regardless the convergence of $\boldsymbol{\Theta}^{(t)}$, the GD estimator $\boldsymbol{\beta}^{(t)}$ will always converge to the 2SLS estimator in (ref) with exponential rate.
To the best of our knowledge, Theorem (ref) provides the first theoretical result demonstrating that 2SLS can be efficiently implemented using a gradient-based method, with an exponential convergence rate. We provide the proof in Appendix (ref) and present simulation results in Appendix (ref) to examine the convergence behavior of the optimization process.
The looped transformer architecture (Definition (ref)), as proposed by giannou2023loopedtransformersprogrammablecomputers, introduces an efficient approach to learn iterative algorithms by cascading the same transformer block for multiple times. With the GD updates in (ref), we will show that there exists a looped transformer architecuture that can efficiently learn the 2SLS estimator. We emphasize here that although we can implement 2SLS by sequentially attaching two separate GD iterates (each handling OLS for one stage), the overall convergence depends heavily on the convergence of the first stage estimate $\hat{\boldsymbol{\Theta}}$. Hence, significantly more number of layers are needed to ensure convergence. In addition, the advantage of looped transformer architecture cannot be fully exploited with this approach.
Our existence proof specifies an attention structure such that one layer updates only the first-stage estimate $\hat{\boldsymbol{x}}_i^{(l)}$ for all samples, followed by another layer to update the parameters $\boldsymbol{\Theta}^{(l)}$ and $\boldsymbol{\beta}^{(l)}$. Furthermore, as noted in the proof of Theorem (ref) (ref. Appendix (ref)), regardless of the initial values of $\boldsymbol{\Theta}^{(l)}, \boldsymbol{\beta}^{(l)}$ and $\hat{\boldsymbol{x}}^{(l)}$, the structures of the transformer blocks remain the same. This allows us to exploit the looped transformer architecture to significantly reduce the number of parameters and improve learning efficiency yang2024loopedtransformersbetterlearning.
By cascading the transformer block $\bar{L}$ times, with Theorem $\ref{thm:2SLS GD}$, one can show that transformers are able to mimic the 2SLS estimator with exponential convergence rate, as described in the following corollary.
We emphasize here that our construction differs from the implementation of statistician for OLS in the following aspects:
With slightly abuse of notations, we denote the (formulated) training prompt as:
Note that we denote each training prompt by the subscript $k=1,\ldots,N$, where $N$ is the total number of prompts. Each training prompt consists of $n$ labeled training samples $\{(\boldsymbol{z}_i,\boldsymbol{x}_i,y_i)\}_{i=1}^{n}$, and one unlabeled query sample $(\boldsymbol{z}_{n+1}, \boldsymbol{x}_{n+1})$. Our goal is to predict $y_{n+1}$ given the context provided by the prompt.
We introduce the following ICL data generating scheme such that endogeneity occurs in the training samples, but does not extend to the query sample. Each training prompt is generated by the in-context distribution $\boldsymbol{\mathcal{P}}$, described by Algorithm (ref).
In Algorithm (ref), $\boldsymbol{u}\in\mathbb{R}^{p}$ is the source of endogenous error, $\boldsymbol{w}\in\mathbb{R}^p, {\epsilon}\in\mathbb{R}$ are the exogenous errors. Note that we have $\epsilon_{1,i}=\boldsymbol{\phi}^\top \boldsymbol{u}_{i} + \epsilon_{i}$ and $\boldsymbol{\epsilon}_{2,i}= \boldsymbol{\Phi}^\top \boldsymbol{u}_{i} + \boldsymbol{\omega}_{i}$, corresponding to the notations in (ref). $\boldsymbol{\Theta}\in\mathbb{R}^{q\times p}, \boldsymbol{\beta}\in\mathbb{R}^{p}, \boldsymbol{\Phi}\in\mathbb{R}^{p\times p}, \boldsymbol{\phi}\in\mathbb{R}^{p}, \boldsymbol{\Sigma}_z\in\mathbb{R}^{q\times q}, \boldsymbol{\Sigma}_u\in\mathbb{R}^{p\times p}, \boldsymbol{\Sigma}_\omega\in\mathbb{R}^{p\times p}, \sigma_{\epsilon}\in\mathbb{R}$ are task-specific parameters following meta distribution $\boldsymbol{\pi}$. $\textsf{clip}_{B}(\cdot)$ is a clipping operator to bound the norm of input within radius $B$. We say that the in-context samples $\{(\boldsymbol{z}_i,\boldsymbol{x}_i,y_i)\}_{i=1}^{n+1}$ are drawn from the in-context distribution $\boldsymbol{\mathcal{P}}$, and $\boldsymbol{\mathcal{P}}\sim\boldsymbol{\pi}$ if the task parameters $(\boldsymbol{\Theta}, \boldsymbol{\beta}, \boldsymbol{\Phi}, \boldsymbol{\phi}, \boldsymbol{\Sigma}_z, \boldsymbol{\Sigma}_u, \boldsymbol{\Sigma}_\omega, \sigma_{\epsilon})$ are sampled from $\boldsymbol{\pi}$. One can check that Assumption (ref) and Assumption (ref)(ii)(iii) are directly satisfied with the data generated from the in-context distribution $\boldsymbol{\mathcal{P}}$.
Following the theoretical framework of statistician, we define the population ICL loss\footnote{All the clipping operations are only for analytical purpose. In practice, the behavior of the trained transformer is consistent even without the clipping bounds.}:
where $\boldsymbol{H}^{(0)}$ is the embedded input as defined in (ref), $\textsf{TF}_{\boldsymbol{\theta}}^R$ is the transformer model with parameter $\boldsymbol{\theta}$ and clipping operation $\textsf{clip}_R(\cdot)$ applied to each layer output. For simplicity, we denote $\widetilde{\textsf{TF}}_{\theta}(\boldsymbol{H}):=\textsf{clip}_{B_y}(\textsf{read}_y(\textsf{TF}_{\boldsymbol{\theta}}^R(\boldsymbol{H}^{(0)})))$.
The transformer is trained to minimize the in-context loss in (ref) with the following empirical loss:
We consider the following constrained optimization problem:
where $\left|\!\left|\!\left|\boldsymbol{\theta}\right|\!\right|\!\right|:=\underset{l\in[L]}{\max}\{\underset{m\in[M]}{\max}\{\|\boldsymbol{Q}_m^{(l)}\|, \|\boldsymbol{K}_m^{(l)}\|\}+\sum_{m=1}^M\|\boldsymbol{V}_m^{(l)}\|+\|\boldsymbol{W}_1^{(l)}\|+\|\boldsymbol{W}_2^{(l)}\|\}$.
We now establish excess loss bound for the trained transformer model.
In practical training, the number of prompts $N$ is usually large enough such that the last term of the above bound is negligible. Thus, given a meta distribution $\boldsymbol{\pi}$, the excess loss is dominated by two factors: (i) number of attention layers, and (ii) number of in-context samples. The proof of Theorem (ref) is provided in Appendix (ref).
The primary goal of IV regression is to estimate the causal effect, i.e. the coefficient $\boldsymbol{\beta}$ under the stated endogeneity in (ref). For 2SLS, the estimated causal effect is given by the coefficients of the endogenous variable in the second stage regression ((ref)). For transformer models, we propose a straightforward method to extract these estimated coefficients by differentiating the output with respect to each dimension of the endogenous variable. The specific approach is summarized in Algorithm (ref).
We observe that the choice of $\Delta$ within a reasonable range does not significantly affect the estimation of the coefficients. In practice, usually a slightly larger $\Delta$ (for example $\Delta=5$) can lead to a more stable estimation, which is possibly due to the elimination of rounding errors during computation.
We conduct a simulation study to evaluate the performance of the ICL-pretrained transformer model in handling endogeneity. We set the maximum input sample size to 51 ($n=50$ training samples and one query sample), the dimension of endogenous variable $p=5$, and the dimension of instrument $q=10$. The training prompts are generated using Algorithm (ref), with task parameters $\boldsymbol{\Theta}, \boldsymbol{\beta}, \boldsymbol{\Phi}, \boldsymbol{\phi}$ sampled from standard Gaussian distribution, and the covariance matrices $\boldsymbol{\Sigma}_z, \boldsymbol{\Sigma}_u, \boldsymbol{\Sigma}_\omega$ set to be identity matrices. The noise level $\sigma_\epsilon$ is set to 1. We ignore all the clipping bounds in the experiment ($B_\beta, B_\Theta, B_z, B_x, B_y, B_\theta, R$ set to infinity).
The backbone of the transformer block is initialized using GPT-2 settings, with 12 attention heads $(M=12)$, 80-dimensional embedding space $(D=80)$ and 2 layers $(L_0=2)$, following the theoretical guidelines in Theorem (ref). We employ the looped transformer architecture, consisting of 10 identical cascading transformer blocks. The transformer model is trained under the ICL loss ((ref)) with a batch size of $N=64$, over a total of 300,000 training steps.
We evaluate the trained transformer model on test prompts that are not included during training. As benchmarks, we compare the transformer's performance against the 2SLS and the OLS estimators, which are obtained by directly fitting the training samples $\{(\boldsymbol{z}_{i},\boldsymbol{x}_i,y_i)\}_{i=1}^n$ within the text prompts. In contrast, the same trained transformer model is used without any parameter adjustments for each task. We compare the performance of these models from two aspects: the in-context prediction error (ICPE) on the query sample $y_{n+1}$, and the mean squared error (MSE) on the coefficient $\boldsymbol{\beta}$.
We first investigate the performance of the trained transformer model over endogeneity tasks with varying training sample sizes from 20 to 50. The results are shown in Figure (ref). Under endogeneity, our transformer model achieves similar performance to that of the 2SLS estimator, with only small gaps in ICPE and MSE, both outperforming the OLS estimator.
Next, we examine the performance of the trained transformer model in handling varying levels of IV strength. The strength of an instrument is measured by the correlation between the IV and the endogenous variable. To vary the IV strength, we generate prompts with $\boldsymbol{z}_{i}$ and $\boldsymbol{x}_{i}$ following different correlation levels. Specifically, in Algorithm (ref), we adjust the IV strength by multiplying $\boldsymbol{\Theta}$ by a factor $r\in(0,2)$ when generating test prompts. The results are shown in Figure (ref).
Interestingly, the trained transformer model outperforms the 2SLS estimator in handling weaker IVs (when IV strength $< 0.5$). This suggests that, beyond merely mimicking 2SLS, the ICL training process may equip the transformer model with a more advanced mechanism for handling endogeneity with weak IVs than the 2SLS estimator. At the same time, when the IV is strong, the transformer model maintains performance comparable to that of the 2SLS estimator.
This finding motivates us to further examine the performance of the trained transformer model in non-standard endogeneity tasks. We consider two scenarios: (a) the IV has a quadratic effect on the endogenous variable, i.e. $\boldsymbol{x}_{i,k}=\boldsymbol{\Theta}_k^\top \boldsymbol{z}_{i,k}^2+\textsf{error}_{i,k}$ in Algorithm (ref), and (b) the dimension of IV is not sufficient to identify the endogenous variable\footnote{For 2SLS estimate, the actual computation uses pseudoinverse to handle rank deficiency.}, where we set $q=3$ (by zeroing out the remaining dimensions of $\boldsymbol{z}$ in test prompts) and $p=5$.
We evaluate the same trained transformer model as before, with results presented in Figure (ref) and Figure (ref), respectively. Once again, the trained transformer model consistently outperforms both 2SLS and OLS estimators in handling these non-standard endogeneity tasks. All these results suggest that the trained transformer can be generalized effectively to a broader range of endogeneity tasks while still providing reliable in-context predictions and coefficient estimates. To further illustrate this capability, we also examine other cases including multicollinearity, complex non-linear IV, and varying endogeneity strengths, see Appendix (ref),(ref),(ref). We suspect that, in our pretraining scheme, although the 2SLS estimator already achieves small excess loss, a gap remains between the 2SLS estimator and the optimal predictor that the transformer model successfully bridges. Finally, we conclude that through ICL training, the transformer model performs at least as well as 2SLS and appears to be a promising tool for handling endogeneity in difficult scenarios.
This paper presents a novel perspective on the transformer model in its ability to handle endogeneity in in-context linear regression. We have theoretically shown that the transformer model exists an intrinsic structure that enables it to learn the 2SLS algorithm through an efficient GD procedure. We have further provided a theoretical guarantee that the trained transformer model can achieve a small excess loss over the optimal loss, under our proposed ICL training scheme. Our simulation study demonstrates that the trained transformer model can achieve comparable performance to the 2SLS estimator in handling standard endogeneity tasks. Furthermore, our investigation illustrates that it exhibits significantly better performances in handling complex scenarios such as weak instruments, non-linear IV, and underdetermined IV problems, compared to the 2SLS estimator. These results suggest that the ICL pre-trained transformer model is a promising tool for making reliable in-context predictions and coefficient estimates under endogeneity, especially when dealing with non-standard IV problems.
The work of H. Liang and L. Lai was supported by National Science Foundation (NSF) under grants CCF-2112504 and CCF-2232907. The work of K. Balasubramanian was supported by NSF under grants DMS-2413426 and DMS-2053918.