AI Logic

Architectures

RWKV

Updated:

Architecture of RWKV. The left side shows the overall flow as a language model (after an embedding initialized with small values and layer normalization, time mixing and channel mixing are stacked, each with layer normalization and a residual connection, followed by layer normalization and a linear head). The center shows the inside of time mixing (after token shift, WKV is computed from k and v, multiplied by σ(r) computed from r, and passed to the linear layer W_o). The right side shows one time step of computing WKV as an RNN (the numerator a and denominator b are decayed by e^{−w} and e^{k_t} v_t and e^{k_t} are added; the output wkv_t is computed from the state before the update and the current token)

Background and overview

RWKV (Receptance Weighted Key Value) is a language model that can be trained in parallel over all time steps like a Transformer, and run at inference like an RNN by updating a fixed-size state one time step at a time. It was proposed by Peng et al. in 2023 in the paper "RWKV: Reinventing RNNs for the Transformer Era". The version covered in the paper is called RWKV-4.

The Transformer can be trained in parallel, but the computation and memory of attention grow with the square of the sequence length, and every generation step revisits all past tokens. RNNs such as the LSTM and GRU need inference computation only proportional to the sequence length, but since each step must wait for the previous step's output, training cannot be parallelized, making them hard to scale to large models.

Starting from AFT (Attention Free Transformer), a Transformer variant without attention, RWKV combines the strengths of both with the following ideas.

  • Turn positional weights into a per-channel decay: the weight of a past token shrinks exponentially in proportion to its distance. In this form, past information can be summarized into two sums (a numerator and a denominator) and carried along as an RNN state.
  • Token shift: the current input and the previous input are mixed before being fed into the linear layers.
  • Receptance gate: σ(r)\sigma(r) determines how much past information to accept.

The paper trains six models from 169M to 14B parameters on The Pile and shows performance on par with Transformers of the same compute. The paper states that this is the first time, among models proposed as alternatives to the Transformer, that the claims have been backed by pretrained models at the scale of tens of billions of parameters.

Theory: WKV and the two mixings

An RWKV model is a stack of blocks with residual connections. Each block consists of time mixing, which mixes tokens with each other, and channel mixing, which mixes features (channels) with each other, each preceded by layer normalization. This is the same ordering as "attention + MLP" in the Transformer.

Time mixing is computed in the following steps.

  1. Mix with token shift: the current input xtx_t and the previous input xt−1x_{t-1} are mixed with per-channel weights μ\mu, then passed through linear layers to produce rt,kt,vtr_t, k_t, v_t (equations (11)–(13) of the paper). Each of r,k,vr, k, v has its own μ\mu.
  2. Compute WKV: the past values viv_i are averaged with weights given by the keys kik_i and a distance-dependent decay (the equation below, equation (16) of the paper).
  3. Multiply by the amount to accept: ot=Wo (σ(rt)⊙wkvt)o_t = W_o\,(\sigma(r_t) \odot wkv_t) (equation (17) of the paper). σ\sigma is the sigmoid.
rt=Wr (μr⊙xt+(1−μr)⊙xt−1)r_t = W_r\,(\mu_r \odot x_t + (1 - \mu_r) \odot x_{t-1}) wkvt=∑i=1t−1e−(t−1−i)w+ki⊙vi+eu+kt⊙vt∑i=1t−1e−(t−1−i)w+ki+eu+ktwkv_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}}

ww is the per-channel decay rate (non-negative), learned during training. Each step further into the past multiplies the weight by e−we^{-w}, so older tokens have less influence. uu is a "bonus" given only to the current token, added to treat the current token separately.

This equation has a form similar to softmax attention, ∑ieqt⊤kivi/∑ieqt⊤ki\sum_i e^{q_t^\top k_i} v_i / \sum_i e^{q_t^\top k_i}, but instead of the dot product of queries and keys, the weights are determined only by the key values and the positional decay. Also, instead of a dot product, it is computed independently for each channel.

Channel mixing also produces rt′,kt′r'_t, k'_t with token shift and is computed by the following equation (equation (18) of the paper). It is an MLP using squared ReLU, multiplied by a gate for the amount to accept.

