Manuscript Offprint
arXiv:2611.09412MIRA: Mitigating Pole Geometry Bias in Recurrent Language Models
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
ABSTRACT
We show that the Transformer’s recurrent successors — such as selective state-space models (SSMs), Receptance Weighted Key Value (RWKV), and Retentive Network (RetNet) — can be characterized as infinite-impulse-response (IIR) systems. The zero-pole geometries of these IIR systems characterize the temporal modes they can represent. However, to trade parallelism, the algebraic structures of the parameterizations of these recurrent systems often give rise to poles constrained to the real axis, thereby inducing an architectural bias in their recurrent dynamics. To unify these recurrent architectures and eliminate their pole geometry bias, inspired by the lattice–ladder realization of general IIR systems, we present MIRA (Modal IIR Recurrent Architecture), a unified family of linear-time recurrent architectures for building large language models (LLMs) with a highly parallel algebraic structure. Each MIRA block realizes a higher-order IIR system that represents temporal modes from token streams through a lattice–ladder structure, followed by a feed-forward network (FFN). This realization enables the model to represent the temporal modes associated with both real and complex-conjugate poles. We pretrain MIRA-S, a 12-layer small-scale LLM with 0.14B parameters composed entirely of MIRA blocks. Throughout the pretraining, MIRA-S achieves lower perplexity than strong recurrent baselines, exhibits stronger context-window generalization beyond the training length, and attains higher throughput with a dedicated CUDA kernel.
1 INTRODUCTION
Large language models (LLMs) based on the Transformer architecture (Vaswani et al., 2017) have achieved remarkable performance across a wide range of natural language processing tasks, including language understanding, reasoning, question answering, and code generation. Since GPT-2 (Radford et al., 2019), the prevailing paradigm has converged on decoder-only architectures and has remained largely unchanged: LLMs are built from stacks of Transformer blocks or its variants that combine causal scaled dot-product attention (SDPA) with feed-forward network (FFN), and are pretrained through next-token prediction on large-scale corpora followed by instruction tuning (Christiano et al., 2017; Ouyang et al., 2022; Rafailov et al., 2023). Despite its success, SDPA incurs quadratic computational complexity with respect to the sequence length .
A growing body of work therefore explores linear-time architectures with computational complexity . Selective state-space models (SSMs), such as Mamba (Gu & Dao, 2024) and its variants, replace the attention mixing module with selective state-space recurrences, while recurrent linear-attention models, such as Receptance Weighted Key Value (RWKV) (Peng et al., 2023), employ re-
*Corresponding author: roisincrtai@gmail.com
Table 1: Transfer-Function Characterization. and denote the numerator (FIR) and denominator (IIR) polynomials of the transfer function . The transfer functions are input-dependent. The roots of are the zeros and the roots of are the poles. We also verify the derived transfer functions numerically, comparing the sequence each predicts against the measured output of its recurrence, with a maximum discrepancy of ; the pole ranges are verified formally, in Lean 4 (Moura & Ullrich, 2021) and Z3 (De Moura & Björner, 2008).
| Method | Zeroes | Poles | ||
|---|---|---|---|---|
| SDPA (Vaswani et al., 2017) | 1 | Complex | - | |
| Selective SSM (Mamba-1, S6) (Gu & Dao, 2024) | Complex | Real (0, 1) | ||
| RWKV (v4-v6) (Peng et al., 2023) | 1 | - | Real (0, 1) | |
| RetNet (v1) (Sun et al., 2023) | 1 | - | Real [0.968, 1) | |
| HGRN2 (v2) (Qin et al., 2024) | - | Real (0.125, 1) | ||
| Hyena (v1) (Poli et al., 2023) | 1 | Complex | - | |
| DeltaNet (v1) (Yang et al., 2024b) | - | Real (0, 1] | ||
| Gated DeltaNet (v1) (Yang et al., 2025) | - | Real (0, 1) | ||
| MIRA | Complex | Complex |
current weighted key-value mechanisms. Other approaches preserve attention-like algebra while replacing the softmax operator: the Linear Transformer (Katharopoulos et al., 2020) factorizes kernelized attention through feature maps and associativity, Retentive Network (RetNet) (Sun et al., 2023) introduces a multi-scale retention mechanism with parallel, recurrent, and chunkwise-recurrent formulations, and Gated Linear Attention (GLA) (Yang et al., 2024a) incorporates data-dependent decay gates with efficient chunkwise computation. DeltaNet (Schlag et al., 2021; Yang et al., 2024b) introduces delta-rule updates to recurrent fast-weight states, while Gated DeltaNet (Yang et al., 2025) further augments the delta-rule recurrence with data-dependent gating. HGRN2 (Qin et al., 2024) develops hierarchical gated recurrent dynamics for linear-time sequence modeling, whereas Hyena (Poli et al., 2023) replaces recurrent state updates with implicitly parameterized long convolutions for efficient long-range sequence mixing.
In the theory of digital signal processing (DSP) (Oppenheim & Schafer, 2010), representations of language sequences are discrete temporal signals. A system that maps an input sequence to an output sequence is a transfer operator. Its input–output response can be characterized by its transfer function. Let be a finite temporal sequence of length . Let be z-transform operator, and be inverse z-transform operator, defined as
respectively, where the counter-clockwise closed integral contour on complex plane encloses all poles of the polynomial for ensuring causal condition and is complex variable (Oppenheim & Schafer, 2010). Let and be input and output sequences of tokens. Let and denote the z-transforms of the input sequence and output sequence , respectively. The ratio of the output to the input in the z-domain is referred to as the transfer function (Oppenheim & Schafer, 2010). We show that recurrent dynamical systems — such as SDPA, SSM, RWKV, RetNet, HGRN2, Hyena, and DeltaNet — admit following input-conditioned transfer operator,
where defines an order- finite-impulse-response (FIR) system, and defines an order- infinite-impulse-response (IIR) system. This transfer function is uniquely characterized by the roots of its numerator and denominator polynomials, where the roots of the numerator polynomial are referred to as zeros, and the roots of the denominator polynomial are referred to as poles. The zero-pole geometry of governs how temporal modes are retrieved from input sequences: zeros attenuate or cancel specific modes, whereas poles determine persistent or resonant temporal modes. Table 1 summarizes the transfer-function and zero-pole


Figure 1: Provable Failure of Causal Mode Retrieval. We synthesize 4-dimensional continuous input tokens and target tokens of a length 200. The ground-truth transfer function contains poles that are not on the real axis. We use parameter-matched single-layer models trained to predict next-token from input sequence by using MSE (mean squared error) loss. Each model is optimized for 1000 steps using AdamW (Loshchilov & Hutter, 2019) with a learning rate of . Left: synthetic temporal signals of length 200. Middle: pole geometries of MIRA, Mamba-S6, RWKV-7, and SDPA. Right: next-token prediction error with logarithmic scale. The results show that MIRA admits complex poles and more accurately retrieves the temporal modes associated with complex poles. The provable failure signal synthesis is provided in Appendix A.6.
characterizations of SDPA, the selective SSM of Mamba-1, RWKV v4–v6, RetNet, HGRN2, Hyena, DeltaNet, and Gated DeltaNet. The proofs are provided in Appendix A.9. To trade parallelism, the algebraic structures of the parameterizations of these methods, such as a diagonal-matrix parameterization in SSM that preserves channel-wise parallelism, often constrain their poles to lie on the real axis.
This pole geometry constrained on real axis therefore induces an architectural bias in recurrent dynamics and delimits the modes that they can represent. To demonstrate this bias, we construct an experiment as shown in Figure 1, using a synthesized token sequence and target sequence with a dimension four, where the true transfer function has poles not constrained on real axis. We train single-layer MIRA, SDPA, Mamba-S6, and RWKV-7 models to perform next-token prediction for predicting the target token sequence using MSE (mean squared error) loss. The experiment demonstrates the provable failure of causal mode retrieval: models with poles constrained to the real axis fail to retrieve modes associated with complex-conjugate poles.
To unify the recurrent architectures and eliminate the pole geometric bias, inspired by general adaptive IIR filters in the form of equation (1), we present MIRA (Modal IIR Recurrent Architecture), pronounced “mee-ruh”, a unified architectural family with linear time complexity for building LLMs with a highly parallel algebraic structure (see Figure 5). As illustrated in Figure 2, for each block, MIRA realizes a higher-order IIR system through a lattice-ladder structure (Oppenheim & Schafer, 2010), followed by a FFN. This structure enables the model to provably represent the feature modes associated with both real and complex-conjugate poles. Its recurrent dynamics inherently encode temporal order, eliminating the need for explicit positional encoding. The contributions are summarized as follows:
• A Unified Architectural Family. We introduce MIRA (Modal IIR Recurrent Architecture), a unified, positional-encoding-free, linear-time architectural family that realizes higher-order IIR dynamics through an adaptive lattice-ladder topology, enabling the representation of temporal modes associated with both real and complex-conjugate poles.
• Dedicated CUDA Kernel. We show that the algebraic structure of the MIRA realization admits computational associativity despite its higher-order recurrent form. We exploit this associativity to parallelize state propagation in our dedicated CUDA kernel, admitting a minimal critical path of where T is sequence length.
• Experimental Validation. Controlled experiments on language corpora show that enabling complex poles improves language-modeling performance, while inference measurements with dedicated CUDA kernel show that the MIRA block achieves higher throughput than strong baselines. We further build and pretrain MIRA-S, a small-scale 0.14B-parameter LLM composed entirely of MIRA blocks, which achieves the highest next-token prediction accuracy and the lowest perplexity among strong baselines.

Figure 2: MIRA Block & Reference LLM. The diagram illustrates lattice circuit at stage (top left), an order- lattice module (bottom left), a MIRA block (top right), and a reference implementation of the MIRA LLM composed entirely of MIRA blocks (bottom right). In the order- lattice module, a rank-one signal mixer forms the input representations through channel-wise signal mixing, the dynamical-modulation signal modulates the lattice-ladder dynamics, the lattice module implements the order- lattice dynamics, and the ladder readout produces the output representations.
Stable Recurrent Lattice Dynamics. Let denote an input token representation sequence, where each token has dimension . As illustrated in Figure 2, we first normalize using RM-SNorm (Root Mean Square Layer Normalization) (Zhang & Sennrich, 2019) and project the representations into an expanded dimension , allowing the lattice dynamics to operate in a

Figure 3: Algebraic Structure of the Lattice Realization. Each node represents the recursive state transition at lattice stage and token position , with edges encoding dependencies on and .
higher-dimensional space
where denotes the input projection matrix and is referred to as expansion factor. Let denote the forward token signal and denote the backward state signal at lattice stage , where represents the token position and indexes the lattice stage and is referred to as per-channel memory size. We construct a generalized, stable, parameterized, matrix-valued dual-port lattice scattering dynamics as follows
under and with initial conditions
where operator denotes the generalized element-wise product with broadcasting defined by is referred to as the forward state which encodes the representation of token at lattice stage , is referred to as the backward state which summarizes the recurrent memory up to token at lattice stage , and is referred to as the reflection coefficient matrix, which governs the forward-backward state transition. This IIR system is parameterized through
where introduces a low-rank state-write bottleneck that enables state writes on a low-dimensional manifold. We construct the rotation matrix as a Cayley map (Cayley, 1846) parameterized by hyperbolic map (see Appendix A.7). The states are reset for every independent input sequence indicated by a special token . We refer to , and as the lattice order, state-write bottleneck size, and memory size, respectively. We further refer to as the characteristic horizon, which governs the decay timescale of the backward state mode with discrete-time pole , since the continuous-time ordinary differential equation (ODE) of the backward state evolution satisfies .

Figure 4: Effects of Lattice Order , State-Write Bottleneck Size , and Memory Size . Using MIRA-XS (65M), we independently vary the lattice order , state-write bottleneck size , and memory size . We match model sizes by varying only the model width and pretrain each model for 10,000 steps on FineWeb-Edu using AdamW. The results show that models admitting complex-conjugate poles () achieve lower perplexity than the model with real poles (). Among the evaluated state-write bottleneck sizes, yields the lowest perplexity. Perplexity generally decreases as increases, reaching its lowest value at .
Representation Readout. Since the backward state carries both the current representation of token and the recurrent memory of preceding tokens, therefore the ladder readout aggregates the backward states across the lattice stages using the input-conditioned ladder readout coefficient , the learned state-read direction , and the selective gate
where denotes the readout projection matrix. The readout coefficient , state-read direction , and readout gate are parameterized as
Stability Condition. Remaining Schur stability of the recurrent dynamics requires all the eigenvalues of to have magnitude strictly smaller than 1 (Schur, 1917; Cohn, 1922; Oppenheim & Schafer, 2010). Our parameterization satisfies this condition almost surely under an absolutely continuous joint distribution of and , since their corresponding entries vanish simultaneously only on a measure-zero set. The proof is provided in Appendix A.10.
Jeffreys Initializer. The initialization of and must ensure a non-nilpotent state transition and meaningful characteristic horizons. Trivial initializations, such as small zero-centered uniform and normal initializers, degenerate the recurrent dynamics because the cross-stage magnitude of state transition decreases exponentially with . When stage coupling vanishes or exact pole-zero cancellations occur, the McMillan degree (Kalman, 1965) falls below , degenerating the IIR dynamics into an FIR system. We therefore design the Jeffreys initializer described in Appendix A.8, which sets the biases of and to coupled pole pairs whose horizons are the quantiles of the Jeffreys prior (Jeffreys, 1946).
3 ALGEBRAIC STRUCTURE AND PARALLELISM
Let
be the state transition given by equation (2), as illustrated in Figure 3. Directly using equation (2) for computing the dynamics up to token position t requires all previous states. To parallelize the computation on GPUs, we need to further explore its algebraic structure that allows parallelism.

