Skip to main content
skill CX Codex

rwkv-architecture — Claude Code skill: RWKV in your project

A skill that explains the RWKV architecture and shows how to run the model in Claude and RNN modes, train it, and handle long context.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add Orchestra-Research/AI-Research-SKILLs --skill rwkv-architecture -a claude-code
npx skills add Orchestra-Research/AI-Research-SKILLs --skill rwkv -a claude-code
Open on GitHub

What rwkv-architecture does

RWKV is an RNN and Transformer hybrid: training runs in parallel like Claude, inference runs sequentially like an RNN. The skill hands your agent working examples of that setup — loading a model through rwkv.model.RWKV, generating token by token with PIPELINE, streaming a long document in chunks, and fine-tuning on PyTorch Lightning with DeepSpeed.

The reason to care: memory per token stays flat. A Transformer KV cache grows with sequence length, while RWKV keeps a fixed-size state, so a million-token document streams through at constant memory. The skill includes a memory and speed comparison against Transformers, a list of common failures, and pointers to the architecture details.

Dependencies are rwkv, torch and transformers; for speed you also set RWKV_JIT_ON and RWKV_CUDA_ON. A 14B model in FP16 wants 32 GB of VRAM, so a small card won't cut it. In RNN mode you must pass state between forward calls — drop it and the model loses everything it read before.

What it helps with

  • stream a million-token document without memory growth
  • generate text token by token in streaming mode
  • compare RWKV and Transformer memory on a long sequence
  • fine-tune a model across several GPUs with DeepSpeed
  • figure out why RNN mode needs state passed between calls

Example prompts for the agent

  • Show me how to load RWKV-4-Pile-14B with rwkv.model.RWKV and enable the CUDA kernel
  • Write a streaming token generation script with PIPELINE that keeps state
  • Compare RWKV and Transformer memory on a 1M token sequence

How to install rwkv-architecture

1Skills CLI (Vercel)

npx skills add Orchestra-Research/AI-Research-SKILLs --skill rwkv-architecture -a claude-code
npx skills add Orchestra-Research/AI-Research-SKILLs --skill rwkv -a claude-code

2Manually: put the files in place

~/.claude/skills/rwkv/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/rwkv/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about rwkv-architecture

How do I install rwkv-architecture in Claude?

Run npx skills add Orchestra-Research/AI-Research-SKILLs --skill rwkv-architecture -a claude-code, then npx skills add Orchestra-Research/AI-Research-SKILLs --skill rwkv -a claude-code. The skill file lands at ~/.claude/skills/rwkv/SKILL.md.

What does rwkv-architecture do?

It documents the RWKV architecture and ships code examples: model loading, generation, long context, fine-tuning. Your agent uses them whenever you work with this model.

How much VRAM does RWKV need?

In FP16, a 169M model fits in 1 GB, 1.5B in 4 GB, 7B in 16 GB, and 14B in 32 GB. During inference, memory per token stays constant.

Source text

SKILL.md · MIT
---
name: rwkv-architecture
description: RNN+Transformer hybrid with O(n) inference. Linear time, infinite context, no KV cache. Train like GPT (parallel), infer like RNN (sequential). Linux Foundation AI project. Production at Windows, Office, NeMo. RWKV-7 (March 2025). Models up to 14B parameters.
version: 1.0.0
author: Orchestra Research
license: MIT
tags: [RWKV, Model Architecture, RNN, Transformer Hybrid, Linear Complexity, Infinite Context, Efficient Inference, Linux Foundation, Alternative Architecture]
dependencies: [rwkv, torch, transformers]
---

# RWKV - Receptance Weighted Key Value

## Quick start

RWKV (RwaKuv) combines Transformer parallelization (training) with RNN efficiency (inference).

**Installation**:
```bash
# Install PyTorch
pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu121

# Install dependencies
pip install pytorch-lightning==1.9.5 deepspeed wandb ninja --upgrade

# Install RWKV
pip install rwkv
```

