A transformer can learn a new regression task from examples in its prompt without changing its weights. A well-known explanation is that one attention layer secretly takes one gradient descent step on a least-squares fit to those examples. That explanation assumes the examples are an unordered bag. Real sensor, clinical and trajectory data arrive at irregular timestamps, and the relationship being learned drifts over time. Practitioners handle this by adding a temporal positional encoding, a function of the time gap between tokens that is folded into the attention scores. What in-context algorithm does such a model then run?
Our answer is that time-encoded attention runs time-weighted gradient descent. Each past example is weighted by a kernel of its time lag. Under the softmax and additive time-bias encodings used in practice, a single head can only produce non-negative weights, so it can only average the past. It cannot extrapolate a trend, because extrapolation needs negative weight on older observations. Multiple heads, recombined by signed output projections, can build signed temporal kernels such as a difference of two exponential decays. This turns "multi-head attention can assign negative weights" into "multi-head attention can extrapolate in time." The same signed kernels put more weight on the most recent tokens, so they also make the model easier to derail with a burst of spurious recent readings. We propose to derive this trade-off, test whether trained transformers find the best point on it, and check whether a single head with an unconstrained signed time kernel does just as well. If it does, heads are only one route to signed kernels, not a necessity.
Core Claim
The claim starts from linear attention with a temporal weighting. Suppose each context token $j$ carries an input $x_j$, a label $y_j$ and a timestamp $t_j$, and the query arrives at time $t_q$. A head computes
$$\hat y_q=\sum_{j} \kappa(t_q-t_j)\, x_q^\top \Gamma\, x_j\, y_j ,$$
where $\kappa$ is the head's temporal kernel and $\Gamma$ its learned key-query product. This is exactly the prediction after one step of preconditioned gradient descent from zero on the weighted loss $\sum_j \kappa(t_q-t_j)(y_j-w^\top x_j)^2$, with $\Gamma$ acting as the preconditioner. With $H$ heads and signed output scalars $c_h$, the effective kernel is $\kappa_{\text{eff}}=\sum_h c_h\kappa_h$.
For softmax attention with an additive bias $\phi(\Delta t)$, which is the form used by interval-aware recommenders and clinical transformers, each $\kappa_h$ is non-negative. So $\kappa_{\text{eff}}$ has a negative lobe only if heads are subtracted.
We conjecture, and intend to prove in the linear setting, three things for a target $w(t)$ that drifts smoothly (for example, an integrated random walk) under Poisson-irregular sampling:
- Any non-negative kernel has an error floor that grows with drift speed times the kernel's time scale.
- Two heads with a signed difference of exponentials remove the first-order part of that floor.
- A burst of $k$ spurious tokens at lag near zero shifts the prediction by roughly $k\,\kappa_{\text{eff}}(0)\,\|x\|^2$. This follows the same one-step displacement argument the context-hijacking analysis uses for depth. Because extrapolating kernels have a larger $\kappa_{\text{eff}}(0)$, the optimal kernel under burst noise must trade bias against hijack sensitivity.
Relation to Prior Work
Our method builds on the gradient-descent equivalence. Transformers Learn In-Context by Gradient Descent and Mahankali et al. show that one linear attention layer computes, and at the pretraining optimum equals, one gradient descent step on unordered data. Transformers learn to implement preconditioned gradient descent for in-context learning adds learned preconditioning. We keep their identity and add a time-lag weight.
The closest work is Gating is Weighting. It shows that gated linear attention runs weighted preconditioned gradient descent, with weights set by the gates, but only for multi-task prompts with categorical delimiters. Our weights are continuous functions of irregular time gaps. Our central question, whether non-negativity restricts which weightings are reachable, does not arise there.
Two lines of work motivate the signed-kernel mechanism. Superiority of Multi-Head Attention in In-Context Linear Regression proves that multiple heads beat one head on i.i.d. Gaussian regression because signed output combinations create negative example weights. It also identifies a bottleneck: each head needs dimension at least $d$. We move the same argument from the example axis to the time axis, and we inherit the bottleneck as a constraint on design. Attention-based representations for multi-task computation shows that a single head faces geometric interference when it must perform two competing functions. Here the competing functions are recent-trend extraction and long-horizon averaging.
The noise side is constrained by On the Robustness of Transformers against Context Hijacking for Linear Classification. It proves that per-layer step size scales as $\tilde\Theta(1/(nL))$, so shallow models are easier to hijack. Our burst analysis is the temporal analogue of that result. It predicts something the depth result cannot: at fixed depth, the shape of the kernel alone changes hijack sensitivity.
Two papers on linear dynamical systems bound our scope. On learning linear dynamical systems in context with attention layers finds that one layer on a regular grid tracks gradient descent or preconditioned conjugate gradient. In-Context Learning of Linear Dynamical Systems with Transformers: Error Bounds and Depth-Separation proves that one layer has an $\Omega(1)$ error floor on these systems and that depth $O(\log T)$ is needed. The two results conflict, and we do not claim that heads resolve the conflict. Our core setting is drifting regression with exogenous covariates, which differs from state-space prediction where the covariates are past states. We test the dynamical-system case separately, as a secondary question, without assuming heads close the depth gap.
On the applied side, Transformer Networks for Trajectory Forecasting, DuETT and the interval-bias attention of Exploring Periodicity and Interactivity in Multi-Interest Framework for Sequential Recommendation supply the encodings we analyze. None of them asks what algorithm those encodings induce.
Research Program
The theory has three parts, all in linear attention with temporal weighting:
- Prove the weighted-GD identity for multiplicative time kernels.
- Characterize the optimal one-layer kernel for drifting regression under Poisson sampling, and compare it with the best achievable using $H$ non-negative exponential heads.
- Derive the burst-displacement bound and the bias–sensitivity frontier as a function of the noise rate.
For softmax heads with additive $\phi(\Delta t)$ we will not claim exact equivalence. Instead we will measure the effective kernel empirically, by regressing a trained model's prediction change onto perturbations at each lag.
The empirical program trains small transformers from scratch on synthetic prompts. We vary the head count, the encoding type (additive-bias softmax, sinusoidal-in-embedding, multiplicative signed MLP kernel), the drift smoothness, the sampling irregularity and the burst rate. We then check three things:
- The recovered $\kappa_{\text{eff}}$ develops a negative lobe only when $H\ge 2$ and the drift is smooth.
- That lobe shrinks as the burst rate rises, tracking the predicted frontier.
- Individual heads specialize into distinct decay scales rather than collapsing onto collinear projections.
Baselines
The naive reference is a one-head softmax transformer with an additive time bias, trained identically. Under our theory it should hit the non-negative-kernel error floor.
The oracle is the best weighted least-squares or steady-state Kalman estimator with the drift and noise parameters known. For linear drift under Gaussian noise the Kalman filter is optimal. Following Transformers as Implicit State Estimators, the question is not whether transformers beat it but how close they come without being given the parameters. We report error as a ratio to this oracle.
The strongest competitor on the central question is a single head with an unconstrained signed multiplicative kernel, parameterized by a small MLP of $\Delta t$. It can represent signed kernels without extra heads.
A matched-depth control replaces extra heads with extra layers at equal parameter count. Depth is the mechanism the hijacking and depth-separation results favor.
The ablation that isolates our ingredient keeps multiple heads but forces every $c_h\ge 0$. If the gain comes from signed temporal combination, this ablation should revert to the single-head floor.
All models share the same data stream, token budget, total parameters, and a fixed hyperparameter search of equal size per model. Separate budgets are reported for the multiplicative-kernel model, because its kernel MLP adds parameters. "Beating" a baseline means lower oracle-ratio error on smooth drift at matched burst sensitivity, measured as prediction displacement per injected burst token.
No reported result was found on Lacuna for irregular-time drifting regression. The closest reported numbers are for regular-grid dynamical systems: alignment with preconditioned conjugate gradient above 0.90 cosine similarity, reported in On learning linear dynamical systems in context with attention layers, which we reuse as a regular-grid sanity check.
On PhysioNet 2012 the strongest reported number is SLAN at AUPRC 55.20 (Modelling Irregularly Sampled Time Series Without Imputation). On MIMIC-IV mortality, DuETT reports ROC-AUC 0.912 (DuETT).
Why not just…?
Why not just use a single head with a signed learned time kernel? This is the real threat, and we treat it as a co-hypothesis rather than dismiss it. In linear attention it can represent any $\kappa_{\text{eff}}$ that heads can. If it matches multi-head models at equal budget, the conclusion becomes that the benefit of heads in temporal encoding is entirely the recovery of signed kernels. That is still a useful, falsifiable account of why heads matter. Heads may still win in two places the experiments will reveal. The first is under softmax, where a multiplicative kernel breaks normalization. The second is where the optimal kernel must depend on the data rather than being fixed.
Why not just add depth? Prior theory shows that depth both reduces hijack sensitivity (context hijacking) and removes the single-layer floor for dynamical systems (depth separation). Our matched-parameter depth control settles whether depth also produces extrapolating kernels. We expect stacked non-negative smoothing layers to compose into signed effective kernels only indirectly and at higher cost. If depth wins cleanly, we will report that.
Why not just run a Kalman filter? It needs the dynamics and noise covariances. It is our oracle, not our competitor. The scientific question is which algorithm a trained transformer implements.
Why not just impute onto a regular grid? Imputation destroys informative missingness. On PhysioNet 2012, SLAN beats the imputation model IPNets by 8.9 points absolute. It would also erase the irregular time gaps whose kernel we want to study. We include a forward-fill-plus-regular-positional-encoding transformer on the synthetic task for completeness.
Proposed Experiments
The decisive synthetic experiment sweeps drift smoothness (random walk versus integrated random walk) against burst rate. The predictions are specific:
- The signed-output multi-head model beats both the one-head model and the non-negative-$c_h$ ablation only under smooth drift.
- Its recovered kernel's negative lobe shrinks monotonically as the burst rate rises.
- Measured burst displacement scales with $\kappa_{\text{eff}}(0)$ as the bound predicts.
If none of these appear, the core claim fails.
A secondary experiment reruns the regular-grid dynamical-system setup of On learning linear dynamical systems in context with attention layers (state dimension 5, length 30) with Poisson-jittered timestamps. It asks whether signed temporal kernels narrow the one-layer gap in that regime. We state in advance that the depth-separation theorem may make this a negative result.
For real data, we probe trained multi-head models on PhysioNet 2012, and on ETH+UCY using the public Trajectory-Transformer code. We ask whether heads form signed decay pairs, and whether forcing $c_h\ge 0$ hurts trajectory extrapolation more than mortality prediction. The theory predicts this ordering, because trajectories need extrapolation while mortality prediction mostly needs averaging. The real-data results are diagnostic, not a leaderboard attempt. SLAN's AUPRC of 55.20 is quoted only as context.
References
- Transformers Learn In-Context by Gradient Descent
- One Step of Gradient Descent is Provably the Optimal In-Context Learner with One Layer of Linear Self-Attention
- Transformers learn to implement preconditioned gradient descent for in-context learning
- Gating is Weighting: Understanding Gated Linear Attention through In-context Learning
- Superiority of Multi-Head Attention in In-Context Linear Regression
- Attention-based representations for multi-task computation
- On the Robustness of Transformers against Context Hijacking for Linear Classification
- On learning linear dynamical systems in context with attention layers
- In-context Learning of Linear Dynamical Systems with Transformers: Approximation Bounds and Depth-separation
- Transformer Networks for Trajectory Forecasting
- DuETT: Dual Event Time Transformer for Electronic Health Records
- Exploring Periodicity and Interactivity in Multi-Interest Framework for Sequential Recommendation
- Transformers as Implicit State Estimators: In-Context Learning in Dynamical Systems
- Modelling Irregularly Sampled Time Series Without Imputation