# RWKV: Reinventing RNNs for the Transformer Era

Bo Peng, Eric Alcaide, Quentin Anthony, Alon Albalak, Samuel Arcadinho, Stella Biderman and 28 more · arXiv · 2023-5-22

- **Problem** Transformer attention cost grows quadratically with sequence length, while RNNs cannot be trained in parallel over time and struggle with vanishing gradients.
- **Method** RWKV replaces dot-product token interaction with a channel-wise, exponentially decayed weighted average, so training runs in parallel over time and inference runs as a recurrence with a fixed-size state.
- **Results** Reached performance on par with similarly sized Transformers at 14 billion parameters.

![Figure 2: Elements within an RWKV block (left) and the complete RWKV residual block, equipped with a final head for language modeling (right)](https://refivu.com/papers/f86c302a-2e46-481a-b0a7-850579f6f3c8/figures/figure-f2c56f13d021de5cd69f6615498f2283.png?thumb=512)

**Figure 2** : Elements within an RWKV block (left) and the complete RWKV residual block, equipped with a final head for language modeling (right).

[Original paper](https://arxiv.org/abs/2305.13048v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Extracted the figure area from page 3 of the original PDF.

## Where Transformers and RNNs fall short

Transformer attention relates every token to every other token, so its time and memory cost grow with the square of the sequence length. RNNs keep a hidden state of fixed size and need less memory on long sequences, but each step depends on the previous one, which blocks parallel training over time and makes gradients vanish across long spans.

The question is whether a recurrent model can reach Transformer-level quality while training in parallel over time and running inference with constant computation and memory per step. Earlier efforts to make Transformers scale have sometimes given up some effectiveness, and the full-attention rows of Table 1 still carry a T^2 term.

## From AFT's pairwise biases to a channel-wise decay

Standard attention in Eq. (7) forms pairwise scores from the query-key product and mixes values with a softmax. AFT keeps a weighted-average form over past tokens but replaces the query-key term with learned pairwise position biases, one scalar per pair of positions.

RWKV follows the same route but makes each bias a channel-wise decay vector w scaled by the distance between positions, so the bias is \\( w\_{t,i} = -(t-i)\\,w \\) and shrinks as the distance grows. Because w is kept non-negative, each exponential weight is at most 1, and the per-channel weights decay backward in time.

## Block layout, token shift and gating

The model is a stack of residual blocks, and each block contains a time-mixing sub-block followed by a channel-mixing sub-block, with layer normalization inside the architecture. A linear projection head with a LayerNorm sits after the last block and produces the logits for next-token prediction.

Token shift forms each projection as a per-channel linear interpolation between the current input and the previous one, with a learned mix factor for each projection, as in \\( r\_t = W\_r \\cdot (\\mu\_r \\odot x\_t + (1-\\mu\_r) \\odot x\_{t-1}) \\) and the same form for \\( k\_t \\) and \\( v\_t \\). The channel-mixing inputs r' and k' are formed in the same way with their own mix factors.

In code this is a one-step temporal offset, implemented with a zero-padding call that shifts the sequence by one position.

The time-mixing output is the WKV vector gated by the sigmoid of the receptance, \\( o\_t = W\_o \\cdot (\\sigma(r\_t) \\odot wkv\_t) \\). The channel-mixing output gates a squared ReLU of the token-shifted key with a sigmoid of r', as in \\( o'\_t = \\sigma(r'\_t) \\odot (W'\_v \\cdot \\max(k'\_t, 0)^2) \\).

## The WKV recurrence

At step t the WKV vector is a normalized weighted average of past value vectors, where each past step i gets the weight e^{-(t-1-i)w+k\_i}, so the decay w and the key k\_i both set how much that step counts. The formula is \\\[ wkv\_t = \\frac{\\sum\_{i=1}^{t-1} e^{-(t-1-i)w+k\_i} \\odot v\_i + e^{u+k\_t} \\odot v\_t}{\\sum\_{i=1}^{t-1} e^{-(t-1-i)w+k\_i} + e^{u+k\_t}} \\\]

The vector u gives the current token its own weight e^{u+k\_t}, so the token being processed is not forced to use the decayed weight that older tokens use. The numerator and denominator sum over the same past steps, and the current token enters both, so the output is an average rather than an unnormalized sum.

## Parallel training and recurrent inference

During training the matrix multiplications for R, K, V and O run over all time steps at once, as in a Transformer. Per layer, these multiplications cost \\( O(BTd^2) \\) for B sequences, T tokens and d channels, while the WKV update is a serial scan costing \\( O(BTd) \\). The WKV update is parallelized along the other two dimensions and runs as a single custom CUDA kernel on training accelerators.

Because the state has fixed size, memory per token stays constant as the context grows, which matches the O(d) space entry in Table 1. The authors note that a parallel scan over the WKV step could reduce its cost to \\( O(B \\log(T) d) \\), which is left for future work.

## Embedding and weight initialization

In a standard Transformer the embedding matrix changes slowly at the start, which keeps the model close to its noisy initial embedding. Small Init Embedding starts the matrix with small values and adds a LayerNorm after it, so a small change in one step turns into a large change in direction after normalization.

Custom Initialization sets most weights to zero and removes biases from linear layers, so blocks start close to passing their input through, while the setup still breaks symmetry to give a clear information flow. The authors report that the choice of initialization affects both the speed and the quality of convergence.

## Model sizes and training setup

Six models were trained, from 169 million to 14 billion parameters, each for one epoch of 330 billion tokens on the Pile.

The parameter count is \\\[ \\#\\text{parameters} = 2VD + 13D^2L + D(11L+4) \\\] where V = 50277 is the vocabulary size, D the model dimension and L the number of layers. A forward pass costs \\( 2(2VD + 13D^2L) \\) FLOP per token, and taking the backward pass as about twice the forward pass gives \\( 6(2VD + 13D^2L) \\) per token.

Training uses the standard Adam optimizer without weight decay, bfloat16 precision and a context length of 1024 tokens. Unlike common Transformer practice, the learning rate stays constant for an initial stretch and then decays exponentially, and an auxiliary loss from PaLM is added to cross-entropy to push the softmax normalizer toward zero.

## Scaling-law fit

The study trains 45 RWKV models over pairs of dataset and parameter count and plots loss against compute. The linear fit to the Pareto optimal points has an r2 of 0.994, and the authors read this as RWKV following the same general form that is established for Transformers.

Extrapolating the fitted curve by one further order of magnitude of compute still gives an r2 of 0.875. This runs against earlier claims that LSTMs do not follow the same log-log linear scaling as Transformers, although the comparison covers RWKV only.

## Zero-shot NLP comparison with Transformers

The comparison is FLOP-matched, because RWKV was trained on 330B tokens, which is close to but not identical to the token counts of Pythia, OPT and BLOOM. The comparison avoids the Chinchilla-optimal regime and the overtrained regime, so the models are compared on similar training budgets.

The zero-shot benchmarks are ARC (Easy and Challenge), BoolQ, COPA, HeadQA, HellaSwag, LAMBADA, OpenBookQA, PIQA, ReCoRD, SciQ and Winogrande. Figure 1 shows average performance across twelve NLP tasks, and the abstract states that RWKV performs on par with similarly sized Transformers.

Figure 5 shows zero-shot accuracy against compute for ARC (Challenge), HellaSwag, LAMBADA (OpenAI), OpenBookQA, ReCoRD and Winogrande, with RWKV plotted against BLOOM, Pythia and OPT. Additional per-benchmark plots are in Appendix J.

## Prompt sensitivity against ChatGPT and GPT-4

In the appendix comparison with ChatGPT and GPT-4, RWKV proved very sensitive to prompt engineering. With the prompts written for GPT, RWKV reached an F1 of 44.2%; after the prompts were re-ordered to suit RWKV, F1 rose to 74.8%.

On sarcasm detection RWKV scored above ChatGPT but slightly below the state-of-the-art solution. The authors argue that the linear attention carries only part of the prompt into the continuation, which would make prompt structure matter more for RWKV than for Transformers.

## Extended context finetuning

Since an RNN has no preset sequence length, the study finetunes on progressively longer sequences, doubling from 1024 to 2048 and then to 4096 and 8192 tokens. The stages use 10B tokens at 2048 and 100B tokens each at 4096 and 8192, all drawn from the original pretraining corpus.

Figure 6 shows mean test loss on the Pile decreasing as context length grows, for the 7B and 14B models. The authors take this as evidence that RWKV can use long contextual information.

## Long-Range Arena results

RWKV ranks second only to S4 on five datasets.

The per-dataset results are in Appendix J.2.

## Inference cost and generation time

Table 1 lists RWKV inference time as \\( O(Td) \\) and space as \\( O(d) \\), against \\( O(T^2 d) \\) time and \\( O(T^2 + Td) \\) space for the full Transformer. The other rows are Reformer, Performer, Linear Transformers, AFT-full, AFT-local and MEGA, with T the sequence length and d the feature dimension. The authors state that this implementation, without approximation, has the lowest computational and memory complexity among the compared models.

Generation speed and memory were measured in float32 precision with HuggingFace Transformers on CPU (x86) and on an NVIDIA A100 80 GB GPU. Cumulative generation time grows linearly for RWKV, whereas it grows differently for Transformers. Quantization settings were left for further work, so these measurements cover float32 only.

## Limitations

Linear attention funnels information through a single vector over many steps, so recall of fine details over very long contexts may be weaker than with full attention. The recurrent design limits how far the model can look back at previous tokens, and learned time decay reduces information loss without matching full self-attention.

Prompt engineering matters more than with standard Transformers, and reordering information pieces almost doubled RWKV performance on some tasks. Quantization was not studied, and inference was measured only in float32.

The largest model has 14B parameters and the longest finetuning context is 8192 tokens, so larger scales and longer contexts were not tested. Larger internal states and modified formulas are named as future directions and were not tested here.

## Paper info

- **Authors**: Bo Peng, Eric Alcaide, Quentin Anthony, Alon Albalak, Samuel Arcadinho, Stella Biderman, Huanqi Cao, Xin Cheng, Michael Chung, Matteo Grella, Kranthi Kiran GV, Xuzheng He, Haowen Hou, Jiaju Lin, Przemyslaw Kazienko, Jan Kocon, Jiaming Kong, Bartlomiej Koptyra, Hayden Lau, Krishna Sri Ipsit Mantri, Ferdinand Mom, Atsushi Saito, Guangyu Song, Xiangru Tang, Bolun Wang, Johan S. Wind, Stanislaw Wozniak, Ruichong Zhang, Zhenyuan Zhang, Qihang Zhao, Peng Zhou, Qinghua Zhou, Jian Zhu, Rui-Jie Zhu
- **Venue**: arXiv · Preprint
- **First published**: 2023-5-22
- **Added**: 2026-10-20
- **Updated**: 2023-12-11
- **Version**: v2
- **arXiv**: 2305.13048
- **Category**: cs.CL · cs.AI
- **Original paper terms**: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)
- **What we show**: Paper info, commentary and permitted figures from the original paper

[Original paper ↗](https://arxiv.org/abs/2305.13048v2) · [PDF ↗](https://arxiv.org/pdf/2305.13048v2)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## Abstract

Transformers have revolutionized almost all natural language processing (NLP) tasks but suffer from memory and computational complexity that scales quadratically with sequence length. In contrast, recurrent neural networks (RNNs) exhibit linear scaling in memory and computational requirements but struggle to match the same performance as Transformers due to limitations in parallelization and scalability. We propose a novel model architecture, Receptance Weighted Key Value (RWKV), that combines the efficient parallelizable training of transformers with the efficient inference of RNNs. Our approach leverages a linear attention mechanism and allows us to formulate the model as either a Transformer or an RNN, thus parallelizing computations during training and maintains constant computational and memory complexity during inference. We scale our models as large as 14 billion parameters, by far the largest dense RNN ever trained, and find RWKV performs on par with similarly sized Transformers, suggesting future work can leverage this architecture to create more efficient models. This work presents a significant step towards reconciling trade-offs between computational efficiency and model performance in sequence processing tasks.

## Quote from the paper

Bo Peng, Eric Alcaide, Quentin Anthony, Alon Albalak, Samuel Arcadinho, Stella Biderman, Huanqi Cao, Xin Cheng, Michael Chung, Matteo Grella, Kranthi Kiran GV, Xuzheng He, Haowen Hou, Jiaju Lin, Przemyslaw Kazienko, Jan Kocon, Jiaming Kong, Bartlomiej Koptyra, Hayden Lau, Krishna Sri Ipsit Mantri et al. (2023). RWKV: Reinventing RNNs for the Transformer Era. arXiv:2305.13048v2. https://arxiv.org/abs/2305.13048v2

**BibTeX**

```
@misc{peng2023rwkv,
  title = {{RWKV: Reinventing RNNs for the Transformer Era}},
  author = {Bo Peng and Eric Alcaide and Quentin Anthony and Alon Albalak and Samuel Arcadinho and Stella Biderman and Huanqi Cao and Xin Cheng and Michael Chung and Matteo Grella and Kranthi Kiran GV and Xuzheng He and Haowen Hou and Jiaju Lin and Przemyslaw Kazienko and Jan Kocon and Jiaming Kong and Bartlomiej Koptyra and Hayden Lau and Krishna Sri Ipsit Mantri and Ferdinand Mom and Atsushi Saito and Guangyu Song and Xiangru Tang and Bolun Wang and Johan S. Wind and Stanislaw Wozniak and Ruichong Zhang and Zhenyuan Zhang and Qihang Zhao and Peng Zhou and Qinghua Zhou and Jian Zhu and Rui-Jie Zhu},
  year = {2023},
  eprint = {2305.13048},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2305.13048v2}
}
```

## Other paper commentary

- [Highway Networks](https://refivu.com/en/papers/78251486-9138-48d8-a03c-8447a3433591-highway-networks.md)
- [Rethinking Attention with Performers](https://refivu.com/en/papers/be31745a-9080-4105-b177-3b88d23e4f59-rethinking-attention-with-performers.md)
- [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://refivu.com/en/papers/386e76e8-fee6-4cba-84e8-0ef90a33b3b6-decision-transformer-reinforcement-learning-via-sequence.md)
- [Efficiently Modeling Long Sequences with Structured State Spaces](https://refivu.com/en/papers/9047ef9d-9e54-48f1-8609-ea4ce704605e-efficiently-modeling-long-sequences-with-structured-state.md)
- [Longformer: The Long-Document Transformer](https://refivu.com/en/papers/095aa21a-9a7f-4317-a80b-f961fdd4e423-longformer-the-long-document-transformer.md)
- [Improving neural networks by preventing co-adaptation of feature detectors](https://refivu.com/en/papers/52fe143b-6258-4d22-888e-8274d7357b11-improving-neural-networks-by-preventing-co-adaptation-of.md)
- [Spectral Normalization for Generative Adversarial Networks](https://refivu.com/en/papers/a69a23bf-3dd6-4b32-9fb1-444f7f67a6e8-spectral-normalization-for-generative-adversarial-networks.md)
- [OLMo: Accelerating the Science of Language Models](https://refivu.com/en/papers/674dc7cc-bbc8-47b3-a55b-69c562d96047-olmo-accelerating-the-science-of-language-models.md)
- [Tree of Thoughts: Deliberate Problem Solving with Large Language Models](https://refivu.com/en/papers/708b6d99-e4dc-4582-abc4-e2de5a72d5d3-tree-of-thoughts-deliberate-problem-solving-with-large.md)
- [Self-Instruct: Aligning Language Models with Self-Generated Instructions](https://refivu.com/en/papers/b7e9c5f5-b8d4-4382-9c03-d006766b8f88-self-instruct-aligning-language-models-with-self-generated.md)
- [DeepSeek-V3 Technical Report](https://refivu.com/en/papers/761895a4-08f3-446f-98de-60152a184c97-deepseek-v3-technical-report.md)
- [The Llama 3 Herd of Models](https://refivu.com/en/papers/27985e84-42ca-486e-8e0e-2fa739789ab4-the-llama-3-herd-of-models.md)

## Terms in this paper

- [Transformer](https://refivu.com/en/terms/48e8be2570bc-transformer)
- [layer normalization](https://refivu.com/en/terms/7af9eccdb60d-layer-normalization)
- [Adam optimizer](https://refivu.com/en/terms/aff9e901333e-adam-optimizer)
- [F1](https://refivu.com/en/terms/a443de87a37a-f1)
- [ChatGPT](https://refivu.com/en/terms/96047648490a-chatgpt)
- [OPT](https://refivu.com/en/terms/a143812dd93a-opt)
- [Auxiliary loss](https://refivu.com/en/terms/24a922efb7e2-auxiliary-loss)
- [linear attention](https://refivu.com/en/terms/102ebaed8489-linear-attention)
- [Pythia](https://refivu.com/en/terms/b66f02e437b6-pythia)
- [RWKV](https://refivu.com/en/terms/c1422018176f-rwkv)
- [vanishing gradient problem](https://refivu.com/en/terms/69def7dda930-vanishing-gradient-problem)
- [Attention Free Transformer (AFT)](https://refivu.com/en/terms/6fdeafffb594-attention-free-transformer-aft)
- [BLOOM](https://refivu.com/en/terms/658bb7a20bd1-bloom)
- [Pile](https://refivu.com/en/terms/52bbdb3a0c68-pile)
- [Recurrent neural networks (RNNs)](https://refivu.com/en/terms/ba404e59b4ae-recurrent-neural-networks-rnns)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/f86c302a-2e46-481a-b0a7-850579f6f3c8-rwkv-reinventing-rnns-for-the-transformer-era)