**Basic usage** (GPT mode + RNN mode):
```python
import os
from rwkv.model import RWKV

os.environ["RWKV_JIT_ON"] = '1'
os.environ["RWKV_CUDA_ON"] = '1'  # Use CUDA kernel for speed

# Load model
model = RWKV(
    model='/path/to/RWKV-4-Pile-1B5-20220903-8040',
    strategy='cuda fp16'
)

# GPT mode (parallel processing)
out, state = model.forward([187, 510, 1563, 310, 247], None)
print(out.detach().cpu().numpy())  # Logits

# RNN mode (sequential processing, same result)
out, state = model.forward([187, 510], None)  # First 2 tokens
out, state = model.forward([1563], state)      # Next token
out, state = model.forward([310, 247], state)  # Last tokens
print(out.detach().cpu().numpy())  # Same logits as above!
```

## Common workflows

### Workflow 1: Text generation (streaming)

**Efficient token-by-token generation**:
```python
from rwkv.model import RWKV
from rwkv.utils import PIPELINE

model = RWKV(model='RWKV-4-Pile-14B-20230313-ctx8192-test1050', strategy='cuda fp16')
pipeline = PIPELINE(model, "20B_tokenizer.json")

# Initial prompt
prompt = "The future of AI is"
state = None

# Generate token by token
for token in prompt:
    out, state = pipeline.model.forward(pipeline.encode(token), state)

# Continue generation
for _ in range(100):
    out, state = pipeline.model.forward(None, state)
    token = pipeline.sample_logits(out)
    print(pipeline.decode(token), end='', flush=True)
```

**Key advantage**: Constant memory per token (no growing KV cache)

### Workflow 2: Long context processing (infinite context)

**Process million-token sequences**:
```python
model = RWKV(model='RWKV-4-Pile-14B', strategy='cuda fp16')

# Process very long document
state = None
long_document = load_document()  # e.g., 1M tokens

# Stream through entire document
for chunk in chunks(long_document, chunk_size=1024):
    out, state = model.forward(chunk, state)

# State now contains information from entire 1M token document
# Memory usage: O(1) (constant, not O(n)!)
```

### Workflow 3: Fine-tuning RWKV

**Standard fine-tuning workflow**:
```python
# Training script
import pytorch_lightning as pl
from rwkv.model import RWKV
from rwkv.trainer import RWKVTrainer

# Configure model
config = {
    'n_layer': 24,
    'n_embd': 1024,
    'vocab_size': 50277,
    'ctx_len': 1024
}

# Setup trainer
trainer = pl.Trainer(
    accelerator='gpu',
    devices=8,
    precision='bf16',
    strategy='deepspeed_stage_2',
    max_epochs=1
)

# Train
model = RWKV(config)
trainer.fit(model, train_dataloader)
```

### Workflow 4: RWKV vs Transformer comparison

**Memory comparison** (1M token sequence):
```python
# Transformer (GPT)
# Memory: O(n²) for attention
# KV cache: 1M × hidden_dim × n_layers × 2 (keys + values)
# Example: 1M × 4096 × 24 × 2 = ~400GB (impractical!)

# RWKV
# Memory: O(1) per token
# State: hidden_dim × n_layers = 4096 × 24 = ~400KB
# 1,000,000× more efficient!
```

**Speed comparison** (inference):
```python
# Transformer: O(n) per token (quadratic overall)
# First token: 1 computation
# Second token: 2 computations
# ...
# 1000th token: 1000 computations

# RWKV: O(1) per token (linear overall)
# Every token: 1 computation
# 1000th token: 1 computation (same as first!)
```

## When to use vs alternatives

**Use RWKV when**:
- Need very long context (100K+ tokens)
- Want constant memory usage
- Building streaming applications
- Need RNN efficiency with Transformer performance
- Memory-constrained deployment

**Key advantages**:
- **Linear time**: O(n) vs O(n²) for Transformers
- **No KV cache**: Constant memory per token
- **Infinite context**: No fixed window limit
- **Parallelizable training**: Like GPT
- **Sequential inference**: Like RNN

**Use alternatives instead**:
- **Transformers**: Need absolute best performance, have compute
- **Mamba**: Want state-space models
- **RetNet**: Need retention mechanism
- **Hyena**: Want convolution-based approach