ot′=σ(rt′)⊙(Wv′⋅max⁡(kt′,0)2)o'_t = \sigma(r'_t) \odot \bigl(W'_v \cdot \max(k'_t, 0)^2\bigr)

Computation as an RNN, and computation in training

If the numerator and denominator are each collapsed into a single vector at,bta_t, b_t, WKV can be updated one time step at a time (equations (19)–(22) in Appendix D of the paper). The right side of the figure at the top of the article shows this one-step computation.

wkvt=at−1+eu+kt⊙vtbt−1+eu+kt,at=e−w⊙at−1+ekt⊙vt,bt=e−w⊙bt−1+ektwkv_t = \frac{a_{t-1} + e^{u + k_t} \odot v_t}{b_{t-1} + e^{u + k_t}}, \qquad a_t = e^{-w} \odot a_{t-1} + e^{k_t} \odot v_t, \qquad b_t = e^{-w} \odot b_{t-1} + e^{k_t}

The recurrence starts from a0=b0=0a_0 = b_0 = 0. The state per layer is only five vectors: the previous inputs to time mixing and channel mixing (for token shift), aa, bb, and an auxiliary value for numerical stability (Appendix D). Therefore, the computation and memory of one generation step are constant regardless of the length of the preceding context. In Table 1 of the paper, inference complexity is O(Td)O(Td) versus O(T2d)O(T^2 d) for the Transformer, and memory is O(d)O(d) versus O(T2+Td)O(T^2 + Td) (TT is the sequence length and dd is the number of features).

In training, the whole sequence is available from the start, so the linear layers that produce r,k,vr, k, v and the outputs can be computed for all time steps at once with matrix multiplications (just like Q,K,VQ, K, V in the Transformer). Only the WKV part requires computation in time order, and it can be parallelized over the batch and channel dimensions, with complexity O(BTd)O(BTd), smaller than the O(BTd2)O(BTd^2) of the linear layers (Section 3.2 of the paper). The paper computes this part in a single pass with a custom CUDA kernel.

Computing ekte^{k_t} directly overflows when ktk_t is large. The official implementation keeps a shared exponent ptp_t for the numerator and denominator separately and takes exponentials after subtracting the max⁡\max (equations (23)–(28) in Appendix D). This is the same idea as computing softmax stably.

Techniques for stable training (Section 3.4 of the paper)

  • Small-valued embeddings: the embeddings are initialized with small values around ±10−4\pm 10^{-4}, and a layer normalization is added right after them. Early in training, the embeddings move away from their initial values quickly, and convergence becomes faster (Appendix F).
  • Near-identity initialization: many weights are initialized to 0, and the linear layers use no biases (Appendix E).

Experimental results

Scaling laws (Section 4.2 of the paper): 45 RWKV models were trained, confirming that the relationship between loss and compute lies on the same log-log line as for Transformers (fit to Pareto-optimal points r2=0.994r^2 = 0.994). This contrasts with prior work claiming that LSTMs do not follow this law.

Zero-shot language understanding (Section 5.1, Figures 1 and 5 of the paper): on 12 tasks including ARC, HellaSwag, and LAMBADA, compared at equal compute with Pythia, OPT, and BLOOM trained on roughly the same number of tokens, RWKV achieved comparable average performance. A comparison with Pythia trained on the same data, tokenization, and amount of training also appears in a table of the Mamba paper (Pile perplexity: 7.70 for RWKV-1.5B, 7.51 for Pythia-1.4B).

Long context (Section 5.2 of the paper): after pretraining with a context length of 1,024 and then continuing training with progressively longer contexts of 2,048 → 4,096 → 8,192, the test loss on The Pile decreased as the context got longer.

Long Range Arena (accuracy %. Excerpt from Table 4 of the paper)

ModelListOpsTextRetrievalImagePathfinderPath-XAvg
Transformer36.3764.2757.4642.4471.40✗53.66
Linear attention16.1365.9053.0942.3475.30✗50.46
S459.6086.8290.9088.6594.2096.3586.09
RWKV55.8886.0488.3470.5358.42✗72.07

The paper says RWKV is "second only to S4 in five datasets," but in the values of the paper's table (which includes eight other models), RWKV ranks second to S4 on four tasks, ListOps, Text, Retrieval, and Image, and on the average. On Pathfinder it is below several other models, and it does not solve Path-X (✗). On tasks related to text and programs (ListOps, Text, Retrieval) it was close to S4, while on image-related tasks (Image, Pathfinder, Path-X) it fell well short of S4.

Character-level language modeling (Enwik8, test bits per character, lower is better. Table 5 of the paper. 12 layers, width 512, length 1,024)

ModelTest bpcInference complexityInference memory
Transformer1.137O(T2d)O(T^2 d)O(T2+Td)O(T^2 + Td)
Reformer1.195O(Tlog⁡T d)O(T \log T\, d)O(Tlog⁡T+Td)O(T \log T + Td)
Linear attention1.207O(Td2)O(Td^2)O(Td+d2)O(Td + d^2)
Performer1.199O(Td2log⁡d)O(Td^2 \log d)O(Tdlog⁡d+d2log⁡d)O(Td \log d + d^2 \log d)
AFT-simple1.209O(Td)O(Td)O(Td)O(Td)
RWKV1.178O(Td)O(Td)O(d)O(d)

RWKV achieved the best value among the low-complexity models, but did not match the standard Transformer.

Practical notes

Keep the following points in mind when using RWKV.

  • Prompt formatting has a large effect: the paper reports that RWKV is sensitive to the order of the prompt. Reordering a prompt designed for ChatGPT to suit RWKV raised the F1 (macro average) on recognizing textual entailment (RTE) from 44.2% to 74.8% (Appendix L). Since an RNN cannot revisit what it has already read, the paper recommends writing the question first and placing the material for the judgment after it.
  • To lengthen the context, continue training in stages: as an RNN, it has no fixed maximum length, but it does not necessarily make good use of contexts longer than those it was trained on. The paper continues training while doubling the length step by step.
  • Use a dedicated kernel for WKV in training: looping over time steps one by one, as in the implementation example below, is slow, so in practice use the CUDA kernel of the official implementation (RWKV-LM).

RWKV compresses past information into a fixed-size vector and carries it along. Therefore, as the paper's "Limitations" section notes, it is at a disadvantage compared with attention, which keeps all tokens, on tasks that require precisely recalling fine details from a long context. The decay ww is a per-channel constant, and it cannot switch to "keep this information longer" depending on the input.

Comparison with other models

RWKV's WKV replaces AFT's weights wt,iw_{t,i} (a T×TT \times T matrix learned for each pair of positions) with a per-channel decay −(t−i)w-(t-i)w (equations (9)(10) of the paper). The Mamba paper views WKV as "the ratio of two input-independent (LTI) recurrent SSMs". Using the same decay for the numerator and denominator is close to adding one more decay to the numerator SiS_i and denominator ZiZ_i of linear attention, while RetNet adds only the decay without a denominator.

Lining up sequence models that replace the Transformer from the same viewpoints gives the following.

ModelHow the sequence is mixedDoes forgetting depend on the input?Training computeOne generation step
TransformerSoftmax attentionNo state (keeps the entire past)Quadratic in lengthProportional to the length so far
Linear attentionAdds feature-map dot products into a stateNever forgets (only accumulates)Linear in lengthConstant
S4Linear SSM (initialized with HiPPO)NoNearly linear in length (FFT)Constant
HyenaLong convolutions and elementwise gatesNo (the kernel is fixed; the gates depend on the input)Nearly linear in length (FFT)Not constant in convolutional form
MambaSSM whose parameters depend on the inputYesLinear in length (parallel scan)Constant
Mamba-2SSM with the state decay restricted to a scalarYesLinear in length (mainly matrix multiplications)Constant
RWKVLinear RNN with an exponentially decaying weighted averageNo (constant per channel)Linear in lengthConstant
RetNetRetention with decayNo (constant per head)Quadratic in parallel form, linear when chunkedConstant

Rough guidelines for choosing:

  • To generate long text with limited memory (on a CPU or a small GPU, etc.): RWKV is a good fit. Generation memory is constant regardless of the context length.
  • To switch between remembering and forgetting depending on the input: consider Mamba or Mamba-2, whose decay depends on the input.
  • To retrieve fine details precisely from a long context: the Transformer is a good fit.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
A small implementation of the RWKV block (the paper's version is RWKV-4) written exactly as in the paper's equations
- Token shift (eqs. 11-15): mix with the input of the previous time step using μ, then pass through a linear layer
- WKV (eq. 16): a weighted average using the per-channel decay w ≥ 0 and the bonus u for the current token
  Here the recurrence of Appendix D (eqs. 19-22) is computed one time step at a time, in the overflow-safe form (eqs. 23-28)
- Time mixing output (eq. 17): W_o (σ(r) ⊙ wkv); channel mixing (eq. 18): σ(r') ⊙ W'_v · max(k', 0)²
For practical use, use the CUDA kernel of the official implementation (RWKV-LM)
"""


def token_shift(x):
  """Shift x: [B, T, C] by one time step, with zeros at the start (same as nn.ZeroPad2d((0, 0, 1, -1)))"""
  return F.pad(x, (0, 0, 1, -1))


def wkv_recurrent(w, u, k, v):
  """
  w, u: [C] (w ≥ 0), k, v: [B, T, C]
  Eqs. (23)-(28) of Appendix D: update the numerator a', denominator b', and shared exponent p one time step at a time
  """
  B, T, C = k.shape
  a = torch.zeros(B, C, device=k.device)
  b = torch.zeros(B, C, device=k.device)
  p = torch.full((B, C), -1e38, device=k.device)
  out = []
  for t in range(T):
    kt, vt = k[:, t], v[:, t]
    q = torch.maximum(p, u + kt)                                  # eq. (23)
    e1, e2 = torch.exp(p - q), torch.exp(u + kt - q)
    out.append((e1 * a + e2 * vt) / (e1 * b + e2))                # eq. (24): wkv_t
    q2 = torch.maximum(p - w, kt)                                 # eq. (25)
    e1, e2 = torch.exp(p - w - q2), torch.exp(kt - q2)
    a, b, p = e1 * a + e2 * vt, e1 * b + e2, q2                   # eqs. (26)-(28)
  return torch.stack(out, dim=1)


def wkv_direct(w, u, k, v):
  """Compute eq. (16) directly (O(T²), for checking)"""
  B, T, C = k.shape
  t = torch.arange(T, device=k.device)
  dist = (t[:, None] - 1 - t[None, :]).float()                    # t-1-i
  logw = -dist[..., None] * w                                     # [T, T, C]
  mask = (t[None, :] < t[:, None])[..., None]                     # i < t
  logits = torch.where(mask, logw[None] + k[:, None], torch.tensor(-float('inf'), device=k.device))
  diag = (u + k)[:, :, None, :]                                   # current token: e^{u+k_t}
  logits = torch.cat([logits, diag], dim=2)                       # [B, T, T+1, C]
  vv = torch.cat([v[:, None].expand(B, T, T, C), v[:, :, None]], dim=2)
  weights = torch.softmax(logits, dim=2)                          # numerator / denominator computed together
  return (weights * vv).sum(dim=2)


class TimeMixing(nn.Module):
  def __init__(self, d):
    super().__init__()
    self.mu_r, self.mu_k, self.mu_v = (nn.Parameter(torch.rand(d)) for _ in range(3))
    self.time_decay = nn.Parameter(torch.zeros(d))                # used as w = exp(time_decay) ≥ 0
    self.time_first = nn.Parameter(torch.zeros(d))                # u (bonus for the current token)
    self.W_r, self.W_k, self.W_v, self.W_o = (nn.Linear(d, d, bias=False) for _ in range(4))

  def forward(self, x):                                           # x: [B, T, d]
    xx = token_shift(x)
    r = self.W_r(self.mu_r * x + (1 - self.mu_r) * xx)            # eq. (11)
    k = self.W_k(self.mu_k * x + (1 - self.mu_k) * xx)            # eq. (12)
    v = self.W_v(self.mu_v * x + (1 - self.mu_v) * xx)            # eq. (13)
    wkv = wkv_recurrent(torch.exp(self.time_decay), self.time_first, k, v)
    return self.W_o(torch.sigmoid(r) * wkv)                       # eq. (17)


class ChannelMixing(nn.Module):
  def __init__(self, d, hidden):
    super().__init__()
    self.mu_r, self.mu_k = nn.Parameter(torch.rand(d)), nn.Parameter(torch.rand(d))
    self.W_r = nn.Linear(d, d, bias=False)
    self.W_k = nn.Linear(d, hidden, bias=False)
    self.W_v = nn.Linear(hidden, d, bias=False)

  def forward(self, x):
    xx = token_shift(x)
    r = self.W_r(self.mu_r * x + (1 - self.mu_r) * xx)            # eq. (14)
    k = self.W_k(self.mu_k * x + (1 - self.mu_k) * xx)            # eq. (15)
    return torch.sigmoid(r) * self.W_v(torch.relu(k) ** 2)        # eq. (18): squared ReLU


class RWKVBlock(nn.Module):
  def __init__(self, d):
    super().__init__()
    self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
    self.att = TimeMixing(d)
    self.ffn = ChannelMixing(d, hidden=4 * d)

  def forward(self, x):
    x = x + self.att(self.ln1(x))
    return x + self.ffn(self.ln2(x))


class RWKV(nn.Module):
  def __init__(self, vocab, d=128, n_layers=4):
    super().__init__()
    self.emb = nn.Embedding(vocab, d)
    nn.init.uniform_(self.emb.weight, -1e-4, 1e-4)                # initialize embeddings with small values (Section 3.4)
    self.ln0 = nn.LayerNorm(d)                                    # add a LayerNorm right after
    self.blocks = nn.ModuleList([RWKVBlock(d) for _ in range(n_layers)])
    self.ln_out = nn.LayerNorm(d)
    self.head = nn.Linear(d, vocab, bias=False)

  def forward(self, idx):                                         # idx: [B, T]
    x = self.ln0(self.emb(idx))
    for blk in self.blocks:
      x = blk(x)
    return self.head(self.ln_out(x))


if __name__ == "__main__":
  torch.manual_seed(0)
  # Check that the recurrent form (Appendix D) and eq. (16) give the same values
  B, T, C = 2, 20, 8
  w, u = torch.rand(C), torch.randn(C)
  k, v = torch.randn(B, T, C), torch.randn(B, T, C)
  print('Difference between recurrence and eq. (16):', (wkv_recurrent(w, u, k, v) - wkv_direct(w, u, k, v)).abs().max().item())

  model = RWKV(vocab=100)
  logits = model(torch.randint(0, 100, (2, 32)))
  print(logits.shape)                                             # torch.Size([2, 32, 100])

FAQ

Q. Is RWKV an RNN or a Transformer?
A.

It is a model that can perform the same computation in both forms. At inference, it runs as an RNN that updates each layer's state (numerator ata_t, denominator btb_t, etc.) one time step at a time. In training, the linear layers are computed for all time steps at once and only WKV is computed in time order, so it can be trained with parallelism close to that of a Transformer.

Q. What do R, W, K, and V stand for?
A.

R (receptance) is a vector that determines how much past information to accept, applied to the output as σ(rt)\sigma(r_t). W is the rate of positional decay, a learned parameter. K and V are vectors corresponding to the keys and values of attention.

Q. What is token shift for?
A.

Before the linear layers, the current input xtx_t and the previous input xt−1x_{t-1} are mixed as μ⊙xt+(1−μ)⊙xt−1\mu \odot x_t + (1 - \mu) \odot x_{t-1}. Separately from the WKV decay, this mechanism lets the model use information from the immediately preceding token directly. The implementation is just a one-step shift along the time axis (nn.ZeroPad2d((0, 0, 1, -1))).

References

  1. B. Peng, E. Alcaide, Q. Anthony, et al., "RWKV: Reinventing RNNs for the Transformer Era," arXiv:2305.13048, 2023.
  2. S. Zhai, W. Talbott, N. Srivastava, C. Huang, H. Goh, R. Zhang, and J. Susskind, "An Attention Free Transformer," arXiv:2105.14103, 2021.
  3. A. Gu and T. Dao, "Mamba: Linear-Time Sequence Modeling with Selective State Spaces," arXiv:2312.00752, 2023.
  4. Official implementation (RWKV-LM)