Manuscript Offprint
arXiv:2611.22941A Transformer-Derived Iterative Preconditioner
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
Transformers trained on in-context prediction problems can learn known numerical algorithms, e.g., gradient descent. We go further, showing that their internal computations can reveal new algorithms with provable guarantees. A softmax-attention transformer trained to solve linear systems implicitly improves matrix conditioning. Tracing reveals an iterative preconditioning primitive, which we develop into RAPID, a standalone algorithm requiring no learned components.
RAPID is an anytime preconditioner for symmetric positive definite (SPD) matrices, using randomized mixing and sparse local corrections to improve conditioning. Proof-of-concept experiments on synthetic and real-world problems consistently improve conditioning and reduce conjugate gradient iterations needed to reach a target accuracy. For a Haar-mixing idealization, we prove convergence to any fixed target condition number regardless of spectral distribution, with only logarithmic dependence on initial conditioning. Together, these results show how a transformer can discover a broadly applicable numerical algorithm.
1 Introduction
Transformers can learn from examples in their input at test time without updating their parameters, a capability known as in-context learning (Brown et al., 2020; Garg et al., 2022). Studies of in-context linear regression have shown that transformers can implement familiar numerical algorithms, including gradient descent, preconditioned gradient descent, and Newton-like methods (Akyürek et al., 2023; Von Oswald et al., 2023; Ahn et al., 2023; Fu et al., 2024). We ask:
Can studying learned transformer computations lead to new, general-purpose numerical algorithms that work independently of the transformer and beyond its training distribution?
We answer affirmatively by uncovering a new preconditioning primitive in a trained transformer’s computations and developing it into a standalone numerical algorithm.
The resulting algorithm: RAPID. Preconditioning is often crucial for efficiently solving symmetric positive definite (SPD) systems . Conjugate gradient (CG) avoids direct factorization, but its convergence depends strongly on the spectrum of (Hestenes and Stiefel, 1952; Saad, 2003). Preconditioners improve convergence by transforming the system into an equivalent, better-conditioned one (Benzi, 2002; Wathen, 2015). Classical approaches often construct approximate factorizations, inverses, or surrogate operators (Meijerink and van der Vorst, 1981; Benzi et al., 1996).
We introduce RAPID (Randomized Anytime Preconditioning by Iterative Dynamics), which improves global conditioning through simple local corrections. Its key idea is to repeatedly randomize the coordinate system, exposing different matrix interactions that can be corrected locally. Specifically, RAPID alternates two steps. First, random orthogonal mixing redistributes matrix interactions without changing the spectrum. Second, each row selects its smallest off-diagonal entry and applies a sparse correction that acts to weaken the selected coupling. Repeating these steps allows local corrections to progressively improve global conditioning without explicitly computing eigenvectors or matrix inverses.
RAPID accumulates these transformations into a preconditioning factor , yielding . Each iteration produces a valid preconditioner, making RAPID an anytime algorithm. Fast structured mixing and sparse corrections enable efficient, highly parallel dense implementations. The underlying update is derived from the trained transformer’s internal computation, as described next.
Algorithm discovery. We train a softmax-attention transformer on in-context linear systems , where need not be SPD. Layerwise orthogonal symmetry interventions (Lutz et al., 2026) allow us to trace the evolution of the Gram matrix during prediction. We observe that its conditioning improves and identify a simple learned congruence update responsible for this effect. Crucially, this update depends only on , allowing RAPID to operate directly on arbitrary SPD matrices without the cost of forming a Gram matrix.
The connection to RAPID follows naturally: the symmetry intervention introduces random rotations, while learned attention applies local corrections that tend to weaken strong matrix interactions. The residual update applies the same row transformation to examples and labels, inducing the congruence update. To obtain an efficient algorithm, RAPID takes the low-temperature limit of softmax to select sparse off-diagonal row-min corrections and replaces dense rotations with fast structured mixing (Yu et al., 2016). The resulting algorithm requires no learned components.
Results and guarantees. We evaluate RAPID on four synthetic spectral families and SuiteSparse SPD matrices, well beyond the transformer’s training distribution. RAPID substantially improves conditioning across all four families and, remarkably, on every SuiteSparse matrix at every tested step count. In contrast, randomized Nyström preconditioning is more sensitive to spectral structure. These improvements also translate into substantially fewer conjugate gradient (CG) iterations to reach a fixed accuracy. Progressive gains with additional RAPID steps illustrate its anytime nature.
Theoretically, we prove that an idealized version of RAPID, using Haar mixing and block-restricted row-min corrections, reaches any fixed target condition number in expected iterations. This holds for any SPD matrix , regardless of its eigenvalue distribution. At this iteration scale, RAPID’s per-step cost of corresponds to near-cubic setup complexity, comparable to classical dense factorization. Unlike direct factorization, however, RAPID can stop early to balance setup cost against preconditioner quality. Although the iteration-complexity guarantee remains limited to an idealized variant, experiments show that its assumptions do not accelerate conditioning on tested spectra, suggesting they facilitate the proof rather than the algorithm’s effectiveness.
Contributions. We make three core contributions:
- We discover a new preconditioning primitive in a trained transformer: a solution-preserving update to the linear system that improves the conditioning of the Gram matrix .
- We develop this mechanism into RAPID, a standalone anytime preconditioner for arbitrary SPD matrices, requiring no learned components and using efficient, parallelizable iterations.
- We establish theoretical and empirical evidence of RAPID’s effectiveness: an idealized variant provably reaches any fixed target condition number for arbitrary SPD matrices, while dense experiments demonstrate broad conditioning gains and substantially faster CG convergence.
Preconditioning for SPD systems. Conjugate gradient (CG) solves SPD systems without direct factorization, but its convergence depends strongly on the spectrum of (Hestenes and Stiefel, 1952; Saad, 2003). Classical preconditioners seek to improve this spectrum through incomplete Cholesky factorizations (Meijerink and van der Vorst, 1981), sparse approximate inverses (Benzi et al., 1996), or algebraic multigrid hierarchies (Vaněk et al., 1996). Rather than constructing such approximations, RAPID iteratively improves conditioning through randomized mixing and sparse local corrections, accumulating a factor with . Each iteration yields a valid SPD preconditioned system, allowing RAPID to stop at any point without requiring a complete factorization or inverse approximation.
Randomized preconditioning and structured transforms. Randomized preconditioners often construct approximations of the original problem. For least squares, sketching methods use subsampled orthogonal transforms or Gaussian projections to build smaller systems for factorization (Avron et al., 2010; Meng et al., 2014); for SPD systems, randomized Nyström methods construct low-rank approximations for preconditioned CG (Frangella et al., 2023). More broadly, fast randomized Hadamard transforms provide efficient alternatives to dense random projections (Ailon and Chazelle, 2009; Le et al., 2013; Yu et al., 2016). RAPID uses fast randomized Hadamard mixing, but applies it repeatedly to expose matrix interactions for sparse local corrections rather than to construct a one-shot approximation.
Learned preconditioners and neural solvers. Recent work has used neural networks to accelerate iterative linear solvers by learning algebraic multigrid components, approximate factorizations, or preconditioners for conjugate-gradient methods (Luz et al., 2020; Li et al., 2023; Trifonov et al., 2026). These approaches evaluate a trained network to construct preconditioners for new systems. In contrast, we use the transformer only to discover a numerical algorithm. Once extracted, RAPID operates directly on arbitrary SPD matrices through explicit randomized updates, without learned components or neural inference at solve time.
Symmetry and equivariance in neural networks. When task symmetries are known, equivariant architectures provide a way to encode them as inductive biases, restricting the learned function class and improving generalization (Cohen and Welling, 2016; Kondor and Trivedi, 2018; Finzi et al., 2021). Layerwise symmetry interventions instead use random, task-preserving coordinate changes to reveal learned transformer computations (Lutz et al., 2026). This technique was originally developed for in-context classification using permutation symmetries; we adapt their identification method to the orthogonal symmetries of linear systems, revealing the conditioning primitive underlying RAPID.
3 Algorithm discovery through in-context learning
In this section, we use a transformer trained on in-context linear systems to discover a numerical preconditioning primitive. We train an attention-only model to predict from examples satisfying , using a layerwise symmetry intervention to make its learned computation identifiable. We extract a two-scalar update that preserves the linear system and evolves the Gram matrix by congruence, substantially improving its conditioning. This primitive motivates RAPID, developed in Section 4 as a standalone SPD preconditioner with no learned components.
3.1 Transformer setup and symmetry intervention
In-context linear systems. Following Garg et al. (2022), we train transformers on synthetic linear systems , where and , . Each task samples and a query with independent standard Gaussian entries, and , then sets . The model observes , but not , and is trained to predict . Since is resampled for every task, prediction requires solving a new instance rather than memorizing a fixed solution.
Transformer architecture. We encode each task as
with the query prediction read from the bottom-right entry of (with a negative sign) after processing through transformer layers. The attention-only transformer applies
where is row-wise softmax and prevents attention to the query token as a key. The model is trained by squared prediction loss, without any supervision on conditioning. Training details are given in Appendix A.1.
Layerwise symmetry intervention. The linear system has an orthogonal symmetry: for any , the group of orthogonal matrices, the transformation
preserves the problem, since and . Thus the same prediction problem can be represented in different example and feature coordinates.
To make the learned computation identifiable, we adapt the layerwise symmetry intervention of Lutz et al. (2026). At each layer, we sample independent , extend them to fix the query and label coordinates as
and evaluate attention in the transformed coordinates before mapping the residual update back:
This is the transformer architecture we train and analyze throughout this section. The intervention discourages reliance on arbitrary coordinate choices, making the learned computation easier to identify, without imposing any conditioning objective or preconditioning algorithm.
3.2 Extracting a conditioning primitive
The transformer achieves increasingly accurate predictions with depth, following an error profile distinct from GD and CG at matched iteration budgets (Appendix A.2). This suggests that the model learns a distinct, nontrivial procedure rather than simply unrolling either classical solver. We therefore examine its trained layers to identify the underlying computation.
Identifying the learned update. The attention layers depend on the weights only through the products and . These products exhibit a simple dominant structure: is concentrated on the feature-feature identity block, while is approximately a scalar identity (Figure 1, left). We therefore approximate each layer by
where and are the mean diagonal entries of the respective identity blocks.
Substituting these approximated weight products into the intervened transformer gives an explicit iteration. Writing for the context state and for its Gram matrix, each layer computes
and updates examples and labels by the same row transformation:
To assess the approximation, we replace the learned weight products in every layer by their two-scalar forms in Eq. (3) and compare predictions against the trained transformer on the same held-out tasks, using identical random rotations. The predictions agree closely (), with a test MSE change of only (Appendix A.3). This confirms that the two-scalar update faithfully reproduces the trained transformer’s predictive behavior.
A solution-preserving congruence update. The key property of Eq. (5) is that it preserves the linear-system relation: if , then . When is invertible, the transformed system has the same solution. Moreover, the Gram matrix evolves by congruence:
Crucially, depends only on and the random rotation , not on the labels or query. Thus the extracted iteration defines a self-contained conditioning mechanism on SPD matrices, independent of the original prediction task.
Empirical conditioning and the learned sign rule. The trained dynamics substantially improve conditioning: the median condition number of decreases from roughly to below at the best layer (Figure 1, right). The two-scalar approximation exhibits similar behavior.
Which layers improve conditioning? We find that layers satisfying
typically reduce the condition number. Across runs, of layers satisfy this rule, and in the median such layer, of test instances experience a condition-number decrease (Appendix A.4).
Together, these results identify a Gram-dependent conditioning primitive within the transformer’s learned prediction procedure. The symmetry intervention provides random coordinate mixing, while the learned attention determines the row corrections. The next section develops this primitive into RAPID by replacing dense rotations and soft attention with efficient structured mixing and sparse updates, yielding a standalone preconditioner without learned components at solve time.