## Common issues

**Issue: Out of memory during training**

Use gradient checkpointing and DeepSpeed:
```python
trainer = pl.Trainer(
    strategy='deepspeed_stage_3',  # Full ZeRO-3
    precision='bf16'
)
```

**Issue: Slow inference**

Enable CUDA kernel:
```python
os.environ["RWKV_CUDA_ON"] = '1'
```

**Issue: Model not loading**

Check model path and strategy:
```python
model = RWKV(
    model='/absolute/path/to/model.pth',
    strategy='cuda fp16'  # Or 'cpu fp32' for CPU
)
```

**Issue: State management in RNN mode**

Always pass state between forward calls:
```python
# WRONG: State lost
out1, _ = model.forward(tokens1, None)
out2, _ = model.forward(tokens2, None)  # No context from tokens1!

# CORRECT: State preserved
out1, state = model.forward(tokens1, None)
out2, state = model.forward(tokens2, state)  # Has context from tokens1
```

## Advanced topics

**Time-mixing and channel-mixing**: See [references/architecture-details.md](references/architecture-details.md) for WKV operation, time-decay mechanism, and receptance gates.

**State management**: See [references/state-management.md](references/state-management.md) for att_x_prev, att_kv, ffn_x_prev states, and numerical stability considerations.

**RWKV-7 improvements**: See [references/rwkv7.md](references/rwkv7.md) for latest architectural improvements (March 2025) and multimodal capabilities.

## Hardware requirements

- **GPU**: NVIDIA (CUDA 11.6+) or CPU
- **VRAM** (FP16):
  - 169M model: 1GB
  - 430M model: 2GB
  - 1.5B model: 4GB
  - 3B model: 8GB
  - 7B model: 16GB
  - 14B model: 32GB
- **Inference**: O(1) memory per token
- **Training**: Parallelizable like GPT

**Performance** (vs Transformers):
- **Speed**: Similar training, faster inference
- **Memory**: 1000× less for long sequences
- **Scaling**: Linear vs quadratic

## Resources

- Paper (RWKV): https://arxiv.org/abs/2305.13048 (May 2023)
- Paper (RWKV-7): https://arxiv.org/abs/2503.14456 (March 2025)
- GitHub: https://github.com/BlinkDL/RWKV-LM ⭐ 12,000+
- Docs: https://wiki.rwkv.com/
- Models: https://huggingface.co/BlinkDL
- Linux Foundation AI: Official project
- Production: Microsoft Windows, Office integration, NeMo support


© Orchestra Research · MIT · Orchestra-Research/AI-Research-SKILLs

Similar skills

Everything for AI and ML →

From the same set66

miles-rl-training A skill that walks your agent through RL training of large MoE models on miles: FP8, INT4, speculative rollout. Useful when you're setting up training on H100/H200. CX Codex +1 946installs nnsight-remote-interpretability Guides neural network interpretability and intervention using nnsight locally or remotely via NDIF. Useful for experimenting with 70B+ models without local GPU clusters. CX Codex +1 945installs llamaguard A skill that wires Meta's 7-8B LlamaGuard model into your agent to filter user prompts and model responses across 6 safety categories. CX Codex +1 945installs skypilot-multi-cloud-orchestration Orchestrates ML training and batch workloads across 20+ clouds while cutting GPU expenses through spot auto-recovery and region selection. CX Codex +1 944installs blip-2-vision-language A skill that hands your agent working BLIP-2 recipes: image captions, visual question answering, and image-text matching. CX Codex +1 944installs autogpt-agents Guides AI coding assistants on building and running continuous AutoGPT agents with visual workflows. Useful for multi-step automations triggered by schedules or webhooks. CX Codex +1 944installs nemo-guardrails This skill helps configure runtime safety for LLM apps, from jailbreak checks to PII filtering. Use it when you need programmable Colang 2.0 rails. CX Codex +1 944installs nemo-evaluator-sdk This skill runs LLM evaluation across 100+ benchmarks from 18+ harnesses: MMLU, HumanEval, GSM8K, safety and VLM tasks. Useful when you need reproducible model comparisons. CX Codex +1 943installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor