RWKV: Reinventing RNNs for the Transformer Era
Replace dot-product attention with decaying averages to train like a Transformer and run like an RNN.
RWKV keeps a running exponential average of past key-value pairs per channel instead of a growing attention cache, so training parallelizes across tokens while generation uses a fixed five-vector state per layer.
Explaining the paperRWKV: Reinventing RNNs for the Transformer EraScaled from 169 million to 14 billion parameters on the Pile, RWKV reaches the accuracy of compute-matched Transformers on twelve benchmarks while keeping inference memory flat across sequence length.
Transformers, RNNs, and the AFT bridge
Every sequence model has to solve two conflicting engineering problems: fast parallel training over long batches of text, and cheap step-by-step generation at inference time. Recurrent neural networks (RNNs) such as the Long Short-Term Memory (LSTM) and the Gated Recurrent Unit (GRU) solve inference cleanly because they summarize the entire past into a fixed-size hidden vector of width . Generating token reads only and , so memory per layer stays whether the conversation is ten tokens long or ten thousand.
An LSTM pays for that constant state during training. Each of its four gates multiplies the previous hidden vector by a dense weight matrix before applying a sigmoid or hyperbolic tangent:
Here is elementwise multiplication, and are the forget and input gates, and is the cell state. Because mixes every channel of into every channel of inside a nonlinearity, the GPU cannot compute step until step finishes. On a 1,024-token sequence, training runs as 1,024 tiny sequential matrix-vector multiplies instead of one large matrix-matrix multiply, leaving modern accelerators underutilized and pushing gradients through a long chain of nonlinear Jacobians where they vanish or explode.
The Transformer flipped the trade-off. Causal self-attention compares every query vector against every earlier key directly and averages the value vectors (omitting multi-head splits and the scale for brevity):
Because , , and depend only on , all positions train in parallel as large matrix multiplications. The cost lands on sequence length : forming all pairwise scores takes compute, and during autoregressive generation the server must keep every past key and value vector in a Key-Value (KV) cache of size per layer and re-read that entire cache for every new token it emits.
Take the paper's 7B configuration ( layers, model width ) in float32, the precision used in Section 6's inference benchmarks. A standard Transformer with one key and value per head (no multi-query sharing) stores floats per cached token, which is 1.00 MB per token (using binary GPU megabytes, bytes). At tokens that KV cache takes 8.00 GB for a single sequence; at tokens it reaches 64.0 GB, filling four-fifths of an 80 GB A100 GPU before counting model weights. RWKV's recurrent state for the same 7B dimensions is floats: 2.50 MB at , 2.50 MB at , and 2.50 MB at .
In Figure 1, sweep sequence length across the four Table 2 model sizes and switch between state memory and cumulative attention-side memory reads. The amber Transformer curve climbs linearly in memory and quadratically in cumulative reads, while the teal RWKV line stays flat in memory and linear in reads.
Two earlier papers bridged (1) and (2). Katharopoulos et al. (2020) replaced with a factorized kernel , turning linear attention into an RNN whose hidden state is a matrix ( time, state per layer). Zhai et al. (2021) went further in the Attention Free Transformer (AFT): instead of any dot product between queries and keys, AFT weights each past value elementwise using the past key plus a learned scalar position bias , then gates the result with a sigmoid of the query :
In AFT, each of the channels computes its own weighted average of past values independently, with no query-key dot-product matrix. Why did AFT not immediately replace Transformers at scale? Because its full version still stores a free table of biases , which costs time and locks the model to a fixed maximum length ; dropping altogether (AFT-simple) makes it but erases all sense of token distance.
How RWKV replaces attention with exponential decay
RWKV keeps AFT's elementwise ratio (3) and replaces the position table with a structured decay that can be updated recursively. Every time-mixing layer uses four vectors of length whose initials give the architecture its name:
- Receptance () passes through a sigmoid to gate how much of the aggregated memory each channel lets into the layer's output.
- Weight decay () is a learned non-negative vector setting how quickly each channel forgets older tokens.
- Key () scores how strongly token writes its value into each channel's running average via .
- Value () holds the content written into each channel's running average.
Instead of looking up an arbitrary scalar for every pair of positions , RWKV decays every past token exponentially by distance at rate , and assigns the current token its own learned per-channel bonus vector (called time_first in the official code). That produces the WKV operator (paper Equation 16):
Read (4) one channel at a time. The numerator is a weighted sum of value numbers , and the denominator is the sum of those exact same positive weights, so is a normalized convex average of past and current values. The immediately preceding token sits at exponent (weight ). Each step further back multiplies that weight by . The current token enters with weight , scaled by independently of .
Why separate from instead of using for every token including ? Consider a channel that specializes in local syntax, such as matching an adjacent adjective to a noun, so training drives its decay rate very large and . Without , every past token would vanish, collapsing to alone. With (4), tokens vanish while token keeps weight and token keeps weight , giving a clean two-token local comparison even when . (Paper Equation 10 sketches the intuition as , while Equation 16, Appendix D, and the CUDA kernel all use for past tokens plus for the current token.)
To guarantee during unconstrained gradient descent, the official implementation stores an unconstrained log-rate parameter (time_decay) initialized across and converts it via before entering the WKV kernel. The per-step retention factor is therefore a double exponential, . At , and , giving a half-life of tokens. At , and , erasing anything older than one step. Across a 4,096-channel layer, some channels hold long-range topics while others track local bigrams.
Work through (4) on one channel over three tokens with (retention ), , keys , and values :
- At , the past sum is empty, so cancels between numerator and denominator and .
- At , token 1 has weight and token 2 has weight :
- At , token 1 decays by one step to , token 2 sits at zero decay with , and token 3 gets :Even though token 3 carries a negative value, token 2's large key () still dominates the channel average one step later.
In Figure 2, drag from to to sweep a single channel from 103-token memory down to a purely local filter, then adjust and click any token bar to boost its key by +3. Notice how a boosted key on "Eiffel" survives at the end of the sentence when is negative, and vanishes once passes about .
Token shift, gating, and channel mixing
A single channel in (4) mixes values over time using only scalar keys and fixed exponential rates, without comparing token pairs via a query-key dot product. Before any linear projection runs, RWKV gives every matrix access to a one-step local blend of the current token and the immediately previous token . This operation is Token Shift, implemented in PyTorch as a one-position temporal shift nn.ZeroPad2d((0, 0, 1, -1)) (so ) followed by a learned per-channel linear interpolation :
Each projection gets its own interpolation vector ( in time-mixing, and in channel-mixing below):
If a channel sets , it reads only the current token; if it sets , it reads the previous token; values in between form a learned two-tap convolution at negligible cost ( per token, adding only one previous-input vector per sub-block to the RNN state). Why not use a wider convolution of length 4 or 8? A width-2 shift keeps the inference state minimal (one vector per sub-block) while stacking across layers still builds a wider local receptive field automatically.
Once is computed by (4), the time-mixing sub-block multiplies it elementwise by the sigmoid of the receptance vector and projects back to the residual stream:
Because is a convex average over past values, its output cannot drop to zero when no past token is relevant. Multiplying by gives each channel a read gate that silences irrelevant history or admits it before mixes across channels.
Every Transformer layer pairs attention with a position-wise feed-forward network (FFN). RWKV replaces that FFN with a Channel-Mixing sub-block that uses the same token-shifted inputs (6), a hidden expansion with the squared ReLU activation from Primer (So et al., 2021), and a second receptance gate :
Squaring the ReLU zeroes negative coordinates like a standard rectified linear unit and squares positive coordinates, concentrating activation mass on larger features in the hidden space. None of the linear layers in either sub-block carry additive biases.
Stacking residual blocks builds the full model. Each block applies LayerNorm before each sub-block (Pre-LN, matching Block.forward in model.py: x = x + att(ln1(x)) followed by x = x + ffn(ln2(x))), with one extra ln0 applied immediately after the embedding lookup in layer 0 and a final ln_out before the untied output projection head.
# One RWKV residual block in time-parallel training mode
# x: [B, T, D] (batch B, sequence length T, model dimension D)
def rwkv_block(x, layer):
# --- Time-Mixing sub-block (Pre-LN residual) ---
h = layer.ln1(x) # [B, T, D]
h_prev = zero_pad_shift(h) # [B, T, D], h_0 = 0
xr = layer.mu_r * h + (1 - layer.mu_r) * h_prev # [B, T, D] Eq. (5)
xk = layer.mu_k * h + (1 - layer.mu_k) * h_prev # [B, T, D] Eq. (5)
xv = layer.mu_v * h + (1 - layer.mu_v) * h_prev # [B, T, D] Eq. (5)
r = xr @ layer.W_r.T # [B, T, D] O(BTd^2)
k = xk @ layer.W_k.T # [B, T, D] O(BTd^2)
v = xv @ layer.W_v.T # [B, T, D] O(BTd^2)
w = exp(layer.time_decay) # [D] > 0
wkv = wkv_cuda(w, layer.u, k, v) # [B, T, D] Eq. (4), O(BTd)
x = x + (sigmoid(r) * wkv) @ layer.W_o.T # [B, T, D] Eq. (7)
# --- Channel-Mixing sub-block (4D hidden width) ---
h = layer.ln2(x) # [B, T, D]
h_prev = zero_pad_shift(h) # [B, T, D]
xr_c = layer.mu_rc * h + (1 - layer.mu_rc) * h_prev # [B, T, D] Eq. (6)
xk_c = layer.mu_kc * h + (1 - layer.mu_kc) * h_prev # [B, T, D] Eq. (6)
k_c = relu(xk_c @ layer.W_kc.T) ** 2 # [B, T, 4*D] Eq. (8)
kv_c = k_c @ layer.W_vc.T # [B, T, D] Eq. (8)
x = x + sigmoid(xr_c @ layer.W_rc.T) * kv_c # [B, T, D] Eq. (8)
return xCounting every matrix in this block accounts for the paper's exact Table 2 parameter formula. Time-mixing has four matrices ( = ). Channel-mixing has one gate matrix () plus two FFN matrices (), totaling . Together each layer holds matrix weights (comparable to a standard Transformer's , with the extra coming from ) and vector parameters (four LayerNorm scale/bias vectors, five time-mixing vectors , and two channel-mixing vectors ). Adding untied input and output embeddings (, with vocabulary size ) and the four vectors of ln0 and ln_out () yields:
Check both formulas on the 169M model (): 77.23M + 92.01M + 0.10M = 169.34M parameters, and one forward token takes 2 × (38.61M + 92.01M) = 261.25M floating-point operations (FLOPs; Table 2 reports parameters and FLOPs). Only one enters the FLOP count because the input embedding is a table lookup with zero multiply-adds, whereas the output head multiplies a -vector by a matrix. Including the backward pass (roughly twice the forward pass) gives about FLOPs per token, matching the standard Transformer accounting from Kaplan et al. (2020).
Parallel training and RNN inference
Why can RWKV train like a Transformer when an LSTM cannot? Look at the dependency graph of (5)–(8). Every dense matrix multiply () reads only and , never a recurrent hidden state from earlier timesteps. During training over a batch of sequences of length , all seven projections run as batched general matrix multiplications (GEMMs) over all tokens simultaneously, taking FLOPs on GPU tensor cores.
Only the WKV operator (4) loops sequentially over , and inside WKV every channel is completely independent of every other channel: no matrix multiply, only scalar adds and exponentials. That scan costs , which is times smaller than the projections (4,096 times smaller at 7B). Following the parallel-projection / elementwise-recurrence separation introduced by Quasi-Recurrent Neural Networks (QRNN, Bradbury et al., 2017) and Simple Recurrent Units (SRU, Lei et al., 2018), the authors fuse the entire forward and backward WKV scan into a single custom CUDA kernel (wkv_cuda.cu) that launches independent threads in parallel, keeping the running state in GPU registers across the loop. (For very long training contexts, Martin and Cundy's associative parallel prefix scan, which combines adjacent updates in a binary tree, could reduce the sequential loop depth from to .)
At generation time, the same trained weights switch into time-sequential (RNN) mode with zero approximation. Split the past numerator and denominator of (4) into two running vectors and initialized to zero:
After producing , decay both running sums by and add the current token:
Unroll (10) by hand to check that it equals (4) identically. At , , so . At , . By induction, after step :
Those two vectors match the past sums in (4) term for term. Counting every vector that must persist from token to token gives the exact per-layer RNN state: the previous time-mixing input (for token shift), the previous channel-mixing input , the running WKV numerator , the running WKV denominator , and the numerical-stability exponent introduced next. That is floats per layer, or floats for the entire -layer network ( in exact arithmetic without ). Because a prompt's entire context fits in one fixed tensor, a server can prefill a shared system prompt in parallel mode, snapshot that state vector, and resume generation from it in RNN mode without re-encoding the prompt.
Figure 3 lets you switch between the time-parallel training graph and the single-step RNN cell on a six-token sequence. Press Play or scrub from 1 to 6 in RNN mode and compare the cell's output against the closed-form sum (4): the two agree to floating-point precision ().
Numerical and gradient stability
Evaluating (9)–(10) directly in floating point breaks as soon as any key coordinate grows moderately large. In IEEE-754 float16 (max value 65,504), overflows to Inf once ; in float32 (max value ), it overflows at . One overflow in and turns the ratio into Inf / Inf = NaN and corrupts every subsequent token in the sequence.
Both wkv_cuda.cu and model_run.py eliminate overflow with the same online max-shift rescaling used by FlashAttention's online softmax. Instead of storing raw and , store scaled versions and alongside their shared log-scale vector (initialized to , in CUDA, or in Appendix D). Before computing , shift both terms by the larger of the two exponents:
Factoring out from numerator and denominator leaves the fraction unchanged while forcing both and , so every exponential lies in . The state update applies the same trick to the decayed exponent and the incoming key :
In Figure 4, drag the peak key magnitude from 0 to 120 and switch between float16 and float32. As soon as the key crosses the precision wall (11.1 in float16, 88.7 in float32), the amber naive denominator hits overflow and outputs NaN. The teal stabilized denominator stays near because the purple vector absorbs the scale.
NaN. Stabilized WKV (Eqs. 11–13) stores the log scale in (dashed violet) so stays bounded and stays exact. Toggle float16/float32 and drag peak .The stabilized step fits in fifteen lines of elementwise array code, and wkv_cuda.cu uses the same rescaling in its backward pass (lines 66–118) so training gradients never overflow either:
# Stabilized WKV single-token RNN step (matches wkv_cuda.cu & model_run.py)
# Inputs: k, v, w_neg (= -exp(time_decay)), u: [D]
# State: aa, bb, pp: [D] (initialized to 0, 0, -1e38 before t = 1)
def wkv_rnn_step(k, v, w_neg, u, aa, bb, pp):
# 1. Output at step t using current-token bonus u Eq. (11)-(12)
ww = u + k # [D]
q = maximum(pp, ww) # [D], shared exponent
e1 = exp(pp - q) # [D] in (0, 1]
e2 = exp(ww - q) # [D] in (0, 1]
wkv = (e1 * aa + e2 * v) / (e1 * bb + e2) # [D]
# 2. Decay old state by exp(w_neg) and fold in (k_t, v_t) Eq. (13)
ww2 = pp + w_neg # [D], equivalent to pp - w
q2 = maximum(ww2, k) # [D]
f1 = exp(ww2 - q2) # [D] in (0, 1]
f2 = exp(k - q2) # [D] in (0, 1]
aa_next = f1 * aa + f2 * v # [D]
bb_next = f1 * bb + f2 # [D]
pp_next = q2 # [D]
return wkv, aa_next, bb_next, pp_nextBeyond floating-point safety, Appendix H proves that WKV gradients do not explode with sequence length . Drop token shifts for a moment and normalize the positive weights for channel (where for and ) into a discrete probability distribution over steps , writing for the expectation over :
Because is an expectation under , differentiating with respect to entry of the value matrix and the key matrix (where indexes input channels) yields an expectation and a covariance:
Both derivatives are uniformly bounded whenever the layer inputs are bounded (which LayerNorm enforces), completely independent of sequence length . Because the gradient from loss back to an earlier token scales with its normalized weight , channels with small carry gradients hundreds of tokens back without multiplying through a chain of dense hidden-state Jacobians.
Initialization and training to 14B
Scaling a recurrent architecture to 40 layers and 14 billion parameters depends heavily on initialization. The first detail targets the token embedding table. Standard Transformers initialize embeddings around . Under Adam, each parameter moves by roughly the learning rate per step ( to in Table 3), so an embedding vector of norm 0.02 changes direction by less than a degree on its first update and spends thousands of steps escaping random initial directions.
RWKV initializes the embedding table tiny, uniformly in in model.py ( in Appendix E), and passes the output straight through an extra LayerNorm (ln0) before block 0. Take a 2D embedding vector starting at angle and apply one Adam step of size toward . At standard radius , the vector barely shifts and projects onto the LayerNorm unit circle at (a turn). At small-init radius , that exact same step swings the normalized direction to (a turn in one update). Appendix F's ablation (Figure 9) shows this drops training loss faster from the very first steps.
Drag the step count and initial radius in Figure 5 to compare how quickly small-init embeddings align with the target direction on the LayerNorm unit circle versus standard initialization.
ln0) of two embeddings starting at under fixed Adam steps toward . Small init () rotates over on step 1; standard init () needs dozens of steps. Sweep steps and .The second detail is residual-block initialization, inspired by ResNet identity mappings (He et al., 2016) and AlphaFold (Jumper et al., 2021). In RWKV-v4neo/src/model.py (lines 940–968), the code zeroes the output and gate projections ( in time-mixing and in channel-mixing), so at step 0 every residual block computes and passes signals cleanly through 40 layers without noise. The remaining dense matrices ( and ) use orthogonal initialization with gain (1 for , 2 for ), and the output head uses orthogonal init scaled by 0.5. (Appendix E accidentally swaps which matrices are zeroed; the Provenance panel records the exact code lines.)
Per-channel vectors also start structured rather than uniform. For channel in layer , the raw time-decay parameter and current-token bonus are initialized to:
The decay curve spreads initial channels across fast and slow horizons with a heavier tilt toward long memory in deeper layers, while the alternating zigzag in breaks channel symmetry. Token-shift weights similarly follow powers of ( for , plus for , and for ).
Appendix I inspects what these channels look like after pretraining. In RWKV-169M, layer 0 keeps many channels near for local lexical features, while top layers push several channels to to carry state across the whole context. Causal tracing on RWKV-430M with the prompt "The Eiffel Tower is located in the city of" (corrupting the input embeddings of "The Eiffel Tower" and restoring one layer at one token, following Meng et al., 2022) shows the location "Paris" is retrieved in layer 4 right after "The Eiffel", travels horizontally through time in layer 20's recurrent state, and drops down to the final output at the token "of".
Using this setup, the authors trained six models on one epoch (330 billion tokens) of the Pile (an 800 GB open text corpus) in bfloat16 (16-bit brain floating point, which keeps float32's exponent range with fewer precision bits) at context length 1,024: 169M (12 layers, ), 430M (24, 1024), 1.5B (24, 2048), 3B (32, 2560), 7B (32, 4096), and 14B (40, 5120). All six trained with Adam (, zero weight decay), batch size 128 or 256 sequences, a constant warmup over 361 to 544 mini-epochs (out of 8,043 mini-epochs of 40,320 samples), and exponential learning-rate decay down to ( for 14B). To keep softmax logits from drifting in bfloat16, Section 4.1 cites PaLM's auxiliary z-loss; in model.py (L2Wrap, lines 700–714), this is implemented as a lightweight gradient applied only to the largest logit per token.
Scaling laws, benchmarks, and long context
Before RWKV, Kaplan et al. (2020) had reported that LSTMs failed to match Transformer scaling laws as compute grew. To test whether a parallelizable RNN could scale predictably, the authors trained 45 RWKV models across varying parameter counts and dataset sizes. The Pareto-optimal frontier (the lowest-loss model at each compute budget) follows the same log-log linear power law seen in Transformers, with a coefficient of determination (where 1.0 is an exact straight-line fit) on the fitted points and when extrapolated an extra order of magnitude in compute (Section 4.2, Figure 4).
On downstream zero-shot tasks (evaluating accuracy directly on test questions with no task-specific finetuning or prompt examples), Section 5.1 compares the six Pile-trained RWKV models against compute-matched open Transformers trained on similar token budgets: Pythia, OPT, and BLOOM (excluding overtrained models such as LLaMA or Chinchilla-optimal runs so compute stays matched). Across twelve standard benchmarks (ARC Easy and Challenge, BoolQ, COPA, HeadQA, HellaSwag, OpenAI LAMBADA, OpenBookQA, PIQA, ReCoRD, SciQ, and Winogrande), average zero-shot accuracy tracks Pythia, OPT, and BLOOM closely from 169M all the way to 14B (paper Figures 1 and 5). Section 6 and Appendix K also benchmark float32 generation on x86 CPUs and an 80 GB NVIDIA A100 GPU through HuggingFace Transformers, confirming that RWKV's cumulative generation time grows linearly with sequence length while OPT, Pythia, BLOOM, and GPT-Neo curve upward and consume linearly growing VRAM (Figures 7, 13, and 14; quantized inference is left to future work).
Because RWKV has no fixed positional embedding table, the same pretrained weights can be finetuned directly onto longer contexts. Starting from the 1,024-token checkpoint, Section 5.2 progressively doubles sequence length on the Pile: 2,048 tokens for 10B tokens, 4,096 for 100B tokens, and 8,192 for another 100B tokens. Mean test loss falls monotonically as context length increases (Figure 6), confirming the recurrent state uses information thousands of tokens back.
Two standardized benchmarks situate RWKV among other long-context and efficient-attention architectures:
- Long-Range Arena (LRA, Table 4) tests classification and retrieval on 1,000- to 16,000-token sequences (higher accuracy % is better). RWKV scores 55.88 on ListOps, 86.04 on Text, 88.34 on Retrieval, 70.53 on Image, and 58.42 on Pathfinder, failing Path-X (16K-pixel spatial connectivity). Its five-task mean is 71.84 (Table 4 prints 72.07), far ahead of standard Transformer (53.66), Reformer (50.56), Performer (51.18), Linear Transformer (50.46), and Hrrformer (60.83), and second only to S4 (86.09 across all six tasks). RWKV nearly matches S4 on text and retrieval (86.04 vs 86.82; 88.34 vs 90.90) while trailing on 2D spatial tasks (Image, Pathfinder, Path-X), where S4's 64-dimensional polynomial state projections preserve fine spatial geometry.
- Enwik8 character modeling (Table 5) measures bits per character (bpc, lower is better) on 100 MB of Wikipedia XML. At , RWKV reaches 1.178 test bpc, outperforming Reformer (1.195), Performer (1.199), Linear Transformer (1.207), and AFT-simple (1.209), while trailing a full quadratic Transformer of the same size (1.137).
Where a fixed-size state breaks down
Compressing an entire prompt into numbers per layer creates a hard structural bottleneck that no amount of training speed removes. In a Transformer, a question sitting at token 500 can cast a fresh query vector back over all 499 untouched key-value pairs and retrieve an arbitrary detail it had no reason to highlight earlier. In RWKV, token 500 can only read the compressed running average . Anything that was not written with a strong key or that decayed under is gone.
Appendix L quantifies this bottleneck directly by comparing the instruction-tuned 14B model (RWKV-4-Raven-14B) against ChatGPT and GPT-4. On Recognizing Textual Entailment (RTE, scored by macro F1, the unweighted average F1 score across classes where higher is better), feeding RWKV the exact prompts designed for ChatGPT (which state the passage first and the question at the end) yields 44.2% F1, less than half of ChatGPT's 88.1% and GPT-4's 91.3%. Reordering the prompt so the question appears before the passage jumps RWKV's score from 44.2% to 74.8% F1 with zero weight changes, because reading the question first primes the recurrent state to write the relevant passage facts at high salience.
Figure 6 illustrates that single-pass state dynamics alongside the paper's Table 6 RTE numbers. Toggle between Passage-first and Question-first order and press Play to watch how exponential decay erodes an unprimed fact before the model reaches "Answer:".
Prompt reordering narrows the gap on some classification tasks: on Sarcasm detection (Table 7), adapted RWKV-4-Raven-14B edges out ChatGPT (50.96% vs 49.88% F1), and on Unhealthy conversation detection it comes within two points (43.30% vs 45.21% F1). On tasks that require tracking multiple intermediate facts or precise back-reference, however, the vector state hits a wall. On MathQA word problems, even with chain-of-thought prompting, RWKV-4-Raven-14B reaches only 5.43% accuracy (4.13% without chain-of-thought) compared to ChatGPT's 71.40%; on fine-grained 28-class emotion tagging (GoEmotions, Table 6), reordering leaves RWKV stuck at 7.9% F1 against ChatGPT's 25.6%.
Section 7 notes that larger internal states and richer decay formulations are the natural next step. That diagnosis shaped the linear-time architectures that followed: Mamba made its decay and input gates depend on the current token so the state can selectively hold or erase entries, while Mamba-2 and later RWKV generations (RWKV-5 and RWKV-6) expanded the per-head state from a -vector to a matrix, trading a modest increase in constant state memory for much higher recall capacity.
Questions you might still have
Is RWKV really an RNN, or is it a Transformer with linear attention?
It is both, depending on how you evaluate Equation (4). During training you run every matrix projection over all T tokens in parallel and scan the elementwise WKV operator once in CUDA; during autoregressive generation you maintain five D-dimensional vectors per layer and advance them one token at a time. The two views compute the exact same output to floating-point precision.
Why does RWKV need a separate current-token bonus u instead of letting w cover i = t?
If a channel learns a very large decay w so exp(-w) approaches zero, every token before t-1 vanishes and the channel acts as a local operator. Putting the immediately previous token at distance 0 (weight exp(k_{t-1})) and the current token under its own parameter u (weight exp(u + k_t)) lets that channel balance the current token against the previous token independently of how fast older history fades.
How does RWKV compare with Mamba and S4?
All three achieve linear time in sequence length and constant memory at inference, but they store different state structures. RWKV-4 keeps a single D-dimensional running numerator and denominator per layer (O(d) state) with static, learned per-channel decay rates w. S4 keeps N complex state modes per channel (typically N = 64), which gives it a large edge on continuous-signal and image tasks in Long-Range Arena (86.09 vs RWKV's 71.84 on five tasks). Mamba makes its decay and write rates depend on the current input token, letting it selectively overwrite or hold state entries without waiting for a fixed exponential half-life.
Why is training still O(BTd^2) if RWKV is linear in sequence length?
Linearity refers to sequence length T, not model width D. Every token still passes through seven dense linear projections per layer (W_r, W_k, W_v, W_o of size D x D, W'_r of size D x D, and W'_k, W'_v of size D x 4D), totaling 13 D^2 multiply-adds per layer per token. That O(BTd^2) cost is identical in structure to a Transformer's projections and saturates GPU tensor cores; what disappears is the quadratic O(BT^2 d) attention matrix.
Does RWKV support infinite context length in practice?
Its memory never grows with sequence length, so you can feed arbitrary numbers of tokens without running out of VRAM or hitting a positional-embedding limit. In practice, however, channels decay exponentially and the entire past must fit inside 5DL floats, so fine details far back in a prompt are gradually overwritten unless a channel has exp(-w) very close to 1 and assigns them a large key k_i.
Why did reordering the prompt lift RWKV's RTE score by 30 points?
In a Transformer, every token in the question at the end of a prompt can directly attend back to every word of the passage before it. An RNN reads strictly left to right: if the passage comes first, RWKV has to compress it into a fixed vector before learning what the question will ask. Placing the question first primes the hidden state so the network knows which facts to retain as it reads the passage.
Footnotes & further reading
- The paper: Peng et al., RWKV: Reinventing RNNs for the Transformer Era (Findings of EMNLP 2023; arXiv v2, December 2023). Official training, CUDA WKV kernel, and inference code: github.com/BlinkDL/RWKV-LM.
- Attention Free Transformer (AFT): Zhai et al., An Attention Free Transformer (2021). Linear attention as an RNN: Katharopoulos et al., Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention (ICML 2020).
- Parallelizable elementwise recurrences: Bradbury et al., Quasi-Recurrent Neural Networks (ICLR 2017); Lei et al., Simple Recurrent Units for Highly Parallelizable Recurrence (EMNLP 2018); Martin & Cundy, Parallelizing Linear Recurrent Neural Nets Over Sequence Length (ICLR 2018).
- Building blocks used in RWKV: squared ReLU from So et al., Primer: Searching for Efficient Transformers for Language Modeling (2021); causal tracing from Meng et al., Locating and Editing Factual Associations in GPT (NeurIPS 2022). Sibling explainers cover Attention Is All You Need, FlashAttention, S4, Mamba, and Mamba-2.
- Training corpus and benchmarks: the Pile (Gao et al., arXiv:2101.00027), Long-Range Arena (Tay et al., ICLR 2021), and Pythia (Biderman et al., ICML 2023).
How could this explainer be improved? Found an error, or something unclear? I read every message.