Figure 5: Performance of Dedicated CUDA Kernel. We compare MIRA module with parameter-matched baseline modules on an NVIDIA RTX A6000 GPU. Execution time: at a context length of 32K, MIRA completes a forward pass in 11.37 ms, yielding speedups of , , , and over MHA (Multi-Head Attention) with FlashAttention, Mamba (S6), RWKV-6, and RWKV-7, respectively (left). Throughput: At the same context length, MIRA reaches 8.36 million tokens per second, exceeding the throughput of the respective baselines by factors of , , , and (right).
Algebraic Associativity & State Interposition. Since propagates only across lattice stages, while carries the temporal memory up to token position , we define the carried state as
Because and depend only on , we show that the complete cascade admits an affine operator
where denotes the transition matrix and denotes the input contribution independent of any . For any , temporal composition of two affine operators is associative
Therefore, for any , this algebraic structure interposes the preceding memory and the segment dynamics within the carried state
where composes : the transition transports the preceding memory accumulated over tokens , whereas the input contribution is accumulated over the segment alone from the zero entry state , and is therefore independent of all tokens preceding . The proof and further details are provided in Appendix A.11.
Critical Parallel Path. Theoretically, this algebraic structure enables chunkwise parallel state propagation along with token axis and admits a critical path , where is chunk size of token sequence. A minimal critical path of is obtained by choosing the chunk size as .
Dedicated CUDA Kernel. We realize this algebraic structure as a dedicated CUDA kernel, such that the computation within the MIRA module remains on-chip. Exploiting associativity in equation (4) and state interposition in equation (5), the token axis is partitioned into chunks of length , and three phases are mapped onto thread blocks, each processing one chunk across adjacent channels with the carried state held in registers: (i) chunk summarization evaluates every chunk concurrently from the zero carried state, yielding its pair ; (ii) associative composition applies equation (5) at the chunk boundaries alone, recovering every chunk-entry state; and (iii) chunk replay restores the interior states concurrently and produces the gated ladder readout. The details are provided in Appendix A.12.
| Model | Size (M) | State (%) | FineWeb-Edu | WikiText-103 | HellaSwag | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 512 | 32K | 512 | 32K | 512 | 32K | |||||||||||||||
| Loss | PPL | Acc (%) | Loss | PPL | Acc (%) | Loss | PPL | Acc (%) | Loss | PPL | Acc (%) | Loss | PPL | Acc (%) | Loss | PPL | Acc (%) | |||
| Transformer (MHA) | 142.52 | 0.000 | 3.400 | 29.96 | 35.31 | 7.317 | 1.51 × 10³ | 4.58 | 3.468 | 32.08 | 36.01 | 7.136 | 1.20 × 10³ | 6.25 | 3.434 | 31.00 | 38.39 | 7.134 | 1.25 × 10³ | 1.43 |
| RWKV-6 | 144.64 | 4.418 | 3.465 | 31.97 | 34.52 | 3.752 | 42.59 | 20.18 | 3.525 | 33.94 | 35.10 | 3.764 | 43.12 | 21.77 | 3.523 | 33.88 | 35.47 | 3.814 | 45.34 | 19.21 |
| RWKV-7 | 142.66 | 3.634 | 3.485 | 32.63 | 34.26 | 3.423 | 30.65 | 34.47 | 3.587 | 36.12 | 34.58 | 3.519 | 33.75 | 34.16 | 3.644 | 38.23 | 35.11 | 3.544 | 34.59 | 34.94 |
| Mamba-1 | 148.73 | 2.107 | 3.582 | 35.93 | 33.70 | 5.08 × 10²¹ | 1.31 | 3.566 | 35.36 | 34.62 | 52.096 | 4.22 × 10²² | 1.02 | 3.680 | 39.63 | 34.05 | 46.162 | 1.12 × 10²² | 1.02 | |
| Mamba-2 | 148.41 | 16.890 | 3.466 | 32.02 | 34.73 | 27.583 | 9.53 × 10²¹ | 1.16 | 3.501 | 33.14 | 35.43 | 27.179 | 6.36 × 10²¹ | 0.75 | 3.436 | 31.07 | 38.69 | 35.386 | 2.33 × 10²² | 0.78 |
| Mink-S | 144.72 | 4.076 | 3.323 | 27.75 | 37.83 | 3.231 | 25.30 | 38.07 | 3.435 | 31.83 | 36.73 | 3.316 | 27.54 | 38.83 | 3.481 | 32.50 | 37.19 | 3.354 | 26.62 | 38.48 |
Table 2: Benchmark Performance. Validation loss, perplexity (PPL) and next-token accuracy at context lengths of 512 and 32,768 tokens. The training context window is 512 tokens. FineWeb-Edu is scored on the held-out last 5% of the corpus; WikiText-103 and HellaSwag on their test splits. State denotes the ratio of the total recurrent state size across all layers to the model parameter count, expressed in parts per thousand.
4 EXPERIMENTS
We build a small-scale model MIRA-S for benchmarking against strong baselines of comparable size, comprising 12 layers with model width , expansion width , memory dimension , state-write bottleneck dimension , lattice order , and FFN width 3072. The model has 0.14B parameters and a state-to-parameter ratio of 4.076 %. We also build an extra-small-scale model MIRA-XS for architectural ablation experiments, comprising 10 layers with model width , expansion width , memory dimension , write bottleneck dimension , lattice order , and FFN width 2048. The model has 65M parameters and a state-to-parameter ratio of 9.760 %. For both MIRA-S and MIRA-XS, we initialize the characteristic horizon of the Jeffreys initializer to range from 10 to 2000 tokens across all layers and from 1 to 128 tokens in the first layer.
Training Protocol. We use the FineWeb-Edu dataset (text corpus) (Penedo et al., 2024) to train a Byte-Pair Encoding (BPE) (Sennrich et al., 2016) tokenizer and yield a tokenizer with a vocabulary of 50,259 tokens. The tokenizer reserves three special tokens: <|end-of-session|>, <|unknown|> and <|pad|>. We pretrain each model with a weight-update budget corresponding to nine billion tokens, following the Chinchilla scaling rule (Hoffmann et al., 2022), with a fixed context length of 512 tokens. For the next-token prediction objective, we weight each sequence-level cross-entropy loss by its number of valid target tokens, thereby averaging the loss uniformly over all predicted tokens (Kaplan et al., 2020). To reduce the GPU memory footprint, we use chunked loss (Liu & Abbeel, 2023) with a chunk size of 8,192 and mixed-precision training, where the model weights and optimizer states are stored in 32-bit floating point (FP32), while activations are stored in brain floating point (BF16) (Kalamkar et al., 2019). We optimize the model using AdamW (Loshchilov & Hutter, 2019) with , , weight decay , and a numerical stability constant of . We use a peak learning rate of , and apply a cosine learning-rate scheduler with a final learning rate of and a linear learning-rate warmup of 500 steps. Before each weight update, we apply gradient clipping with a maximum norm of 1.0.
Architectural Ablation. For MIRA-XS, we independently vary the lattice order while fixing and ; vary the write bottleneck size while fixing and ; and vary the memory size while fixing and . We match model sizes by varying only the model width and pretrain each model for 10,000 steps on FineWeb-Edu. Figure 4 shows that models admitting complex-conjugate poles () achieve lower perplexity than the model with real poles (), while yields the lowest perplexity among the evaluated state-write bottleneck sizes. Perplexity generally decreases as increases, reaching its lowest value at . Since the MIRA module has parameter size , therefore higher lattice orders, wider state-write bottlenecks, and larger memory sizes incur greater computational costs and memory footprints, we choose , , and as the default configuration scheme of MIRA, balancing performance and computational efficiency. Full experiments are presented in Appendix A.1.
CUDA Kernel Performance. We benchmark the dedicated MIRA CUDA kernel against strong GPU-optimized baselines whose CUDA kernels are available, including MHA with FlashAttention (Dao et al., 2022), Mamba (S6), RWKV-6, and RWKV-7, using parameter-matched models on an NVIDIA RTX A6000 GPU. As shown in Figure 5, MIRA consistently achieves lower execution

