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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
---
|
| 4 |
+
# EmbeddingRWKV
|
| 5 |
+
|
| 6 |
+
A high-efficiency text embedding and reranking model based on RWKV architecture.
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
## 🤖 Models & Weights
|
| 10 |
+
|
| 11 |
+
You can download the weights from the [HuggingFace Repository](https://huggingface.co/howard-hou/EmbeddingRWKV/tree/main).
|
| 12 |
+
|
| 13 |
+
| Size / Level | Embedding Model (Main) | Matching Reranker (Paired) | Notes |
|
| 14 |
+
| :--- | :--- | :--- | :--- |
|
| 15 |
+
| **Tiny** | `rwkv0b1-emb-curriculum.pth` | `rwkv0b1-reranker.pth` | Ultra-fast, minimal memory. |
|
| 16 |
+
| **Base** | `rwkv0b4-emb-curriculum.pth` | `rwkv0b3-reranker.pth` | Balanced speed & performance. |
|
| 17 |
+
| **Large** | `rwkv1b4-emb-curriculum.pth` | `rwkv1b3-reranker.pth` | Best performance, higher VRAM usage. |
|
| 18 |
+
|
| 19 |
+
## 🚀 Quick Start (End-to-End)
|
| 20 |
+
|
| 21 |
+
Get text embeddings in just a few lines. The tokenizer and model are designed to work seamlessly together.
|
| 22 |
+
|
| 23 |
+
> **Note**: Always set `add_eos=True` during tokenization. The model relies on the EOS token (`65535`) to mark the end of a sentence for correct embedding generation.
|
| 24 |
+
|
| 25 |
+
```python
|
| 26 |
+
import os
|
| 27 |
+
# Set environment for JIT compilation (Optional, set to '1' for CUDA acceleration)
|
| 28 |
+
os.environ["RWKV_CUDA_ON"] = '1'
|
| 29 |
+
|
| 30 |
+
from rwkv_emb.tokenizer import RWKVTokenizer
|
| 31 |
+
from rwkv_emb.model import EmbeddingRWKV
|
| 32 |
+
|
| 33 |
+
# Fast retrieval, good for initial candidate filtering.
|
| 34 |
+
emb_model = EmbeddingRWKV(model_path='/path/to/model.pth')
|
| 35 |
+
tokenizer = RWKVTokenizer()
|
| 36 |
+
|
| 37 |
+
query = "What represents the end of a sequence?"
|
| 38 |
+
documents = [
|
| 39 |
+
"The EOS token is used to mark the end of a sentence.",
|
| 40 |
+
"Apples are red and delicious fruits.",
|
| 41 |
+
"Machine learning requires large datasets."
|
| 42 |
+
]
|
| 43 |
+
# Encode Query
|
| 44 |
+
q_tokens = tokenizer.encode(query, add_eos=True)
|
| 45 |
+
q_emb, _ = emb_model.forward(q_tokens, None) # shape: [1, Dim]
|
| 46 |
+
|
| 47 |
+
# Encode Documents (Batch)
|
| 48 |
+
doc_batch = [tokenizer.encode(doc, add_eos=True) for doc in documents]
|
| 49 |
+
max_doc_len = max(len(t) for t in doc_batch)
|
| 50 |
+
for i in range(len(doc_batch)):
|
| 51 |
+
pad_len = max_doc_len - len(doc_batch[i])
|
| 52 |
+
# Prepend 0s (Left Padding)
|
| 53 |
+
doc_batch[i] = [0] * pad_len + doc_batch[i]
|
| 54 |
+
|
| 55 |
+
d_embs, _ = emb_model.forward(doc_batch, None)
|
| 56 |
+
|
| 57 |
+
# Calculate Cosine Similarity
|
| 58 |
+
scores_emb = F.cosine_similarity(q_emb, d_embs)
|
| 59 |
+
print("\nEmbeddingRWKV Cosine Similarity:")
|
| 60 |
+
for doc, score in zip(documents, scores_emb):
|
| 61 |
+
print(f"[{score.item():.4f}] {doc}")
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
For production use cases, running inference in batches is significantly faster.
|
| 65 |
+
|
| 66 |
+
### ⚠️ Critical Performance Tip: Pad to Same Length
|
| 67 |
+
|
| 68 |
+
While the model supports batches with variable sequence lengths, **we strongly recommend padding all sequences to the same length** for maximum GPU throughput.
|
| 69 |
+
|
| 70 |
+
- **Pad Token**: `0`
|
| 71 |
+
- **Performance**: Fixed-length batches allow the CUDA kernel to parallelize computation efficiently. Variable-length batches will trigger a slower execution path.
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
## 🎯 RWKVReRanker (State-based Reranker)
|
| 75 |
+
|
| 76 |
+
The `RWKVReRanker` utilizes the final hidden state produced by the main `EmbeddingRWKV` model to score the relevance between a query and a document.
|
| 77 |
+
|
| 78 |
+
### Online Mode
|
| 79 |
+
|
| 80 |
+
#### Workflow
|
| 81 |
+
1. **Format** Query and Document based on Online template.
|
| 82 |
+
2. Run the **Embedding Model** to generate the final State.
|
| 83 |
+
3. Feed the **Attention State** (`state[1]`) into the **ReRanker** to get a relevance score.
|
| 84 |
+
|
| 85 |
+
#### 📝 Online Mode Usage Example
|
| 86 |
+
|
| 87 |
+
```python
|
| 88 |
+
import torch
|
| 89 |
+
from rwkv_emb.tokenizer import RWKVTokenizer
|
| 90 |
+
from rwkv_emb.model import EmbeddingRWKV, RWKVReRanker
|
| 91 |
+
|
| 92 |
+
# 1. Load Models
|
| 93 |
+
# The ReRanker weights are stored in the differernt checkpoint
|
| 94 |
+
emb_model = EmbeddingRWKV(model_path='/path/to/EmbeddingRWKV.pth')
|
| 95 |
+
reranker = RWKVReRanker(model_path='/path/to/RWKVReRanker.pth')
|
| 96 |
+
|
| 97 |
+
tokenizer = RWKVTokenizer()
|
| 98 |
+
|
| 99 |
+
# 2. Prepare Data (Query + Candidate Documents)
|
| 100 |
+
query = "What represents the end of a sequence?"
|
| 101 |
+
documents = [
|
| 102 |
+
"The EOS token is used to mark the end of a sentence.",
|
| 103 |
+
"Apples are red and delicious fruits.",
|
| 104 |
+
"Machine learning requires large datasets."
|
| 105 |
+
]
|
| 106 |
+
|
| 107 |
+
# 3. Construct Input Pairs
|
| 108 |
+
# We treat the Query and Document as a single sequence.
|
| 109 |
+
pairs = []
|
| 110 |
+
online_template = "Instruct: Given a query, retrieve documents that answer the query\nDocument: {document}\nQuery: {query}"
|
| 111 |
+
for doc in documents:
|
| 112 |
+
# Format: Instruct + Document + Query
|
| 113 |
+
text = online_template.format(document=doc, query=query)
|
| 114 |
+
pairs.append(text)
|
| 115 |
+
|
| 116 |
+
# 4. Tokenize & Pad (Critical for Batch Performance)
|
| 117 |
+
batch_tokens = [tokenizer.encode(p, add_eos=True) for p in pairs]
|
| 118 |
+
|
| 119 |
+
# Left pad to same length for efficiency
|
| 120 |
+
max_len = max(len(t) for t in batch_tokens)
|
| 121 |
+
for i in range(len(batch_tokens)):
|
| 122 |
+
batch_tokens[i] = [0] * (max_len - len(batch_tokens[i])) + batch_tokens[i]
|
| 123 |
+
|
| 124 |
+
# 5. Get States from Embedding Model
|
| 125 |
+
# We don't need the embedding output here, we only need the final 'state'
|
| 126 |
+
_, state = emb_model.forward(batch_tokens, None)
|
| 127 |
+
|
| 128 |
+
# 6. Score with ReRanker
|
| 129 |
+
# The ReRanker expects the Attention State: state[1]
|
| 130 |
+
# state[1] shape: [Layers, Batch, Heads, HeadSize, HeadSize]
|
| 131 |
+
logits = reranker.forward(state[1])
|
| 132 |
+
scores = torch.sigmoid(logits) # Convert logits to probabilities (0-1)
|
| 133 |
+
|
| 134 |
+
# 7. Print Results
|
| 135 |
+
print("\nRWKVReRanker Online Scores:")
|
| 136 |
+
for doc, score in zip(documents, scores):
|
| 137 |
+
print(f"[{score:.4f}] {doc}")
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
### Offline Mode (Cached Doc State)
|
| 141 |
+
For scenarios where documents are static but queries change (e.g., Search Engines, RAG), you can **pre-compute and cache the document states**. This reduces query-time latency from $O(L_{doc} + L_{query})$ to just $O(L_{query})$.
|
| 142 |
+
|
| 143 |
+
#### Workflow
|
| 144 |
+
|
| 145 |
+
1. **Indexing**: Process `Instruct + Document` -\> Save State.
|
| 146 |
+
2. **Querying**: Load State -\> Process `Query` -\> Score.
|
| 147 |
+
|
| 148 |
+
#### 📝 Offline Mode Usage Example
|
| 149 |
+
|
| 150 |
+
```python
|
| 151 |
+
# --- Phase 1: Indexing (Pre-computation) ---
|
| 152 |
+
# Note: Do NOT add EOS here, because the sequence continues with the query later.
|
| 153 |
+
doc_template = "Instruct: Given a query, retrieve documents that answer the query\nDocument: {document}\n"
|
| 154 |
+
cached_states = []
|
| 155 |
+
|
| 156 |
+
print("Indexing documents...")
|
| 157 |
+
for doc in documents:
|
| 158 |
+
text = doc_template.format(document=doc)
|
| 159 |
+
# add_eos=False is CRITICAL here
|
| 160 |
+
tokens = tokenizer.encode(text, add_eos=False)
|
| 161 |
+
|
| 162 |
+
# Forward pass
|
| 163 |
+
_, state = emb_model.forward(tokens, None)
|
| 164 |
+
|
| 165 |
+
# Move state to CPU to save GPU memory during storage
|
| 166 |
+
# State structure: [Tensor(Tokenshift), Tensor(TimeMix)]
|
| 167 |
+
cpu_state = [s.cpu() for s in state]
|
| 168 |
+
cached_states.append(cpu_state)
|
| 169 |
+
# Save cached states to disk (optional)
|
| 170 |
+
torch.save(cached_states, 'cached_doc_states.pth')
|
| 171 |
+
|
| 172 |
+
# --- Phase 2: Querying (Fast Retrieval) ---
|
| 173 |
+
query_template = "Query: {query}"
|
| 174 |
+
query_text = query_template.format(query=query)
|
| 175 |
+
# Now we add EOS to mark the end of the full sequence
|
| 176 |
+
query_tokens = tokenizer.encode(query_text, add_eos=True)
|
| 177 |
+
|
| 178 |
+
print(f"Processing query: '{query}' against {len(cached_states)} cached docs...")
|
| 179 |
+
|
| 180 |
+
# We can batch the query processing against multiple document states
|
| 181 |
+
# 1. Prepare a batch of states (Move back to GPU)
|
| 182 |
+
# Note: We must CLONE/DEEPCOPY because RWKV modifies state in-place!
|
| 183 |
+
batch_states = [[], []]
|
| 184 |
+
for cpu_s in cached_states:
|
| 185 |
+
batch_states[0].append(cpu_s[0].clone().cuda()) # Tokenshift State
|
| 186 |
+
batch_states[1].append(cpu_s[1].clone().cuda()) # TimeMix State
|
| 187 |
+
|
| 188 |
+
# Stack into batch tensors
|
| 189 |
+
# State[0]: [Layers, 2, 1, Hidden] -> Stack dim 2 -> [Layers, 2, Batch, Hidden]
|
| 190 |
+
# State[1]: [Layers, 1, Heads, HeadSize, HeadSize] -> Stack dim 1 -> [Layers, Batch, Heads, ...]
|
| 191 |
+
state_input = [
|
| 192 |
+
torch.stack(batch_states[0], dim=2).squeeze(3),
|
| 193 |
+
torch.stack(batch_states[1], dim=1).squeeze(2)
|
| 194 |
+
]
|
| 195 |
+
|
| 196 |
+
# 2. Prepare query tokens (Broadcast query to batch size)
|
| 197 |
+
batch_size = len(documents)
|
| 198 |
+
batch_query_tokens = [query_tokens] * batch_size
|
| 199 |
+
|
| 200 |
+
# 3. Fast Forward (Only processing query tokens!)
|
| 201 |
+
_, final_state = emb_model.forward(batch_query_tokens, state_input)
|
| 202 |
+
logits = reranker.forward(final_state[1])
|
| 203 |
+
scores = torch.sigmoid(logits)
|
| 204 |
+
|
| 205 |
+
print("\nRWKVReRanker Offline Scores:")
|
| 206 |
+
for doc, score in zip(documents, scores):
|
| 207 |
+
print(f"[{score:.4f}] {doc}")
|
| 208 |
+
```
|
| 209 |
+
|
| 210 |
+
## Summary of Differences
|
| 211 |
+
|
| 212 |
+
| Feature | 1. Embedding (Cosine) | 2. Online Reranking | 3. Offline Reranking |
|
| 213 |
+
| :--- | :--- | :--- | :--- |
|
| 214 |
+
| **Accuracy** | Good | **Best** | **Best** (Identical to Online) |
|
| 215 |
+
| **Latency** | Extremely Fast | Slow ($L_{doc} + L_{query}$) | Fast ($L_{query}$ only) |
|
| 216 |
+
| **Input** | Query & Doc separate | `Instruct + Doc + Query` | `Query` (on top of cached Doc) |
|
| 217 |
+
| **Storage** | Low (Vector only) | None | High (Stores Hidden States) |
|
| 218 |
+
| **Best For** | Initial Retrieval (Top-k) | Reranking few candidates | Reranking many candidates |
|