Upload folder using huggingface_hub
Browse files- .ipynb_checkpoints/configuration_rwkv7-checkpoint.py +65 -0
- README.md +173 -0
- __pycache__/configuration_rwkv7.cpython-312.pyc +0 -0
- __pycache__/modeling_rwkv7.cpython-312.pyc +0 -0
- config.json +30 -0
- configuration_rwkv7.py +65 -0
- convert.py +107 -0
- cuda/wkv7_cuda.cu +138 -0
- cuda/wkv7_op.cpp +29 -0
- generation_config.json +8 -0
- model.safetensors +3 -0
- modeling_rwkv7.py +464 -0
- tokenizer.json +0 -0
- tokenizer_config.json +13 -0
- verify.py +68 -0
.ipynb_checkpoints/configuration_rwkv7-checkpoint.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
########################################################################################################
|
| 2 |
+
# RWKV-7 "Goose" (x070 / g1d) HuggingFace configuration
|
| 3 |
+
# Based on the reference implementation from https://github.com/BlinkDL/RWKV-LM
|
| 4 |
+
########################################################################################################
|
| 5 |
+
|
| 6 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class RWKV7Config(PretrainedConfig):
|
| 10 |
+
"""Configuration for the RWKV-7 (x070 / g1d) language model.
|
| 11 |
+
|
| 12 |
+
The defaults match the ``rwkv7-g1d-0.1b`` checkpoint
|
| 13 |
+
(L12-D768, head_size 64), but the embedding / lm-head vocabulary has been
|
| 14 |
+
re-sized (and re-initialized) to match the OLMo tokenizer.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
model_type = "rwkv7"
|
| 18 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 19 |
+
|
| 20 |
+
def __init__(
|
| 21 |
+
self,
|
| 22 |
+
vocab_size=100278,
|
| 23 |
+
hidden_size=768,
|
| 24 |
+
num_hidden_layers=12,
|
| 25 |
+
head_size=64,
|
| 26 |
+
intermediate_size=3072,
|
| 27 |
+
decay_lora=64,
|
| 28 |
+
aaa_lora=64,
|
| 29 |
+
mv_lora=32,
|
| 30 |
+
gate_lora=128,
|
| 31 |
+
layer_norm_epsilon=1e-5,
|
| 32 |
+
group_norm_epsilon=64e-5,
|
| 33 |
+
bos_token_id=None,
|
| 34 |
+
eos_token_id=100257,
|
| 35 |
+
pad_token_id=100277,
|
| 36 |
+
tie_word_embeddings=False,
|
| 37 |
+
use_cuda_kernel=True,
|
| 38 |
+
chunk_len=16,
|
| 39 |
+
**kwargs,
|
| 40 |
+
):
|
| 41 |
+
self.vocab_size = vocab_size
|
| 42 |
+
self.hidden_size = hidden_size
|
| 43 |
+
self.num_hidden_layers = num_hidden_layers
|
| 44 |
+
self.head_size = head_size
|
| 45 |
+
self.intermediate_size = intermediate_size
|
| 46 |
+
self.decay_lora = decay_lora
|
| 47 |
+
self.aaa_lora = aaa_lora
|
| 48 |
+
self.mv_lora = mv_lora
|
| 49 |
+
self.gate_lora = gate_lora
|
| 50 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 51 |
+
self.group_norm_epsilon = group_norm_epsilon
|
| 52 |
+
# attention/ffn dims are derived from hidden_size in the reference model
|
| 53 |
+
self.attention_hidden_size = hidden_size
|
| 54 |
+
self.use_cuda_kernel = use_cuda_kernel
|
| 55 |
+
self.chunk_len = chunk_len
|
| 56 |
+
|
| 57 |
+
assert hidden_size % head_size == 0, "hidden_size must be divisible by head_size"
|
| 58 |
+
|
| 59 |
+
super().__init__(
|
| 60 |
+
bos_token_id=bos_token_id,
|
| 61 |
+
eos_token_id=eos_token_id,
|
| 62 |
+
pad_token_id=pad_token_id,
|
| 63 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 64 |
+
**kwargs,
|
| 65 |
+
)
|
README.md
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# RWKV-7 "g1d" 0.1B — HuggingFace port (OLMo tokenizer)
|
| 2 |
+
|
| 3 |
+
A `trust_remote_code=True` HuggingFace wrapper around the BlinkDL
|
| 4 |
+
**RWKV-7 "Goose" g1d 0.1B** checkpoint
|
| 5 |
+
(`rwkv7-g1d-0.1b-20260129-ctx8192.pth`), re-headed for the **OLMo tokenizer**.
|
| 6 |
+
|
| 7 |
+
- The 12 transformer-style RWKV-7 blocks keep their **pretrained** weights.
|
| 8 |
+
- The **embedding** and **lm-head** are **re-initialized** (from RWKV's 65536-token
|
| 9 |
+
vocab to OLMo's 100278-token vocab), so they are *untrained* and need fine-tuning.
|
| 10 |
+
- Time-mixing runs on a **fused CUDA kernel** (forward **and** backward) when a GPU
|
| 11 |
+
+ CUDA toolchain are available, and transparently **falls back to pure PyTorch**
|
| 12 |
+
otherwise.
|
| 13 |
+
|
| 14 |
+
> Because emb/head are freshly initialized, `generate()` produces gibberish until
|
| 15 |
+
> you fine-tune on OLMo-tokenized data. The model *body* is pretrained; only the
|
| 16 |
+
> vocabulary projection is new.
|
| 17 |
+
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
## Files
|
| 21 |
+
|
| 22 |
+
| File | Purpose |
|
| 23 |
+
|------|---------|
|
| 24 |
+
| `config.json` | Serialized `RWKV7Config` (dims + `auto_map` to the remote-code classes). |
|
| 25 |
+
| `configuration_rwkv7.py` | `RWKV7Config` — all architecture hyperparameters. |
|
| 26 |
+
| `modeling_rwkv7.py` | Model code: CUDA-kernel dispatch + PyTorch fallback, `RWKV7Model`, `RWKV7ForCausalLM`. |
|
| 27 |
+
| `cuda/wkv7_cuda.cu`, `cuda/wkv7_op.cpp` | The fused bf16 "wind_backstepping" RWKV-7 kernel (forward + backward), copied from `RWKV-v7/train_temp/cuda/`. |
|
| 28 |
+
| `model.safetensors` | Converted weights (bf16, ~244M params). |
|
| 29 |
+
| `tokenizer.json`, `tokenizer_config.json` | OLMo tokenizer (vocab 100278, GPT2-style BPE). |
|
| 30 |
+
| `generation_config.json` | Default generation settings (eos/pad ids). |
|
| 31 |
+
| `convert.py` | Reproduces `model.safetensors` from the original `.pth`. |
|
| 32 |
+
| `verify.py` | End-to-end smoke test (load / forward / parity / backward / generate). |
|
| 33 |
+
|
| 34 |
+
## Architecture (from `config.json`)
|
| 35 |
+
|
| 36 |
+
| field | value | meaning |
|
| 37 |
+
|-------|-------|---------|
|
| 38 |
+
| `num_hidden_layers` | 12 | RWKV-7 blocks |
|
| 39 |
+
| `hidden_size` | 768 | embedding dim `C` |
|
| 40 |
+
| `head_size` | 64 | → 12 heads (`H = C / head_size`) |
|
| 41 |
+
| `intermediate_size` | 3072 | channel-mix (FFN) hidden |
|
| 42 |
+
| `decay_lora` / `aaa_lora` / `mv_lora` / `gate_lora` | 64 / 64 / 32 / 128 | LoRA ranks for `w` / `a` / `v` / `g` |
|
| 43 |
+
| `vocab_size` | 100278 | OLMo tokenizer size (re-initialized emb/head) |
|
| 44 |
+
| `chunk_len` | 16 | CUDA kernel chunk length; sequence is padded to a multiple of this |
|
| 45 |
+
| `use_cuda_kernel` | true | prefer the fused kernel when possible |
|
| 46 |
+
|
| 47 |
+
---
|
| 48 |
+
|
| 49 |
+
## Usage
|
| 50 |
+
|
| 51 |
+
```python
|
| 52 |
+
import torch
|
| 53 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 54 |
+
|
| 55 |
+
PATH = "/workspace/rwkv7-g1d-olmo"
|
| 56 |
+
|
| 57 |
+
tok = AutoTokenizer.from_pretrained(PATH, trust_remote_code=True)
|
| 58 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 59 |
+
PATH, trust_remote_code=True, dtype=torch.bfloat16
|
| 60 |
+
).cuda().eval()
|
| 61 |
+
|
| 62 |
+
ids = tok("The Eiffel tower is in the city of", return_tensors="pt").input_ids.cuda()
|
| 63 |
+
with torch.no_grad():
|
| 64 |
+
logits = model(ids).logits # (1, T, 100278)
|
| 65 |
+
|
| 66 |
+
# training / backward
|
| 67 |
+
model.train()
|
| 68 |
+
out = model(ids, labels=ids) # shifted cross-entropy loss
|
| 69 |
+
out.loss.backward() # gradients flow through the CUDA kernel
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
### Forcing the PyTorch fallback
|
| 73 |
+
|
| 74 |
+
Set the flag on the config (useful on CPU, non-bf16, or to debug the kernel):
|
| 75 |
+
|
| 76 |
+
```python
|
| 77 |
+
model.config.use_cuda_kernel = False # every RWKV-7 op now runs in pure PyTorch
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
The kernel is also skipped automatically when: no CUDA device, input dtype is not
|
| 81 |
+
bfloat16, or the kernel fails to compile — in all cases the fallback is used and a
|
| 82 |
+
one-line notice is printed.
|
| 83 |
+
|
| 84 |
+
---
|
| 85 |
+
|
| 86 |
+
## How the CUDA kernel + fallback work (`modeling_rwkv7.py`)
|
| 87 |
+
|
| 88 |
+
The time-mixing recurrence is dispatched by `run_rwkv7(r, w, k, v, a, b, config)`:
|
| 89 |
+
|
| 90 |
+
1. **Kernel path** (`_rwkv7_cuda`) — used when `config.use_cuda_kernel` is set, the
|
| 91 |
+
tensors are CUDA + bf16, and `_try_load_cuda_kernel()` succeeds. On first call it
|
| 92 |
+
JIT-compiles `cuda/wkv7_op.cpp` + `cuda/wkv7_cuda.cu` via
|
| 93 |
+
`torch.utils.cpp_extension.load` (flags `-D_C_=head_size`, `-D_CHUNK_LEN_=chunk_len`)
|
| 94 |
+
and registers the `wind_backstepping` op. Compilation happens once per process and
|
| 95 |
+
is cached; any failure is caught and flips the model to the fallback.
|
| 96 |
+
- `_WindBackstepping` is a `torch.autograd.Function`:
|
| 97 |
+
- **forward** → `wind_backstepping.forward` (produces `y` plus the saved state
|
| 98 |
+
`s` and `sa` needed for backprop).
|
| 99 |
+
- **backward** → `wind_backstepping.backward` (returns gradients for all six
|
| 100 |
+
inputs `w, q, k, v, z, b`), so training works end-to-end on the kernel.
|
| 101 |
+
- The sequence length is padded to a multiple of `chunk_len` (16) and sliced back.
|
| 102 |
+
|
| 103 |
+
2. **Fallback path** (`_rwkv7_pytorch`) — a plain sequential-over-time
|
| 104 |
+
implementation of the same recurrence
|
| 105 |
+
`state = state*exp(-exp(w)) + state·aᵀ·b + vᵀ·k`, `y = state·r`, in fp32.
|
| 106 |
+
It is fully differentiable through ordinary autograd (no custom backward needed).
|
| 107 |
+
|
| 108 |
+
Both paths take the **raw (pre-exp) decay `w`** and apply `exp(-exp(w))` internally,
|
| 109 |
+
so they are numerically interchangeable. `verify.py` confirms kernel-vs-fallback
|
| 110 |
+
parity (identical bf16 logits and top-1 prediction).
|
| 111 |
+
|
| 112 |
+
### Model structure
|
| 113 |
+
|
| 114 |
+
`RWKV7ForCausalLM` → `.rwkv` (`RWKV7Model`) + `.head` (lm-head). `RWKV7Model` holds
|
| 115 |
+
`emb`, `blocks[0..11]` (`RWKV7Block` = `ln1` + `att` time-mix, `ln2` + `ffn`
|
| 116 |
+
channel-mix; block 0 also has `ln0`), and `ln_out`. State-dict keys mirror the
|
| 117 |
+
original RWKV layout under the `rwkv.` prefix (e.g. `rwkv.blocks.0.att.receptance.weight`).
|
| 118 |
+
Generation runs in **GPT mode** (no incremental KV cache — the full sequence is
|
| 119 |
+
recomputed each step; correct but not the fastest).
|
| 120 |
+
|
| 121 |
+
---
|
| 122 |
+
|
| 123 |
+
## Reproducing the conversion (`convert.py`)
|
| 124 |
+
|
| 125 |
+
```bash
|
| 126 |
+
# 1) download the original checkpoint (already done in /workspace)
|
| 127 |
+
wget https://huggingface.co/BlinkDL/rwkv7-g1/resolve/main/rwkv7-g1d-0.1b-20260129-ctx8192.pth \
|
| 128 |
+
-O /workspace/rwkv7-g1d-0.1b-20260129-ctx8192.pth
|
| 129 |
+
|
| 130 |
+
# 2) convert -> /workspace/rwkv7-g1d-olmo
|
| 131 |
+
python convert.py
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
What `convert.py` does:
|
| 135 |
+
|
| 136 |
+
1. Loads the OLMo tokenizer to read the target vocab size (100278).
|
| 137 |
+
2. Loads the `.pth` and infers all dims from the tensor shapes → builds `RWKV7Config`.
|
| 138 |
+
3. Remaps the original RWKV keys to the HF module layout (`rwkv.` prefix), **dropping**
|
| 139 |
+
`emb.weight` / `head.weight`, and loads them with `strict=False`
|
| 140 |
+
(asserts there are **no** unexpected or unmatched keys besides emb/head).
|
| 141 |
+
4. **Re-initializes** the embedding (`uniform(±1e-4)`) and head
|
| 142 |
+
(`orthogonal`, gain `0.5·√(vocab/hidden)`) for the new vocabulary — RWKV's own
|
| 143 |
+
init scheme.
|
| 144 |
+
5. Saves weights (`safetensors`), config, tokenizer, and copies the remote-code files.
|
| 145 |
+
|
| 146 |
+
## Verifying (`verify.py`)
|
| 147 |
+
|
| 148 |
+
```bash
|
| 149 |
+
python verify.py
|
| 150 |
+
```
|
| 151 |
+
|
| 152 |
+
Checks: load via `AutoModelForCausalLM(trust_remote_code=True)`, CUDA-kernel forward,
|
| 153 |
+
kernel-vs-fallback parity, a backward pass (gradients on emb / attention / decay-LoRA),
|
| 154 |
+
and a short greedy `generate()`.
|
| 155 |
+
|
| 156 |
+
> Note: 399/402 parameters receive gradients — the 3 without are
|
| 157 |
+
> `blocks.0.att.v0/v1/v2` (the value-residual params are unused in layer 0 by design).
|
| 158 |
+
|
| 159 |
+
---
|
| 160 |
+
|
| 161 |
+
## Requirements
|
| 162 |
+
|
| 163 |
+
- PyTorch with CUDA (bf16-capable GPU; tested on RTX 3060 / CUDA 13.0) for the kernel;
|
| 164 |
+
CPU/other works via the fallback.
|
| 165 |
+
- `transformers >= 5`, `safetensors`.
|
| 166 |
+
- A working CUDA toolchain (`nvcc`) for first-call kernel JIT compilation; if absent,
|
| 167 |
+
the model still runs on the PyTorch fallback.
|
| 168 |
+
|
| 169 |
+
## Credits
|
| 170 |
+
|
| 171 |
+
RWKV-7 architecture and the original checkpoint/kernels by **BlinkDL** —
|
| 172 |
+
<https://github.com/BlinkDL/RWKV-LM>. Kernel sources copied from
|
| 173 |
+
`RWKV-v7/train_temp/cuda/`.
|
__pycache__/configuration_rwkv7.cpython-312.pyc
ADDED
|
Binary file (2 kB). View file
|
|
|
__pycache__/modeling_rwkv7.cpython-312.pyc
ADDED
|
Binary file (28.1 kB). View file
|
|
|
config.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"aaa_lora": 64,
|
| 3 |
+
"architectures": [
|
| 4 |
+
"RWKV7ForCausalLM"
|
| 5 |
+
],
|
| 6 |
+
"attention_hidden_size": 768,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_rwkv7.RWKV7Config",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_rwkv7.RWKV7ForCausalLM"
|
| 10 |
+
},
|
| 11 |
+
"bos_token_id": null,
|
| 12 |
+
"chunk_len": 16,
|
| 13 |
+
"decay_lora": 64,
|
| 14 |
+
"dtype": "bfloat16",
|
| 15 |
+
"eos_token_id": 100257,
|
| 16 |
+
"gate_lora": 128,
|
| 17 |
+
"group_norm_epsilon": 0.00064,
|
| 18 |
+
"head_size": 64,
|
| 19 |
+
"hidden_size": 768,
|
| 20 |
+
"intermediate_size": 3072,
|
| 21 |
+
"layer_norm_epsilon": 1e-05,
|
| 22 |
+
"model_type": "rwkv7",
|
| 23 |
+
"mv_lora": 32,
|
| 24 |
+
"num_hidden_layers": 12,
|
| 25 |
+
"pad_token_id": 100277,
|
| 26 |
+
"tie_word_embeddings": false,
|
| 27 |
+
"transformers_version": "5.14.1",
|
| 28 |
+
"use_cuda_kernel": true,
|
| 29 |
+
"vocab_size": 100278
|
| 30 |
+
}
|
configuration_rwkv7.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
########################################################################################################
|
| 2 |
+
# RWKV-7 "Goose" (x070 / g1d) HuggingFace configuration
|
| 3 |
+
# Based on the reference implementation from https://github.com/BlinkDL/RWKV-LM
|
| 4 |
+
########################################################################################################
|
| 5 |
+
|
| 6 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class RWKV7Config(PretrainedConfig):
|
| 10 |
+
"""Configuration for the RWKV-7 (x070 / g1d) language model.
|
| 11 |
+
|
| 12 |
+
The defaults match the ``rwkv7-g1d-0.1b`` checkpoint
|
| 13 |
+
(L12-D768, head_size 64), but the embedding / lm-head vocabulary has been
|
| 14 |
+
re-sized (and re-initialized) to match the OLMo tokenizer.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
model_type = "rwkv7"
|
| 18 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 19 |
+
|
| 20 |
+
def __init__(
|
| 21 |
+
self,
|
| 22 |
+
vocab_size=100278,
|
| 23 |
+
hidden_size=768,
|
| 24 |
+
num_hidden_layers=12,
|
| 25 |
+
head_size=64,
|
| 26 |
+
intermediate_size=3072,
|
| 27 |
+
decay_lora=64,
|
| 28 |
+
aaa_lora=64,
|
| 29 |
+
mv_lora=32,
|
| 30 |
+
gate_lora=128,
|
| 31 |
+
layer_norm_epsilon=1e-5,
|
| 32 |
+
group_norm_epsilon=64e-5,
|
| 33 |
+
bos_token_id=None,
|
| 34 |
+
eos_token_id=100257,
|
| 35 |
+
pad_token_id=100277,
|
| 36 |
+
tie_word_embeddings=False,
|
| 37 |
+
use_cuda_kernel=True,
|
| 38 |
+
chunk_len=16,
|
| 39 |
+
**kwargs,
|
| 40 |
+
):
|
| 41 |
+
self.vocab_size = vocab_size
|
| 42 |
+
self.hidden_size = hidden_size
|
| 43 |
+
self.num_hidden_layers = num_hidden_layers
|
| 44 |
+
self.head_size = head_size
|
| 45 |
+
self.intermediate_size = intermediate_size
|
| 46 |
+
self.decay_lora = decay_lora
|
| 47 |
+
self.aaa_lora = aaa_lora
|
| 48 |
+
self.mv_lora = mv_lora
|
| 49 |
+
self.gate_lora = gate_lora
|
| 50 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 51 |
+
self.group_norm_epsilon = group_norm_epsilon
|
| 52 |
+
# attention/ffn dims are derived from hidden_size in the reference model
|
| 53 |
+
self.attention_hidden_size = hidden_size
|
| 54 |
+
self.use_cuda_kernel = use_cuda_kernel
|
| 55 |
+
self.chunk_len = chunk_len
|
| 56 |
+
|
| 57 |
+
assert hidden_size % head_size == 0, "hidden_size must be divisible by head_size"
|
| 58 |
+
|
| 59 |
+
super().__init__(
|
| 60 |
+
bos_token_id=bos_token_id,
|
| 61 |
+
eos_token_id=eos_token_id,
|
| 62 |
+
pad_token_id=pad_token_id,
|
| 63 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 64 |
+
**kwargs,
|
| 65 |
+
)
|
convert.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Convert the BlinkDL rwkv7-g1d-0.1b .pth checkpoint into a HuggingFace
|
| 2 |
+
`trust_remote_code` model directory, re-sizing (and re-initializing) the
|
| 3 |
+
embedding + lm-head to the OLMo tokenizer vocabulary.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import math
|
| 9 |
+
import shutil
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
|
| 14 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 15 |
+
from configuration_rwkv7 import RWKV7Config
|
| 16 |
+
from modeling_rwkv7 import RWKV7ForCausalLM
|
| 17 |
+
|
| 18 |
+
PTH = "/workspace/rwkv7-g1d-0.1b-20260129-ctx8192.pth"
|
| 19 |
+
OLMO = "/workspace/olmo"
|
| 20 |
+
OUT = "/workspace/rwkv7-g1d-olmo"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def main():
|
| 24 |
+
from transformers import AutoTokenizer
|
| 25 |
+
|
| 26 |
+
tok = AutoTokenizer.from_pretrained(OLMO, trust_remote_code=True)
|
| 27 |
+
new_vocab = len(tok)
|
| 28 |
+
print(f"OLMo tokenizer vocab = {new_vocab}")
|
| 29 |
+
|
| 30 |
+
sd = torch.load(PTH, map_location="cpu")
|
| 31 |
+
old_vocab, n_embd = sd["emb.weight"].shape
|
| 32 |
+
print(f"checkpoint: vocab={old_vocab}, n_embd={n_embd}")
|
| 33 |
+
|
| 34 |
+
config = RWKV7Config(
|
| 35 |
+
vocab_size=new_vocab,
|
| 36 |
+
hidden_size=n_embd,
|
| 37 |
+
num_hidden_layers=12,
|
| 38 |
+
head_size=64,
|
| 39 |
+
intermediate_size=sd["blocks.0.ffn.key.weight"].shape[0],
|
| 40 |
+
decay_lora=sd["blocks.0.att.w1"].shape[1],
|
| 41 |
+
aaa_lora=sd["blocks.0.att.a1"].shape[1],
|
| 42 |
+
mv_lora=sd["blocks.0.att.v1"].shape[1],
|
| 43 |
+
gate_lora=sd["blocks.0.att.g1"].shape[1],
|
| 44 |
+
eos_token_id=tok.eos_token_id,
|
| 45 |
+
pad_token_id=tok.pad_token_id,
|
| 46 |
+
torch_dtype="bfloat16",
|
| 47 |
+
architectures=["RWKV7ForCausalLM"],
|
| 48 |
+
auto_map={
|
| 49 |
+
"AutoConfig": "configuration_rwkv7.RWKV7Config",
|
| 50 |
+
"AutoModelForCausalLM": "modeling_rwkv7.RWKV7ForCausalLM",
|
| 51 |
+
},
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
# remap RWKV native keys -> HF module layout (rwkv.* + head)
|
| 55 |
+
remap = {}
|
| 56 |
+
for k, v in sd.items():
|
| 57 |
+
if k == "emb.weight" or k == "head.weight":
|
| 58 |
+
continue # re-initialized below
|
| 59 |
+
if k.startswith("blocks.") or k.startswith("ln_out."):
|
| 60 |
+
remap["rwkv." + k] = v
|
| 61 |
+
else:
|
| 62 |
+
remap["rwkv." + k] = v
|
| 63 |
+
|
| 64 |
+
model = RWKV7ForCausalLM(config).to(dtype=torch.bfloat16)
|
| 65 |
+
|
| 66 |
+
missing, unexpected = model.load_state_dict(remap, strict=False)
|
| 67 |
+
# emb/head are expected to be "missing" from `remap` (we drop them on purpose)
|
| 68 |
+
missing = [m for m in missing if not (m == "rwkv.emb.weight" or m == "head.weight")]
|
| 69 |
+
print("unexpected keys:", unexpected)
|
| 70 |
+
print("missing (besides emb/head):", missing)
|
| 71 |
+
assert not unexpected, f"unexpected keys present: {unexpected}"
|
| 72 |
+
assert not missing, f"unmatched keys: {missing}"
|
| 73 |
+
|
| 74 |
+
# Re-initialize embedding + head for the new (OLMo) vocabulary, using the
|
| 75 |
+
# RWKV reference init scheme.
|
| 76 |
+
with torch.no_grad():
|
| 77 |
+
emb = torch.empty(new_vocab, n_embd)
|
| 78 |
+
nn.init.uniform_(emb, a=-1e-4, b=1e-4)
|
| 79 |
+
model.rwkv.emb.weight.copy_(emb.to(torch.bfloat16))
|
| 80 |
+
|
| 81 |
+
head = torch.empty(new_vocab, n_embd)
|
| 82 |
+
scale = 0.5 * math.sqrt(new_vocab / n_embd) if new_vocab > n_embd else 0.5
|
| 83 |
+
nn.init.orthogonal_(head, gain=scale)
|
| 84 |
+
model.head.weight.copy_(head.to(torch.bfloat16))
|
| 85 |
+
print(f"re-initialized emb {tuple(model.rwkv.emb.weight.shape)} and head "
|
| 86 |
+
f"{tuple(model.head.weight.shape)} (head gain {scale:.4f})")
|
| 87 |
+
|
| 88 |
+
os.makedirs(OUT, exist_ok=True)
|
| 89 |
+
model.save_pretrained(OUT, safe_serialization=True)
|
| 90 |
+
config.save_pretrained(OUT)
|
| 91 |
+
|
| 92 |
+
# tokenizer + generation config
|
| 93 |
+
tok.save_pretrained(OUT)
|
| 94 |
+
|
| 95 |
+
# make sure the remote-code files sit alongside the weights
|
| 96 |
+
for fn in ["configuration_rwkv7.py", "modeling_rwkv7.py"]:
|
| 97 |
+
src = os.path.join(os.path.dirname(os.path.abspath(__file__)), fn)
|
| 98 |
+
dst = os.path.join(OUT, fn)
|
| 99 |
+
if os.path.abspath(src) != os.path.abspath(dst):
|
| 100 |
+
shutil.copy(src, dst)
|
| 101 |
+
|
| 102 |
+
print("saved to", OUT)
|
| 103 |
+
print("files:", sorted(os.listdir(OUT)))
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
main()
|
cuda/wkv7_cuda.cu
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <cuda_bf16.h>
|
| 2 |
+
#include <assert.h>
|
| 3 |
+
|
| 4 |
+
using bf = __nv_bfloat16;
|
| 5 |
+
__device__ inline float to_float(const bf & u) { return __bfloat162float(u); }
|
| 6 |
+
__device__ inline bf to_bf(const float & u) { return __float2bfloat16_rn(u); }
|
| 7 |
+
|
| 8 |
+
typedef bf * __restrict__ F_;
|
| 9 |
+
|
| 10 |
+
__global__ void forward_kernel(int T, int H, F_ w_, F_ q_, F_ k_, F_ v_, F_ a_, F_ b_, bf* y_, float* s_, float* sa_) {
|
| 11 |
+
constexpr int C = _C_;
|
| 12 |
+
int bb = blockIdx.y, hh = blockIdx.x, i = threadIdx.x;
|
| 13 |
+
|
| 14 |
+
float state[C] = {0};
|
| 15 |
+
__shared__ float q[C], k[C], w[C], a[C], b[C];
|
| 16 |
+
|
| 17 |
+
for (int t = 0; t < T; t++) {
|
| 18 |
+
int ind = bb*T*H*C + t*H*C + hh * C + i;
|
| 19 |
+
__syncthreads();
|
| 20 |
+
q[i] = to_float(q_[ind]);
|
| 21 |
+
w[i] = __expf(-__expf(to_float(w_[ind])));
|
| 22 |
+
k[i] = to_float(k_[ind]);
|
| 23 |
+
a[i] = to_float(a_[ind]);
|
| 24 |
+
b[i] = to_float(b_[ind]);
|
| 25 |
+
__syncthreads();
|
| 26 |
+
|
| 27 |
+
float sa = 0;
|
| 28 |
+
#pragma unroll
|
| 29 |
+
for (int j = 0; j < C; j++) {
|
| 30 |
+
sa += a[j] * state[j];
|
| 31 |
+
}
|
| 32 |
+
sa_[ind] = sa;
|
| 33 |
+
|
| 34 |
+
float v = to_float(v_[ind]);
|
| 35 |
+
float y = 0;
|
| 36 |
+
#pragma unroll
|
| 37 |
+
for (int j = 0; j < C; j++) {
|
| 38 |
+
float& s = state[j];
|
| 39 |
+
s = s * w[j] + sa * b[j] + k[j] * v;
|
| 40 |
+
y += s * q[j];
|
| 41 |
+
}
|
| 42 |
+
y_[ind] = to_bf(y);
|
| 43 |
+
|
| 44 |
+
if ((t+1)%_CHUNK_LEN_ == 0) {
|
| 45 |
+
int base = (bb*H+hh)*(T/_CHUNK_LEN_)*C*C + (t/_CHUNK_LEN_)*C*C + i;
|
| 46 |
+
#pragma unroll
|
| 47 |
+
for (int j = 0; j < C; j++) {
|
| 48 |
+
s_[base + j*C] = state[j];
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
__global__ void backward_kernel(int T, int H, F_ w_, F_ q_, F_ k_, F_ v_, F_ a_, F_ b_, F_ dy_, float * __restrict__ s_, float * __restrict__ sa_, bf* dw_, bf* dq_, bf* dk_, bf* dv_, bf* da_, bf* db_) {
|
| 55 |
+
constexpr int C = _C_;
|
| 56 |
+
int bb = blockIdx.y, hh = blockIdx.x, i = threadIdx.x;
|
| 57 |
+
|
| 58 |
+
float stateT[C] = {0}, dstate[C] = {0}, dstateT[C] = {0};
|
| 59 |
+
__shared__ float w[C], q[C], k[C], v[C], a[C], b[C], dy[C], sa[C], dSb_shared[C];
|
| 60 |
+
float qi, wi, ki, ai, bi, dyi;
|
| 61 |
+
|
| 62 |
+
for (int t = T-1; t >= 0; t--) {
|
| 63 |
+
int ind = bb*T*H*C + t*H*C + hh * C + i;
|
| 64 |
+
__syncthreads();
|
| 65 |
+
q[i] = qi = to_float(q_[ind]);
|
| 66 |
+
float wi_fac = -__expf(to_float(w_[ind]));
|
| 67 |
+
w[i] = wi = __expf(wi_fac);
|
| 68 |
+
k[i] = ki = to_float(k_[ind]);
|
| 69 |
+
a[i] = ai = to_float(a_[ind]);
|
| 70 |
+
b[i] = bi = to_float(b_[ind]);
|
| 71 |
+
v[i] = to_float(v_[ind]);
|
| 72 |
+
dy[i] = dyi = to_float(dy_[ind]);
|
| 73 |
+
sa[i] = sa_[ind];
|
| 74 |
+
__syncthreads();
|
| 75 |
+
|
| 76 |
+
if ((t+1)%_CHUNK_LEN_ == 0) {
|
| 77 |
+
int base = (bb*H+hh)*(T/_CHUNK_LEN_)*C*C + (t/_CHUNK_LEN_)*C*C + i*C;
|
| 78 |
+
#pragma unroll
|
| 79 |
+
for (int j = 0; j < C; j++) {
|
| 80 |
+
stateT[j] = s_[base + j];
|
| 81 |
+
}
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
float dq = 0;
|
| 85 |
+
#pragma unroll
|
| 86 |
+
for (int j = 0; j < C; j++) {
|
| 87 |
+
dq += stateT[j]*dy[j];
|
| 88 |
+
}
|
| 89 |
+
dq_[ind] = to_bf(dq);
|
| 90 |
+
|
| 91 |
+
float iwi = 1.0f/wi;
|
| 92 |
+
#pragma unroll
|
| 93 |
+
for (int j = 0; j < C; j++) {
|
| 94 |
+
stateT[j] = (stateT[j] - ki*v[j] - bi*sa[j]) * iwi;
|
| 95 |
+
dstate[j] += dyi * q[j];
|
| 96 |
+
dstateT[j] += qi * dy[j];
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
float dw = 0, dk = 0, dv = 0, db = 0, dSb = 0;
|
| 100 |
+
#pragma unroll
|
| 101 |
+
for (int j = 0; j < C; j++) {
|
| 102 |
+
dw += dstateT[j]*stateT[j];
|
| 103 |
+
dk += dstateT[j]*v[j];
|
| 104 |
+
dv += dstate[j]*k[j];
|
| 105 |
+
dSb += dstate[j]*b[j];
|
| 106 |
+
db += dstateT[j]*sa[j];
|
| 107 |
+
}
|
| 108 |
+
dw_[ind] = to_bf(dw * wi * wi_fac);
|
| 109 |
+
dk_[ind] = to_bf(dk);
|
| 110 |
+
dv_[ind] = to_bf(dv);
|
| 111 |
+
db_[ind] = to_bf(db);
|
| 112 |
+
|
| 113 |
+
__syncthreads();
|
| 114 |
+
dSb_shared[i] = dSb;
|
| 115 |
+
__syncthreads();
|
| 116 |
+
|
| 117 |
+
float da = 0;
|
| 118 |
+
#pragma unroll
|
| 119 |
+
for (int j = 0; j < C; j++) {
|
| 120 |
+
da += stateT[j]*dSb_shared[j];
|
| 121 |
+
}
|
| 122 |
+
da_[ind] = to_bf(da);
|
| 123 |
+
|
| 124 |
+
#pragma unroll
|
| 125 |
+
for (int j = 0; j < C; j++) {
|
| 126 |
+
dstate[j] = dstate[j]*w[j] + dSb * a[j];
|
| 127 |
+
dstateT[j] = dstateT[j]*wi + ai * dSb_shared[j];
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
void cuda_forward(int B, int T, int H, bf*w, bf*q, bf*k, bf*v, bf*z, bf*a, bf*y, float*s, float*sa) {
|
| 133 |
+
forward_kernel<<<dim3(H,B), dim3(_C_)>>>(T,H,w,q,k,v,z,a,y,s,sa);
|
| 134 |
+
}
|
| 135 |
+
void cuda_backward(int B, int T, int H, bf*w, bf*q, bf*k, bf*v, bf*z, bf*a, bf*dy, float*s, float*sa, bf*dw, bf*dq, bf*dk, bf*dv, bf*dz, bf*da) {
|
| 136 |
+
assert(T%_CHUNK_LEN_ == 0);
|
| 137 |
+
backward_kernel<<<dim3(H,B), dim3(_C_)>>>(T,H,w,q,k,v,z,a,dy,s,sa,dw,dq,dk,dv,dz,da);
|
| 138 |
+
}
|
cuda/wkv7_op.cpp
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <torch/extension.h>
|
| 2 |
+
#include <cuda_bf16.h>
|
| 3 |
+
using bf = __nv_bfloat16;
|
| 4 |
+
|
| 5 |
+
void cuda_forward(int B, int T, int H, bf*w, bf*q, bf*k, bf*v, bf*z, bf*a, bf*y, float*s, float*sa);
|
| 6 |
+
|
| 7 |
+
void forward(torch::Tensor &w, torch::Tensor &q, torch::Tensor &k, torch::Tensor &v, torch::Tensor &z, torch::Tensor &a, torch::Tensor &y, torch::Tensor &s, torch::Tensor &sa) {
|
| 8 |
+
int B = w.sizes()[0], T = w.sizes()[1], H = w.sizes()[2];
|
| 9 |
+
cuda_forward(B, T, H, (bf*)w.data_ptr(), (bf*)q.data_ptr(), (bf*)k.data_ptr(), (bf*)v.data_ptr(), (bf*)z.data_ptr(), (bf*)a.data_ptr(), (bf*)y.data_ptr(), (float*)s.data_ptr(), (float*)sa.data_ptr());
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
void cuda_backward(int B, int T, int H, bf*w, bf*q, bf*k, bf*v, bf*z, bf*a, bf*dy, float*s, float*sa, bf*dw, bf*dq, bf*dk, bf*dv, bf*dz, bf*da);
|
| 13 |
+
|
| 14 |
+
void backward(torch::Tensor &w, torch::Tensor &q, torch::Tensor &k, torch::Tensor &v, torch::Tensor &z, torch::Tensor &a, torch::Tensor &dy,
|
| 15 |
+
torch::Tensor &s, torch::Tensor &sa, torch::Tensor &dw, torch::Tensor &dq, torch::Tensor &dk, torch::Tensor &dv, torch::Tensor &dz, torch::Tensor &da) {
|
| 16 |
+
int B = w.sizes()[0], T = w.sizes()[1], H = w.sizes()[2];
|
| 17 |
+
cuda_backward(B, T, H, (bf*)w.data_ptr(), (bf*)q.data_ptr(), (bf*)k.data_ptr(), (bf*)v.data_ptr(), (bf*)z.data_ptr(), (bf*)a.data_ptr(), (bf*)dy.data_ptr(),
|
| 18 |
+
(float*)s.data_ptr(), (float*)sa.data_ptr(), (bf*)dw.data_ptr(), (bf*)dq.data_ptr(), (bf*)dk.data_ptr(), (bf*)dv.data_ptr(), (bf*)dz.data_ptr(), (bf*)da.data_ptr());
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
TORCH_LIBRARY(wind_backstepping, m) {
|
| 22 |
+
m.def("forward(Tensor w, Tensor q, Tensor k, Tensor v, Tensor z, Tensor a, Tensor(a!) y, Tensor(b!) s, Tensor(c!) sa) -> ()");
|
| 23 |
+
m.def("backward(Tensor w, Tensor q, Tensor k, Tensor v, Tensor z, Tensor a, Tensor dy, Tensor s, Tensor sa, Tensor(a!) dw, Tensor(b!) dq, Tensor(c!) dk, Tensor(d!) dv, Tensor(e!) dz, Tensor(f!) da) -> ()");
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
TORCH_LIBRARY_IMPL(wind_backstepping, CUDA, m) {
|
| 27 |
+
m.impl("forward", &forward);
|
| 28 |
+
m.impl("backward", &backward);
|
| 29 |
+
}
|
generation_config.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"eos_token_id": 100257,
|
| 4 |
+
"output_attentions": false,
|
| 5 |
+
"output_hidden_states": false,
|
| 6 |
+
"pad_token_id": 100277,
|
| 7 |
+
"transformers_version": "5.14.1"
|
| 8 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a56cd7c04a4265fda944e60f27c63f2b7875fe6b1d3cb636f63ade926eb44d1d
|
| 3 |
+
size 488935616
|
modeling_rwkv7.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
########################################################################################################
|
| 2 |
+
# RWKV-7 "Goose" (x070 / g1d) HuggingFace modeling code
|
| 3 |
+
# Based on the reference implementation from https://github.com/BlinkDL/RWKV-LM
|
| 4 |
+
#
|
| 5 |
+
# This file provides a `trust_remote_code=True` compatible RWKV-7 model that:
|
| 6 |
+
# * uses a fused CUDA kernel (fwd + bwd, "wind_backstepping" bf16) when a GPU
|
| 7 |
+
# + a working CUDA toolchain are available, and
|
| 8 |
+
# * transparently falls back to a pure-PyTorch implementation otherwise
|
| 9 |
+
# (autograd handles the backward pass automatically in the fallback).
|
| 10 |
+
########################################################################################################
|
| 11 |
+
|
| 12 |
+
import os
|
| 13 |
+
import math
|
| 14 |
+
from typing import Optional, Tuple, Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
|
| 20 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 21 |
+
from transformers.modeling_outputs import (
|
| 22 |
+
BaseModelOutputWithPast,
|
| 23 |
+
CausalLMOutputWithPast,
|
| 24 |
+
)
|
| 25 |
+
from transformers.generation import GenerationMixin
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
from .configuration_rwkv7 import RWKV7Config
|
| 29 |
+
except ImportError: # allow running as a plain script (e.g. conversion)
|
| 30 |
+
from configuration_rwkv7 import RWKV7Config
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
########################################################################################################
|
| 34 |
+
# CUDA kernel loading (lazy, best-effort). If anything goes wrong we silently
|
| 35 |
+
# fall back to the pure-PyTorch path.
|
| 36 |
+
########################################################################################################
|
| 37 |
+
|
| 38 |
+
_KERNEL_STATE = {"loaded": False, "ok": False, "op": None, "chunk_len": 16, "head_size": 64}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _try_load_cuda_kernel(head_size: int, chunk_len: int):
|
| 42 |
+
"""Compile & register the wind_backstepping RWKV-7 CUDA op. Returns True on success."""
|
| 43 |
+
if _KERNEL_STATE["loaded"]:
|
| 44 |
+
return _KERNEL_STATE["ok"]
|
| 45 |
+
_KERNEL_STATE["loaded"] = True
|
| 46 |
+
_KERNEL_STATE["head_size"] = head_size
|
| 47 |
+
_KERNEL_STATE["chunk_len"] = chunk_len
|
| 48 |
+
|
| 49 |
+
if not torch.cuda.is_available():
|
| 50 |
+
_KERNEL_STATE["ok"] = False
|
| 51 |
+
return False
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
from torch.utils.cpp_extension import load
|
| 55 |
+
|
| 56 |
+
this_dir = os.path.dirname(os.path.abspath(__file__))
|
| 57 |
+
cuda_dir = os.path.join(this_dir, "cuda")
|
| 58 |
+
sources = [
|
| 59 |
+
os.path.join(cuda_dir, "wkv7_op.cpp"),
|
| 60 |
+
os.path.join(cuda_dir, "wkv7_cuda.cu"),
|
| 61 |
+
]
|
| 62 |
+
if not all(os.path.exists(s) for s in sources):
|
| 63 |
+
_KERNEL_STATE["ok"] = False
|
| 64 |
+
return False
|
| 65 |
+
|
| 66 |
+
flags = [
|
| 67 |
+
"-res-usage",
|
| 68 |
+
f"-D_C_={head_size}",
|
| 69 |
+
f"-D_CHUNK_LEN_={chunk_len}",
|
| 70 |
+
"--use_fast_math",
|
| 71 |
+
"-O3",
|
| 72 |
+
"-Xptxas -O3",
|
| 73 |
+
"--extra-device-vectorization",
|
| 74 |
+
]
|
| 75 |
+
load(
|
| 76 |
+
name=f"wind_backstepping_c{head_size}_l{chunk_len}",
|
| 77 |
+
sources=sources,
|
| 78 |
+
is_python_module=False,
|
| 79 |
+
verbose=False,
|
| 80 |
+
extra_cuda_cflags=flags,
|
| 81 |
+
)
|
| 82 |
+
_KERNEL_STATE["op"] = torch.ops.wind_backstepping
|
| 83 |
+
_KERNEL_STATE["ok"] = True
|
| 84 |
+
return True
|
| 85 |
+
except Exception as e: # noqa: BLE001 - any failure -> fallback
|
| 86 |
+
print(f"[RWKV7] CUDA kernel unavailable, using PyTorch fallback ({type(e).__name__}: {e})")
|
| 87 |
+
_KERNEL_STATE["ok"] = False
|
| 88 |
+
return False
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class _WindBackstepping(torch.autograd.Function):
|
| 92 |
+
"""Fused RWKV-7 kernel wrapper (bf16). Implements both forward and backward.
|
| 93 |
+
|
| 94 |
+
Inputs are shaped (B, T, H, C) with T % CHUNK_LEN == 0 and dtype bfloat16.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
@staticmethod
|
| 98 |
+
def forward(ctx, w, q, k, v, z, b):
|
| 99 |
+
op = _KERNEL_STATE["op"]
|
| 100 |
+
chunk_len = _KERNEL_STATE["chunk_len"]
|
| 101 |
+
B, T, H, C = w.shape
|
| 102 |
+
assert T % chunk_len == 0, "pad T to a multiple of CHUNK_LEN"
|
| 103 |
+
assert all(i.dtype == torch.bfloat16 for i in [w, q, k, v, z, b])
|
| 104 |
+
assert all(i.is_contiguous() for i in [w, q, k, v, z, b])
|
| 105 |
+
y = torch.empty_like(v)
|
| 106 |
+
s = torch.empty(B, H, T // chunk_len, C, C, dtype=torch.float32, device=w.device)
|
| 107 |
+
sa = torch.empty(B, T, H, C, dtype=torch.float32, device=w.device)
|
| 108 |
+
op.forward(w, q, k, v, z, b, y, s, sa)
|
| 109 |
+
ctx.save_for_backward(w, q, k, v, z, b, s, sa)
|
| 110 |
+
return y
|
| 111 |
+
|
| 112 |
+
@staticmethod
|
| 113 |
+
def backward(ctx, dy):
|
| 114 |
+
op = _KERNEL_STATE["op"]
|
| 115 |
+
assert dy.dtype == torch.bfloat16
|
| 116 |
+
dy = dy.contiguous()
|
| 117 |
+
w, q, k, v, z, b, s, sa = ctx.saved_tensors
|
| 118 |
+
dw, dq, dk, dv, dz, db = [torch.empty_like(x) for x in [w, q, k, v, z, b]]
|
| 119 |
+
op.backward(w, q, k, v, z, b, dy, s, sa, dw, dq, dk, dv, dz, db)
|
| 120 |
+
return dw, dq, dk, dv, dz, db
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _rwkv7_cuda(r, w, k, v, a, b, head_size, chunk_len):
|
| 124 |
+
"""CUDA path. r,w,k,v,a,b are (B, T, C) bf16. a = -kk, b = kk*a_gate."""
|
| 125 |
+
B, T, C = r.shape
|
| 126 |
+
H = C // head_size
|
| 127 |
+
pad = (chunk_len - T % chunk_len) % chunk_len
|
| 128 |
+
if pad:
|
| 129 |
+
r, w, k, v, a, b = [F.pad(x, (0, 0, 0, pad)) for x in (r, w, k, v, a, b)]
|
| 130 |
+
Tp = T + pad
|
| 131 |
+
r, w, k, v, a, b = [x.view(B, Tp, H, head_size).contiguous() for x in (r, w, k, v, a, b)]
|
| 132 |
+
y = _WindBackstepping.apply(w, r, k, v, a, b).view(B, Tp, C)
|
| 133 |
+
if pad:
|
| 134 |
+
y = y[:, :T]
|
| 135 |
+
return y
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _rwkv7_pytorch(r, w, k, v, a, b, head_size):
|
| 139 |
+
"""Pure-PyTorch reference (sequential over time). Differentiable via autograd.
|
| 140 |
+
|
| 141 |
+
w is the raw (pre-exp) log-decay; the recurrence uses exp(-exp(w)).
|
| 142 |
+
"""
|
| 143 |
+
B, T, C = r.size()
|
| 144 |
+
H = C // head_size
|
| 145 |
+
N = head_size
|
| 146 |
+
dtype_in = r.dtype
|
| 147 |
+
r = r.view(B, T, H, N).float()
|
| 148 |
+
k = k.view(B, T, H, N).float()
|
| 149 |
+
v = v.view(B, T, H, N).float()
|
| 150 |
+
a = a.view(B, T, H, N).float()
|
| 151 |
+
b = b.view(B, T, H, N).float()
|
| 152 |
+
w = torch.exp(-torch.exp(w.view(B, T, H, N).float()))
|
| 153 |
+
|
| 154 |
+
out = torch.zeros((B, T, H, N), device=r.device, dtype=torch.float32)
|
| 155 |
+
state = torch.zeros((B, H, N, N), device=r.device, dtype=torch.float32)
|
| 156 |
+
for t in range(T):
|
| 157 |
+
kk = k[:, t, :].view(B, H, 1, N)
|
| 158 |
+
rr = r[:, t, :].view(B, H, N, 1)
|
| 159 |
+
vv = v[:, t, :].view(B, H, N, 1)
|
| 160 |
+
aa = a[:, t, :].view(B, H, N, 1)
|
| 161 |
+
bb = b[:, t, :].view(B, H, 1, N)
|
| 162 |
+
state = state * w[:, t, :, None, :] + state @ aa @ bb + vv @ kk
|
| 163 |
+
out[:, t, :] = (state @ rr).view(B, H, N)
|
| 164 |
+
return out.view(B, T, C).to(dtype=dtype_in)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def run_rwkv7(r, w, k, v, a, b, config, force_fallback=False):
|
| 168 |
+
"""Dispatch to CUDA kernel when possible, otherwise PyTorch fallback."""
|
| 169 |
+
use_kernel = (
|
| 170 |
+
config.use_cuda_kernel
|
| 171 |
+
and not force_fallback
|
| 172 |
+
and r.is_cuda
|
| 173 |
+
and r.dtype == torch.bfloat16
|
| 174 |
+
and _try_load_cuda_kernel(config.head_size, config.chunk_len)
|
| 175 |
+
)
|
| 176 |
+
if use_kernel:
|
| 177 |
+
return _rwkv7_cuda(r, w, k, v, a, b, config.head_size, config.chunk_len)
|
| 178 |
+
return _rwkv7_pytorch(r, w, k, v, a, b, config.head_size)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
########################################################################################################
|
| 182 |
+
# RWKV-7 time-mixing ("attention") block
|
| 183 |
+
########################################################################################################
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class RWKV7TimeMix(nn.Module):
|
| 187 |
+
def __init__(self, config: RWKV7Config, layer_id: int):
|
| 188 |
+
super().__init__()
|
| 189 |
+
self.config = config
|
| 190 |
+
self.layer_id = layer_id
|
| 191 |
+
self.head_size = config.head_size
|
| 192 |
+
C = config.hidden_size
|
| 193 |
+
self.n_head = C // self.head_size
|
| 194 |
+
H, N = self.n_head, self.head_size
|
| 195 |
+
|
| 196 |
+
self.x_r = nn.Parameter(torch.empty(1, 1, C))
|
| 197 |
+
self.x_w = nn.Parameter(torch.empty(1, 1, C))
|
| 198 |
+
self.x_k = nn.Parameter(torch.empty(1, 1, C))
|
| 199 |
+
self.x_v = nn.Parameter(torch.empty(1, 1, C))
|
| 200 |
+
self.x_a = nn.Parameter(torch.empty(1, 1, C))
|
| 201 |
+
self.x_g = nn.Parameter(torch.empty(1, 1, C))
|
| 202 |
+
|
| 203 |
+
self.w0 = nn.Parameter(torch.empty(1, 1, C))
|
| 204 |
+
self.w1 = nn.Parameter(torch.empty(C, config.decay_lora))
|
| 205 |
+
self.w2 = nn.Parameter(torch.empty(config.decay_lora, C))
|
| 206 |
+
|
| 207 |
+
self.a0 = nn.Parameter(torch.empty(1, 1, C))
|
| 208 |
+
self.a1 = nn.Parameter(torch.empty(C, config.aaa_lora))
|
| 209 |
+
self.a2 = nn.Parameter(torch.empty(config.aaa_lora, C))
|
| 210 |
+
|
| 211 |
+
self.v0 = nn.Parameter(torch.empty(1, 1, C))
|
| 212 |
+
self.v1 = nn.Parameter(torch.empty(C, config.mv_lora))
|
| 213 |
+
self.v2 = nn.Parameter(torch.empty(config.mv_lora, C))
|
| 214 |
+
|
| 215 |
+
self.g1 = nn.Parameter(torch.empty(C, config.gate_lora))
|
| 216 |
+
self.g2 = nn.Parameter(torch.empty(config.gate_lora, C))
|
| 217 |
+
|
| 218 |
+
self.k_k = nn.Parameter(torch.empty(1, 1, C))
|
| 219 |
+
self.k_a = nn.Parameter(torch.empty(1, 1, C))
|
| 220 |
+
self.r_k = nn.Parameter(torch.empty(H, N))
|
| 221 |
+
|
| 222 |
+
self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
|
| 223 |
+
self.receptance = nn.Linear(C, C, bias=False)
|
| 224 |
+
self.key = nn.Linear(C, C, bias=False)
|
| 225 |
+
self.value = nn.Linear(C, C, bias=False)
|
| 226 |
+
self.output = nn.Linear(C, C, bias=False)
|
| 227 |
+
self.ln_x = nn.GroupNorm(H, C, eps=config.group_norm_epsilon)
|
| 228 |
+
|
| 229 |
+
def forward(self, x, v_first):
|
| 230 |
+
B, T, C = x.size()
|
| 231 |
+
H = self.n_head
|
| 232 |
+
xx = self.time_shift(x) - x
|
| 233 |
+
|
| 234 |
+
xr = x + xx * self.x_r
|
| 235 |
+
xw = x + xx * self.x_w
|
| 236 |
+
xk = x + xx * self.x_k
|
| 237 |
+
xv = x + xx * self.x_v
|
| 238 |
+
xa = x + xx * self.x_a
|
| 239 |
+
xg = x + xx * self.x_g
|
| 240 |
+
|
| 241 |
+
r = self.receptance(xr)
|
| 242 |
+
# soft-clamp to (-inf, -0.5); the recurrence applies exp(-exp(w))
|
| 243 |
+
w = -F.softplus(-(self.w0 + torch.tanh(xw @ self.w1) @ self.w2)) - 0.5
|
| 244 |
+
k = self.key(xk)
|
| 245 |
+
v = self.value(xv)
|
| 246 |
+
if self.layer_id == 0:
|
| 247 |
+
v_first = v
|
| 248 |
+
else:
|
| 249 |
+
v = v + (v_first - v) * torch.sigmoid(self.v0 + (xv @ self.v1) @ self.v2)
|
| 250 |
+
a = torch.sigmoid(self.a0 + (xa @ self.a1) @ self.a2) # in-context learning rate
|
| 251 |
+
g = torch.sigmoid(xg @ self.g1) @ self.g2
|
| 252 |
+
|
| 253 |
+
kk = k * self.k_k
|
| 254 |
+
kk = F.normalize(kk.view(B, T, H, -1), dim=-1, p=2.0).view(B, T, C)
|
| 255 |
+
k = k * (1 + (a - 1) * self.k_a)
|
| 256 |
+
|
| 257 |
+
x = run_rwkv7(r, w, k, v, -kk, kk * a, self.config)
|
| 258 |
+
x = self.ln_x(x.view(B * T, C)).view(B, T, C)
|
| 259 |
+
|
| 260 |
+
x = x + (
|
| 261 |
+
(r.view(B, T, H, -1) * k.view(B, T, H, -1) * self.r_k).sum(dim=-1, keepdim=True)
|
| 262 |
+
* v.view(B, T, H, -1)
|
| 263 |
+
).view(B, T, C)
|
| 264 |
+
x = self.output(x * g)
|
| 265 |
+
return x, v_first
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
########################################################################################################
|
| 269 |
+
# RWKV-7 channel-mixing (FFN) block
|
| 270 |
+
########################################################################################################
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class RWKV7ChannelMix(nn.Module):
|
| 274 |
+
def __init__(self, config: RWKV7Config, layer_id: int):
|
| 275 |
+
super().__init__()
|
| 276 |
+
self.layer_id = layer_id
|
| 277 |
+
self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
|
| 278 |
+
self.x_k = nn.Parameter(torch.empty(1, 1, config.hidden_size))
|
| 279 |
+
self.key = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 280 |
+
self.value = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 281 |
+
|
| 282 |
+
def forward(self, x):
|
| 283 |
+
xx = self.time_shift(x) - x
|
| 284 |
+
k = x + xx * self.x_k
|
| 285 |
+
k = torch.relu(self.key(k)) ** 2
|
| 286 |
+
return self.value(k)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
class RWKV7Block(nn.Module):
|
| 290 |
+
def __init__(self, config: RWKV7Config, layer_id: int):
|
| 291 |
+
super().__init__()
|
| 292 |
+
self.layer_id = layer_id
|
| 293 |
+
eps = config.layer_norm_epsilon
|
| 294 |
+
if layer_id == 0:
|
| 295 |
+
self.ln0 = nn.LayerNorm(config.hidden_size, eps=eps)
|
| 296 |
+
self.ln1 = nn.LayerNorm(config.hidden_size, eps=eps)
|
| 297 |
+
self.ln2 = nn.LayerNorm(config.hidden_size, eps=eps)
|
| 298 |
+
self.att = RWKV7TimeMix(config, layer_id)
|
| 299 |
+
self.ffn = RWKV7ChannelMix(config, layer_id)
|
| 300 |
+
|
| 301 |
+
def forward(self, x, v_first):
|
| 302 |
+
if self.layer_id == 0:
|
| 303 |
+
x = self.ln0(x)
|
| 304 |
+
x_attn, v_first = self.att(self.ln1(x), v_first)
|
| 305 |
+
x = x + x_attn
|
| 306 |
+
x = x + self.ffn(self.ln2(x))
|
| 307 |
+
return x, v_first
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
########################################################################################################
|
| 311 |
+
# HuggingFace wrappers
|
| 312 |
+
########################################################################################################
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
class RWKV7PreTrainedModel(PreTrainedModel):
|
| 316 |
+
config_class = RWKV7Config
|
| 317 |
+
base_model_prefix = "rwkv"
|
| 318 |
+
supports_gradient_checkpointing = True
|
| 319 |
+
_no_split_modules = ["RWKV7Block"]
|
| 320 |
+
|
| 321 |
+
def _init_weights(self, module):
|
| 322 |
+
# Weights normally come from a pretrained checkpoint; this only covers
|
| 323 |
+
# freshly-created (e.g. re-sized embedding / head) parameters.
|
| 324 |
+
if isinstance(module, nn.Linear):
|
| 325 |
+
module.weight.data.normal_(mean=0.0, std=0.02)
|
| 326 |
+
if module.bias is not None:
|
| 327 |
+
module.bias.data.zero_()
|
| 328 |
+
elif isinstance(module, nn.Embedding):
|
| 329 |
+
module.weight.data.normal_(mean=0.0, std=1e-4)
|
| 330 |
+
elif isinstance(module, nn.LayerNorm):
|
| 331 |
+
module.weight.data.fill_(1.0)
|
| 332 |
+
module.bias.data.zero_()
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
class RWKV7Model(RWKV7PreTrainedModel):
|
| 336 |
+
def __init__(self, config: RWKV7Config):
|
| 337 |
+
super().__init__(config)
|
| 338 |
+
self.config = config
|
| 339 |
+
self.emb = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 340 |
+
self.blocks = nn.ModuleList(
|
| 341 |
+
[RWKV7Block(config, i) for i in range(config.num_hidden_layers)]
|
| 342 |
+
)
|
| 343 |
+
self.ln_out = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
| 344 |
+
self.gradient_checkpointing = False
|
| 345 |
+
self.post_init()
|
| 346 |
+
|
| 347 |
+
def get_input_embeddings(self):
|
| 348 |
+
return self.emb
|
| 349 |
+
|
| 350 |
+
def set_input_embeddings(self, value):
|
| 351 |
+
self.emb = value
|
| 352 |
+
|
| 353 |
+
def forward(
|
| 354 |
+
self,
|
| 355 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 356 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 357 |
+
output_hidden_states: Optional[bool] = None,
|
| 358 |
+
return_dict: Optional[bool] = None,
|
| 359 |
+
**kwargs,
|
| 360 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 361 |
+
return_dict = return_dict if return_dict is not None else True
|
| 362 |
+
output_hidden_states = (
|
| 363 |
+
output_hidden_states
|
| 364 |
+
if output_hidden_states is not None
|
| 365 |
+
else self.config.output_hidden_states
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
if inputs_embeds is None:
|
| 369 |
+
inputs_embeds = self.emb(input_ids)
|
| 370 |
+
x = inputs_embeds
|
| 371 |
+
|
| 372 |
+
all_hidden_states = () if output_hidden_states else None
|
| 373 |
+
v_first = torch.empty_like(x)
|
| 374 |
+
for block in self.blocks:
|
| 375 |
+
if output_hidden_states:
|
| 376 |
+
all_hidden_states += (x,)
|
| 377 |
+
if self.gradient_checkpointing and self.training:
|
| 378 |
+
x, v_first = self._gradient_checkpointing_func(
|
| 379 |
+
block.__call__, x, v_first
|
| 380 |
+
)
|
| 381 |
+
else:
|
| 382 |
+
x, v_first = block(x, v_first)
|
| 383 |
+
|
| 384 |
+
x = self.ln_out(x)
|
| 385 |
+
if output_hidden_states:
|
| 386 |
+
all_hidden_states += (x,)
|
| 387 |
+
|
| 388 |
+
if not return_dict:
|
| 389 |
+
return tuple(v for v in [x, all_hidden_states] if v is not None)
|
| 390 |
+
return BaseModelOutputWithPast(
|
| 391 |
+
last_hidden_state=x,
|
| 392 |
+
hidden_states=all_hidden_states,
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
class RWKV7ForCausalLM(RWKV7PreTrainedModel, GenerationMixin):
|
| 397 |
+
_tied_weights_keys = []
|
| 398 |
+
|
| 399 |
+
def __init__(self, config: RWKV7Config):
|
| 400 |
+
super().__init__(config)
|
| 401 |
+
self.rwkv = RWKV7Model(config)
|
| 402 |
+
self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 403 |
+
self.post_init()
|
| 404 |
+
|
| 405 |
+
def get_input_embeddings(self):
|
| 406 |
+
return self.rwkv.emb
|
| 407 |
+
|
| 408 |
+
def set_input_embeddings(self, value):
|
| 409 |
+
self.rwkv.emb = value
|
| 410 |
+
|
| 411 |
+
def get_output_embeddings(self):
|
| 412 |
+
return self.head
|
| 413 |
+
|
| 414 |
+
def set_output_embeddings(self, new_embeddings):
|
| 415 |
+
self.head = new_embeddings
|
| 416 |
+
|
| 417 |
+
def get_decoder(self):
|
| 418 |
+
return self.rwkv
|
| 419 |
+
|
| 420 |
+
def forward(
|
| 421 |
+
self,
|
| 422 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 423 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 424 |
+
labels: Optional[torch.LongTensor] = None,
|
| 425 |
+
output_hidden_states: Optional[bool] = None,
|
| 426 |
+
return_dict: Optional[bool] = None,
|
| 427 |
+
**kwargs,
|
| 428 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 429 |
+
return_dict = return_dict if return_dict is not None else True
|
| 430 |
+
|
| 431 |
+
outputs = self.rwkv(
|
| 432 |
+
input_ids=input_ids,
|
| 433 |
+
inputs_embeds=inputs_embeds,
|
| 434 |
+
output_hidden_states=output_hidden_states,
|
| 435 |
+
return_dict=True,
|
| 436 |
+
)
|
| 437 |
+
hidden = outputs.last_hidden_state
|
| 438 |
+
logits = self.head(hidden)
|
| 439 |
+
|
| 440 |
+
loss = None
|
| 441 |
+
if labels is not None:
|
| 442 |
+
labels = labels.to(logits.device)
|
| 443 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 444 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 445 |
+
loss = F.cross_entropy(
|
| 446 |
+
shift_logits.view(-1, shift_logits.size(-1)).float(),
|
| 447 |
+
shift_labels.view(-1),
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
if not return_dict:
|
| 451 |
+
output = (logits,) + (outputs.hidden_states,) if outputs.hidden_states else (logits,)
|
| 452 |
+
return ((loss,) + output) if loss is not None else output
|
| 453 |
+
|
| 454 |
+
return CausalLMOutputWithPast(
|
| 455 |
+
loss=loss,
|
| 456 |
+
logits=logits,
|
| 457 |
+
hidden_states=outputs.hidden_states,
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
def prepare_inputs_for_generation(self, input_ids, inputs_embeds=None, **kwargs):
|
| 461 |
+
# RWKV-7 here runs in GPT mode (no incremental KV cache); recompute the
|
| 462 |
+
# full sequence each step. Correct, though not the fastest.
|
| 463 |
+
model_inputs = {"input_ids": input_ids}
|
| 464 |
+
return model_inputs
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_prefix_space": false,
|
| 3 |
+
"backend": "tokenizers",
|
| 4 |
+
"bos_token": null,
|
| 5 |
+
"clean_up_tokenization_spaces": false,
|
| 6 |
+
"eos_token": "<|endoftext|>",
|
| 7 |
+
"is_local": true,
|
| 8 |
+
"local_files_only": false,
|
| 9 |
+
"model_max_length": 65536,
|
| 10 |
+
"pad_token": "<|pad|>",
|
| 11 |
+
"tokenizer_class": "TokenizersBackend",
|
| 12 |
+
"unk_token": "<|endoftext|>"
|
| 13 |
+
}
|
verify.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""End-to-end verification of the converted RWKV-7 HF model."""
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 4 |
+
|
| 5 |
+
PATH = "/workspace/rwkv7-g1d-olmo"
|
| 6 |
+
|
| 7 |
+
print("=" * 70)
|
| 8 |
+
print("1) Loading with AutoModelForCausalLM(trust_remote_code=True)")
|
| 9 |
+
tok = AutoTokenizer.from_pretrained(PATH, trust_remote_code=True)
|
| 10 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 11 |
+
PATH, trust_remote_code=True, dtype=torch.bfloat16
|
| 12 |
+
).cuda()
|
| 13 |
+
model.eval()
|
| 14 |
+
print(" model class:", type(model).__name__)
|
| 15 |
+
print(" emb:", tuple(model.get_input_embeddings().weight.shape),
|
| 16 |
+
"head:", tuple(model.get_output_embeddings().weight.shape))
|
| 17 |
+
nparams = sum(p.numel() for p in model.parameters())
|
| 18 |
+
print(f" params: {nparams/1e6:.1f}M")
|
| 19 |
+
|
| 20 |
+
ids = tok("The Eiffel tower is in the city of", return_tensors="pt").input_ids.cuda()
|
| 21 |
+
print(" input ids:", ids.tolist())
|
| 22 |
+
|
| 23 |
+
print("=" * 70)
|
| 24 |
+
print("2) Forward with CUDA kernel")
|
| 25 |
+
with torch.no_grad():
|
| 26 |
+
out_k = model(ids).logits
|
| 27 |
+
print(" logits:", tuple(out_k.shape), out_k.dtype)
|
| 28 |
+
|
| 29 |
+
print("=" * 70)
|
| 30 |
+
print("3) Forward with PyTorch fallback + kernel-vs-fallback parity")
|
| 31 |
+
model.config.use_cuda_kernel = False
|
| 32 |
+
with torch.no_grad():
|
| 33 |
+
out_f = model(ids).logits
|
| 34 |
+
model.config.use_cuda_kernel = True
|
| 35 |
+
|
| 36 |
+
diff = (out_k.float() - out_f.float()).abs()
|
| 37 |
+
print(f" max abs diff kernel vs fallback: {diff.max().item():.4e}")
|
| 38 |
+
print(f" mean abs diff: {diff.mean().item():.4e}")
|
| 39 |
+
# argmax agreement on last token
|
| 40 |
+
print(" kernel top-1 next id:", out_k[0, -1].argmax().item(),
|
| 41 |
+
"| fallback:", out_f[0, -1].argmax().item())
|
| 42 |
+
|
| 43 |
+
print("=" * 70)
|
| 44 |
+
print("4) Backward pass (gradients flow through kernel)")
|
| 45 |
+
model.train()
|
| 46 |
+
ids2 = tok("Backward test sentence for gradient check.", return_tensors="pt").input_ids.cuda()
|
| 47 |
+
out = model(ids2, labels=ids2)
|
| 48 |
+
loss = out.loss
|
| 49 |
+
loss.backward()
|
| 50 |
+
gnorm_emb = model.get_input_embeddings().weight.grad
|
| 51 |
+
g_att = model.rwkv.blocks[0].att.receptance.weight.grad
|
| 52 |
+
g_w1 = model.rwkv.blocks[6].att.w1.grad
|
| 53 |
+
print(f" loss: {loss.item():.4f}")
|
| 54 |
+
print(f" emb.grad is not None: {gnorm_emb is not None}, norm={gnorm_emb.float().norm().item():.4e}")
|
| 55 |
+
print(f" blocks.0.att.receptance.grad norm: {g_att.float().norm().item():.4e}")
|
| 56 |
+
print(f" blocks.6.att.w1 (decay-lora) grad norm: {g_w1.float().norm().item():.4e}")
|
| 57 |
+
n_with_grad = sum(1 for p in model.parameters() if p.grad is not None and p.grad.abs().sum() > 0)
|
| 58 |
+
n_total = sum(1 for _ in model.parameters())
|
| 59 |
+
print(f" params with non-zero grad: {n_with_grad}/{n_total}")
|
| 60 |
+
|
| 61 |
+
print("=" * 70)
|
| 62 |
+
print("5) generate()")
|
| 63 |
+
model.eval()
|
| 64 |
+
with torch.no_grad():
|
| 65 |
+
gen = model.generate(ids, max_new_tokens=10, do_sample=False)
|
| 66 |
+
print(" generated:", tok.decode(gen[0]))
|
| 67 |
+
print("=" * 70)
|
| 68 |
+
print("ALL CHECKS DONE")
|