Figure 1: Extracting a conditioning primitive. Left: Representative learned weight products and , showing the dominant two-scalar structure in Eq. (3). Right: Median condition number of the context Gram matrix across layers of the trained transformer, decreasing from roughly to below at the best layer.
4 RAPID: Randomized Anytime Preconditioning by Iterative Dynamics
Section 3 identified a Gram-dependent congruence update learned by a transformer trained only for prediction. We now develop this primitive into RAPID, a standalone preconditioner for explicit SPD systems . RAPID retains random coordinate mixing and row-wise corrections, but replaces dense rotations and soft attention with efficient structured transforms and sparse updates. It requires no trained model or learned parameters at solve time.
4.1 Constructing the RAPID update
Randomized mixing. Starting from , RAPID repeatedly applies an orthogonal change of coordinates,
This preserves the eigenvalues, but exposes different off-diagonal interactions that can be corrected locally. To obtain this mixing efficiently, RAPID replaces dense random rotations with products of randomized Walsh–Hadamard transforms:
where is the normalized Walsh–Hadamard matrix and are independent diagonal matrices with random entries. Such transforms spread information across coordinates similarly to dense random rotations while preserving orthogonality (Ailon and Chazelle, 2009; Le et al., 2013; Yu et al., 2016). For fixed , they cost per vector, rather than for a dense rotation.
From learned attention to sparse row corrections. The learned conditioning rule (7) identifies opposite signs for and , with . RAPID fixes the convention of positive residual steps , corresponding to negative attention scales in the learned model; the opposite convention analogously motivates negative steps with row-maximum selection.
With a negative attention scale, softmax favors smaller entries of the mixed Gram matrix. For computational efficiency, RAPID replaces dense soft attention with selection of the smallest off-diagonal entry in each row:
We exclude the diagonal to target interactions between different rows rather than simply rescaling individual rows. The resulting one-sparse-per-row operator reduces the cost of the congruence update from to . This sparsification is a design choice motivated by the learned attention.
Writing , RAPID applies
This retains the congruence structure of the learned iteration, now with an explicit sparse row operator.
Why does this improve conditioning? The intuition is clearest for a matrix with a single exceptional eigenvalue. Consider , where , , and , so all eigenvalues equal except . Adding a small positive fraction of row to row , together with the corresponding column operation, changes the exceptional eigenvalue to first order by
Thus, for sufficiently small , a negative moves toward : decreasing it when and increasing it when . Random mixing can expose negative off-diagonal entries even when none are present initially, and row-minimum selection favors such entries when available. For general matrices, individual corrections need not improve conditioning; Section 6 establishes a global guarantee for an idealized variant. The first-order calculation is detailed in Appendix C.9.
Step-size selection. Each row of selects one column, but multiple rows may select the same column. Let
denote the maximum column load. Since , we use
where is a tunable scale. This keeps the overall update magnitude independent of the column load, controlling the effect of simultaneous row corrections. Section 6 provides a complementary motivation based on the expected improvement in conditioning.
4.2 RAPID as an anytime preconditioner
Accumulating the preconditioner. RAPID maintains a factor satisfying
Thus the random basis changes are accumulated rather than reversed after each correction.
To ensure a valid preconditioner at every iteration, we choose so that . Indeed, is row-stochastic, so its eigenvalues have magnitude at most . Hence is invertible whenever . Each congruence update therefore preserves positive definiteness.
After any iterations, RAPID produces the equivalent SPD system
which can be solved using conjugate gradients. Since every iteration yields a valid factor , RAPID is an anytime preconditioner: the iteration budget trades setup cost against the conditioning achieved. The factor can also be reused for multiple right-hand sides.
Complete algorithm. Algorithm 1 summarizes the practical RAPID iteration, using structured orthogonal mixing and row-minimum selection.
Algorithm 1 RAPID: Practical preconditioning algorithm
1: Input: , iterations , mixer depth , scale
2:
3: for do
4: Draw via (8); random mixing
5: defined as in (9) row selection
6: ; \alpha_{t}\leftarrow s_{\alpha}/\sqrt{m_{t}d\log d}$$\triangleright compute step-size
7: sparse correction
8: ; update operator
9: end for
10: return P_{T},A_{T}$$\triangleright verifies
Computational cost and theoretical scope. Row-minimum selection and the sparse congruence update each cost . Applying a fixed number of Walsh–Hadamard transforms to a dense matrix costs , which dominates the per-iteration complexity. These operations are highly parallelizable and require no matrix factorization. For dimensions that are not powers of two, the implementation uses padding (Appendix B).
Section 5 evaluates the practical algorithm, while Section 6 analyzes a related variant using Haar mixing and block-restricted row selection.
5 Experimental Evaluation
In this section, we show that RAPID improves conditioning across SPD matrices well beyond the transformer’s training distribution, and that these improvements translate into faster CG convergence. We use the practical algorithm of Section 4, with Walsh–Hadamard mixing and global row-minimum selection. No trained model is used in these experiments.
Experimental protocol. We generate synthetic matrices , with Haar-random , dimension , and condition number . We consider four distinct spectral distributions: Chebyshev, linear, logarithmic, and power-law, with independent matrices per family. We also evaluate SPD matrices from SuiteSparse (Kolodziej et al., 2019), selected independently of RAPID’s performance by dimension () and post-Jacobi condition number (–). All matrices are treated as dense operators. Details appear in Appendix B.
After Jacobi scaling, we compare RAPID () with randomized Nyström preconditioning (Frangella et al., 2023), which uses a one-shot low-rank approximation rather than RAPID’s iterative congruence updates (sketch sizes – of ). We report condition numbers relative to the Jacobi-scaled matrix and CG iterations relative to Jacobi-preconditioned CG. All methods use the same right-hand side and stopping criterion , evaluated in the original Jacobi-scaled coordinates, ensuring a common accuracy target.
Figure 2: Conditioning and CG convergence across synthetic and real-world SPD matrices. Top: condition number relative to the Jacobi-scaled system. Bottom: CG iterations required to reach the common residual tolerance, relative to Jacobi-preconditioned CG. Lower is better in both rows. Blue curves show RAPID means and shaded bands the minimum and maximum; dashed lines show mean Nyström results at different sketch sizes. Each synthetic panel contains independent matrices; SuiteSparse contains . The corresponding absolute values are reported in Appendix B.
Broad improvements in conditioning. Figure 2 (top) shows that RAPID substantially improves conditioning across all four spectral families. In contrast, Nyström is strongly dependent on the eigenvalue distribution: it is particularly effective on the logarithmic spectrum, but achieves much smaller improvements on Chebyshev and linear spectra, even with large sketches. Remarkably, at every tested step count , RAPID reduces the condition number of all 31 SuiteSparse matrices, not just the average. These results demonstrate that RAPID generalizes well beyond the Gaussian Gram matrices used during transformer training.
Fewer CG iterations at fixed accuracy. Figure 2 (bottom) shows that RAPID’s conditioning gains also translate into substantially fewer CG iterations to reach the same accuracy, across all four synthetic families and, on average, across SuiteSparse matrices. This is significant because CG convergence depends on the full spectrum, not just the condition number. Thus, RAPID not only improves conditioning broadly, but also makes these systems easier to solve iteratively. All solvers reached the target accuracy, except for Nyström preconditioning with a sketch which failed on a single SuiteSparse instance.
Practical considerations. The progressive improvements with increasing illustrate RAPID’s anytime nature, allowing a trade-off between setup cost and preconditioner quality. A RAPID step costs , matching a dense CG iteration up to logarithmic factors. In practice, RAPID can be more expensive per step, as its operations do not benefit from the same highly optimized GPU implementations available for CG’s matrix–vector products. The setup cost may nevertheless pay off through fewer CG iterations, especially when amortized across multiple right-hand sides. A definitive runtime comparison requires optimized implementations of both methods and is left for future work.
6 Analyzing the Extracted Preconditioner
We analyze an idealized version of RAPID using two simplifications relative to Algorithm 1: (i) Haar-random mixing, which enables an exact calculation of a certain expected ‘row-min drift’ term, and (ii) block-restricted row selection, which bounds the maximum column load of . These assumptions enable our proof, but are not required by the practical algorithm. We first establish the conditioning guarantee, then examine the empirical effect of both simplifications.
6.1 Conditioning guarantee under simplifying assumptions
Our proof tracks a smooth approximation to the log-condition number and shows that it decreases in expectation until the matrix becomes well-conditioned. The key is to balance two effects: the favorable first-order drift induced by row-min selection, and a second-order error that depends on how many rows select the same column. Haar mixing allows us to characterize the drift, while blocking controls the error.
Specifically, we take and replace the global row-min operator with a block-restricted version. Partition the indices into blocks of size at most , and let denote the block containing . Define
Here is the block size; setting recovers the original global row-min operator . By restricting selection to each row’s block, we ensure that no column is selected more than times. We now establish the two bounds and combine them to obtain the conditioning guarantee. Full proofs appear in Appendix C.
Potential Function & First-order analysis. To measure progress toward a well-conditioned matrix, we construct the following potential function:
where . This scale and basis invariant potential essentially corresponds to the log of the ratio of a softmax and softmin of the spectrum (with temperature ) and satisfies
We will set below, making the approximation error constant. The key lemma capturing the decay of this potential arises from a Taylor expansion, where the curvature term is controlled by submultiplicativity of Schatten -norms.
Lemma 1.
Let be the maximal column load of the matrix . If then
where
Row-min drift. The key question is whether the first-order term is negative in expectation, so that it outweighs the second-order growth. Haar mixing allows us to characterize this term exactly.
Lemma 2.
Suppose independently of the history, and that . Then
where and depends on the spectral properties of and . In particular, if and then
is a measure of the correlation of spectrum of with its th power. The lemma guarantees a negative first-order drift of magnitude when . This bound is conservative: can be as large as when or has a highly spiked spectrum (Appendix C.8).
Main Result. With control on both the drift and the second order growth, as long as , and the column-load is not too large, we can observe a decay in the potential . Notice that this column load is directly controlled by using since due to the blocking structure, each column can have at most ones. Exploiting this yields a concrete bound on which allows us to control the expected time to conditioning.
Theorem 3.
Suppose , and with . Let and set Let . Then
Thus, the idealized RAPID variant achieves conditioning in expected iterations, with logarithmic dependence on the initial condition number (see Appendix C). The proof uses the pessimistic bound ; more favorable spectra can yield faster conditioning and permit larger step sizes.
Practical step size without blocking. Balancing the negative drift of Lemma 2 against the second-order term of Lemma 1 suggests that we should choose to to maximize the expected gain. While is easily computed, depends on the spectrum and is difficult to estimate. The proof therefore controls through blocking and uses a worst-case bound on . Empirically, however, we observe even with global row selection, across diverse spectra and dimensions (Appendix C.10). This suggests the practical step-size rule , which we use in our experiments.
Beyond Haar mixing. The Taylor bound of Lemma 1 and the spectral bound on do not depend on the mixing distribution. Haar mixing is used only to establish the exact expected-drift identity (15), exploiting its rotational symmetry to characterize the effect of row-min selection. Randomized Walsh–Hadamard transforms also spread information across coordinates, but lack full rotational symmetry, making the drift harder to characterize. Extending the guarantee to randomized Walsh–Hadamard mixing would therefore require a corresponding drift bound, which remains open (see Appendix C.7).
6.2 Empirical role of the simplifying assumptions
Theorem 3 assumes Haar mixing to compute the expected drift and block-restricted row minima to bound the column load. We test whether these assumptions also improve empirical conditioning. Both comparisons use synthetic matrices with and initial .
Fast mixing. We compare Haar rotations with randomized Walsh–Hadamard transforms, using identical initial matrices, global row selection, and step-size rules. Across trials per spectral family, Table 2 shows that the final condition numbers after steps differ by at most . Thus, fast structured mixing achieves essentially the same conditioning as Haar mixing.
Global versus block row selection. We compare the practical global selector (9) with block-restricted selection (14) (block size ), using identical Walsh–Hadamard mixing sequences. The global variant uses , while the blocked variant uses . Table 2 shows that both improve conditioning, but the practical configuration achieves substantially larger reductions. Results are averaged over trials; standard deviations are below percentage points everywhere.
Table 1: Haar versus Walsh–Hadamard mixing. Final condition numbers after steps (mean standard deviation).
| Spectrum | Haar | Walsh–Hadamard |
|---|---|---|
| Chebyshev | ||
| Linear | ||
| Log | ||
| Power-law |
Table 2: Global versus block row minima. Mean condition-number reduction (%).
| Spectrum | Global | Block | Global | Block |
| Chebyshev | 43.1 | 1.0 | 98.8 | 26.6 |
| Linear | 56.2 | 6.5 | 99.6 | 37.8 |
| Log | 71.5 | 16.2 | 98.7 | 55.0 |
| Power-law | 54.5 | 8.2 | 98.8 | 38.2 |
Together, these results show that the simplifying assumptions used in our proof are not needed for effective conditioning in practice: fast mixing matches Haar, while the practical global configuration substantially outperforms blocking. Establishing a theoretical guarantee for the practical algorithm remains open.
7 Conclusion
We introduced RAPID, an anytime SPD preconditioner derived from a conditioning mechanism discovered in a transformer trained for in-context learning. The extracted update preserves the linear-system relation and evolves its Gram matrix by congruence. RAPID turns this mechanism into a standalone algorithm combining randomized mixing and sparse row corrections, accumulating a preconditioner . The transformer provides only the algorithmic primitive; RAPID requires neither model inference nor learned parameters at solve time. For an idealized Haar-mixing, block-restricted variant, we prove convergence to any fixed condition-number target for arbitrary SPD matrices, with near-linear dependence on dimension and logarithmic dependence on initial conditioning. Experiments with practical RAPID show broad conditioning improvements and reduced CG iteration counts on synthetic and SuiteSparse matrices.
Several challenges remain. Extending the convergence guarantee to practical Walsh–Hadamard mixing and global row-minimum selection would close the gap between theory and implementation. Establishing competitive end-to-end runtime requires optimized implementations and careful accounting of setup costs, particularly when amortized across multiple right-hand sides. Finally, extending RAPID to sparse and matrix-free systems will require avoiding explicitly formed dense mixed matrices. More broadly, RAPID illustrates how studying learned transformer computations can lead to independent numerical algorithms that apply well beyond the original learning task.
Acknowledgments
This research was supported by the National Science Foundation grant CPS-2317079.
References
K. Ahn, X. Cheng, H. Daneshmand, and S. Sra Transformers learn to implement preconditioned gradient descent for in-context learning. In Advances in Neural Information Processing Systems, A. Oh, T. Naumann, A. Globerson, K. Saenko, M. Hardt, and S. Levine (Eds.), Vol. 36, pp. 45614–45650. External Links: Link Cited by: §1, §2.
N. Ailon and B. Chazelle The fast johnson–lindenstrauss transform and approximate nearest neighbors. SIAM J. Comput. 39 (1), pp. 302–322. External Links: Link, Document Cited by: §2, §4.1.
E. Akyürek, D. Schuurmans, J. Andreas, T. Ma, and D. Zhou What learning algorithm is in-context learning? investigations with linear models. In The Eleventh International Conference on Learning Representations, External Links: Link Cited by: §1, §2.
H. Avron, P. Maymounkov, and S. Toledo Blendenpik: supercharging LAPACK’s least-squares solver. SIAM Journal on Scientific Computing 32 (3), pp. 1217–1236. External Links: Document Cited by: §2.
M. Benzi, C. D. Meyer, and M. Tŭma A sparse approximate inverse preconditioner for the conjugate gradient method. SIAM Journal on Scientific Computing 17 (5), pp. 1135–1149. Cited by: §1, §2.
M. Benzi Preconditioning techniques for large linear systems: a survey. Journal of Computational Physics 182 (2), pp. 418–477. External Links: Document Cited by: §1.
T. Brown, B. Mann, N. Ryder, M. Subbiah, J. D. Kaplan, P. Dhariwal, A. Neelakantan, P. Shyam, G. Sastry, A. Askell, et al. Language models are few-shot learners. Advances in neural information processing systems 33, pp. 1877–1901. Cited by: §1.
T. Cohen and M. Welling Group equivariant convolutional networks. In International conference on machine learning, pp. 2990–2999. Cited by: §2.
T. Dao Fast hadamard transform in cuda, with a pytorch interface. External Links: Link Cited by: Appendix B, §D.1.
M. Finzi, M. Welling, and A. G. Wilson A practical method for constructing equivariant multilayer perceptrons for arbitrary matrix groups. In International conference on machine learning, pp. 3318–3328. Cited by: §2.
Z. Frangella, J. A. Tropp, and M. Udell Randomized Nyström preconditioning. SIAM Journal on Matrix Analysis and Applications 44 (2), pp. 718–752. External Links: Document Cited by: §2, §5.
D. Fu, T. Chen, R. Jia, and V. Sharan Transformers learn to achieve second-order convergence rates for in-context linear regression. Advances in Neural Information Processing Systems 37, pp. 98675–98716. Cited by: §1, §2.
S. Garg, D. Tsipras, P. S. Liang, and G. Valiant What can transformers learn in-context? a case study of simple function classes. In Advances in Neural Information Processing Systems, S. Koyejo, S. Mohamed, A. Agarwal, D. Belgrave, K. Cho, and A. Oh (Eds.), Vol. 35, pp. 30583–30598. External Links: Link Cited by: §1, §2, §3.1.
M. R. Hestenes and E. Stiefel Methods of conjugate gradients for solving linear systems. Journal of Research of the National Bureau of Standards 49 (6), pp. 409–436. Cited by: §1, §2.
S. P. Kolodziej, M. Aznaveh, M. Bullock, J. David, T. A. Davis, M. Henderson, Y. Hu, and R. Sandstrom The suitesparse matrix collection website interface. Journal of Open Source Software 4 (35), pp. 1244. Cited by: Appendix B, §5.
R. Kondor and S. Trivedi On the generalization of equivariance and convolution in neural networks to the action of compact groups. In International conference on machine learning, pp. 2747–2755. Cited by: §2.
Q. Le, T. Sarlós, and A. Smola Fastfood-approximating kernel expansions in loglinear time. In Proceedings of the international conference on machine learning, Cited by: §2, §4.1.
Y. Li, P. Y. Chen, T. Du, and W. Matusik Learning preconditioners for conjugate gradient pde solvers. In International Conference on Machine Learning, pp. 19425–19439. Cited by: §2.
P. Lutz, A. Gangrade, H. Daneshmand, and V. Saligrama Linear transformers implicitly discover unified numerical algorithms. In The Thirty-ninth Annual Conference on Neural Information Processing Systems, External Links: Link Cited by: §2.
P. Lutz, T. Haris, A. Chandra, A. Gangrade, and V. Saligrama Layerwise dynamics for in-context classification in transformers. arXiv preprint arXiv:2604.11613. Cited by: §1, §2, §3.1.
I. Luz, M. Galun, H. Maron, R. Basri, and I. Yavneh Learning algebraic multigrid using graph neural networks. In International Conference on Machine Learning, pp. 6489–6499. Cited by: §2.
J. Meijerink and H. A. van der Vorst Guidelines for the usage of incomplete decompositions in solving sets of linear equations as they occur in practical problems. Journal of computational physics 44 (1), pp. 134–155. Cited by: §1, §2.
X. Meng, M. A. Saunders, and M. W. Mahoney LSRN: a parallel iterative solver for strongly over- or underdetermined systems. SIAM Journal on Scientific Computing 36 (2), pp. C95–C118. External Links: Document Cited by: §2.
Y. Saad Iterative methods for sparse linear systems. SIAM. Cited by: §1, §2.
V. Trifonov, A. Rudikov, O. Iliev, Y. M. Laevsky, I. Oseledets, and E. Muravleva Learning from linear algebra: a graph neural network approach to preconditioner design for conjugate gradient solvers. Computational Methods in Applied Mathematics. Cited by: §2.
P. Vaněk, J. Mandel, and M. Brezina Algebraic multigrid by smoothed aggregation for second and fourth order elliptic problems. Computing 56 (3), pp. 179–196. Cited by: §2.
A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, L. Kaiser, and I. Polosukhin Attention is all you need. In Advances in Neural Information Processing Systems, Vol. 30. Cited by: §A.1.
M. Vladymyrov, J. von Oswald, M. Sandler, and R. Ge Linear transformers are versatile in-context learners. In Advances in Neural Information Processing Systems, Cited by: §2.
J. Von Oswald, E. Niklasson, E. Randazzo, J. Sacramento, A. Mordvintsev, A. Zhmoginov, and M. Vladymyrov Transformers learn in-context by gradient descent. In Proceedings of the 40th International Conference on Machine Learning, A. Krause, E. Brunskill, K. Cho, B. Engelhardt, S. Sabato, and J. Scarlett (Eds.), Proceedings of Machine Learning Research, Vol. 202, pp. 35151–35174. External Links: Link Cited by: §A.1, §1, §2.
J. Wang, E. Blaser, H. Daneshmand, and S. Zhang Transformers can learn temporal difference methods for in-context reinforcement learning. In International Conference on Learning Representations, Vol. 2025. Cited by: §2.
A. J. Wathen Preconditioning. Acta Numerica 24, pp. 329–376. Cited by: §1.
Q. Ye, D. Fu, R. Jia, and V. Sharan Transformers provably learn algorithmic solutions for graph connectivity, but only with the right data. In Proceedings of the 43rd International Conference on Machine Learning, Cited by: §2.
F. X. X. Yu, A. T. Suresh, K. M. Choromanski, D. N. Holtmann-Rice, and S. Kumar Orthogonal random features. Advances in neural information processing systems 29. Cited by: §1, §2, §4.1.
R. Zhang, S. Frei, and P. L. Bartlett Trained transformers learn linear models in-context. Journal of Machine Learning Research 25 (49), pp. 1–55. External Links: Link Cited by: §2.
Appendix A Supplementary material for Section 3
A.1 Transformer architecture and training details
This appendix specifies the training setup used for the in-context regression experiments in Section 3.1. We train attention-only transformers on noiseless synthetic linear regression instances. Unless stated otherwise, the experiments use covariates and tokens: context examples and one query example.
Data distribution.
For each batch element, we sample
and set
The factor is a normalization convention; equivalently, the effective regression coefficient has covariance . The model input is
and the loss is the squared error on the query label only,
The implementation reads the prediction from the bottom-right entry of the final token matrix with the same negative-output convention as Von Oswald et al. [2023]: . Fresh inputs and fresh regression coefficients are resampled at every training iteration.
Architecture.
We use a residual attention-only transformer with no feed-forward blocks. Each layer has one attention head and embedding dimension . For , layer computes
where
All linear projections are bias-free. The matrices are initialized with Xavier uniform initialization, while the output projection is initialized at zero. Thus the initial network is the identity map through the residual connection. For notational simplicity, we absorb the factor commonly present in the attention architecture [Vaswani et al., 2017] into the attention weights.
The attention mask removes the query token as a key/value:
Thus every token may attend to the labeled context examples, but no token may attend to the query token. The query row is therefore used only as the prediction site.
Attention-logit clipping.
For numerical stability and to avoid nearly one-hot attention early in training, we clip attention logits after centering each attention row. Let
denote the unmasked attention score, and let be the set of allowed (non-masked) keys under the attention mask. Before the softmax, we replace each allowed score by
and keep masked scores equal to . Hence the largest allowed logit in each row is zero, and all allowed logits are lower bounded by . This bounds the maximum probability ratio between two allowed tokens by . We found this clipping useful for numerical stability when training deep models.
Symmetry augmentation.
The reported training runs use the symmetry-augmented implementation. At each layer and for each forward pass, we draw independent Haar orthogonal matrices and , extend them by a fixed final row/column, and apply the attention block in the transformed coordinates:
The attention update is then rotated back before being added residually to . This augmentation preserves the distinguished query row and label coordinate while randomizing the basis of the context examples and features.
Optimization.
We train each model with AdamW for steps using batch size , learning rate , , no weight decay, and global gradient clipping at norm . The learning rate is linearly warmed up for the first steps and then held fixed. We resample both the covariates and regression coefficient at every step. We train ten independent runs for each depth
and use the depth- models for the extraction analysis unless otherwise specified.
Training curves.
Figure 3 reports the training loss for the depth- models used in the extraction analysis. Thin curves show individual runs; the thick curve shows the mean across runs, with the shaded band denoting the central interval.
Figure 3: Training curves for depth- transformers. The loss is the squared error on the query prediction. Inputs and regression coefficients are resampled at every optimization step.
A.2 Behavioral diagnostics
We evaluate the trained symmetry-intervened transformers in the square linear-system setting. For each depth , GD and CG are run for iterations from zero. GD uses a fixed stepsize selected separately for each iteration budget from 60 logarithmically spaced values in , minimizing query-prediction MSE on 4,096 validation tasks. Results are evaluated on 4,096 independent test tasks.
Prediction error.
Figure 4 (left) shows that test MSE decreases with model depth. The error profile differs from GD and CG at matched iteration budgets, suggesting that the transformer does not simply reproduce either classical solver.
Spectral inverse-kernel diagnostic.
For each fixed context , we probe the endpoint with random queries and fit the best linear query map
We then express in the eigenbasis of . Since exact OLS satisfies
the ideal gain in eigendirection is . The plotted gain is the zero-intercept slope mapping to , after pooling eigendirections across contexts and binning by :
Figure 4 (right) shows that the fitted gain approaches the OLS response as depth increases, including at small eigenvalues. Thus the transformer increasingly captures the full inverse spectral response rather than only the well-conditioned directions.
Figure 4: Prediction behavior across transformer depths. Left: Test MSE decreases with model depth, following a profile distinct from GD and CG at matched iteration budgets. Right: The fitted endpoint spectral gain approaches the OLS response across eigendirections of , including small eigenvalues.
Linearity of the query map.
This spectral diagnostic is meaningful only if, for fixed context, the endpoint is well approximated by a linear function of the query. We check this by plotting the squared residual fraction
As shown in Figure 5 (right), this residual fraction decreases with depth and is below at depth . Thus the fitted linear query map explains more than of the transformer’s prediction energy on the probe queries, validating the spectral-filter interpretation for the depth- models.
Figure 5: Additional behavioral diagnostics. Left: Pearson correlations between centered residual-error vectors on shared test tasks. Transformer runs remain more aligned with each other than with GD or CG. Right: Squared residual fraction of the best linear query-to-prediction map for each context. The small residual at depth supports the spectral-filter interpretation.
Residual-error alignment.
To compare failure modes, we compute the centered residual-error vector
on a shared test set, and report Pearson correlations between such vectors. Transformer-Transformer (TF-TF) alignment is computed by splitting trained transformer runs into two groups and correlating the group-averaged residuals; TF-GD and TF-CG compare the same transformer averages to GD and CG. As shown in Figure 5 (left), TF-TF alignment remains high at depth (), while TF-GD and TF-CG fall below . Thus independently trained transformers share a stable residual structure that is not well explained by either classical baseline.
A.3 Extracted iteration and fidelity diagnostics
We describe the two-scalar approximation used in Section 3.2. For each trained layer, let
We approximate these products as
Here is the mean diagonal entry of the feature-feature block of , and is the mean diagonal entry of the feature-feature block of . In the projected value map, the label coordinate is tied to the same scalar , giving the two-scalar template used in the main text. All off-diagonal entries and all entries involving the label coordinate are discarded.
Write the full state as
Under the symmetry intervention, the layer applies attention in a randomly rotated context basis and then rotates the update back. With the projected weights, the context attention is
and the corresponding context update is
Thus the projection gives the row-side iteration used in the main text. The same projected layer also updates the query row and readout. If
is the query-to-context attention row, then
Fidelity of the projection.
We evaluate the projection by comparing the original depth- transformer and the projected iteration on the same held-out tasks, using the same random rotations in both forward passes. Predictions are pooled across evaluation tasks and trained runs. The reported is the squared Pearson correlation between the original transformer predictions and the projected-iteration predictions:
The MSE change is computed on the same pooled predictions as
The projection preserves the trained model closely: , and the test MSE changes by only . Figure 6 shows the corresponding prediction-level agreement.
Figure 6: Fidelity of the projected iteration. Each point compares the original depth- transformer prediction with the prediction from the two-scalar projected iteration on the same held-out task. The high shows that the low-dimensional projection captures the dominant predictive behavior of the trained model.
A.4 Conditioning behavior and the layerwise sign rule
This appendix gives the empirical evidence behind the preconditioning interpretation in Section 3.2. The main questions are: (i) does the extracted iteration actually improve conditioning layer by layer, and (ii) when does a layer act as a conditioning step?
Conditioning under the extracted and projected iterations.
Figure 7 compares the conditioning trajectories of the trained depth- transformer and its two-scalar approximation. In both cases, the median condition number of decreases from above to below at the best layer. Thus the low-dimensional approximation captures the conditioning behavior of the trained model.
The right panel shows that most learned step sizes are close to . Since the softmax matrix is row-stochastic, guarantees that is invertible, preserving positive definiteness under the congruence update. The learned values suggest that the model prefers large residual steps within this invertibility range.
Both trajectories exhibit occasional increases in condition number, particularly near the final layers. This is consistent with the transformer being trained for best final prediction at fixed depth, rather than for monotone conditioning at every intermediate layer.
Which layers condition?
Empirically, layers tend to reduce the condition number when their parameters satisfy
For example, when and , attention favors smaller entries of the mixed Gram matrix, which receive positive weight in the residual update. Figure 8 compares this rule with the observed layerwise conditioning trajectories.
Across runs, of layers satisfy the rule, and in the median such layer, of test instances decrease their condition number. Thus the learned parameters provide a useful empirical indicator of conditioning steps, although the rule does not guarantee a decrease on every instance.
Figure 7: Conditioning overview. Left: Condition number of across layers of the trained transformer. Center: The corresponding trajectory under the two-scalar approximation. Both reduce the median condition number from above to below at the best layer. Right: Distribution of learned step sizes , most of which lie close to the sufficient invertibility threshold .
Figure 8: Layerwise sign rule and conditioning. Layerwise condition numbers compared with the empirical criterion and . Layers satisfying this rule typically decrease the condition number.
Appendix B Additional Experimental Details
Synthetic matrices. We generate , where is Haar-random orthogonal and has one of four spectra, defined for :
We set the spectral endpoints to and and use , with independent draws per family.
SuiteSparse matrices. We use SPD matrices from the SuiteSparse Matrix Collection [Kolodziej et al., 2019], selected by dimension () and post-Jacobi condition number (–), independently of RAPID’s performance. The selected instances, grouped by collection, are:
Boeing: msc00726, msc01440;
Cannizzo: sts4098;
Cylshell: s1rmq4m1, s1rmt3m1;
HB: 1138_bus, 494_bus, 662_bus, 685_bus, bcsstk03, bcsstk04, bcsstk05, bcsstk06, bcsstk07, bcsstk08, bcsstk09, bcsstk10, bcsstk13, bcsstk14, bcsstk15, bcsstk21, bcsstk22, bcsstk26, bcsstk27, bcsstm12, lund_a, nos3, nos5;
Nasa: nasa1824, nasa2910;
TKK: plbuckle.
All matrices are converted to dense form. We normalize by an estimate of the largest eigenvalue (20 power iterations) and apply Jacobi scaling. For each matrix, we sample an independent Gaussian right-hand side before applying the same coordinate scaling.
RAPID implementation. We implement RAPID on the GPU using PyTorch/Triton and fast Walsh–Hadamard transforms [Dao, 2024]. We use one randomized Hadamard mixing stage (), global row-minimum selection, and . A single mixing stage suffices in practice, as repeated RAPID iterations progressively mix the coordinates. The row-selection kernel finds the smallest off-diagonal entry in each row and computes the maximum column multiplicity . A parallel Triton kernel then applies the congruence update entrywise:
where . We accumulate the transformation as in Section 4 to recover solutions in the original coordinates. Non-power-of-two dimensions are padded to the next power of two with an identity block; the right-hand side is padded with zeros. We evaluate RAPID after steps.
Nyström preconditioning. For each sketch fraction , we use a Gaussian sketch of rank , orthonormalized by QR. We form and , then construct a stabilized Nyström approximation using Cholesky and eigendecomposition. Its approximate eigenvectors and positive eigenvalue estimates define the preconditioner
We apply within preconditioned CG.
CG and evaluation. All solves use a common GPU float32 CG implementation, initialized at zero, with at most iterations. The true relative residual is checked every iterations, after recovering the solution in the Jacobi-scaled reference system . Convergence requires
Condition numbers are computed from the extreme eigenvalues of the transformed matrices. Figure 2 reports condition numbers and CG iteration counts relative to the Jacobi baseline, with means and minimum-maximum ranges for RAPID and means for Nyström. All comparisons use the same matrices and right-hand sides.
Table 3: Absolute condition numbers and CG iterations. Mean values across independent matrices per synthetic family and SuiteSparse matrices. All RAPID runs reached the target accuracy ( per synthetic family and for SuiteSparse) at every tested step count. The only non-convergent run was Nyström with a sketch on the SuiteSparse matrix Cylshell/s1rmt3m1. These averages of absolute quantities differ from the averages of per-instance ratios shown in Figure 2.
| RAPID steps | |||||||
|---|---|---|---|---|---|---|---|
| Dataset | Jacobi baseline | 10 | 20 | 50 | 100 | 200 | 500 |
| Condition number | |||||||
| Chebyshev | 10,155.43 | 10,402.86 | 9,371.71 | 6,106.86 | 2,746.62 | 480.23 | 4.89 |
| Linear | 10,007.98 | 9,342.59 | 8,066.53 | 4,816.50 | 1,857.98 | 228.63 | 4.82 |
| Logarithmic | 9,978.65 | 7,429.91 | 5,697.62 | 2,983.64 | 1,316.00 | 330.48 | 6.07 |
| Power-law | 10,010.99 | 8,940.11 | 7,707.07 | 4,845.05 | 2,216.73 | 425.81 | 4.94 |
| SuiteSparse | 94,992.34 | 82,687.66 | 73,149.07 | 53,286.53 | 35,442.72 | 18,391.60 | 4,600.00 |
| CG iterations to target accuracy | |||||||
| Chebyshev | 319.10 | 322.60 | 308.00 | 252.90 | 176.60 | 80.50 | 10.00 |
| Linear | 127.90 | 122.00 | 115.50 | 90.30 | 59.70 | 29.80 | 10.00 |
| Logarithmic | 373.30 | 322.70 | 283.40 | 207.80 | 140.70 | 74.50 | 17.80 |
| Power-law | 332.80 | 313.80 | 291.60 | 233.60 | 163.20 | 79.00 | 10.00 |
| SuiteSparse | 266.45 | 250.65 | 230.32 | 189.35 | 145.48 | 99.35 | 40.65 |
Appendix C Proof of the Haar Block-Row-Min Guarantee
This appendix proves Theorem 3. Let us define the block row selector:
Block row-min selector.
For a partition of into blocks of size , Define
where is the block containing . Ties are broken deterministically.
Algorithm 2 Block row-min preconditioning
1: Input: , step size , iterations , block size , mixer distribution .
2: for do
3: Draw and a block partition of with block size .
4: .
5: .
6: .
7: end for
8: return .
The theory uses ; experiments also use block-local choices based on product of Hadamard matrices of .
Let us state the theorem in full generality here. We analyze the Gram recursion extracted in Section 3:
started from an arbitrary . The theorem is proved for fresh uniform random orthogonal mixing, . This distributional assumption is used only in the local row-min drift calculation; the Taylor expansion, trace identities, block-load bound, spectral lower bound, and stopping-time argument hold for any orthogonal mixer.
For the block selector defined in (17), each row selects one off-diagonal entry from its block and each column can be selected by at most rows. Thus
This deterministic load bound is the only property of the block mask used in the Taylor remainder.
Theorem 4 (Uniform-random-rotation block row-min preconditioning).
Let , , and . Fix a target condition number , and define
Choose
Let
There are universal constants such that, for
the iteration (18) with fresh satisfies
For each fixed , uniformly in . Hence, for fixed and fixed ,
Theorem 4 is a refinement of Theorem 3 from the main text. The rest of the analysis will focus on proving this result. In the process, we will show improved versions of Lemma 2 and Lemma 1.
C.1 Setup and potential
Let and let
Fix a block partition , . For , define
with deterministic tie-breaking. A fresh independent random partition may also be used, but the Haar proof only needs the candidate sets to be fixed independently of .
For , define
This potential is scale-invariant and satisfies
Let be the eigenvalues of , and let
Define
Ratios below are defined to be zero when . Set
and
C.2 Block masking controls the load
For each row , exactly one entry of is nonzero, so . Fix a column . Only rows in can select column , so the column has at most nonzeros. Therefore
C.3 Taylor drift estimate
Lemma 5 (Taylor estimate).
Let , , and
If and , then
and there is a universal constant such that, for every ,
One may take .
Proof.
Since
the trace-power chain rule gives
By cyclicity of trace,
The negative-power term similarly gives
This proves the formula for .
For the curvature bound, put
For , the assumption implies
Moreover,
Let . For the Schatten -norm, the standard 2-smoothness estimate for gives
Consequently, for a twice differentiable path ,
For the positive-power term, write
With , we have , and Schatten submultiplicativity gives
For the negative-power term,
so
With ,
and hence
Combining the two terms and using yields
∎
Applying Lemma 5 to one update and using gives
where by orthogonal invariance.
C.4 Block-local row-min drift
Lemma 6 (Haar row-min drift).
For fixed , let , , and let be the block row-min selector. Then
Proof.
For any real , symmetry of gives
Thus
It suffices to compute the one-row expectation. For each row, the candidate set has size and is independent of . By exchangeability of Haar coordinates, the one-row law depends only on this size. We analyze row with a fixed candidate set , .
Let
and
Then the row contribution is .
Write and set . Then . Conditional on the first row of , choose an orthonormal basis for . The remaining rows of form a Haar frame in , so there is such that
The vectors are deterministic after conditioning on .
Assume first that . Decompose
Then
The index is a function only of . Conditional on , the law of is invariant under rotations fixing . These rotations leave , and hence , unchanged, while they average the -component to zero. Therefore
and
If , both sides are interpreted using the zero-ratio convention.
Since , with ,
Thus
Now average over . If , then . Since ,
Therefore
and
Summing over the rows gives
Dividing by the deterministic traces yields the claimed identity. ∎
C.5 Lower bound on the spectral factor
Lemma 7 (Spectral lower bound).
Let , and define
If and
then
Proof.
By scale invariance, set , , and . Define
Since ,
Monotonicity gives and . Hence
For ,
Applying this identity gives
Therefore
It remains to show . Let
Then . Let
Since at least one eigenvalue equals ,
Therefore
Similarly, with
one has
and hence
Thus
The lemma follows. ∎
C.6 Hitting-time bound
For , Lemma 7 gives . Combining Lemma 6 with the Taylor estimate gives
Choose
and enlarge the universal constant in Theorem 4, if necessary, to ensure . Then
Therefore
is a supermartingale. Since , optional stopping gives
Letting and using yields
It remains to record the fixed-block behavior of . Since ,
By rotational invariance, , so
For ,
which gives a positive lower bound uniformly in . Conversely,
Thus, by Jensen,
Hence for fixed . Since , Theorem 4 follows.
C.7 Fast structured mixing and the required transfer condition
Dense Haar mixing is the clean object for analysis, but it is not the intended implementation for large matrices. Sampling and applying a dense Haar matrix costs cubic time at the scale of a dense Gram matrix. A much faster alternative is to use a product of normalized Walsh-Hadamard transforms and random sign diagonals. Let denote the normalized Walsh-Hadamard matrix, and let be independent diagonal matrices with Rademacher entries. A typical fast mixer is
where is an independent random permutation. Each factor is orthogonal, and multiplication by can be performed with the fast Hadamard transform. Thus forming for dense costs , rather than the dense-rotation cost. The sparse row-min update then costs , and the block row-min search costs once the relevant entries of are available.
The theorem above does not automatically apply to . Haar mixing supplies exact conditional rotational invariance, which is used in the row-min drift lemma. A finite product of Hadamard/sign factors is a structured discrete distribution and need not have that exact invariance. A single Hadamard-sign layer is certainly insufficient in the worst case: if and , then , so the mixed matrix is diagonal and the row-min signal vanishes. Multiple layers and a random permutation are used to avoid such alignment effects. This worst-case observation does not contradict the empirical effectiveness of a single mixing stage per RAPID iteration (), since successive iterations introduce fresh mixing interleaved with sparse corrections, allowing the effects of mixing to accumulate over time.
The rest of the proof, however, is insensitive to the source of orthogonal mixing. The Taylor expansion, trace invariance, load bound, spectral lower bound, and stopping-time argument all hold for any orthogonal distribution. The only missing ingredient is a local row-min comparison estimate. We state it explicitly.
For an orthogonal mixing distribution , define, for a fixed row , block candidate set , and exponent ,
and
Let
Define the local Haar-comparison errors
and the normalized error
Proposition 8 (Transfer from Haar to a structured orthogonal mixer).
Let be any distribution on . Suppose that for every with ,
Then the block row-min iteration with satisfies the same hitting-time guarantee as Theorem 4, up to universal constant factors:
Proof.
The Haar drift identity gives
By the definition of , the corresponding drift under satisfies
If , then , and the assumed comparison bound gives
Substituting this into the same Taylor estimate used in the Haar proof yields
until . Choosing and applying the same optional-stopping argument proves the claim. ∎
Proposition 8 is stated as a local comparison condition, not as a new convergence theorem for fast Hadamard products. Proving the condition for requires showing that the hard row-min statistic has nearly the same expectation under the structured mixer as under Haar. This is the precise theoretical gap left by replacing continuous Haar rotations with fast structured orthogonal transforms. Existing incoherence and fast Johnson-Lindenstrauss results for randomized Hadamard transforms suggest why such a comparison should be plausible after several independent sign/Hadamard layers, but they do not by themselves supply the conditional rotational invariance used in the Haar proof. Empirically, we therefore use the fast Hadamard mixer for scalability, while the theorem above gives the exact guarantee for Haar mixing and identifies the comparison estimate needed to transfer the guarantee to the fast implementation.
C.8 Spiky spectra give a drift gain
In the worst-case argument above we only used the uniform lower bound
For spiky spectra, can be much larger. We record the simplest case, where the spectrum consists of one large spike and a flat bulk.
Lemma 9 (Rank-one spike).
Assume, after rescaling, that
Let
Then
where
Moreover,
Consequently, if
then
for a universal numerical constant . In fact, in this regime,
Proof.
Let
For the rank-one spike,
Set
Then
A direct calculation gives
Therefore, using the zero-ratio convention when ,
Writing
we have
Also,
Hence
equals
It remains to estimate . Since
we get
Using
and
we obtain
By the standard gamma-ratio estimate,
and hence
Thus
Finally, if , then
for a universal constant . The second term is nonnegative, so
The upper bound follows from the same formula and the fact that both bracketed terms are at most . ∎
Remark 1 (Interpretation).
The uniform theorem only uses . For a rank-one spike with , the useful spectral drift is larger:
This happens because a Haar row assigns mass
to the spiked eigendirection, and
The definition of contains an additional factor of , so the net scale is .
C.8.1 Consequence for the drift rate in the spiky regime
We now spell out the resulting improvement in the one-step drift. Recall the general drift estimate
Suppose that, on some portion of the trajectory before reaching the target condition number, the iterates satisfy the stronger spiky lower bound
for some . Using the same globally safe step size
we obtain
for a universal numerical constant , after absorbing the Taylor remainder into the leading negative term.
Consequently, if
holds until the hitting time
then the stopped-supermartingale argument gives
Since
we get
For fixed block size , . Thus, in the spiky regime,
With the usual choice , this becomes
This is a genuine improvement over the worst-case bound.
C.9 Establishing intuition: First-order effect of a row correction
We now justify the illustrative eigenvalue calculation in Section 4; this example is not used in the proof of Theorem 4. Consider , with , , and . The eigenvalue is simple, with eigenvector , while all remaining eigenvalues equal .
For distinct coordinates , the congruence update
Expanding around gives
By first-order eigenvalue perturbation, the eigenvalue originating from satisfies
Since for ,
For and sufficiently small , the exceptional eigenvalue therefore moves toward , whether or .
This calculation tracks only the exceptional eigenvalue under a single row correction. Other eigenvalues may also change, so it does not establish a decrease in the condition number of the full matrix.
C.10 Empirical evidence for the unblocked load bound
The proof in Section 6 uses block selection to control the load of the row-min update. We test whether the same type of control holds for the unblocked selector used in the practical algorithm. For a mixed matrix , define
Thus is the maximum number of rows whose minimum off-diagonal entry selects the same column. The step-size scaling used in our simulations is supported if
where is the spectral drift used in Lemma 2 and defined in (26). We therefore measure this ratio directly after Haar mixing with global argmin selection, with no blocking.
Throughout this experiment we set . We generate centered log-spectra , with , and retain only spectra with . To search for possible failures of the bound, we sweep several adversarial spectral families: top spikes ( large eigenvalues), bottom holes ( small eigenvalues), two-block spectra (a fraction at and the rest at ), power-law spectra (), and lognormal spectra (, ). Concretely, we vary
These families target concentrated outliers, low-eigenvalue holes, balanced two-cluster spectra that may create collisions, smooth spectral decay, and irregular heavy-tailed spectra.
For each retained spectrum and dimension, we draw independent Haar matrices , form , compute the exact global row-min selector , and record . We estimate independently using Dirichlet samples, matching the squared coordinates of a Haar row. Figure 9 summarizes the results, and Table 4 reports the main aggregate statistics by dimension.
Across the tested dimensions and spectral families, remains bounded away from zero. The smallest values occur for the most symmetric high-collision cases, especially half-mass two-block spectra and the matching top-spike and bottom-hole constructions. Even there, the ratio stays well above zero, supporting the empirical relation
Substituting this into the one-step drift bound gives
matching the blocked rate up to replacing the block load by the actual unblocked load.
Figure 9: Empirical load scaling for the unblocked selector. Left: distribution of versus dimension, aggregated over all retained spectra and Haar trials. Right: median by spectral family. In all tested cases the ratio remains bounded away from zero.
| # spectra | min | 10th perc. | median | median | 90th perc. | max | |
|---|---|---|---|---|---|---|---|
| 32 | 67 | 0.814 | 1.045 | 1.207 | 5 | 15 | 24 |
| 64 | 67 | 0.804 | 1.031 | 1.228 | 7 | 22 | 42 |
| 128 | 75 | 0.810 | 0.993 | 1.235 | 8 | 37 | 81 |
| 256 | 75 | 0.753 | 0.996 | 1.240 | 9 | 117 | 152 |
| 512 | 76 | 0.706 | 0.941 | 1.326 | 9 | 121 | 289 |
| 1024 | 76 | 0.706 | 0.893 | 1.320 | 9 | 265 | 561 |
| 2048 | 76 | 0.707 | 0.894 | 1.358 | 9 | 430 | 1085 |
Table 4: Aggregate statistics for the unblocked load experiment. Each row aggregates over all retained spectra and Haar trials at the given dimension.
Appendix D Reproducibility details
D.1 Compute resources
All experiments were run on a machine with an Intel Xeon Gold 6438M CPU, 125GiB system memory, and four NVIDIA RTX 6000 Ada Generation GPUs. Reported experiments used a single GPU. The software stack used Python 3.12.4, PyTorch 2.4.0+cu121, CUDA 12.8 tooling, and Triton 3.0.0.
The transformer diagnostics used depths and independent runs per depth, for total training runs requiring approximately cumulative GPU-hours. The RAPID numerical experiments were run on the same hardware using PyTorch/Triton kernels, explicit CUDA synchronization for timing, and GPU fast Walsh–Hadamard transforms [Dao, 2024].
D.2 Existing assets and licenses
The experiments use synthetic matrices generated by our scripts and public SuiteSparse Matrix Collection instances. SuiteSparse matrices were accessed through ssgetpy; the SuiteSparse Matrix Collection is credited in the main text, and ssgetpy is distributed under the MIT/X11 license.
Our implementation uses Python 3.12.4, PyTorch 2.4.0+cu121, Triton 3.0.0, CUDA tooling, NumPy, SciPy, and fast-hadamard-transform. PyTorch is distributed under a BSD-style license, Triton under the MIT license, NumPy and SciPy under BSD-style licenses, fast-hadamard-transform under the BSD-3-Clause license, and the CUDA Toolkit is governed by the NVIDIA CUDA Toolkit EULA. We use these packages only as software dependencies and do not redistribute modified versions of them.