OLS Guarantees and Attention Mechanics in Transformers
Machine LearningModel answerLast updated
Explain when OLS is the best linear unbiased estimator, how correlated features inflate variance, and how attention, positional signals and long-context costs work in Transformers.
This is a two-part conceptual question. Answer it as you would in a technical discussion: give precise conditions, explain why each claim holds, and note trade-offs.
Part 1: Ordinary least squares
You fit a linear model by ordinary least squares on a dataset with $n$ rows and $p$ predictors.
- Which assumptions about the data and the error term must hold for OLS to be the best linear unbiased estimator (BLUE)? Say which assumptions are not needed.
- Suppose several predictors are strongly correlated with one another. What happens to the variance of the estimated coefficients, and why does that make it hard to interpret the effect of any single predictor?
Part 2: Transformers
- Walk through the computation of scaled dot-product attention. Why are the query-key scores divided by $\sqrt{d_k}$, and what would go wrong during training without it?
- Attention by itself does not know the order of tokens. Why must position information be added, and how do fixed sinusoidal additive encodings compare with learned position embeddings, particularly when sequences at test time are longer than those seen in training?
- State the time and memory cost of self-attention as a function of sequence length $L$ and model width $d$. If the context grows to 100,000 tokens, which components become the main bottlenecks, and how can they be mitigated?
Hints
Hint 1
For BLUE, list the conditions on the design matrix and on the error's mean and covariance, then ask which of them is actually used to prove unbiasedness and which to prove minimum variance. Is a Gaussian error needed?
Hint 2
Write the variance of a single coefficient in terms of the R-squared obtained by regressing that predictor on the others, or look at the eigenvalues of X^T X. What happens when one is near zero?
Hint 3
For the scaling factor, assume query and key entries are independent with zero mean and unit variance and compute the variance of their dot product. Then think about the softmax gradient when the output is almost one-hot.
Hint 4
For long context, separately count the cost of the L-by-L score matrix, the arithmetic, and the key/value cache kept during generation. Memory-saving kernels fix some of these but not all.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
The goal is to show you know the exact conditions behind familiar results, not just slogans. Each claim below comes with its reason.
Part 1: Linear regression
1. When OLS is BLUE
Model: $y = X\beta + \varepsilon$, with estimator $\hat\beta = (X^\top X)^{-1}X^\top y$. The Gauss-Markov conditions are:
- Linear in parameters. Features may be nonlinear transforms of the raw inputs (such as $x^2$ or $\log x$), but the model is linear in $\beta$.
- Full column rank. $\operatorname{rank}(X)=p$, so $X^\top X$ is invertible and the solution is unique. This fails under perfect collinearity or when $n<p$.
- Strict exogeneity. $E[\varepsilon\mid X]=0$. This alone gives unbiasedness: $E[\hat\beta\mid X]=\beta+(X^\top X)^{-1}X^\top E[\varepsilon\mid X]=\beta$.
- Spherical errors. $\operatorname{Var}(\varepsilon\mid X)=\sigma^2 I$, meaning constant variance and uncorrelated errors.
Under these, $\operatorname{Var}(\hat\beta\mid X)=\sigma^2(X^\top X)^{-1}$, and no other linear unbiased estimator has a smaller covariance matrix.
Normality is not required. It adds exact finite-sample t and F tests, makes OLS the maximum likelihood estimator, and extends optimality to all unbiased estimators (not only linear ones).
If condition 4 fails, OLS stays unbiased but is no longer best, and the textbook standard errors are wrong. Use GLS or WLS if the error structure is known, or keep OLS with heteroscedasticity-robust (HC) or autocorrelation-robust (HAC) standard errors. If condition 3 fails (omitted variables, measurement error, simultaneity), OLS is biased and you need instruments or a different design.
2. Multicollinearity
For one coefficient:
$$ \operatorname{Var}(\hat\beta_j)=\frac{\sigma^2}{\sum_i (x_{ij}-\bar x_j)^2}\cdot\frac{1}{1-R_j^2}, $$
where $R_j^2$ is from regressing $x_j$ on the other predictors. The factor $\mathrm{VIF}_j=1/(1-R_j^2)$ explodes as $x_j$ becomes predictable from the rest (VIF above roughly 5 to 10 is a common warning).
Spectral view: $(X^\top X)^{-1}=\sum_k \lambda_k^{-1}v_kv_k^\top$, so tiny eigenvalues amplify variance along near-degenerate directions.
Consequences:
- Estimates remain unbiased, but have high variance. Coefficients can change a lot or flip sign between resamples.
- Individual t-tests look insignificant while the joint F-test is strongly significant.
- Interpretation breaks. $\beta_j$ means the effect of $x_j$ holding the others fixed, but if $x_j$ and $x_k$ move together, the data contain almost no examples where one changes and the other does not. The model can pin down a combination such as $\beta_j+\beta_k$ but not how it splits.
- Predictions on data with the same correlation structure remain fine. They degrade if the correlation pattern shifts.
Remedies: drop or combine redundant features, use PCA, or use ridge regression, $\hat\beta=(X^\top X+\lambda I)^{-1}X^\top y$, which raises every eigenvalue by $\lambda$. This caps variance at the price of some bias.
Part 2: Transformers
1. Scaled dot-product attention
With input $X\in\mathbb R^{L\times d}$, compute $Q=XW_Q$, $K=XW_K$, $V=XW_V$, then
$$ \operatorname{Attn}(Q,K,V)=\operatorname{softmax}!\Big(\frac{QK^\top}{\sqrt{d_k}}+M\Big)V. $$
Row $i$ of $QK^\top$ scores query $i$ against every key; a row-wise softmax turns scores into weights summing to 1; the output is the weighted average of value vectors. $M$ is an optional mask (for example $-\infty$ above the diagonal for causal decoding).
Why $1/\sqrt{d_k}$. If query and key entries are independent with mean 0 and variance 1, then $q\cdot k$ has mean 0 and variance $d_k$. For $d_k=128$ the logits have standard deviation of about 11, so softmax becomes nearly one-hot. The softmax Jacobian $\operatorname{diag}(s)-ss^\top$ is close to zero in that regime, so gradients to $Q$ and $K$ vanish and training stalls. Dividing by $\sqrt{d_k}$ returns logits to unit variance regardless of head size.
2. Positional information
Without positions, self-attention is permutation-equivariant: shuffling the input rows shuffles the outputs the same way (and with pooling the result is invariant). "Dog bites man" and "man bites dog" would be indistinguishable, so order must be injected.
Sinusoidal, additive: $PE_{pos,2i}=\sin(pos/10000^{2i/d})$, $PE_{pos,2i+1}=\cos(\cdot)$.
- No parameters; defined at every position.
- $PE_{pos+k}$ is a linear (rotation) function of $PE_{pos}$, so relative offsets are in principle easy to represent.
- In practice extrapolation beyond the training length is weak, and adding position to content entangles the two signals.
Learned absolute embeddings:
- Adapt to the data and often fit slightly better within the training range.
- Have a hard maximum length; positions beyond it have no embedding.
- Late positions are seen rarely and are undertrained.
Practice today: relative schemes. RoPE rotates queries and keys so the score depends on the offset $i-j$. ALiBi adds a distance-proportional penalty to the logits. RoPE is typically extended to longer contexts with position interpolation or NTK/YaRN-style rescaling, plus some long-context fine-tuning.
3. Cost and the 100k-token regime
Per layer:
| Step | Time | Memory |
|---|---|---|
| Q, K, V, output projections | $O(Ld^2)$ | $O(Ld)$ |
| $QK^\top$ | $O(L^2d)$ | $O(L^2)$ per head |
| softmax times $V$ | $O(L^2d)$ | n/a |
| Feed-forward | $O(Ld^2)$ | $O(Ld)$ |
Attention dominates when $L>d$. At $L=10^5$:
- Score matrix: $10^{10}$ entries, about 20 GB in fp16 per head per layer if materialized.
- Compute: FlashAttention tiles the computation so the matrix is never stored (memory becomes $O(L)$), but FLOPs remain $O(L^2d)$, so throughput still suffers.
- KV cache at inference: $2\cdot n_{layers}\cdot L\cdot d\cdot \text{bytes}$. For 32 layers, $d=4096$, fp16, that is about 52 GB per sequence, and decoding becomes memory-bandwidth bound.
- Training activations: need sequence or ring parallelism across devices.
- Data and positions: little training data has true long-range dependencies, and positional schemes must extrapolate.
Mitigations: FlashAttention, grouped-query or multi-query attention to shrink the KV cache, sliding-window or sparse attention, KV quantization or eviction, ring attention, and linear-attention or state-space hybrids.
Common mistakes
- Claiming OLS needs normal errors to be BLUE.
- Saying multicollinearity biases coefficients (it inflates variance).
- Explaining the $\sqrt{d_k}$ factor as "keeping numbers small" without the variance argument and the vanishing-gradient consequence.
- Saying FlashAttention makes attention linear in time; it fixes memory, not FLOPs.
- Forgetting the KV cache when discussing long-context inference.