Figure 6: Context-Window Generalization. We evaluate the context-window generalization for the pretrained MIRA on a holdout set of FineWeb-Edu, WikiText-103, and HellaSwag, respectively. The dotted vertical line marks the training context length. MIRA attains the lowest perplexity among the recurrent baselines and matches or improves on the MHA reference.
time and higher throughput across the evaluated context lengths. At a context length of 32,768, MIRA completes a forward pass in 11.37 ms, corresponding to speedups of , , , and over MHA with FlashAttention, Mamba (S6), RWKV-6, and RWKV-7, respectively. At the same context length, MIRA achieves a throughput of 8.36 million tokens per second, exceeding the respective baselines by , , , and . Compared with the baselines, MIRA exposes parallelism along with token chunks, expanded channels, and memory components, while its fixed number of lattice stages is unrolled at compile time.
Pretraining Benchmark. We pretrain MIRA-S on FineWeb-Edu and compare MIRA-S with strong recurrent language model baselines, including Mamba-v1 (S6), Mamba-v2 (SSD), RWKV-6, and RWKV-7, with MHA as a reference baseline. The Transformer-based MHA baseline uses RoPE (Rotary Position Embedding) (Su et al., 2024) for positional encoding. For a fair comparison, we adjust the model width of each architecture to maintain the approximately identical parameter size. On the training dataset, MIRA-S consistently achieves lower perplexity and higher next-token prediction accuracy than the strong baselines throughout pretraining. Table 2 presents the validation results, with detailed results reported in Appendix A.1. Additional experiments, including evaluation on the MMLU (Massive Multitask Language Understanding) test set across all 57 subjects (Hendrycks et al., 2021b;a), evaluation on the AI2 Reasoning Challenge (ARC) (Clark et al., 2018), and memory-state projection, are presented in Appendix A.1.
Context Window Generalization. We evaluate context-length generalization for MIRA, Mamba-1 (S6), Mamba-2 (SSD), RWKV-6, and RWKV-7, with MHA as a reference, on three corpora: a held-out set of FineWeb-Edu (230 documents, 263,837 tokens), WikiText-103 (Merity et al., 2016), and HellaSwag (Zellers et al., 2019). Besides MHA without positional-encoding extrapolation (legend “MHA”), we also apply YaRN (Peng et al., 2024) to MHA beyond the training context length, with legend “MHA (YaRN)”. Figure 6 reports perplexity for context lengths from 256 to 32,768 tokens, with a fixed training context of 512 tokens. Throughout the evaluation, MIRA attains the lowest perplexity among the strong recurrent baselines and matches or improves on MHA. Full experiments are presented in Appendix A.1.
5 CONCLUSIONS
We present MIRA, a recurrent, linear-time architectural family that eliminates the pole-geometry bias. MIRA unifies recurrent architectures and removes the pole-geometry bias through lattice-ladder realizations of higher-order IIR systems. The lattice-ladder parameterization admits chunk-wise associativity, enabling efficient GPU parallelism. We implement a dedicated CUDA kernel by leveraging this algebraic structure. Language modeling experiments demonstrate that MIRA outperforms strong recurrent language model baselines and generalizes beyond the training context without explicit positional encoding. These results establish MIRA as a promising direction for efficient LLMs.
AI USE STATEMENT
In this work, we used generative AI tools for: polishing writing drafted by the human authors; checking for typographical and grammatical errors; refining wording choices; partially assisting with the development of experimental code; assisting human mathematicians in verifying and normalizing proofs (e.g., standardizing notations); and retrieving related literature. We have not used generative AI tools for drafting the manuscript, fully deriving proofs without the supervision of the human mathematician (the first author), or developing the theoretical model, retrieving bibliography, and the rest of the required disclosure tasks are not applicable to this work. We have reviewed all AI-assisted work. For example, we carefully reviewed LLM-polished sentences; verified LLM-normalized proofs through numerical experiments, symbolic algebra, and independent examination by human mathematicians; and manually verified LLM-aided literature retrieval by consulting the ACM Digital Library or the literature's original publication venues, such as OpenReview, and having human experts read the retrieved works. We take responsibility for the final content of this work, including text, claims or artifacts produced with the aid of generative AI.
ACKNOWLEDGMENTS
This research was financially supported in part by Taighde Éireann – Research Ireland under Grant No. 18/CRT/6223, and by the J.E. Cairnes School of Business & Economics, University of Galway, Ireland. It was also supported in part by computational resources and services provided by Calcul Québec (calculquebec.ca) and the Digital Research Alliance of Canada (alliancecan.ca). Partial computational support was also provided by Taighde Éireann – Research Ireland under Grant No. SFI/12/RC/2289_P2 and the Insight Research Ireland Centre for Data Analytics. The authors gratefully acknowledge Prof. Karyn Morrissey of the J.E. Cairnes School of Business & Economics, University of Galway, Ireland, for the support. For the purpose of open access, the author has applied a CC BY public copyright licence to any Author Accepted Manuscript version arising from this submission.
REFERENCES
Simran Arora, Sabri Eyuboglu, Aman Timalsina, Isys Johnson, Michael Poli, James Zou, Atri Rudra, and Christopher Re. Zoology: Measuring and improving recall in efficient language models. In The Twelfth International Conference on Learning Representations, 2024. URL https://openreview.net/forum?id=LY3ukUANko.
George A. Campbell. Physical theory of the electric wave-filter. Bell System Technical Journal, 1(2): 1–32, 1922. doi: https://doi.org/10.1002/j.1538-7305.1922.tb00386.x. URL https://onlinelibrary.wiley.com/doi/abs/10.1002/j.1538-7305.1922.tb00386.x.
Arthur Cayley. Sur quelques propriétés des déterminants gauches. Journal für die reine und angewandte Mathematik, 32:119–123, 1846.
Paul F. Christiano, Jan Leike, Tom B. Brown, Miljan Martic, Shane Legg, and Dario Amodei. Deep reinforcement learning from human preferences. In Proceedings of the 31st International Conference on Neural Information Processing Systems, NIPS'17, pp. 4302–4310, Red Hook, NY, USA, 2017. Curran Associates Inc. ISBN 9781510860964.
Peter Clark, Isaac Cowhey, Oren Etzioni, Tushar Khot, Ashish Sabharwal, Carissa Schoenick, and Oyvind Tafjord. Think you have solved question answering? try arc, the ai2 reasoning challenge, 2018. URL https://arxiv.org/abs/1803.05457.
A. Cohn. Über die anzahl der wurzeln einer algebraischen gleichung in einem kreise. Mathematische Zeitschrift, 14(1):110–148, 1922. doi: 10.1007/BF01215894. URL https://doi.org/10.1007/BF01215894.
Tri Dao, Daniel Y Fu, Stefano Ermon, Atri Rudra, and Christopher Re. Flashattention: Fast and memory-efficient exact attention with IO-awareness. In Alice H. Oh, Alekh Agarwal, Danielle Belgrave, and Kyunghyun Cho (eds.), Advances in Neural Information Processing Systems, 2022. URL https://openreview.net/forum?id=H4DqfPSibmx.
Leonardo De Moura and Nikolaj Bjørner. Z3: an efficient smt solver. In Proceedings of the Theory and Practice of Software, 14th International Conference on Tools and Algorithms for the Construction and Analysis of Systems, TACAS'08/ETAPS'08, pp. 337–340, Berlin, Heidelberg, 2008. Springer-Verlag. ISBN 3540787992.
A. Gray and J. Markel. Digital lattice and ladder filter synthesis. IEEE Transactions on Audio and Electroacoustics, 21(6):491–500, 1973. doi: 10.1109/TAU.1973.1162522.
Albert Gu and Tri Dao. Mamba: Linear-time sequence modeling with selective state spaces. In First Conference on Language Modeling, 2024. URL https://openreview.net/forum?id=tEYskw1VY2.
Dan Hendrycks, Collin Burns, Steven Basart, Andrew Critch, Jerry Li, Dawn Song, and Jacob Steinhardt. Aligning ai with shared human values. Proceedings of the International Conference on Learning Representations (ICLR), 2021a.
Dan Hendrycks, Collin Burns, Steven Basart, Andy Zou, Mantas Mazeika, Dawn Song, and Jacob Steinhardt. Measuring massive multitask language understanding. Proceedings of the International Conference on Learning Representations (ICLR), 2021b.
Jordan Hoffmann, Sebastian Borgeaud, Arthur Mensch, Elena Buchatskaya, Trevor Cai, Eliza Rutherford, Diego de Las Casas, Lisa Anne Hendricks, Johannes Welbl, Aidan Clark, Tom Hennigan, Eric Noland, Katie Millican, George van den Driessche, Bogdan Damoc, Aurelia Guy, Simon Osindero, Karen Simonyan, Erich Elsen, Oriol Vinyals, Jack W. Rae, and Laurent Sifre. Training compute-optimal large language models. In Proceedings of the 36th International Conference on Neural Information Processing Systems, NIPS '22, Red Hook, NY, USA, 2022. Curran Associates Inc. ISBN 9781713871088.
Cheng-Ping Hsieh, Simeng Sun, Samuel Kriman, Shantanu Acharya, Dima Rekesh, Fei Jia, and Boris Ginsburg. RULER: What's the real context size of your long-context language models? In First Conference on Language Modeling, 2024. URL https://openreview.net/forum?id=kloBbc76Sy.
Harold Jeffreys. An invariant form for the prior probability in estimation problems. Proceedings of the Royal Society of London. Series A, 186(1007):453–461, 1946.
Samy Jelassi, David Brandfonbrener, Sham M. Kakade, and Eran Malach. Repeat after me: transformers are better than state space models at copying. In Proceedings of the 41st International Conference on Machine Learning, ICML'24. JMLR.org, 2024.
Dhiraj Kalamkar, Dheevatsa Mudigere, Naveen Mellempudi, Dipankar Das, Kunal Banerjee, Sasikanth Avancha, Dharma Teja Vooturi, Nataraj Jammalamadaka, Jianyu Huang, Hector Yuen, Jiyan Yang, Jongsoo Park, Alexander Heinecke, Evangelos Georganas, Sudarshan Srinivasan, Abhisek Kundu, Misha Smelyanskiy, Bharat Kaul, and Pradeep Dubey. A study of bfloat16 for deep learning training, 2019. URL https://arxiv.org/abs/1905.12322.
R. E. Kalman. Irreducible realizations and the degree of a rational matrix. Journal of the Society for Industrial and Applied Mathematics, 13(2):520–544, 1965. doi: 10.1137/0113034. URL https://doi.org/10.1137/0113034.
Greg Kamradt. Needle in a haystack. GitHub repository, 2023. URL https://github.com/gkamradt/needle-in-a-haystack.
Jared Kaplan, Sam McCandlish, Tom Henighan, Tom B. Brown, Benjamin Chess, Rewon Child, Scott Gray, Alec Radford, Jeffrey Wu, and Dario Amodei. Scaling laws for neural language models, 2020. URL https://arxiv.org/abs/2001.08361.
Angelos Katharopoulos, Apoorv Vyas, Nikolaos Pappas, and François Fleuret. Transformers are rnns: fast autoregressive transformers with linear attention. In Proceedings of the 37th International Conference on Machine Learning, ICML'20. JMLR.org, 2020.
Hao Liu and Pieter Abbeel. Blockwise parallel transformers for large context models. In Thirty-seventh Conference on Neural Information Processing Systems, 2023. URL https://openreview.net/forum?id=KbqQMoqfLQ.
Ilya Loshchilov and Frank Hutter. Decoupled weight decay regularization. In International Conference on Learning Representations, 2019. URL https://openreview.net/forum?id=Bkg6RiCqY7.
Stephen Merity, Caiming Xiong, James Bradbury, and Richard Socher. Pointer sentinel mixture models, 2016.
Leonardo de Moura and Sebastian Ullrich. The lean 4 theorem prover and programming language. In Automated Deduction – CADE 28: 28th International Conference on Automated Deduction, Virtual Event, July 12–15, 2021, Proceedings, pp. 625–635, Berlin, Heidelberg, 2021. Springer-Verlag. ISBN 978-3-030-79875-8. doi: 10.1007/978-3-030-79876-5_37. URL https://doi.org/10.1007/978-3-030-79876-5_37.
Alan V. Oppenheim and Ronald W. Schafer. Discrete-Time Signal Processing. Pearson, 3rd edition, 2010.
Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, Carroll L. Wainwright, Pamela Mishkin, Chong Zhang, Sandhini Agarwal, Katarina Slama, Alex Ray, John Schulman, Jacob Hilton, Fraser Kelton, Luke Miller, Maddie Simens, Amanda Askell, Peter Welinder, Paul Christiano, Jan Leike, and Ryan Lowe. Training language models to follow instructions with human feedback. In Proceedings of the 36th International Conference on Neural Information Processing Systems, NIPS '22, Red Hook, NY, USA, 2022. Curran Associates Inc. ISBN 9781713871088.
Guilherme Penedo, Hynek Kydlíček, Loubna Ben allal, Anton Lozhkov, Margaret Mitchell, Colin Raffel, Leandro Von Werra, and Thomas Wolf. The fineweb datasets: Decanting the web for the finest text data at scale. In The Thirty-eight Conference on Neural Information Processing Systems Datasets and Benchmarks Track, 2024. URL https://openreview.net/forum?id=n6SCKn2QaG.
Bo Peng, Eric Alcaide, Quentin Anthony, Alon Albalak, Samuel Arcadinho, Stella Biderman, Huanqi Cao, Xin Cheng, Michael Chung, Leon Derczynski, Xingjian Du, Matteo Grella, Kranthi Gv, Xuzheng He, Haowen Hou, Przemyslaw Kazienko, Jan Kocon, Jiaming Kong, Bartlomiej Koptyra, Hayden Lau, Jiaju Lin, Krishna Sri Ipsit Mantri, Ferdinand Mom, Atsushi Saito, Guangyu Song, Xiangru Tang, Johan Wind, Stanislaw Woźniak, Zhenyuan Zhang, Qinghua Zhou, Jian Zhu, and Rui-Jie Zhu. RWKV: Reinventing RNNs for the transformer era. In Houda Bouamor, Juan Pino, and Kalika Bali (eds.), Findings of the Association for Computational Linguistics: EMNLP 2023, pp. 14048–14077, Singapore, December 2023. Association for Computational Linguistics. doi: 10.18653/v1/2023.findings-emnlp.936. URL https://aclanthology.org/2023.findings-emnlp.936/.
Bowen Peng, Jeffrey Quesnelle, Honglu Fan, and Enrico Shippole. YaRN: Efficient context window extension of large language models. In The Twelfth International Conference on Learning Representations, 2024. URL https://openreview.net/forum?id=wHBfxhZu1u.
Michael Poli, Stefano Massaroli, Eric Nguyen, Daniel Y. Fu, Tri Dao, Stephen Baccus, Yoshua Bengio, Stefano Ermon, and Christopher Ré. Hyena hierarchy: towards larger convolutional language models. In Proceedings of the 40th International Conference on Machine Learning, ICML'23. JMLR.org, 2023.
Zhen Qin, Songlin Yang, Weixuan Sun, Xuyang Shen, Dong Li, Weigao Sun, and Yiran Zhong. HGRN2: Gated linear RNNs with state expansion. In First Conference on Language Modeling, 2024. URL https://openreview.net/forum?id=y6SqbJfCSk.
Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. Language models are unsupervised multitask learners. OpenAI Technical Report, 2019.
Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, Christopher D. Manning, and Chelsea Finn. Direct preference optimization: your language model is secretly a reward model. In Proceedings of the 37th International Conference on Neural Information Processing Systems, NIPS '23, Red Hook, NY, USA, 2023. Curran Associates Inc.
Imanol Schlag, Kazuki Irie, and Jürgen Schmidhuber. Linear transformers are secretly fast weight programmers. In Marina Meila and Tong Zhang (eds.), Proceedings of the 38th International Conference on Machine Learning, volume 139 of Proceedings of Machine Learning Research, pp. 9355–9366. PMLR, 18–24 Jul 2021. URL https://proceedings.mlr.press/v139/schlag21a.html.
J. Schur. Über potenziereihen, die im innern des einheitskreises beschränkt sind. Journal für die reine und angewandte Mathematik, 1917(147):205–232, 1917. doi: 10.1515/crl1.1917.147.205. URL https://doi.org/10.1515/crl1.1917.147.205.
Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units. In Katrin Erk and Noah A. Smith (eds.), Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pp. 1715–1725, Berlin, Germany, August 2016. Association for Computational Linguistics. doi: 10.18653/v1/P16-1162. URL https://aclanthology.org/P16-1162/.
Jianlin Su, Murtadha Ahmed, Yu Lu, Shengfeng Pan, Wen Bo, and Yunfeng Liu. Roformer: Enhanced transformer with rotary position embedding. Neurocomput., 568(C), February 2024. ISSN 0925-2312. doi: 10.1016/j.neucom.2023.127063. URL https://doi.org/10.1016/j.neucom.2023.127063.
Yutao Sun, Li Dong, Shaohan Huang, Shuming Ma, Yuqing Xia, Jilong Xue, Jianyong Wang, and Furu Wei. Retentive network: A successor to transformer for large language models. arXiv preprint, August 2023. URL https://www.microsoft.com/en-us/research/publication/retentive-network-a-successor-to-transformer-for-large-language-models/.
Laurens van der Maaten and Geoffrey Hinton. Visualizing data using t-sne. Journal of Machine Learning Research, 9(86):2579–2605, 2008. URL http://jmlr.org/papers/v9/vandermaaten08a.html.
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, and Illia Polosukhin. Attention is all you need. In Proceedings of the 31st International Conference on Neural Information Processing Systems, NIPS'17, pp. 6000–6010, Red Hook, NY, USA, 2017. Curran Associates Inc. ISBN 9781510860964.
Eli Yablonovitch. Inhibited spontaneous emission in solid-state physics and electronics. Phys. Rev. Lett., 58:2059–2062, May 1987. doi: 10.1103/PhysRevLett.58.2059. URL https://link.aps.org/doi/10.1103/PhysRevLett.58.2059.
Songlin Yang, Bailin Wang, Yikang Shen, Rameswar Panda, and Yoon Kim. Gated linear attention transformers with hardware-efficient training. In Ruslan Salakhutdinov, Zico Kolter, Katherine Heller, Adrian Weller, Nuria Oliver, Jonathan Scarlett, and Felix Berkenkamp (eds.), Proceedings of the 41st International Conference on Machine Learning, volume 235 of Proceedings of Machine Learning Research, pp. 56501–56523. PMLR, 21–27 Jul 2024a. URL https://proceedings.mlr.press/v235/yang24ab.html.
Songlin Yang, Bailin Wang, Yu Zhang, Yikang Shen, and Yoon Kim. Parallelizing linear transformers with the delta rule over sequence length. In The Thirty-eighth Annual Conference on Neural Information Processing Systems, 2024b. URL https://openreview.net/forum?id=y8Rm4VNRPH.
Songlin Yang, Jan Kautz, and Ali Hatamizadeh. Gated delta networks: Improving mamba2 with delta rule. In The Thirteenth International Conference on Learning Representations, 2025. URL https://openreview.net/forum?id=r8H7xhYPwz.
Rowan Zellers, Ari Holtzman, Yonatan Bisk, Ali Farhadi, and Yejin Choi. Hellaswag: Can a machine really finish your sentence? In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, 2019.
Biao Zhang and Rico Sennrich. Root mean square layer normalization. Curran Associates Inc., Red Hook, NY, USA, 2019.
A APPENDIX
A.1 ADDITIONAL EXPERIMENTAL RESULTS
A.1.1 PRETRAINING DYNAMICS (ACCURACY, LOSS, AND PERPLEXITY)

Figure 7: Dynamics of Pretraining Benchmark. We implement a small-scale reference LLM composed entirely of MIRA blocks, denoted as MIRA-S. Pretraining results show that MIRA-S achieves the lowest perplexity among strong recurrent language model baselines and Transformer-based MHA, while attaining higher token-prediction accuracy than the recurrent baselines and comparable token-prediction accuracy to MHA.

Figure 8: Final-Stage Dynamics of the Pretraining Benchmark. Training loss over the final stage of pretraining for MIRA-S and the baseline models.
A.1.2 ZERO-SHOT & FEW-SHOT PROMPTING
Zero-Shot & Few-Shot Prompting. We evaluate the pretrained LLMs on the full MMLU (Massive Multitask Language Understanding) test set across all 57 subjects (Hendrycks et al., 2021b;a) using zero-shot and 5-shot prompting. Zero-shot prompts contain the test question and its answer choices, whereas five-shot prompts additionally include five answered examples from the corresponding subject's development split. We select the answer choice with the highest predicted probability and report overall test accuracy without updating model parameters. For prompts exceeding the training context window of the baseline Transformer, we apply YaRN (Peng et al., 2024) for extrapolating the positional embeddings.

Figure 9: Zero-Shot & Few-Shot Prompting.
A.1.3 ARC REASONING
ARC Reasoning. We evaluate the pretrained LLMs on the AI2 Reasoning Challenge (ARC) (Clark et al., 2018), a benchmark of grade-school science questions with three to five answer choices, divided into an Easy set and a Challenge set, the latter containing the questions that both a retrieval-based and a word co-occurrence baseline answer incorrectly; we use the full test sets of 2,376 Easy and 1,172 Challenge questions, of which 3,530 out of 3,548 have four answer choices. Zero-shot prompts consist of the test question in the form
Question: ... Answer:
whereas 25-shot prompts additionally precede the test question with 25 answered examples in the same form, taken in order from the training split of the same set. We score each answer choice by the sum of the log-probabilities that the model assigns to the tokens of that choice conditioned on the prompt, divided by the number of characters in the choice so that longer choices are not penalized, select the answer choice with the highest normalized score, and report the resulting length-normalized test accuracy in Figure 10.

Figure 10: ARC Reasoning with Zero-Shot & Few-Shot Prompting.
A.1.4 CONTEXT-WINDOW GENERALIZATION EXPERIMENTS
Context Window Generalization. We evaluate context-length generalization for MIRA, Mamba-1 (S6), Mamba-2 (SSD), RWKV-6, and RWKV-7, with MHA as a reference, on three corpora: a held-out set of FineWeb-Edu (230 documents, 263,837 tokens), WikiText-103 (Merity et al., 2016), and HellaSwag (Zellers et al., 2019). Besides MHA without positional-encoding extrapolation (legend “MHA”), we also apply YaRN (Peng et al., 2024) to MHA beyond the training context length, with legend “MHA (YaRN)”. Figure 6 reports perplexity for context lengths from 256 to 32,768 tokens, with a fixed training context of 512 tokens. Throughout the evaluation, MIRA attains the lowest perplexity among the strong recurrent baselines and matches or improves on MHA.

(a) Loss.

(b) Perplexity.

(c) Token accuracy.
Figure 11: Context-window generalization experiments.
A.1.5 EXTRA CONTEXT-WINDOW GENERALIZATION EXPERIMENTS
Extra context-window generalization experiments. We further evaluate the pretrained MIRA-S on sequences extending beyond their training context windows to assess their ability to generalize to longer contexts, reporting results on held-out FineWeb-Edu (Penedo et al., 2024), WikiText-103 (Merity et al., 2016), and HellaSwag (Zellers et al., 2019). We use four tasks: needle-in-a-haystack retrieval of a single fact embedded in background text (Kamradt, 2023), RULER-style multi-key retrieval with distractors (Hsieh et al., 2024), multi-query associative recall (MQAR) of multiple key-value associations queried in a different order (Arora et al., 2024), and copying of an earlier text span (Jelassi et al., 2024). We vary the evaluation context length while keeping model parameters fixed and report token accuracy on the retrieved answers or copied continuations.

(a) Needle-in-a-haystack retrieval.

(b) RULER-style multi-key retrieval.

(c) Multi-query associative recall.

(d) Copying.
Figure 12: Extra context-window generalization experiments.
A.1.6 PROFILING DYNAMICS
Profiling dynamics. We profile MIRA-S throughout training to track the per-layer evolution of the rotation angle of Cayley matrix , radius , and characteristic horizon , where indexes tokens, indexes lattice stages, and indexes channels. At each profiling step, we compute these quantities from the token-dependent coefficients and report their 10-th, 50-th, and 90-th percentiles within each layer. We additionally compute the poles of the assembled lattice transition matrix for each token and channel, reporting the fraction with nonzero imaginary parts in the rotation-angle panel and the median pole modulus in the radius panel.

Figure 13: Profiling rotation-angle dynamics ().

Figure 14: Profiling pole-radius dynamics ().

Figure 15: Characteristic-horizon dynamics ().
A.1.7 INITIALIZER ABLATION
Initializer Ablation. We ablate the initialization of the coefficient projection, namely the weights and the biases , on MIRA-XS with and , where every other parameter is initialized identically, and train each variant for 10,000 steps on The Stack and on FineWeb-Edu, reporting held-out perplexity and token accuracy, with each bar labelled in the legend by the name of its initializer. Throughout, .
-
uniform w/ jeffreys is our default: the characteristic horizons of a layer are the quantiles of the Jeffreys prior on , with the Fisher information of the decay rate and in the first layer), assigned to channels by a random permutation; channel starts from the pole pair with , cycling through 5, 7, 11, 17, 23, 31, 43, 61, and when ; the step-down recursion converts its denominator into reflection coefficients , realized as and and inverted through the radius and rotation maps into and ; every weight is drawn from , and take a random sign and a magnitude uniform in .
-
pytorch-uniform resets the coefficient projection to the PyTorch default of a linear layer, , which removes any structure from the initial poles.
-
pytorch-normal draws , which likewise removes any structure from the initial poles.
-
jeffreys w/ uniform is the control for placing the Jeffreys poles in the biases: it draws and sets every entry of row of to , where is the bias of that row under the default and is the -th entry of the control , with the normalized input taken as standard normal; the initial poles therefore equal those of the default on average over tokens, but are carried by the weights rather than the biases; are those of the default.
-
jeffreys w/ normal is the same control with .
-
normal w/ jeffreys keeps the biases of the default and draws the weights from , of the same standard deviation.
• uniform w/ b nested jeffreys assigns one Jeffreys horizon per pole pair, pair at the quantile shifted by the van der Corput value , and scales by , which makes it identical to the default at .
• uniform horizon w/ fixed angles draws and the fixed angle , obtains and by the same recursion, draws each entry of a row of with a random sign and a magnitude uniform in for the bias of that row, and draws with a random sign and a magnitude uniform in .
• uniform horizon w/ fixed angles, right half-plane places every pole in the right half-plane, the real pole of odd orders at and the angles taken from a second table, and coincides with uniform horizon w/ fixed angles at K = 2.
uniform draws from , maps the drawn biases to the poles they define under and , and initializes as uniform horizon w/ fixed angles does.

Figure 16: Initializer ablation experiment.
A.1.8 VISUALIZING MEMORY-STATE PROJECTION
Visualizing memory-state projection. To examine what the recurrent state of MIRA-S retains about a document, we treat each of the 14,042 questions of the MMLU test set (Hendrycks et al., 2021b;a), formatted as its zero-shot prompt and terminated by the end-of-document token <|end-of-session|>, as one document and feed it to the pretrained MIRA-S from a zero initial state. The state of the last layer at <|end-of-session|>, the final token of the document, flattened into a vector of entries, serves as the document embedding, and the subject of the question, one of the 57 MMLU subjects, serves as its label. The embeddings are projected onto their first 50 principal components and mapped to two dimensions with t-SNE (van der Maaten & Hinton, 2008) at perplexity 30. Figure 17 shows the resulting embedding, colored by subject. Figure 18 shows the corresponding projection of GPT-2's last-layer hidden states for reference. This suggests that MIRA has the potential to extract more discriminative embeddings.

Figure 17: Visualizing memory-state projection.

Figure 18: Visualizing the projection of GPT-2's last-layer hidden states for reference.
A.1.9 BPE TOKENIZER
Python BPE versus C++ BPE. Our byte-level BPE tokenizer has two implementations, one in Python and one in C++17 that depends on nothing beyond the C++ standard library, and the C++ implementation is the default. Figure 19 shows the benchmark on WikiText-103.

Figure 19: BPE Tokenizer benchmark.
A.1.10 MODULUS & ARGUMENT MAPS
Modulus & Argument Maps. Each lattice stage places its pole at modulus and argument , where indexes the token; is produced from the control by a modulus map and from the control by an argument map. We compare the following modulus maps:
• Cauchy (default): ;
• Gaussian: ;
• exp-exp: ;
• exp-softplus: , where ;
and the following argument maps:
• hyperbolic (default): ;
• Möbius: , ;
• identity: .

Figure 20: Modulus map.

Figure 21: Argument map.
A.2 MIRA NON-CUDA-ACCELERATED PSEUDO CODE
The following PyTorch pseudocode implements the MIRA forward pass sequentially using the Cauchy radius and hyperbolic rotation.
A.2.1 SEQUENTIAL-LATTICE IMPLEMENTATION (CONCEPTUAL CODE)
def forward(self, x, state=None): B, T, d = x.shape de, dr, dm, K = self.de, self.dr, self.dm, self.K
z = self.rn1(x) x_tilde, raw_s = self.W_in_s(z).split([de, dm], dim=-1) s = F.silu(raw_s) c = F.silu(self.W_c(z)) alpha, beta, rho, nu = self.W_control(c).split( [K * de, K * de, (K + 1) * de, (K + 1) * dm], dim=-1)
alpha = alpha.float().reshape(B, T, de, K) beta = beta.float().reshape(B, T, de, K) rho = rho.float().reshape(B, T, de, K + 1) nu = nu.float().reshape(B, T, K + 1, dm) gamma = F.silu(self.W_gamma(z).float()) x_tilde, s = x_tilde.float(), s.float()
if state is None: state = torch.zeros( B, K, de, dm, device=x.device, dtype=torch.float32) else: state = state.to(device=x.device, dtype=torch.float32)
outputs = [] for t in range(T): U = x_tilde[:, t, :, None] * s[:, t, None, :] V = [None] * (K + 1)
for k in range(K, 0, -1): V_prev = state[:, k - 1] alpha_t = alpha[:, t, :, k - 1, None] beta_t = beta[:, t, :, k - 1, None]
r = 1 / (1 + beta_t.square()) cos_theta = 1 / torch.cosh(alpha_t) sin_theta = torch.sinh(alpha_t) / torch.cosh(alpha_t)
V[k] = r * (sin_theta * U + cos_theta * V_prev) U = r * (cos_theta * U - sin_theta * V_prev)
V[0] = U V = torch.stack(V, dim=1) state = V[:, :K]
y = torch.einsum("bkem,bkm->bke", V, nu[:, t]) y = (rho[:, t].transpose(1, 2) * y).sum(dim=1) outputs.append(gamma[:, t] * y)
y = torch.stack(outputs, dim=1).to(z.dtype) x = x + self.W_out(y) x = x + self.ffn(self.rn2(x)) return x, state
A.2.2 PARALLEL-LATTICE IMPLEMENTATION (PRODUCT VERSION)
def forward(self, x, state=None): B, T, d = x.shape de, dr, dm, K = self.de, self.dr, self.dm, self.K
z = self.rn1(x) x_tilde, raw_s = self.W_in_s(z).split([de, dm], dim=-1) s = F.silu(raw_s) c = F.silu(self.W_c(z)) alpha, beta, rho, nu = self.W_control(c).split([K * de, K * de, (K + 1) * de, (K + 1) * dm], dim=-1)
alpha = alpha.float().reshape(B, T, de, K) beta = beta.float().reshape(B, T, de, K) rho = rho.float().reshape(B, T, de, K + 1) nu = nu.float().reshape(B, T, K + 1, dm) gamma = F.silu(self.W_gamma(z).float()) x_tilde, s = x_tilde.float(), s.float()
D^(k) = r^(k) cos(theta^(k)),
# E^(k) = r^(k) sin(theta^(k)),
# every token and stage at once; stage k at index k - 1
r = 1 / (1 + beta.square())
D = r / torch.cosh(alpha)
E = r * torch.tanh(alpha)
# D0[... , k] = D^(k); E0[... , k] = E^(k), E0[... , 0] = 1
one = torch.ones_like(D[... , :1])
D0 = torch.cat([one, D], dim=-1)
E0 = torch.cat([one, E], dim=-1)
G[k, i] = D^(k+1) ... D^(i) for i >= k (G[k, k] = 1),
# else 0
upper = torch.ones(K + 1, K + 1, dtype=torch.bool,
device=x.device).triu()
G = torch.where(upper.triu(1), D0[... , None, :], 1.0)
G = G.cumprod(-1) * upper
the K stages solved in closed form:
# U^(k) = G[k, K] U^(K)
# - sum_{j} >= k} G[k, j] E^(j+1) V_{t-1}^(j)
# V^(k) = E^(k) U^(k) + D^(k) V_{t-1}^(k-1)
# V^(0) = U^(0)
# so V_t^(0..K) = Phi_t V_{t-1}^(0..K-1)
# + S_coef_t U_t^(K);
# rows 0..K-1 of Phi_t are Phi_t, row K gives V_t^(K)
# S_coef: (B, T, de, K+1), Phi: (B, T, de, K+1, K)
S_coef = E0 * G[... , K]
Phi = (-E0[... , None] * G[... , :K] * E[... , None, :])
+ torch.diag_embed(D, offset=-1) [... , :K])
U_t^(K) = x_tilde_t s_t^T
U = x_tilde[... , None] * s[:, :, None, :]
if state is None: state = torch.zeros(B, K, de, dm, device=x.device, dtype=torch.float32) else: state = state.to(device=x.device, dtype=torch.float32)
the affine scan V_t = Phi_t V_{t-1} + S_t over tokens
V = []
scan tokens
for t in range(T): S_t = (S_coef[:, t].transpose(1, 2) [..., None] * U[:, t, None]) V_t = torch.einsum("bekj,bjem->bkem", Phi[:, t], state) + S_t state = V_t[:, :K] V.append(V_t)
V: (B, T, K+1, de, dm)
V = torch.stack(V, dim=1)
y_t = (sum_k rho_t^(k) * (V_t^(k) nu_t^(k))) * gamma_t
y = gamma * torch.einsum("btkem,btkm,btek->bte", V, nu, rho)
y = y.to(z.dtype) x = x + self.W_out(y) x = x + self.ffn(self.rn2(x)) return x, state
A.3 MIRA PARAMETER AND STATE SIZES
Parameter & State Sizes. Let be the number of layers, be the model width, be the lattice-channel width, be the write bottleneck size, be the memory dimension, be the lattice order, and be the FFN width. Let and be the parameter counts of the MIRA mixer and a complete layer, respectively, and let be the recurrent state size per sequence. Collecting the parameter contributions, with the width-product terms preceding the bias terms, gives
Let be the vocabulary size. Including tied embedding and output weights and the final affine RMSNorm, the model parameter count , recurrent state size , and state-to-parameter ratio are
A.3.1 CONFIGURATION REFERENCE TABLE
| d | d_e | d_r | d_m | d_fn | K | P_mixer | P_layer | S_layer | S_layer/P_layer (%) |
|---|---|---|---|---|---|---|---|---|---|
| 768 | 1536 | 48 | 16 | 3072 | 2 | 4.119 M | 8.843 M | 49.152 K | 5.56 |
| 768 | 1536 | 48 | 16 | 3072 | 4 | 4.572 M | 9.296 M | 98.304 K | 10.57 |
| 768 | 1536 | 48 | 16 | 3072 | 8 | 5.478 M | 10.202 M | 196.608 K | 19.27 |
| 768 | 1536 | 96 | 16 | 3072 | 2 | 4.674 M | 9.398 M | 49.152 K | 5.23 |
| 768 | 1536 | 96 | 16 | 3072 | 4 | 5.571 M | 10.295 M | 98.304 K | 9.55 |
| 768 | 1536 | 96 | 16 | 3072 | 8 | 7.365 M | 12.089 M | 196.608 K | 16.26 |
| 768 | 1536 | 48 | 32 | 3072 | 2 | 4.134 M | 8.857 M | 98.304 K | 11.10 |
| 768 | 1536 | 48 | 32 | 3072 | 4 | 4.588 M | 9.312 M | 196.608 K | 21.11 |
| 768 | 1536 | 48 | 32 | 3072 | 8 | 5.498 M | 10.222 M | 393.216 K | 38.47 |
| 768 | 1536 | 96 | 32 | 3072 | 2 | 4.691 M | 9.415 M | 98.304 K | 10.44 |
| 768 | 1536 | 96 | 32 | 3072 | 4 | 5.591 M | 10.315 M | 196.608 K | 19.06 |
| 768 | 1536 | 96 | 32 | 3072 | 8 | 7.392 M | 12.116 M | 393.216 K | 32.46 |
| 768 | 1536 | 48 | 64 | 3072 | 2 | 4.163 M | 8.887 M | 196.608 K | 22.12 |
| 768 | 1536 | 48 | 64 | 3072 | 4 | 4.621 M | 9.345 M | 393.216 K | 42.08 |
| 768 | 1536 | 48 | 64 | 3072 | 8 | 5.536 M | 10.260 M | 786.432 K | 76.65 |
| 768 | 1536 | 96 | 64 | 3072 | 2 | 4.725 M | 9.449 M | 196.608 K | 20.81 |
| 768 | 1536 | 96 | 64 | 3072 | 4 | 5.631 M | 10.355 M | 393.216 K | 37.97 |
| 768 | 1536 | 96 | 64 | 3072 | 8 | 7.444 M | 12.168 M | 786.432 K | 64.63 |
| 1024 | 2048 | 64 | 64/3 | 4096 | 2 | 7.317 M | 15.713 M | 87.381 K | 5.56 |
| 1024 | 2048 | 64 | 64/3 | 4096 | 4 | 8.118 M | 16.514 M | 174.763 K | 10.58 |
| 1024 | 2048 | 64 | 64/3 | 4096 | 8 | 9.721 M | 18.117 M | 349.525 K | 19.29 |
| 1024 | 2048 | 128 | 64/3 | 4096 | 2 | 8.304 M | 16.700 M | 87.381 K | 5.23 |
| 1024 | 2048 | 128 | 64/3 | 4096 | 4 | 9.895 M | 18.291 M | 174.763 K | 9.55 |
| 1024 | 2048 | 128 | 64/3 | 4096 | 8 | 13.076 M | 21.472 M | 349.525 K | 16.28 |
| 1024 | 2048 | 64 | 128/3 | 4096 | 2 | 7.343 M | 15.739 M | 174.763 K | 11.10 |
| 1024 | 2048 | 64 | 128/3 | 4096 | 4 | 8.147 M | 16.543 M | 349.525 K | 21.13 |
| 1024 | 2048 | 64 | 128/3 | 4096 | 8 | 9.756 M | 18.152 M | 699.051 K | 38.51 |
| 1024 | 2048 | 128 | 128/3 | 4096 | 2 | 8.334 M | 16.730 M | 174.763 K | 10.45 |
| 1024 | 2048 | 128 | 128/3 | 4096 | 4 | 9.930 M | 18.326 M | 349.525 K | 19.07 |
| 1024 | 2048 | 128 | 128/3 | 4096 | 8 | 13.123 M | 21.519 M | 699.051 K | 32.49 |
| 1024 | 2048 | 64 | 256/3 | 4096 | 2 | 7.395 M | 15.791 M | 349.525 K | 22.13 |
| 1024 | 2048 | 64 | 256/3 | 4096 | 4 | 8.205 M | 16.601 M | 699.051 K | 42.11 |
| 1024 | 2048 | 64 | 256/3 | 4096 | 8 | 9.824 M | 18.220 M | 1.398 M | 76.73 |
| 1024 | 2048 | 128 | 256/3 | 4096 | 2 | 8.394 M | 16.790 M | 349.525 K | 20.82 |
| 1024 | 2048 | 128 | 256/3 | 4096 | 4 | 10.002 M | 18.397 M | 699.051 K | 38.00 |
| 1024 | 2048 | 128 | 256/3 | 4096 | 8 | 13.216 M | 21.612 M | 1.398 M | 64.69 |
| 2048 | 4096 | 128 | 128/3 | 8192 | 2 | 29.235 M | 62.804 M | 349.525 K | 5.57 |
| 2048 | 4096 | 128 | 128/3 | 8192 | 4 | 32.416 M | 65.985 M | 699.051 K | 10.59 |
| 2048 | 4096 | 128 | 128/3 | 8192 | 8 | 38.779 M | 72.347 M | 1.398 M | 19.32 |
| 2048 | 4096 | 256 | 128/3 | 8192 | 2 | 33.183 M | 66.752 M | 349.525 K | 5.24 |
| 2048 | 4096 | 256 | 128/3 | 8192 | 4 | 39.521 M | 73.090 M | 699.051 K | 9.56 |
| 2048 | 4096 | 256 | 128/3 | 8192 | 8 | 52.197 M | 85.766 M | 1.398 M | 16.30 |
| 2048 | 4096 | 128 | 256/3 | 8192 | 2 | 29.339 M | 62.907 M | 699.051 K | 11.11 |
| 2048 | 4096 | 128 | 256/3 | 8192 | 4 | 32.531 M | 66.100 M | 1.398 M | 21.15 |
| 2048 | 4096 | 128 | 256/3 | 8192 | 8 | 38.916 M | 72.484 M | 2.796 M | 38.58 |
| 2048 | 4096 | 256 | 256/3 | 8192 | 2 | 33.304 M | 66.872 M | 699.051 K | 10.45 |
| 2048 | 4096 | 256 | 256/3 | 8192 | 4 | 39.664 M | 73.232 M | 1.398 M | 19.09 |
| 2048 | 4096 | 256 | 256/3 | 8192 | 8 | 52.383 M | 85.952 M | 2.796 M | 32.53 |
| 2048 | 4096 | 128 | 512/3 | 8192 | 2 | 29.546 M | 63.115 M | 1.398 M | 22.15 |
| 2048 | 4096 | 128 | 512/3 | 8192 | 4 | 32.761 M | 66.330 M | 2.796 M | 42.16 |
| 2048 | 4096 | 128 | 512/3 | 8192 | 8 | 39.189 M | 72.758 M | 5.592 M | 76.86 |
| 2048 | 4096 | 256 | 512/3 | 8192 | 2 | 33.544 M | 67.113 M | 1.398 M | 20.83 |
| 2048 | 4096 | 256 | 512/3 | 8192 | 4 | 39.948 M | 73.517 M | 2.796 M | 38.03 |
| 2048 | 4096 | 256 | 512/3 | 8192 | 8 | 52.756 M | 86.324 M | 5.592 M | 64.78 |
A.4 INITIALIZER PSEUDO CODE
A.4.1 CONSTANTS AND HORIZONS
---
CONSTANTS
T_J : lag window of the Fisher information
GRID : points of the log-rate grid
H_TIE : horizon from which a pair angle is tied
KAPPA : a tied angle is min(angle, KAPPA / H)
SIGMA_W : standard deviation of the uniform W rows
GAP : stage radius r = 1 - GAP (1 - |kappa|)
PERIODS : phase-bank periods, cycled over channels
F_BOTH : fixed pair angles / pi, both half-planes
F_RIGHT : fixed pair angles / pi, right half-plane
T_J, GRID = 256, 200001 H_TIE, KAPPA, SIGMA_W = 100.0, 2.0, 0.02 GAP = 2.0 ** -13 PERIODS = (5, 7, 11, 17, 23, 31, 43, 61) F_BOTH = (0.25, 0.5, 0.75, 0.125, 0.375, 0.625, 0.875, 0.0625) F_RIGHT = (0.25, 0.125, 0.375, 0.0625, 0.1875, 0.3125, 0.4375, 0.03125)
---
RANDOM SIGN, magnitude from U(lo, hi)
def signed_uniform(shape, lo, hi): magnitude = torch.empty(shape).uniform_(lo, hi) sign = torch.empty(shape).bernoulli_(0.5) * 2 - 1 return magnitude * sign
---
JEFFREYS QUANTILES of the horizon H = 1 / lambda
density per unit log lambda: sqrt(I(lambda)) lambda,
I(lambda) = sum_{t=1}^{t} {T_J} t q^t, q = exp(-2 lambda),
on lambda in [1/hi, 1/lo]; levels in (0, 1), counted
from the fastest decay
def jeffreys_quantiles(levels, lo, hi): u = torch.linspace(math.log(1 / hi), math.log(1 / lo), GRID, dtype=torch.float64) q = torch.exp(-2 * torch.exp(u)) info = q * (1 - (T_J + 1) * q.pow(T_J) + T_J * q.pow(T_J + 1)) info = info / (1 - q).square() p = info.sqrt() * torch.exp(u) # cumulative distribution by trapezoids, then inverted F = torch.cumsum(0.5 * (p[1:] + p[-1]) * u.diff(), 0) F = torch.cat((F.new_zeros(1), F)) / F[-1] i = torch.searchsorted(F, levels).clamp(1, GRID - 1) w = (levels - F[i - 1]) / (F[i] - F[i - 1]) return torch.exp(-(u[i - 1] + w * (u[i] - u[i - 1]))))
the d_e quantiles (c - 1/2) / d_e, c = 1..d_e
def jeffreys_horizons(d_e, lo, hi): levels = (torch.arange(d_e, dtype=torch.float64) + 0.5) / d_e return jeffreys_quantiles(levels, lo, hi)
base-2 van der Corput value: 0, 1/2, 1/4, 3/4, 1/8, ...
def van_der_corput(m): value, digit = 0.0, 0.5
while m: value += digit * (m & 1) m >> = 1 digit *= 0.5 return value
NESTED JEFFREYS HORIZONS, one per pole: [d_e, ceil(K/2)]
column 0: the jeffreys horizon of the permuted channel
column m: quantile at (l_c + phi_m) mod 1,
l_c = (perm[c] + 1/2) / d_e,
phi_m = van_der_corput(m)
def nested_jeffreys_horizons(perm, K, lo, hi): d_e = len(perm) columns = [jeffreys_horizons(d_e, lo, hi)[perm]] levels = (perm.double() + 0.5) / d_e for m in range(1, (K + 1) // 2): shifted = torch.remainder( levels + van_der_corput(m), 1.0) columns.append(jeffreys_quantiles(shifted, lo, hi)) return torch.stack(columns, dim=-1)
A.4.2 POLES AND COEFFICIENTS
PRODUCT OF POLYNOMIALS in z^-1, one row per channel
def poly_mul(a, b): width = a.shape[1] + b.shape[1] - 1 out = a.new_zeros(a.shape[0], width) for i in range(b.shape[1]): out[:, i:i + a.shape[1]] += a * b[:, i:i + 1] return out
REFLECTION COEFFICIENTS kappa [d_e, K] (float64)
H [d_e]: one horizon per channel; pair j has radius
exp(-(1 + j/J)/H), the real pole (odd K) exp(-1/H)
H [d_e, ceil(K/2)]: one horizon per pole (nested)
real pole: -p (right=False) or +p (right=True)
pair angle: bank=False: pi F[j]
bank=True: the phase bank, tied to
min(angle, KAPPA / H_j) when H_j >= H_TIE
step-down (Schur) recursion of the denominator
def reflection_coefficients(H, K, right=False, bank=False): per_pole = H.ndim == 2 rad = torch.exp(-torch reciprocal(H.double())) first = rad[:, 0] if per_pole else rad d_e = first.shape[0] poly = torch.ones(d_e, 1, dtype=torch.float64) factors = [] if K % 2: p = rad[:, K // 2] if per_pole else first coef = -p if right else p factors.append(torch.stack( (torch.ones_like(p), coef), dim=-1)) poly = poly_mul(poly, factors[-1]) F = torch.tensor(F_RIGHT if right else F_BOTH, dtype=torch.float64) J = K // 2 for j in range(J): p = (rad[:, j] if per_pole else first.pow(1.0 + j / max(1, J))) if bank: c = torch.arange(d_e) P = torch.tensor(PERIODS, dtype=torch.float64) P = P[cremainder(len(PERIODS))] shift = 2 * math.pi / P - math.pi / 4 angle = torch.acos( torch.cos(math.pi * F[j] + shift)) H_j = -torch.reciprocal(torch.log(p)) tied = torch.minimum(angle, KAPPA / H_j) angle = torch.where(H_j >= H_TIE, tied, angle) else: angle = math.pi * F[j] factors.append(torch.stack( (torch.ones_like(first), -2 * p * torch.cos(angle), p.square()), dim=-1)) poly = poly_mul(poly, factors[-1]) kappa = torch.empty(d_e, K, dtype=torch.float64) a = poly for k in range(K, 0, -1): last = a[:, -1] kappa[:, k - 1] = last a = ((a - last.unsqueeze(-1) * a.flip(-1))[:, :-1] / (1 - last.square)).unsqueeze(-1)) # a channel whose float64 recursion gives some # |kappa| >= 1, or a value that is not finite, is # recomputed by step_down_decimal: the same recursion # in 100-digit decimal arithmetic ok = kappa.isfinite().all(-1) & (kappa.abs() < 1).all(-1) for c in (~ok).nonzero().flatten().tolist(): kappa[c] = kappa.new_tensor(step_down_decimal( [f[c].tolist() for f in factors], K)) return kappa
STAGE COEFFICIENTS, cauchy radius x hyperbolic rotation
r = 1 - GAP (1 - |kappa|), sin(theta) = kappa / r
alpha = aranh(sin(theta)), in float64 because r is
within GAP of 1
beta = sign * sqrt(1/r - 1)
def stage_coefficients(kappa, beta_sign): r64 = 1 - (1 - kappa.abs()) * GAP alpha = torch.atanh(kappa / r64).float() k32 = kappa.float() r32 = 1 - (1 - k32.abs()) * GAP beta = beta_sign * torch.sqrt(torch.reciprocal(r32) - 1) return alpha, beta
A.4.3 SHARED FUNCTIONS
THE COEFFICIENT PROJECTION of one layer, m:
m.W [rows, d_r], m.b [rows]; rows, in order: alpha [K d_e], beta [K d_e], rho [(K+1) d_e], nu [(K+1) d_m]; stage k of channel c: row c K + k - 1 m.W_c [d_r, d], m.b_c [d_r]: the control projection m.K, m.d_e, m.d_r, m.d_m; (m.lo, m.hi): the horizon range of the layer
def spans(m): a = m.K * m.d_e rho = (2 * a, 2 * a + (m.K + 1) * m.d_e) nu = (rho[1], rho[1] + (m.K + 1) * m.d_m) return a, rho, nu
s = (K+1) ^ (-1/4) / sqrt(d_r)
def readout_scale(m): return 1 / math.sqrt(m.d_r) * (m.K + 1) ** -0.25
START: every W and b entry has a random sign and a magnitude from U(s/4, s)
def start(m): s = readout_scale(m) m.W.copy_(signed_uniform(m.W.shape, s / 4, s)) m.b.copy_(signed_uniform(m.b.shape, s / 4, s))
PLACE POLES of horizons H into b_alpha, b_beta and scale
the W_alpha, W_beta rows to them
W_alpha, W_beta row: random sign, magnitude from
U(1/4, 1) min(|b_mob| / (4 sqrt(d_r)), s) x ratio,
b_mob: the cauchy x mobius coefficient of the stage,
alpha_mob = sign sqrt((1 - sin)/(1 + sin));
ratio (alpha rows): (d theta_mob / d alpha_mob)
/ (d theta / d alpha)
= 2 / (1 + alpha_mob^2) x cosh(alpha); beta rows: 1
returns (alpha, beta) [d_e, K]
def place_poles(m, H, right=False, bank=False): a, , __ = spans(m) kappa = reflection_coefficients(H, m.K, right, bank) shape = (m.d_e, m.K) alpha_sign = torch.empty(shape).bernoulli(0.5) * 2 - 1 beta_sign = torch.empty(shape).bernoulli(0.5) * 2 - 1 alpha, beta = stage_coefficients(kappa, beta_sign) k32 = kappa.float() sin32 = k32 / (1 - (1 - k32.abs)) * GAP) alpha_mob = alpha_sign * torch.sqrt((1 - sin32) / (1 + sin32)) b_mob = torch.cat(((alpha_mob.reshape(-1), beta.reshape(-1))) size = (b_mob.abs().clamp_min(1e-6) / (4 * math.sqrt(m.d_r))) size = size.clamp_max(readout_scale(m)) rotation = (2 / (1 + alpha_mob.double().square()) * torch.cosh(alpha.double())) ratio = torch.cat((rotation.reshape(-1), torch.ones(beta.numel(), dtype=torch.float64))) size = size * ratio.float() m.W[:2 * a] = (signed_uniform((2 * a, m.d_r), 0.25, 1.0) * size.unsqueeze(-1)) m.b[:a] = alpha.reshape(-1) m.b[a:2 * a] = beta.reshape(-1) return alpha, beta
UNIFORM W ROWS: every W entry from
U(-sqrt(3) SIGMA_W, sqrt(3) SIGMA_W); b is kept
nested: W_rho, W_nu then scaled by (3/(K+1))^ (1/4)
def uniform_weight_rows(m, nested=False):
limit = math.sqrt(3) * SIGMA_W m.W.uniform_(-limit, limit) if nested: _, rho, nu = spans(m) scale = (3 / (m.K + 1)) ** 0.25 m.W[rho[0]:rho[1]] *= scale m.W[nu[0]:nu[1]] *= scale
CONTROL MEAN E[c_j] of c = silu(W_c z + b_c), z ~ N(0, I):
pre-activation j ~ N(b_c[j], ||W_c[j]||^2), integrated
on 4801 points of [-12, 12] standard deviations
def control_mean(m): mean = m.b_c.double() spread = m.W_c.double().norm(dim=1) x = torch.linspace(-12, 12, 4801, dtype=torch.float64) w = torch.exp(-0.5 * x.square()) w = w / w.sum() pts = mean.unsqueeze(-1) + spread.unsqueeze(-1) * x return (F.silu(pts) * w).sum(-1)
A.4.4 IMPLEMENTATIONS
THE TEN INITIALIZERS, each on one layer m
W uniform w/ b jeffreys (the default)
def W_uniform_b_jeffreys(m): start(m) H = jeffreys_horizons(m.d_e, m.lo, m.hi) H = H[torch.randnperm(m.d_e)].float() coefficients = place_poles(m, H, bank=True) uniform_weight_rows(m) return coefficients
W uniform w/ b nested jeffreys
def W_uniform_b_nested_jeffreys(m): start(m) H = nested_jeffreys_horizons(torch.randnperm(m.d_e), m.K, m.lo, m.hi).float() place_poles(m, H, bank=True) uniform_weight_rows(m, nested=True)
W normal w/ b jeffreys
def W_normal_b_jeffreys(m): W_uniform_b_jeffreys(m) m.W.normal_(0, SIGMA_W)
W,b pytorch-uniform
def W_b_uniform(m): W_uniform_b_jeffreys(m) limit = 1 / math.sqrt(m.d_r) m.W.uniform_(-limit, limit) m.b.uniform_(-limit, limit)
W,b pytorch-normal
def W_b_normal(m): W_uniform_b_jeffreys(m) scale = 1 / math.sqrt(m.d_r) m.W.normal_(0, scale)
m.b.normal_(0, scale)
W JEFFREYS: the jeffreys stage coefficients carried by
the W_alpha, W_beta rows, b_alpha, b_beta redrawn:
every entry of row i = (b*i - b_i) / sum_j E[c_j],
b*i the W_uniform_b_jeffreys coefficient of the row,
so E[alpha], E[beta] equal those of the default
def place_in_weight_rows(m, coefficients, draw_bias): a, __, __ = spans(m) draw_bias(m.b[:2 * a]) response = control_mean(m).sum() alpha, beta = coefficients target = torch.cat((alpha.reshape(-1), beta.reshape(-1))).double() rows = (target - m.b[:2 * a].double()) / response m.W[:2 * a] = rows.unsqueeze(-1).expand( -1, m.d_r).float()
W jeffreys w/ b uniform
def W_jeffreys_b_uniform(m): bound = 1 / math.sqrt(m.d_r) place_in_weight_rows(m, W_uniform_b_jeffreys(m), lambda b: b.uniform_(-bound, bound))
W jeffreys w/ b normal
def W_jeffreys_b_normal(m): bound = 1 / math.sqrt(m.d_r) place_in_weight_rows(m, W_uniform_b_jeffreys(m), lambda b: b.normal_(0, bound))
uniform horizon w/ fixed angles
def uniform_horizon_fixed_angles(m): start(m) H = torch.empty(m.d_e).uniform_(m.lo, m.hi) place_poles(m, H)
uniform horizon w/ fixed angles, right half-plane
def uniform_horizon_fixed_angles_right(m): start(m) H = torch.empty(m.d_e).uniform_(m.lo, m.hi) place_poles(m, H, right=True)
ALPHA, BETA UNIFORM: W_alpha, W_beta, b_alpha, b_beta
from U(-1/sqrt(d_r), 1/sqrt(d_r)); b_alpha is read as
the cauchy x mobius coefficient,
sin(theta) = (1 - b^2) / (1 + b^2),
and mapped to the hyperbolic alpha = arctan(sin(theta))
of the same pole; b_beta is already a cauchy radius
def alpha_beta_uniform(m): start(m) a, , __ = spans(m) bound = 1 / math.sqrt(m.d_r) m.W[:2 * a].uniform(-bound, bound) m.b[:2 * a].uniform(-bound, bound) draw = m.b[:a].double() sin = ((1 - draw.square()) / (1 + draw.square))).clamp( -1 + 1e-12, 1 - 1e-12) m.b[:a] = torch.atanh(sin).float()
A.5 BENCHMARK CONFIGURATION
| Model | Configuration | Parameter size | State size | State-to-parameter ratio |
|---|---|---|---|---|
| MIRA-S | Width 768; FFN width 3072; lattice order 2; lattice width 1536; write bottleneck 48; memory dimension 16 | 144,715,392 | 589,824 | 0.004076 |
| Transformer | Width 912; FFN width 2587; 12 attention heads; head dimension 76; RoPE | 142,516,452 | 11,206,656 | 0.078634 |
| RWKV-6 | Width 832; FFN width 2836; 13 heads; head dimension 64 | 144,637,296 | 638,976 | 0.004418 |
| RWKV-7 | Width 720; FFN width 3277; 12 heads; head dimension 60 | 142,664,124 | 518,400 | 0.003634 |
| Mamba-1 | Width 816; FFN width 2891; inner width 1632; state dimension 16; convolution width 4; time-step rank 51 | 148,731,108 | 313,344 | 0.002107 |
| Mamba-2 | Width 816; FFN width 2891; inner width 1632; state dimension 128; 12 heads; head dimension 136; convolution width 4; one group | 148,413,972 | 2,506,752 | 0.016890 |
Table 3: Benchmark configurations. All models use 12 layers, a vocabulary of 50,259 tokens, tied input and output embeddings, and a training context window of 512 tokens. Parameter size counts all trainable parameters. State size counts recurrent-state elements per sequence across all layers, excluding convolution buffers; for the Transformer, it counts key-value cache elements at 512 tokens. The state-to-parameter ratio is the state size divided by the parameter size.
A.6 SYNTHESIZING PROVABLE FAILURE SIGNALS FOR CAUSAL MODE RETRIEVAL
We synthesize four-channel input and target signals related by a true transfer function with nonreal poles. We first construct the input signal and the true transfer function , and then generate the target signal as . The transfer function is withheld from the models and must be learned from the input-target sequences.
Input Signal. We construct an input signal containing both magnitude and phase noise. For a sequence of tokens, with token index and channel index , the latent input is
where denotes Gaussian noise, denotes a random phase, and
The unnormalized input is
(13)
where denotes independent Gaussian noise and
Using the channel mean
and channel standard deviation
the normalized input is
True Transfer Function. For each channel , we construct the true transfer function as
where the coefficient is entry of
and the numerator coefficient is entry of
Multiplying the numerator and denominator by gives
in which the factor z in the denominator is the one-token delay of (20) and contributes a further pole at the origin. The zeros for channel c are the roots of the numerator polynomial:
and the poles are the roots of the denominator polynomial:
For the specified values of and , the resulting zero and pole sets are listed below, rounded to six decimal places. The zero sets are
and the resulting pole sets are
Each channel therefore contains a complex-conjugate pole pair, ensuring that the constructed true transfer function contains poles not constrained to the real axis, and every pole lies strictly inside the unit circle, with approximately equal to 0.994400, 0.990691, 0.981400 and 0.975600 for the four channels.
Target Signal. We generate the target signal by applying the true transfer function to the input signal, such that . Here, the input is zero outside , and transforms the full causal zero-state response, whose first samples form the target sequence. Equivalently,
The corresponding direct causal recurrence is
A.7 CONSTRUCTING CAYLEY MAP
For any skew-symmetric , the matrix is invertible and the Cayley map (Cayley, 1846)
is a rotation. Orthogonality follows from together with the commutation of and ,
and by continuity from S = 0. The map therefore parameterizes rotations without trigonometric evaluation, and its image is the set of rotations that do not have -1 as an eigenvalue.
In two dimensions every skew-symmetric matrix carries a single free parameter,
so that a planar rotation is determined by alone. Evaluating equation (36) with gives
and therefore
which is the general Cayley parameterization of a planar rotation.
Hyperbolic map. Choosing gives the hyperbolic parameterization
with . The identity preserves orthogonality.
A.8 WEIGHT INITIALIZATION
Characteristic Horizon. Consider a stable continuous-time oscillatory mode
Its evolution over one token interval is
Therefore, the corresponding discrete-time pole is , where its radius and horizon satisfy
Here denotes the radius of an assembled recurrent pole rather than the local contraction coefficient .
Jeffreys Prior. The Jeffreys prior of a parameter is , where denotes the Fisher information of ; it is invariant under reparameterization, so that equal prior mass corresponds to equal statistical distinguishability (Jeffreys, 1946). We apply it to the decay rate of a channel whose readout depends on the preceding writes through the energy-normalized memory kernel
which is the response of the pole pair averaged over the readout phase and normalized to unit energy. For a readout with gain , uncorrelated unit-variance writes and noise , the Fisher information of is , the variance of the lag under the weights . The Jeffreys prior per unit is therefore
which is constant for and decays as for . We evaluate it through the closed form
which has the same two regimes.
Initialization. On the horizon range , let denote the cumulative distribution of the density (44). The horizons are its quantiles , and channel receives , where is a uniformly random permutation of . For , channel takes the target pole pair with and
where cycles through the integers , and and denote the horizon threshold and the constant of the horizon-tied angle. Matching the characteristic polynomial of the two-stage transition of equation (2), where , to at gives the stage coefficients, from which each stage takes its radius and sine with a margin ,
The realized pole pair has modulus . Inverting and gives the biases
where are independent uniformly random signs that leave the poles unchanged. Every entry of , and is drawn independently from , where denotes the standard deviation of the weight entries, and each entry of and has a uniformly random sign and a magnitude drawn from .
A.9 POLES OF RECURRENT SYSTEMS
We characterize the poles induced by the recurrent dynamics of each sequence mixer. For methods with input-dependent coefficients, we fix the coefficients at token position t and analyze the resulting frozen system. The denominators below are unreduced; actual transfer poles may be removed by cancellation.
Theorem 1 (Poles of First-Order Systems). Let , , and denote the input, recurrent state, and output at token position , respectively. Consider the first-order system
where is the recurrent transition matrix and , and are the input, readout, and feedthrough matrices of compatible dimensions. With , the corresponding transfer function is
where
Here, is the z-transform variable, is the identity matrix, and denote the adjugate and determinant, respectively, and are the eigenvalues of . The finite poles of the transfer function form a subset of , after clearing negative powers of and cancelling common factors.
Proof. Let and denote the z-transforms of the input sequence and recurrent-state sequence, respectively. Taking the z-transform of the state equation gives
and therefore
Substitution into the output equation yields
Using
gives the stated numerator and denominator. Moreover,
Thus, , so every finite transfer pole, including any pole at the origin, is an eigenvalue of ; numerator cancellation can remove such poles.
For token-dependent coefficients evaluated along the input sequence, , , and , repeated substitution gives
where indexes the input position and the product is for . This exact response retains the coefficient history. When the coefficients are held constant, the product becomes and the rational transfer function above applies.
Corollary 1 (Symmetric Transitions Imply Real Poles). If is symmetric, or if there exists a positive-definite diagonal matrix such that is symmetric, then every pole of the corresponding recurrent system is real.
Proof. If is symmetric, the spectral theorem gives
If and is symmetric, then
is symmetric. Since similar matrices have the same eigenvalues, also has a real spectrum. The result then follows from Theorem 1.
A.9.1 SCALED DOT-PRODUCT ATTENTION
Let and denote the query, key, and value at token position , where is the query-key dimension and is the value dimension. Causal SDPA computes
where s and index preceding token positions. An exact recurrent representation retains the preceding keys and values,
whose dimension grows with t. In particular, the softmax kernel does not admit an exact finite-dimensional factorization because
where indexes the polynomial degree. The kernel has infinite feature rank: even for scalar queries and keys, the functions for arbitrarily many distinct keys are linearly independent. Thus, unrestricted SDPA has no exact fixed finite-dimensional linear feature-state representation and no corresponding fixed finite-order rational LTI transfer function. At a fixed finite context with attention weights frozen, its output is instead a finite weighted sum of delayed values.
A.9.2 LINEAR ATTENTION
Let denote a finite-dimensional feature map, where is the feature dimension. Linear attention maintains the matrix state and normalization state :
Using to denote column-wise matrix vectorization and to denote the Kronecker product, the stacked state
satisfies
where denotes the identity matrix. The state transition is therefore the identity matrix, with denominator
Thus, all poles of the recurrent state lie at z = 1. The normalized output remains a ratio of two linear functionals of the state; without the normalizer and with query and key coefficients frozen, the map from values to outputs is a first-order linear system.
A.9.3 SELECTIVE STATE SPACE MODELS
Let and denote the input and output at token position and channel . Let denote the corresponding recurrent state, where is the state dimension. A selective SSM has the frozen recurrent dynamics
where is the input-dependent step size, is the continuous-time transition coefficient of state , and is the input coefficient. Let and denote the readout and feedthrough coefficients, respectively. The corresponding transfer function is
with denominator
The frozen transition matrix is diagonal and therefore symmetric. By Corollary 1, all poles are real. Since and ,
so every pole lies on the positive real axis inside the unit circle.
A.9.4 RWKV-6
For each head, let denote the recurrent state and let denote the receptance, key, value, and decay vectors, respectively, where is the head dimension and . RWKV-6 updates
Its readout is
where denotes the time-mixing bonus coefficient. Since is invertible,
and therefore
where denotes element-wise multiplication. For each state column, the transition matrix is
Its denominator polynomial is
Because is diagonal, all poles are real and satisfy
A.9.5 RWKV-7
Let denote the recurrent state, where is the head dimension. Let denote the value, key, and receptance vectors; let denote the decay vector; let denote the learning-rate vector; and let denote a normalized key direction satisfying . RWKV-7 updates
Factoring the state terms gives
After transposition, the left-acting transition matrix is
The matrix determinant lemma gives
Although is not generally symmetric, define the positive-definite diagonal matrix
Then
is symmetric. Equivalently,
is symmetric. Corollary 1 therefore guarantees that all poles of RWKV-7 are real.
A.9.6 RETNET
For each head, let denote the recurrent state, where and are the key and value dimensions, respectively. Let and denote the query, key, and value at token position . In the original RetNet formulation, the positional rotations are incorporated into the query and key:
where denotes the complex positional rotation at token position and denotes its complex conjugate. The recurrent representation is
where is the head-specific decay coefficient.
The recurrent transition matrix is , where I denotes the identity matrix. Freezing the complete query and key coefficients, including their positional rotations, the corresponding transfer function has the denominator
Therefore, the only possible pole of each frozen RetNet head is
For multi-scale retention with head-specific decay coefficients , the candidate pole set is
where H is the number of heads. Thus, all poles of this frozen representation are real and lie strictly inside the unit circle. This conclusion does not apply when the positional rotations retain their temporal progression, which can produce complex lag factors.
A.9.7 HGRN2
Let denote the recurrent state, where is the feature dimension and is the value dimension. Let denote the forget gate, the input value, and the output vector. HGRN2 updates
with readout
For each state column, the transition matrix is
The corresponding denominator is
The transition matrix is diagonal, and its eigenvalues are
Thus, all poles of HGRN2 are real and lie strictly inside the unit circle.
A.9.8 HYENA
Let and denote the input and output of a Hyena convolutional stage. The stage applies a finite causal convolution
where is the filter length, is the filter coefficient at lag , and is the feedthrough coefficient. The filter coefficients are generated from position according to
where is the positional embedding at lag n, is the sinusoidal filter-generating network, and controls exponential decay. Introducing the shift-register state
gives
where is the down-shift matrix and is the first standard basis vector. The transfer function is
whose denominator is
Therefore, a Hyena convolutional stage is an FIR system and has no nonzero finite poles.
A.9.9 DELTANET AND GATED DELTANET
Let denote the recurrent state, where and are the key and value dimensions. Let and denote the normalized key and value, with . Let denote the update rate and denote the decay coefficient for Gated DeltaNet; for DeltaNet, . The dynamics are
where is the decayed state and is the delta-rule update. Substitution gives
(106)
The transition matrix is therefore
with denominator
Since
where denotes any vector orthogonal to , the spectrum is
The transition matrix is symmetric, so Corollary 1 guarantees that all poles are real.
A.10 TRANSFER FUNCTION OF LATTICE-LADDER NETWORK
This section derives the transfer function of the parameterized lattice–ladder network. We consider a single expanded feature channel and omit the channel index for clarity. For the frozen-system analysis at token position , we treat the input-conditioned reflection angles , radius coefficients , readout coefficients , memory write projection , and memory readout projections as constants, denoted by , , , , and , respectively. Since the lattice recursion acts independently across expanded feature channels, the derivation applies to every channel.
Let denote the lattice order and denote the lattice stage. For token positions , the lattice recursion is
with the boundary conditions
Here, denotes the input signal, denotes the forward signal at stage k, and denotes the recurrent state at stage k. The ladder readout is
where denotes the output signal.
A.10.1 POLYNOMIAL RECURSION OF THE LATTICE STAGES
Let , , and denote the -transforms of , , and , respectively, with the input zero outside and the frozen recursion continued causally beyond . Ratios of the row-vector signals below denote scalar response factors, not vector division. Under the zero-state condition, taking the -transform of the lattice recursion gives
Assuming at every stage for the intermediate divisions, rearranging the first equation and substituting it into the second equation gives
(118)
Define the normalized stage polynomial and ladder-basis polynomial by
(119)
Inductively, contains the factor . Cancelling this factor in the recursion for and its -th factor in the recursion for makes every coefficient polynomial in , , and . The final polynomial transfer formula therefore extends continuously to parameters with . We first establish the stage-response identities
For , the identity follows immediately from , , and . Suppose that it holds at stage . Substituting equation (120) into the first equation of equation (118) gives
(121)
Similarly, the second equation of equation (118) gives
(122)
which proves equation (120) for every .
Write the order-k stage polynomials as
where and denote the coefficients of . The initial coefficients are
Matching coefficients in equation (119) gives
(125) where coefficients whose second index exceeds the polynomial degree are zero. After lattice stages,
Since equation (120) gives
every ladder-stage response relative to has the common denominator . Therefore, the denominator polynomial induced by the lattice recursion is
where
A.10.2 LADDER READOUT AND NUMERATOR POLYNOMIAL
From the stage-response identity in equation (120), the intermediate lattice states satisfy
with
Let denote the -transform of the output sequence . The ladder readout becomes
The ladder-basis polynomial satisfies
Substituting
gives
Therefore, the transfer function is
(136) where the numerator and denominator polynomials are
Expanding the numerator as
where denotes the coefficient of , gives
Hence, the order- lattice-ladder network realizes the transfer function
where the numerator coefficients and denominator coefficients are induced by the reflection angles , radius coefficients , readout coefficients , memory write projection , and memory readout projections through the lattice recursion.
Complex-Conjugate Poles. For , take , , and . The polynomial recursion gives and . Choosing and the remaining ladder contributions zero yields , with uncancelled complex-conjugate poles .
Stability of the Carried State. For homogeneous propagation, set and let . Orthogonality of each stage rotation gives . Summing over stages and using yields
Thus, the complete carried-state transition is nonexpansive for and Schur stable for , so all poles of the frozen transfer function lie strictly inside the unit circle under the latter sufficient condition. For time-varying coefficients, the same bound holds at each token with ; a uniform bound guarantees uniform exponential decay.
A.11 ALGEBRAIC STRUCTURE FOR PARALLELISM
We define the transition as
Its component-wise update is given by equation (2), as illustrated in Figure 3. The transitions within token form a dependent cascade from to . Since the recurrence acts independently across channels, we define the carried state as
For compactness, we define
Let denote the state transition, where is the corresponding transition operator. We now derive its explicit form using the closure . By equation (2), recursively expanding the forward signal gives
and substituting into the update of yields
Because , and depend only on , the complete cascade defines the affine operator
where the transition matrix and input contribution are
respectively. Therefore, for any , temporal composition of the affine operators is associative
(144)
In general, they are non-commutative:
Iterating equation (144), the composition of for any remains affine,
with the empty product . This follows by induction on . At the composition is itself, for which and . Composing with the hypothesis at gives together with
Applying this operator to gives equation (5), in which transports the preceding memory across the segment, whereas setting identifies as the segment dynamics generated from a zero entry state, independent of all tokens preceding .
A.12 CUDA IMPLEMENTATION
Chunk Partition. The token axis is partitioned into contiguous chunks, chunk spanning with and . Every chunk but the last has the same length , so and , where is computed in closed form from , the batch size , and the number of thread blocks the GPU holds at once: is chosen so that the thread blocks of phase (iii) come close to a whole multiple of that number, and unless the split is predicted to be more than 1.125 times faster, in which case phases (i) and (ii) are not executed and phase (iii) starts from . Writing the carried state in stacked form
each chunk is delimited by an entry state and an exit state , related across chunks by . This relation orders the chunks strictly, and the following three phases remove it by exploiting the affine structure of equation (3) and its associativity in equation (4).
Phase (i): Chunk Summarization. All chunks are summarized concurrently, each from a zero entry state; in inference the last chunk is skipped, since phase (ii) never reads its summary. With
the token transition of equation (2) is
where of equation (3) is determined by and . Chunk retains the pair of equation (5) at and ,
the transition being obtained by homogeneous propagation of the standard basis states and shared across memory components. Since the token transition is affine in , this pair characterizes the chunk for an arbitrary entry state,
so that no chunk requires the output of another. The states traversed under the zero entry are therefore auxiliary for and are not retained.
Phase (ii): Boundary Composition. Applying equation (145) for in token order from the sequence reset recovers the entry state of every chunk, and by the associativity of equation (4) these applications are evaluated as one parallel scan. Since couples only the stages of one channel and is shared across memory components, every sequence, channel and group of memory components forms an independent stream, and each stream is assigned threads, where is the smallest power of two at which all streams together occupy the threads the GPU holds at once, limited to 256 and to rounded up to a power of two. Each thread composes the pairs of its consecutive chunks into one pair, the composed pairs are combined by a Kogge–Stone scan with warp shuffles within a warp and shared memory across warps, and each thread applies the composition of the pairs preceding its own to and replays equation (145) over its chunks, writing their entry states. The depth is compositions instead of , and is the sequential composition in steps. This is the only exchange of information between chunks. It resolves the chunk boundaries alone: no interior state is evaluated, and its cost is independent of .
Phase (iii): Chunk Replay. The ladder readout is defined at every token position, so the boundary states of phase (ii) are not sufficient and the interior states must be restored. All chunks are replayed concurrently, chunk repeating the token transition from the entry state obtained in phase (ii). This recovers at every token and every stage and yields
A.12.1 PARALLEL TOKEN SCAN

Figure 22: Chunk summarization (i), boundary composition (ii) and chunk replay (iii) for one stream, read from the bottom up: tokens in chunks of tokens, and threads of two chunks each (threads 4 to not drawn). A box holds the pair of equation (5); two adjacent pairs compose by equation (4). In the successive scan steps, a thread composes its pair with that of the thread positions to its left (dashed). For , the steps run within each warp of 32 threads, and each thread also composes the pair of every earlier warp.
A.12.2 CHUNK PARTITION ON HOST
PARTITION, closed form from the shape and the queried GPU
R_* : resident blocks of a kernel (SMs x blocks/SM)
N_* : blocks of a kernel grid at one chunk
e_b : bytes per element
kernel constants, read from the compiled kernels:
S : b3 segment length (tokens)
A_tile : token tile staged by p1 and p3
C_tile : channels of one b3 block
KV_max : registers of state a tree-scan thread holds
TREE_T : threads per tree-scan block
W_max : most workers per tree-scan unit
def partition(B, T, de, dm, K, training): # BACKWARD FINE CHUNK f (training) # f_smem: longest multiple of S whose b3 shared # block fits the per-block budget sigma # f_par : keeps at least one wave of b3 blocks f_smem = S * floor((sigma - smem_b3(0)) / (S * smem_b3_per_token)) f_par = S * floor(B * T * ceil(de / C_tile) / (S * R_b3)) f_min = min(f_smem, max(f_par, S)) f = min(T, max(S, 2 ** floor(log2(f_min)))
FORWARD COARSE CHUNK c, a multiple of a
a = f if training else A_tile
c0 = A_tile + 4 * (3*K**2 + 5*K*dm) / (e_b * (5*K + 5))
q = max((2*K + 1) / (3*K + 4), ops_p1 / ops_p3)
x = N_p3 / R_p3
W = max(ceil(x), floor(x * sqrt(T / c0)))
n = min(floor(W * R_p3 / N_p3), floor(sqrt(T)),
ceil(T / a))
c = min(T, a * ceil(T / (n * a)))
n = ceil(T / c)
t1 = ceil(x) * T
if training:
t1 += q * ceil(N_p1 / R_p1) * T
tn = (ceil(n * N_p3 / R_p3) * (c + c0)
+ q * ceil(n * N_p1 / R_p1) * c)
# split only when predicted more than 1.125x faster
if not (n > 1 and t1 > 1.125 * tn):
c, n = T, 1
TREE SCAN over the n coarse chunks
workers, r = tree_plan(B, de, dm, K, n)
return f, c, n, workers, r
TREE PLAN for n chunks
unit = (sequence, channel, V memory columns)
def tree_plan(B, de, dm, K, n): V = max(1, min(dm, KV_max // K)) units = B * de * (dm // V) workers = pow2ceil(R_tree * TREE_T / units) workers = clamp(workers, 1, min(pow2ceil(n), W_max)) r = ceil(n / workers) return workers, r
A.13 REFERENCE CUDA KERNEL PSEUDO CODE
A.13.1 SHARED DEVICE FUNCTIONS
// // STAGE COEFFICIENTS of one (b, t, e, k) // D = r cos(theta), E = r sin(theta) // dtheta/dalpha, (dr/dbeta)/r: cached for the backward // struct Stage { float D, E, dth_dal, dlr_dbe; };
device Stage stage(float alpha, float beta) { float r = 1.f / (1.f + beta * beta); return {r / coshf(alpha), r * tanhf(alpha), 1.f / coshf(alpha), -2.f * beta * r}; }
// // TOKEN STEP, one channel e, one memory column m // in: V[0..K-1] = V_{t-1}^(0..K-1), U = U_t^(K) // out: V[0..K-1] = V_t^(0..K-1) // lev[0..K] = V_t^(0..K) // stg[k] holds stage k, k = 1..K
template <int K> device void step(const Stage *stg, float *V, float U, float *lev) { for (int k = K; k >= 1; --k) { lev[k] = stg[k].E * U + stg[k].D * V[k-1]; U = stg[k].D * U - stg[k].E * V[k-1]; } lev[0] = U; for (int k = 0; k < K; ++k) V[k] = lev[k]; }
// // LEVELS of one token, for the backward // in: Vp[0..K-1] = V_{t-1}^(0..K-1), u = U_t^(K) // out: U[0..K] = U_t^(0..K), Vt[0..K] = V_t^(0..K) //
template <int K> device void levels(const Stage *stg, const float *Vp, float u, float *U, float *Vt) { U[K] = u; for (int k = K; k >= 1; --k) { Vt[k] = stg[k].E * U[k] + stg[k].D * Vp[k-1]; U[k-1] = stg[k].D * U[k] - stg[k].E * Vp[k-1]; } Vt[0] = U[0]; }
// // ADJOINT STEP, one channel e, one memory column m // in: dV[0..K-1] = dL/dV_t^(0..K-1) from token t+1 // g[0..K] = local dL/dV_t^(0..K) // out: dV[0..K-1] = dL/dV_{t-1}^(0..K-1) // returns dL/dU_t^(K) //
template <int K> device float adjoint_step(const Stage *stg, float *dV, const float *g) { float gU = g[0] + dV[0]; for (int k = 1; k <= K; ++k) { float gV = g[k] + (k < K ? dV[k] : 0.f); } } dV[k-1] = stg[k].D * gV - stg[k].E * gU; gU = stg[k].D * gU + stg[k].E * gV; } return gU;
// AFFINE MAP x -> A x + c of one unit (b, e, V columns) // A: K x K, c: K x V // compose(m2, m) applies m first: // (A2, c2) o (A, c) = (A2 A, A2 c + c2) // struct Map { Mat A; Vec c; };
device Map compose(const Map &m2, const Map &m) { return {m2.A * m.A, m2.A * m.c + m2.c}; }
// TREE SCAN, run by p2 and b2 // unit u = (b, e, V columns), W worker threads per unit // worker w owns chunks [w r, (w+1) r) // out[u][j] = state ENTERING chunk j: // x_{j+1} = A_j x_j + c_j, x_0 = x0[u] // depth: 2 r + log2(W) + W/32 - 1 compositions
device void tree_scan(const Map *chunk, const Vec *x0, Vec *out, int n, int W, int r) { int u = (blockIdx.x * blockDim.x + threadIdx.x) / W; int w = threadIdx.x % W; int lo = w * r, hi = min(n, lo + r); // 1. fold: compose the chunks of this worker Map own = identity(); for (int j = lo; j < hi; ++j) own = compose(chunk[u][j], own); // 2. exclusive Kogge-Stone scan over the W workers: // __shfl_up_sync in a warp, shared memory across Map inc = own; for (int d = 1; d < W; d *= 2) { Map prev = shfl_up(inc, d); if (w >= d) inc = compose(inc, prev); } Map pre = w > 0 ? shfl_up(inc, 1) : identity(); // 3. replay: write the entry state of each chunk Vec x = pre.A * x0[u] + pre.c; for (int j = lo; j < hi; ++j) { out[u][j] = x; x = chunk[u][j].A * x + chunk[u][j].c; } }
A.13.2 FORWARD ON DEVICE
// FORWARD KERNEL // block (b, chunk j, channel group of G channels), // thread (e, m): channel e, memory column m // (a lane holds d_m / L columns) // the kernel reads W_gamma z_t and forms // gamma_t = silu(W_gamma z_t) itself
// p1: CHUNK SUMMARY from a zero entry state // S_j = V at the chunk end, V_{t_j - 1} = 0 // Phi_j = Phi_{t_j + c - 1} ... Phi_{t_j}: lane m < K // carries basis state m with zero input, the // column m of Phi_j
template <int K> global void p1_chunk_summary(Args a) { auto [b, j, e, m] = coordinates(); // P: column m of the current fine transition // Pc: column m of the coarse transition Phi_j float V[K] = { }, P[K] = { }, Pc[K] = { }, lev[K + 1]; if (m < K) P[m] = Pc[m] = 1.f; for (int t = first(j)); t < last(j); ++t) { Stage stg[K + 1]; for (int k = 1; k <= K; ++k) stg[k] = stage(a.alpha[b][t][e][k], a.beta[b][t][e][k]); float U = a.x_tilde[b][t][e] * a.s[b][t][m]; step<K>(stg, V, U, lev); if (m < K) step<K>(stg, P, 0.f, lev); // training: close fine chunk i every f tokens if (a.training && closes_fine_chunk(t)) { int i = fine_index(t); if (m < K) { a.Phi_fine[b][i][e].col(m) = P; // Phi_j <- P Phi_j, the rows of P // gathered by __shfl_sync Pc = mul_lanes(P, Pc); reset(P, m); } } } a.S[b][j][e].col(m) = V; if (m < K) a.Phi[b][j][e].col(m) = a.training ? Pc : P; }
// p2: BOUNDARY COMPOSITION, the state entering every // coarse chunk, by the tree scan over n chunks global void p2_boundary_composition(Args a, int n, int W, int r) { tree_scan(a.chunk_maps(), a.V_0, a.V_in, n, W, r); }
// p3: CHUNK REPLAY from its entry state template <int K> global void p3_chunk_replay(Args a) { auto [b, j, e, m] = coordinates(); float V[K], lev[K + 1]; load(V, a.V_in[b][j][e].col(m)); for (int t = first(j); t < last(j); ++t) { // training: checkpoint the state entering // every fine chunk i if (a.training && opens_fine_chunk(t)) a.V_ck[b][fine_index(t)] [e].col(m) = V; Stage stg[K + 1]; load_stage(stg, a, b, t, e); float U = a.x_tilde[b][t][e] * a.s[b][t][m]; step<K>(stg, V, U, lev); // y_t = gamma_t sum_k rho_t^(k) (V_t^(k) nu_t^(k)) // V_t^(k) nu_t^(k): sum over the d_m lanes float acc = 0.f; for (int k = 0; k <= K; ++k) acc += a.rho[b][t][e][k] * warp_sum(lev[k] * a.nu[b][t][k][m]); if (m == 0) a.y[b][t][e] = silu(a.W_gamma_z[b][t][e]) * acc; } if (last(j) == T) a.V_T[b][e].col(m) = V; }
// FORWARD, host: p1 -> p2 -> p3 // n = 1 in inference: p3 alone, from V_0 // T = 1 in inference: one fused step kernel
void forward(Args a) { Plan pl = partition(B, T, de, dm, K, a.training); int blocks = B * pl.n * ceil_div(de, G); if (pl.n > 1 || a.training) { p1_chunk_summary<K><<<blocks, G * L>>> (a); int tb = tree_blocks(pl.n, pl.workers); p2_boundary_composition<<tb, TREE_T>>> ( a, pl.n, pl.workers, pl.r); } p3_chunk_replay<K><<<blocks, G * L>>> (a); }
A.13.3 BACKWARD ON DEVICE
// BACKWARD KERNEL, over fine chunks i gamma_t = silu(W_gamma z_t) dsilu(a) = sigmoid(a) (1 + a (1 - sigmoid(a))) local level gradient: g_t^(k) = dy_t gamma_t rho_t^(k) nu_t^(k)
// b1: ADJOINT SUMMARY from a zero future // block (b, fine chunk i, channel group), thread (e, m) template <int K> global void b1_adjoint_summary(Args a) { auto [b, i, e, m] = coordinates(); float dV[K] = {}, g[K + 1]; for (int t = last(i) - 1; t >= first(i); --t) { Stage stg[K + 1]; load_stage(stg, a, b, t, e); local_gradient(g, a, b, t, e, m); adjoint_step<K>(stg, dV, g); } a.L[b][i][e].col(m) = dV; }
// b2: BOUNDARY COMPOSITION in reverse, the adjoint at // the end of every fine chunk, by the tree scan over // nf chunks: maps (Phi_fine[i+1]^T, L[i+1]), read // last to first global void b2_boundary_composition(Args a, int nf, int W, int r) { tree_scan(a.reverse_maps(), zeros, a.dV_out, nf, W, r); }
// b3: CHUNK GRADIENTS // block (b, fine chunk i, tile of C_tile channels), // S: segment length (tokens) template <int K, int S> global void b3_chunk_gradients(Args a) { auto [b, i, e, m] = coordinates(); // pass 1: replay from V_ck[i], keep the state at // every S-token segment start (shared) shared float seg_ck[SEGMENTS][G][K][dm]; replay_segments(seg_ck, a.V_ck[b][i][e], m); float dV[K]; load(dV, a.dV_out[b][i][e].col(m)); for (int sg = segments(i) - 1; sg >= 0; --sg) { // pass 2: replay the segment: V_{t-1} in registers, // q_t^(k) = V_t^(k) nu_t^(k) in shared float Vp[S][K], q[S][K + 1]; replay_segment(Vp, q, seg_ck[sg], a, m); // pass 3: reverse over the segment for (int u = S - 1; u >= 0; --u) { int t = first(i) + sg * S + u; if (t >= last(i)) continue; float gm = a.dy[b][t][e] * silu(a.W_gamma_z[b][t][e]); float total = 0.f, g[K + 1]; local_gradient(g, a, b, t, e, m); for (int k = 0; k <= K; ++k) { a.drho[b][t][e][k] = gm * q[u][k]; total += a.rho[b][t][e][k] * q[u][k]; } // dL/d(W_gamma z_t) a.dW_gamma_z[b][t][e] = a.dy[b][t][e] * total
- dsilu(a.W_gamma_z[b][t][e]); Stage stg[K + 1]; load_stage(stg, a, b, t, e); // recompute U_t^(0..K), V_t^(0..K) from V_{t-1} float xt = a.x_tilde[b][t][e]; float U[K + 1], Vt[K + 1]; levels<K>(stg, Vp[u], xt * a.s[b][t][m], U, Vt); float gU = g[0] + dV[0]; for (int k = 1; k <= K; ++k) { float gV = g[k] + (k < K ? dV[k] : 0.f); // dL/dtheta^(k), r dL/dr^(k), // summed over the d_m lanes float dth = warp_sum(gV * U[k-1]) - gU * Vt[k]); float dlr = warp_sum(gV * Vt[k]) + gU * U[k-1]); a.dalpha[b][t][e][k] = dth * stg[k].dth_dal; a.dbeta[b][t][e][k] = dlr * stg[k].dlr_dbe; dV[k-1] = stg[k].D * gV - stg[k].E * gU; gU = stg[k].D * gU + stg[k].E * gV; } // gU = dL/dU_t^(K), U_t^(K) = x_tilde_t s_t^T a.dx_tilde[b][t][e] = warp_sum(gU * a.s[b][t][m]); // partial sums over the channels of this tile a.ds_part[tile][b][t][m] = tile_sum(gU * xt); for (int k = 0; k <= K; ++k) a.dnu_part[tile][b][t][k][m] = tile_sum( gm * a.rho[b][t][e][k] * Vt[k]); }
// b4: TILE REDUCTION, sum the channel-tile partials global void b4_tile_reduction(Arg s) { a.ds = sum_overTiles(a.ds_part); a.dnu = sum_overTiles(a.dnu_part); }
// BACKWARD, host: b1 -> b2 -> b3 -> b4 // dV_out[i] = dL/dV at the end of fine chunk i // dV_out[i] = Phi_fine[i+1]^T dV_out[i+1] + L[i+1] // dV_out[last] = 0
void backward(Arg a) { Plan pl = partition(B, T, de, dm, K, true); int nf = ceil_div(T, pl.f); // the reverse tree scan joins the nf fine chunks, so // it takes a tree plan of its own over nf auto [wb, rb] = tree_plan(B, de, dm, K, nf); int groups = ceil_div(de, G); int tiles = ceil_div(de, C_tile); int values = B * T * (K + 2) * dm; b1_adjoint_summary<K><<<B * nf * groups, G * L>>>(a); int tb = tree_blocks(nf, wb); b2_boundary_composition<<tb, TREE_T>>>(a, nf, wb, rb); b3_chunk_gradients<K, S><<<B * nf * tiles, threads_b3>>>(a); b4_tile_reduction<<ceil_div(values, RED_T), RED_T>>>(a); }