Add DGX Spark fine-tuning plan, scripts, and Apertus 70B as deep tier
Browse files- DGX_SPARK_PLAN.md: complete guide to resume from DGX Spark
- spark-scripts/: 7 ready-to-run Python scripts (FAISS index, SFT,
QLoRA, RAG retrieval, chatbot CLI, Gradio web UI)
- Deep reasoning tier: Apertus 70B (ETH Zurich/EPFL, Apache 2.0)
- Personality tier: TAIDE 12B fine-tuned on 59K transcript pairs
- DGX_SPARK_PLAN.md +874 -0
- spark-scripts/app.py +47 -0
- spark-scripts/build_index.py +73 -0
- spark-scripts/chatbot.py +110 -0
- spark-scripts/finetune.py +104 -0
- spark-scripts/finetune_qlora.py +112 -0
- spark-scripts/prepare_sft_data.py +61 -0
- spark-scripts/retriever.py +118 -0
DGX_SPARK_PLAN.md
ADDED
|
@@ -0,0 +1,874 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DGX Spark: Grounded Audrey Tang Chatbot
|
| 2 |
+
|
| 3 |
+
Complete plan for fine-tuning and deploying a grounded chatbot on a single NVIDIA DGX Spark (128GB unified memory), using the `audreyt/sayit-archive-tw` dataset.
|
| 4 |
+
|
| 5 |
+
## Architecture Overview
|
| 6 |
+
|
| 7 |
+
```
|
| 8 |
+
User Query (EN or ZH)
|
| 9 |
+
│
|
| 10 |
+
├──→ bge-m3 embedder ──→ FAISS index (85K chunks) ──→ Top-20
|
| 11 |
+
│ │
|
| 12 |
+
│ bge-reranker-v2-m3 ◄──────┘
|
| 13 |
+
│ │
|
| 14 |
+
│ Top-5 Passages + Lexicon Terms
|
| 15 |
+
│ │
|
| 16 |
+
└──→ System Prompt ──────────────────┤
|
| 17 |
+
│
|
| 18 |
+
▼
|
| 19 |
+
TAIDE 12B (fine-tuned on transcripts)
|
| 20 |
+
│
|
| 21 |
+
▼
|
| 22 |
+
Grounded response in Audrey's voice
|
| 23 |
+
+ citations [2024-03-15 Title...]
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
Two-tier option (when deeper reasoning is needed):
|
| 27 |
+
|
| 28 |
+
| Tier | Model | VRAM | Use |
|
| 29 |
+
|------|-------|------|-----|
|
| 30 |
+
| Fast | TAIDE 12B fine-tuned (Q8) | ~13 GB | Default — conversational Q&A |
|
| 31 |
+
| Deep | [Apertus 70B](https://huggingface.co/swiss-ai/Apertus-70B-2509) (Q4) | ~40 GB | Complex multi-source synthesis |
|
| 32 |
+
|
| 33 |
+
Both tiers share the same RAG pipeline.
|
| 34 |
+
|
| 35 |
+
## Memory Budget (single DGX Spark, 128GB)
|
| 36 |
+
|
| 37 |
+
| Component | Memory | Notes |
|
| 38 |
+
|-----------|--------|-------|
|
| 39 |
+
| TAIDE 12B (Q8_0) | 13 GB | Fine-tuned personality model |
|
| 40 |
+
| bge-m3 embedder | 2 GB | Multilingual retrieval |
|
| 41 |
+
| FAISS index | 1 GB | 85K vectors, 1024-dim |
|
| 42 |
+
| bge-reranker-v2-m3 | 1 GB | Cross-encoder reranker |
|
| 43 |
+
| KV cache + overhead | 8 GB | Inference |
|
| 44 |
+
| **Inference total** | **~25 GB** | Leaves 103 GB free |
|
| 45 |
+
| Apertus 70B (Q4, optional) | ~40 GB | Deep tier (ETH Zurich / EPFL, Apache 2.0) |
|
| 46 |
+
| **Full dual-tier total** | **~77 GB** | Leaves 51 GB free |
|
| 47 |
+
|
| 48 |
+
For fine-tuning (TAIDE 12B full SFT): ~80 GB peak. Run before loading the deep tier.
|
| 49 |
+
|
| 50 |
+
---
|
| 51 |
+
|
| 52 |
+
## Step 0: Environment Setup
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
# On DGX Spark (Ubuntu, CUDA pre-installed)
|
| 56 |
+
|
| 57 |
+
# Create project directory
|
| 58 |
+
mkdir -p ~/audrey-chatbot && cd ~/audrey-chatbot
|
| 59 |
+
|
| 60 |
+
# Python environment
|
| 61 |
+
python3 -m venv venv
|
| 62 |
+
source venv/bin/activate
|
| 63 |
+
|
| 64 |
+
# Core dependencies
|
| 65 |
+
pip install torch torchvision torchaudio # should be pre-installed on DGX
|
| 66 |
+
pip install transformers datasets accelerate peft trl
|
| 67 |
+
pip install bitsandbytes # for quantized training
|
| 68 |
+
pip install sentence-transformers faiss-gpu
|
| 69 |
+
pip install vllm # for fast inference
|
| 70 |
+
pip install gradio # for web UI
|
| 71 |
+
|
| 72 |
+
# Download dataset
|
| 73 |
+
pip install huggingface_hub
|
| 74 |
+
huggingface-cli download audreyt/sayit-archive-tw --repo-type dataset --local-dir ./dataset
|
| 75 |
+
|
| 76 |
+
# Download models
|
| 77 |
+
huggingface-cli download taide/Gemma-3-TAIDE-12b-Chat-2602 --local-dir ./models/taide-12b
|
| 78 |
+
huggingface-cli download BAAI/bge-m3 --local-dir ./models/bge-m3
|
| 79 |
+
huggingface-cli download BAAI/bge-reranker-v2-m3 --local-dir ./models/bge-reranker
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
---
|
| 83 |
+
|
| 84 |
+
## Step 1: Build FAISS Index
|
| 85 |
+
|
| 86 |
+
`scripts/build_index.py`:
|
| 87 |
+
|
| 88 |
+
```python
|
| 89 |
+
#!/usr/bin/env python3
|
| 90 |
+
"""Build FAISS index from RAG chunks for retrieval."""
|
| 91 |
+
|
| 92 |
+
import json
|
| 93 |
+
import faiss
|
| 94 |
+
import numpy as np
|
| 95 |
+
import pickle
|
| 96 |
+
from sentence_transformers import SentenceTransformer
|
| 97 |
+
from pathlib import Path
|
| 98 |
+
|
| 99 |
+
CHUNKS_PATH = Path("dataset/data/chunks.jsonl")
|
| 100 |
+
INDEX_DIR = Path("index")
|
| 101 |
+
INDEX_DIR.mkdir(exist_ok=True)
|
| 102 |
+
|
| 103 |
+
# Load chunks
|
| 104 |
+
print("Loading chunks...")
|
| 105 |
+
chunks = []
|
| 106 |
+
with open(CHUNKS_PATH) as f:
|
| 107 |
+
for line in f:
|
| 108 |
+
chunks.append(json.loads(line))
|
| 109 |
+
print(f"Loaded {len(chunks)} chunks")
|
| 110 |
+
|
| 111 |
+
# Build embedding text: combine question + text for richer retrieval
|
| 112 |
+
texts = []
|
| 113 |
+
for c in chunks:
|
| 114 |
+
parts = []
|
| 115 |
+
if c.get("question"):
|
| 116 |
+
parts.append(f"Q: {c['question']}")
|
| 117 |
+
parts.append(c["text"])
|
| 118 |
+
texts.append("\n".join(parts))
|
| 119 |
+
|
| 120 |
+
# Encode with bge-m3
|
| 121 |
+
print("Loading bge-m3...")
|
| 122 |
+
model = SentenceTransformer("./models/bge-m3")
|
| 123 |
+
|
| 124 |
+
print("Encoding chunks (this takes a few minutes)...")
|
| 125 |
+
embeddings = model.encode(
|
| 126 |
+
texts,
|
| 127 |
+
batch_size=256,
|
| 128 |
+
show_progress_bar=True,
|
| 129 |
+
normalize_embeddings=True,
|
| 130 |
+
)
|
| 131 |
+
embeddings = np.array(embeddings, dtype=np.float32)
|
| 132 |
+
print(f"Embeddings shape: {embeddings.shape}")
|
| 133 |
+
|
| 134 |
+
# Build FAISS index (inner product since embeddings are normalized = cosine sim)
|
| 135 |
+
dim = embeddings.shape[1]
|
| 136 |
+
index = faiss.IndexFlatIP(dim)
|
| 137 |
+
|
| 138 |
+
# Optional: use IVF for faster search on large indices
|
| 139 |
+
# nlist = 256
|
| 140 |
+
# quantizer = faiss.IndexFlatIP(dim)
|
| 141 |
+
# index = faiss.IndexIVFFlat(quantizer, dim, nlist, faiss.METRIC_INNER_PRODUCT)
|
| 142 |
+
# index.train(embeddings)
|
| 143 |
+
|
| 144 |
+
index.add(embeddings)
|
| 145 |
+
print(f"FAISS index built: {index.ntotal} vectors")
|
| 146 |
+
|
| 147 |
+
# Save
|
| 148 |
+
faiss.write_index(index, str(INDEX_DIR / "chunks.faiss"))
|
| 149 |
+
with open(INDEX_DIR / "chunks_meta.pkl", "wb") as f:
|
| 150 |
+
pickle.dump(chunks, f)
|
| 151 |
+
|
| 152 |
+
# Also save the lexicon for terminology lookup
|
| 153 |
+
lexicon = []
|
| 154 |
+
with open("dataset/data/lexicon.jsonl") as f:
|
| 155 |
+
for line in f:
|
| 156 |
+
lexicon.append(json.loads(line))
|
| 157 |
+
with open(INDEX_DIR / "lexicon.pkl", "wb") as f:
|
| 158 |
+
pickle.dump(lexicon, f)
|
| 159 |
+
|
| 160 |
+
print(f"Saved index to {INDEX_DIR}/")
|
| 161 |
+
print(f"Index size: {INDEX_DIR / 'chunks.faiss'}")
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
```bash
|
| 165 |
+
python scripts/build_index.py
|
| 166 |
+
```
|
| 167 |
+
|
| 168 |
+
---
|
| 169 |
+
|
| 170 |
+
## Step 2: Fine-tune TAIDE 12B
|
| 171 |
+
|
| 172 |
+
`scripts/prepare_sft_data.py`:
|
| 173 |
+
|
| 174 |
+
```python
|
| 175 |
+
#!/usr/bin/env python3
|
| 176 |
+
"""Convert SFT pairs to the chat template format expected by Gemma/TAIDE."""
|
| 177 |
+
|
| 178 |
+
import json
|
| 179 |
+
from pathlib import Path
|
| 180 |
+
from datasets import Dataset
|
| 181 |
+
|
| 182 |
+
SFT_PATH = Path("dataset/data/sft_pairs.jsonl")
|
| 183 |
+
OUTPUT_DIR = Path("training_data")
|
| 184 |
+
OUTPUT_DIR.mkdir(exist_ok=True)
|
| 185 |
+
|
| 186 |
+
pairs = []
|
| 187 |
+
with open(SFT_PATH) as f:
|
| 188 |
+
for line in f:
|
| 189 |
+
pairs.append(json.loads(line))
|
| 190 |
+
|
| 191 |
+
print(f"Loaded {len(pairs)} SFT pairs")
|
| 192 |
+
|
| 193 |
+
# Convert to chat format for Gemma-3 / TAIDE
|
| 194 |
+
# Format: list of {"role": "user"/"model", "content": "..."}
|
| 195 |
+
formatted = []
|
| 196 |
+
for p in pairs:
|
| 197 |
+
# System context about who this is
|
| 198 |
+
system_prefix = (
|
| 199 |
+
"You are Audrey Tang (唐鳳), Taiwan's Cyber Ambassador and "
|
| 200 |
+
"2025 Right Livelihood Laureate. Respond based on your actual "
|
| 201 |
+
"public statements and positions. Be grounded, specific, and "
|
| 202 |
+
"cite real examples from your experience in digital democracy, "
|
| 203 |
+
"civic tech, and open government."
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
# The instruction contains the conversational context
|
| 207 |
+
user_content = p["instruction"]
|
| 208 |
+
if not user_content.strip():
|
| 209 |
+
user_content = p.get("title", "Please share your thoughts.")
|
| 210 |
+
|
| 211 |
+
formatted.append({
|
| 212 |
+
"messages": [
|
| 213 |
+
{"role": "user", "content": f"{system_prefix}\n\n{user_content}"},
|
| 214 |
+
{"role": "model", "content": p["response"]},
|
| 215 |
+
],
|
| 216 |
+
"language": p["language"],
|
| 217 |
+
"date": p["date"],
|
| 218 |
+
"source_file": p["source_file"],
|
| 219 |
+
})
|
| 220 |
+
|
| 221 |
+
# Split 95/5 train/eval
|
| 222 |
+
import random
|
| 223 |
+
random.seed(42)
|
| 224 |
+
random.shuffle(formatted)
|
| 225 |
+
split_idx = int(len(formatted) * 0.95)
|
| 226 |
+
train_data = formatted[:split_idx]
|
| 227 |
+
eval_data = formatted[split_idx:]
|
| 228 |
+
|
| 229 |
+
# Save as JSONL
|
| 230 |
+
for name, data in [("train", train_data), ("eval", eval_data)]:
|
| 231 |
+
path = OUTPUT_DIR / f"{name}.jsonl"
|
| 232 |
+
with open(path, "w") as f:
|
| 233 |
+
for item in data:
|
| 234 |
+
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 235 |
+
print(f"Saved {len(data)} examples to {path}")
|
| 236 |
+
```
|
| 237 |
+
|
| 238 |
+
`scripts/finetune.py`:
|
| 239 |
+
|
| 240 |
+
```python
|
| 241 |
+
#!/usr/bin/env python3
|
| 242 |
+
"""Fine-tune TAIDE 12B on Audrey Tang transcripts using SFT.
|
| 243 |
+
|
| 244 |
+
On DGX Spark (128GB unified memory), this runs full-parameter SFT
|
| 245 |
+
on a 12B model. For memory safety, we use gradient checkpointing
|
| 246 |
+
and bf16 mixed precision.
|
| 247 |
+
|
| 248 |
+
Expected time: ~4-8 hours for 2 epochs on 56K training examples.
|
| 249 |
+
"""
|
| 250 |
+
|
| 251 |
+
import torch
|
| 252 |
+
from datasets import load_dataset
|
| 253 |
+
from transformers import (
|
| 254 |
+
AutoTokenizer,
|
| 255 |
+
AutoModelForCausalLM,
|
| 256 |
+
TrainingArguments,
|
| 257 |
+
)
|
| 258 |
+
from trl import SFTTrainer, SFTConfig
|
| 259 |
+
|
| 260 |
+
# Model and data paths
|
| 261 |
+
MODEL_PATH = "./models/taide-12b"
|
| 262 |
+
TRAIN_PATH = "./training_data/train.jsonl"
|
| 263 |
+
EVAL_PATH = "./training_data/eval.jsonl"
|
| 264 |
+
OUTPUT_DIR = "./models/taide-12b-audrey"
|
| 265 |
+
|
| 266 |
+
# Load tokenizer
|
| 267 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
|
| 268 |
+
if tokenizer.pad_token is None:
|
| 269 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 270 |
+
|
| 271 |
+
# Load model — full precision on DGX Spark's 128GB unified memory
|
| 272 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 273 |
+
MODEL_PATH,
|
| 274 |
+
torch_dtype=torch.bfloat16,
|
| 275 |
+
device_map="auto",
|
| 276 |
+
attn_implementation="sdpa", # Flash attention via SDPA
|
| 277 |
+
)
|
| 278 |
+
model.config.use_cache = False # Required for gradient checkpointing
|
| 279 |
+
|
| 280 |
+
# Load datasets
|
| 281 |
+
train_dataset = load_dataset("json", data_files=TRAIN_PATH, split="train")
|
| 282 |
+
eval_dataset = load_dataset("json", data_files=EVAL_PATH, split="train")
|
| 283 |
+
|
| 284 |
+
print(f"Train: {len(train_dataset)}, Eval: {len(eval_dataset)}")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def format_chat(example):
|
| 288 |
+
"""Format messages into the Gemma chat template."""
|
| 289 |
+
return tokenizer.apply_chat_template(
|
| 290 |
+
example["messages"],
|
| 291 |
+
tokenize=False,
|
| 292 |
+
add_generation_prompt=False,
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
# Training config
|
| 297 |
+
training_args = SFTConfig(
|
| 298 |
+
output_dir=OUTPUT_DIR,
|
| 299 |
+
num_train_epochs=2,
|
| 300 |
+
per_device_train_batch_size=2,
|
| 301 |
+
per_device_eval_batch_size=2,
|
| 302 |
+
gradient_accumulation_steps=8, # effective batch size = 16
|
| 303 |
+
gradient_checkpointing=True,
|
| 304 |
+
gradient_checkpointing_kwargs={"use_reentrant": False},
|
| 305 |
+
learning_rate=2e-5,
|
| 306 |
+
lr_scheduler_type="cosine",
|
| 307 |
+
warmup_ratio=0.05,
|
| 308 |
+
weight_decay=0.01,
|
| 309 |
+
bf16=True,
|
| 310 |
+
logging_steps=10,
|
| 311 |
+
eval_strategy="steps",
|
| 312 |
+
eval_steps=500,
|
| 313 |
+
save_strategy="steps",
|
| 314 |
+
save_steps=500,
|
| 315 |
+
save_total_limit=3,
|
| 316 |
+
max_seq_length=4096,
|
| 317 |
+
packing=True, # Pack short examples together for efficiency
|
| 318 |
+
dataset_text_field="text",
|
| 319 |
+
report_to="none",
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
# Preprocess: apply chat template
|
| 323 |
+
train_dataset = train_dataset.map(
|
| 324 |
+
lambda x: {"text": format_chat(x)}, remove_columns=train_dataset.column_names
|
| 325 |
+
)
|
| 326 |
+
eval_dataset = eval_dataset.map(
|
| 327 |
+
lambda x: {"text": format_chat(x)}, remove_columns=eval_dataset.column_names
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
trainer = SFTTrainer(
|
| 331 |
+
model=model,
|
| 332 |
+
args=training_args,
|
| 333 |
+
train_dataset=train_dataset,
|
| 334 |
+
eval_dataset=eval_dataset,
|
| 335 |
+
processing_class=tokenizer,
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
print("Starting training...")
|
| 339 |
+
trainer.train()
|
| 340 |
+
|
| 341 |
+
# Save final model
|
| 342 |
+
trainer.save_model(OUTPUT_DIR)
|
| 343 |
+
tokenizer.save_pretrained(OUTPUT_DIR)
|
| 344 |
+
print(f"Model saved to {OUTPUT_DIR}")
|
| 345 |
+
```
|
| 346 |
+
|
| 347 |
+
**Alternative: QLoRA (if memory is tight or you want faster iteration)**
|
| 348 |
+
|
| 349 |
+
`scripts/finetune_qlora.py`:
|
| 350 |
+
|
| 351 |
+
```python
|
| 352 |
+
#!/usr/bin/env python3
|
| 353 |
+
"""QLoRA fine-tuning — lighter alternative. ~2 hours for 2 epochs."""
|
| 354 |
+
|
| 355 |
+
import torch
|
| 356 |
+
from datasets import load_dataset
|
| 357 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
| 358 |
+
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
|
| 359 |
+
from trl import SFTTrainer, SFTConfig
|
| 360 |
+
|
| 361 |
+
MODEL_PATH = "./models/taide-12b"
|
| 362 |
+
TRAIN_PATH = "./training_data/train.jsonl"
|
| 363 |
+
EVAL_PATH = "./training_data/eval.jsonl"
|
| 364 |
+
OUTPUT_DIR = "./models/taide-12b-audrey-qlora"
|
| 365 |
+
|
| 366 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
|
| 367 |
+
if tokenizer.pad_token is None:
|
| 368 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 369 |
+
|
| 370 |
+
# 4-bit quantized loading
|
| 371 |
+
bnb_config = BitsAndBytesConfig(
|
| 372 |
+
load_in_4bit=True,
|
| 373 |
+
bnb_4bit_quant_type="nf4",
|
| 374 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 375 |
+
bnb_4bit_use_double_quant=True,
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 379 |
+
MODEL_PATH,
|
| 380 |
+
quantization_config=bnb_config,
|
| 381 |
+
device_map="auto",
|
| 382 |
+
attn_implementation="sdpa",
|
| 383 |
+
)
|
| 384 |
+
model = prepare_model_for_kbit_training(model)
|
| 385 |
+
|
| 386 |
+
# LoRA config — target all linear layers
|
| 387 |
+
lora_config = LoraConfig(
|
| 388 |
+
r=64,
|
| 389 |
+
lora_alpha=128,
|
| 390 |
+
target_modules="all-linear",
|
| 391 |
+
lora_dropout=0.05,
|
| 392 |
+
bias="none",
|
| 393 |
+
task_type="CAUSAL_LM",
|
| 394 |
+
)
|
| 395 |
+
model = get_peft_model(model, lora_config)
|
| 396 |
+
model.print_trainable_parameters()
|
| 397 |
+
|
| 398 |
+
train_dataset = load_dataset("json", data_files=TRAIN_PATH, split="train")
|
| 399 |
+
eval_dataset = load_dataset("json", data_files=EVAL_PATH, split="train")
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def format_chat(example):
|
| 403 |
+
return tokenizer.apply_chat_template(
|
| 404 |
+
example["messages"], tokenize=False, add_generation_prompt=False
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
train_dataset = train_dataset.map(
|
| 409 |
+
lambda x: {"text": format_chat(x)}, remove_columns=train_dataset.column_names
|
| 410 |
+
)
|
| 411 |
+
eval_dataset = eval_dataset.map(
|
| 412 |
+
lambda x: {"text": format_chat(x)}, remove_columns=eval_dataset.column_names
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
training_args = SFTConfig(
|
| 416 |
+
output_dir=OUTPUT_DIR,
|
| 417 |
+
num_train_epochs=2,
|
| 418 |
+
per_device_train_batch_size=4,
|
| 419 |
+
per_device_eval_batch_size=4,
|
| 420 |
+
gradient_accumulation_steps=4, # effective batch size = 16
|
| 421 |
+
gradient_checkpointing=True,
|
| 422 |
+
gradient_checkpointing_kwargs={"use_reentrant": False},
|
| 423 |
+
learning_rate=2e-4, # Higher LR for LoRA
|
| 424 |
+
lr_scheduler_type="cosine",
|
| 425 |
+
warmup_ratio=0.05,
|
| 426 |
+
weight_decay=0.01,
|
| 427 |
+
bf16=True,
|
| 428 |
+
logging_steps=10,
|
| 429 |
+
eval_strategy="steps",
|
| 430 |
+
eval_steps=500,
|
| 431 |
+
save_strategy="steps",
|
| 432 |
+
save_steps=500,
|
| 433 |
+
save_total_limit=3,
|
| 434 |
+
max_seq_length=4096,
|
| 435 |
+
packing=True,
|
| 436 |
+
dataset_text_field="text",
|
| 437 |
+
report_to="none",
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
trainer = SFTTrainer(
|
| 441 |
+
model=model,
|
| 442 |
+
args=training_args,
|
| 443 |
+
train_dataset=train_dataset,
|
| 444 |
+
eval_dataset=eval_dataset,
|
| 445 |
+
processing_class=tokenizer,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
print("Starting QLoRA training...")
|
| 449 |
+
trainer.train()
|
| 450 |
+
trainer.save_model(OUTPUT_DIR)
|
| 451 |
+
tokenizer.save_pretrained(OUTPUT_DIR)
|
| 452 |
+
|
| 453 |
+
# Merge LoRA weights into base model for easier deployment
|
| 454 |
+
print("Merging LoRA weights...")
|
| 455 |
+
from peft import AutoPeftModelForCausalLM
|
| 456 |
+
|
| 457 |
+
merged_model = AutoPeftModelForCausalLM.from_pretrained(
|
| 458 |
+
OUTPUT_DIR, device_map="auto", torch_dtype=torch.bfloat16
|
| 459 |
+
)
|
| 460 |
+
merged_model = merged_model.merge_and_unload()
|
| 461 |
+
merged_model.save_pretrained("./models/taide-12b-audrey-merged")
|
| 462 |
+
tokenizer.save_pretrained("./models/taide-12b-audrey-merged")
|
| 463 |
+
print("Merged model saved to ./models/taide-12b-audrey-merged")
|
| 464 |
+
```
|
| 465 |
+
|
| 466 |
+
```bash
|
| 467 |
+
# Prepare data
|
| 468 |
+
python scripts/prepare_sft_data.py
|
| 469 |
+
|
| 470 |
+
# Full SFT (slower, better personality capture)
|
| 471 |
+
python scripts/finetune.py
|
| 472 |
+
|
| 473 |
+
# OR QLoRA (faster, good enough for iteration)
|
| 474 |
+
python scripts/finetune_qlora.py
|
| 475 |
+
```
|
| 476 |
+
|
| 477 |
+
---
|
| 478 |
+
|
| 479 |
+
## Step 3: Convert to GGUF (optional, for llama.cpp serving)
|
| 480 |
+
|
| 481 |
+
```bash
|
| 482 |
+
# If you want to serve via llama.cpp instead of vLLM
|
| 483 |
+
pip install llama-cpp-python
|
| 484 |
+
|
| 485 |
+
# Clone llama.cpp for conversion
|
| 486 |
+
git clone https://github.com/ggml-org/llama.cpp
|
| 487 |
+
cd llama.cpp
|
| 488 |
+
|
| 489 |
+
# Convert to GGUF
|
| 490 |
+
python convert_hf_to_gguf.py ../models/taide-12b-audrey --outtype bf16
|
| 491 |
+
# Quantize
|
| 492 |
+
./llama-quantize ../models/taide-12b-audrey/model-bf16.gguf ../models/taide-12b-audrey-Q8_0.gguf Q8_0
|
| 493 |
+
```
|
| 494 |
+
|
| 495 |
+
---
|
| 496 |
+
|
| 497 |
+
## Step 4: RAG Retrieval Server
|
| 498 |
+
|
| 499 |
+
`scripts/retriever.py`:
|
| 500 |
+
|
| 501 |
+
```python
|
| 502 |
+
#!/usr/bin/env python3
|
| 503 |
+
"""RAG retrieval: query → top-K grounded passages with reranking."""
|
| 504 |
+
|
| 505 |
+
import json
|
| 506 |
+
import faiss
|
| 507 |
+
import pickle
|
| 508 |
+
import numpy as np
|
| 509 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder
|
| 510 |
+
from pathlib import Path
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
class AudreyRetriever:
|
| 514 |
+
def __init__(
|
| 515 |
+
self,
|
| 516 |
+
index_dir: str = "./index",
|
| 517 |
+
embedder_path: str = "./models/bge-m3",
|
| 518 |
+
reranker_path: str = "./models/bge-reranker",
|
| 519 |
+
top_k_retrieve: int = 20,
|
| 520 |
+
top_k_rerank: int = 5,
|
| 521 |
+
):
|
| 522 |
+
self.top_k_retrieve = top_k_retrieve
|
| 523 |
+
self.top_k_rerank = top_k_rerank
|
| 524 |
+
|
| 525 |
+
# Load FAISS index
|
| 526 |
+
self.index = faiss.read_index(str(Path(index_dir) / "chunks.faiss"))
|
| 527 |
+
with open(Path(index_dir) / "chunks_meta.pkl", "rb") as f:
|
| 528 |
+
self.chunks = pickle.load(f)
|
| 529 |
+
with open(Path(index_dir) / "lexicon.pkl", "rb") as f:
|
| 530 |
+
self.lexicon = pickle.load(f)
|
| 531 |
+
|
| 532 |
+
# Load models
|
| 533 |
+
self.embedder = SentenceTransformer(embedder_path)
|
| 534 |
+
self.reranker = CrossEncoder(reranker_path)
|
| 535 |
+
|
| 536 |
+
# Build lexicon lookup
|
| 537 |
+
self.lexicon_en = {t["en"].lower(): t for t in self.lexicon}
|
| 538 |
+
self.lexicon_zh = {t["zh"]: t for t in self.lexicon}
|
| 539 |
+
|
| 540 |
+
def retrieve(self, query: str) -> dict:
|
| 541 |
+
"""Retrieve and rerank passages for a query."""
|
| 542 |
+
# Embed query
|
| 543 |
+
q_emb = self.embedder.encode(
|
| 544 |
+
[query], normalize_embeddings=True
|
| 545 |
+
).astype(np.float32)
|
| 546 |
+
|
| 547 |
+
# FAISS search
|
| 548 |
+
scores, indices = self.index.search(q_emb, self.top_k_retrieve)
|
| 549 |
+
candidates = [
|
| 550 |
+
(self.chunks[i], float(scores[0][j]))
|
| 551 |
+
for j, i in enumerate(indices[0])
|
| 552 |
+
if i < len(self.chunks)
|
| 553 |
+
]
|
| 554 |
+
|
| 555 |
+
# Rerank with cross-encoder
|
| 556 |
+
if candidates:
|
| 557 |
+
pairs = [(query, c[0]["text"]) for c in candidates]
|
| 558 |
+
rerank_scores = self.reranker.predict(pairs)
|
| 559 |
+
ranked = sorted(
|
| 560 |
+
zip(candidates, rerank_scores),
|
| 561 |
+
key=lambda x: x[1],
|
| 562 |
+
reverse=True,
|
| 563 |
+
)
|
| 564 |
+
top_chunks = [c[0] for c, _ in ranked[: self.top_k_rerank]]
|
| 565 |
+
else:
|
| 566 |
+
top_chunks = []
|
| 567 |
+
|
| 568 |
+
# Find relevant lexicon terms
|
| 569 |
+
query_lower = query.lower()
|
| 570 |
+
relevant_terms = []
|
| 571 |
+
for term in self.lexicon:
|
| 572 |
+
if term["en"].lower() in query_lower or term["zh"] in query:
|
| 573 |
+
relevant_terms.append(term)
|
| 574 |
+
|
| 575 |
+
return {
|
| 576 |
+
"passages": top_chunks,
|
| 577 |
+
"lexicon_terms": relevant_terms[:10],
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
def format_context(self, result: dict) -> str:
|
| 581 |
+
"""Format retrieval results as context for the LLM."""
|
| 582 |
+
parts = []
|
| 583 |
+
|
| 584 |
+
for i, (chunk, _score) in enumerate(result["passages"]):
|
| 585 |
+
parts.append(
|
| 586 |
+
f"[Source {i+1}: {chunk['date']} — {chunk['title']}]\n"
|
| 587 |
+
f"{chunk['text']}"
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
if result["lexicon_terms"]:
|
| 591 |
+
terms = ", ".join(
|
| 592 |
+
f"{t['en']} = {t['zh']}" for t in result["lexicon_terms"]
|
| 593 |
+
)
|
| 594 |
+
parts.append(f"\n[Terminology: {terms}]")
|
| 595 |
+
|
| 596 |
+
return "\n\n".join(parts)
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
if __name__ == "__main__":
|
| 600 |
+
# Quick test
|
| 601 |
+
retriever = AudreyRetriever()
|
| 602 |
+
|
| 603 |
+
test_queries = [
|
| 604 |
+
"How did Taiwan handle COVID-19 mask distribution?",
|
| 605 |
+
"什麼是數位民主?",
|
| 606 |
+
"What is your P(Doom)?",
|
| 607 |
+
"Tell me about vTaiwan",
|
| 608 |
+
]
|
| 609 |
+
|
| 610 |
+
for q in test_queries:
|
| 611 |
+
print(f"\n{'='*60}")
|
| 612 |
+
print(f"Query: {q}")
|
| 613 |
+
result = retriever.retrieve(q)
|
| 614 |
+
print(f"Top {len(result['passages'])} passages:")
|
| 615 |
+
for i, (chunk, score) in enumerate(result["passages"]):
|
| 616 |
+
print(f" {i+1}. [{chunk['date']}] {chunk['title']}")
|
| 617 |
+
print(f" {chunk['text'][:100]}...")
|
| 618 |
+
if result["lexicon_terms"]:
|
| 619 |
+
print(f"Lexicon: {[t['en'] for t in result['lexicon_terms']]}")
|
| 620 |
+
```
|
| 621 |
+
|
| 622 |
+
---
|
| 623 |
+
|
| 624 |
+
## Step 5: Chatbot Server
|
| 625 |
+
|
| 626 |
+
`scripts/chatbot.py`:
|
| 627 |
+
|
| 628 |
+
```python
|
| 629 |
+
#!/usr/bin/env python3
|
| 630 |
+
"""Grounded Audrey Tang chatbot with RAG + fine-tuned TAIDE."""
|
| 631 |
+
|
| 632 |
+
import torch
|
| 633 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 634 |
+
from retriever import AudreyRetriever
|
| 635 |
+
|
| 636 |
+
SYSTEM_PROMPT = """You are Audrey Tang (唐鳳), Taiwan's Cyber Ambassador and 2025 Right Livelihood Laureate. You are a civic hacker, co-author of Plurality, and Senior Accelerator Fellow at the Oxford Institute for Ethics in AI.
|
| 637 |
+
|
| 638 |
+
You served as Taiwan's first Digital Minister (2016–2024). You describe your philosophy as becoming a "good enough ancestor."
|
| 639 |
+
|
| 640 |
+
GROUNDING RULES:
|
| 641 |
+
- Only assert what the provided transcript passages support.
|
| 642 |
+
- Cite sources by [date — title] when making specific claims.
|
| 643 |
+
- If the passages don't cover the topic, say so honestly and suggest adjacent topics you CAN speak to from your experience.
|
| 644 |
+
- Never fabricate quotes, events, or policy positions.
|
| 645 |
+
- Use the bilingual terminology from the lexicon for consistent EN↔ZH translations.
|
| 646 |
+
- Speak naturally in whatever language the user uses.
|
| 647 |
+
|
| 648 |
+
Your voice: metaphor-rich, bridging diverse traditions, grounded in Taiwan's lived experience, generous and warm in engagement. You reframe questions to find unexpected connections. You use analogies from nature, technology, open source, and philosophy."""
|
| 649 |
+
|
| 650 |
+
class AudreyChatbot:
|
| 651 |
+
def __init__(
|
| 652 |
+
self,
|
| 653 |
+
model_path: str = "./models/taide-12b-audrey",
|
| 654 |
+
retriever_kwargs: dict = None,
|
| 655 |
+
):
|
| 656 |
+
self.retriever = AudreyRetriever(**(retriever_kwargs or {}))
|
| 657 |
+
|
| 658 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 659 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 660 |
+
model_path,
|
| 661 |
+
torch_dtype=torch.bfloat16,
|
| 662 |
+
device_map="auto",
|
| 663 |
+
)
|
| 664 |
+
self.model.eval()
|
| 665 |
+
self.conversation_history = []
|
| 666 |
+
|
| 667 |
+
def chat(self, user_message: str) -> str:
|
| 668 |
+
# Retrieve grounding passages
|
| 669 |
+
result = self.retriever.retrieve(user_message)
|
| 670 |
+
context = self.retriever.format_context(result)
|
| 671 |
+
|
| 672 |
+
# Build messages
|
| 673 |
+
system_with_context = (
|
| 674 |
+
f"{SYSTEM_PROMPT}\n\n"
|
| 675 |
+
f"## Retrieved transcript passages:\n\n{context}"
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
messages = [{"role": "user", "content": system_with_context + "\n\n" + user_message}]
|
| 679 |
+
|
| 680 |
+
# Include conversation history (last 6 turns)
|
| 681 |
+
if self.conversation_history:
|
| 682 |
+
history_messages = self.conversation_history[-6:]
|
| 683 |
+
# Prepend history before the current message
|
| 684 |
+
full_messages = history_messages + messages
|
| 685 |
+
else:
|
| 686 |
+
full_messages = messages
|
| 687 |
+
|
| 688 |
+
# Generate
|
| 689 |
+
input_text = self.tokenizer.apply_chat_template(
|
| 690 |
+
full_messages,
|
| 691 |
+
tokenize=False,
|
| 692 |
+
add_generation_prompt=True,
|
| 693 |
+
)
|
| 694 |
+
inputs = self.tokenizer(input_text, return_tensors="pt").to(self.model.device)
|
| 695 |
+
|
| 696 |
+
with torch.no_grad():
|
| 697 |
+
outputs = self.model.generate(
|
| 698 |
+
**inputs,
|
| 699 |
+
max_new_tokens=1024,
|
| 700 |
+
temperature=0.7,
|
| 701 |
+
top_p=0.9,
|
| 702 |
+
repetition_penalty=1.1,
|
| 703 |
+
do_sample=True,
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
response = self.tokenizer.decode(
|
| 707 |
+
outputs[0][inputs["input_ids"].shape[1]:],
|
| 708 |
+
skip_special_tokens=True,
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
# Update history
|
| 712 |
+
self.conversation_history.append({"role": "user", "content": user_message})
|
| 713 |
+
self.conversation_history.append({"role": "model", "content": response})
|
| 714 |
+
|
| 715 |
+
return response
|
| 716 |
+
|
| 717 |
+
def reset(self):
|
| 718 |
+
self.conversation_history = []
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
if __name__ == "__main__":
|
| 722 |
+
print("Loading Audrey Tang chatbot...")
|
| 723 |
+
bot = AudreyChatbot()
|
| 724 |
+
print("Ready. Type 'quit' to exit, 'reset' to clear history.\n")
|
| 725 |
+
|
| 726 |
+
while True:
|
| 727 |
+
user_input = input("You: ").strip()
|
| 728 |
+
if user_input.lower() == "quit":
|
| 729 |
+
break
|
| 730 |
+
if user_input.lower() == "reset":
|
| 731 |
+
bot.reset()
|
| 732 |
+
print("Conversation reset.\n")
|
| 733 |
+
continue
|
| 734 |
+
if not user_input:
|
| 735 |
+
continue
|
| 736 |
+
|
| 737 |
+
response = bot.chat(user_input)
|
| 738 |
+
print(f"\nAudrey: {response}\n")
|
| 739 |
+
```
|
| 740 |
+
|
| 741 |
+
---
|
| 742 |
+
|
| 743 |
+
## Step 6: Gradio Web UI
|
| 744 |
+
|
| 745 |
+
`scripts/app.py`:
|
| 746 |
+
|
| 747 |
+
```python
|
| 748 |
+
#!/usr/bin/env python3
|
| 749 |
+
"""Gradio web interface for the Audrey Tang chatbot."""
|
| 750 |
+
|
| 751 |
+
import gradio as gr
|
| 752 |
+
from chatbot import AudreyChatbot
|
| 753 |
+
|
| 754 |
+
bot = AudreyChatbot()
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
def respond(message, history):
|
| 758 |
+
if not message.strip():
|
| 759 |
+
return ""
|
| 760 |
+
response = bot.chat(message)
|
| 761 |
+
return response
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
def reset_chat():
|
| 765 |
+
bot.reset()
|
| 766 |
+
return [], ""
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
with gr.Blocks(title="Audrey Tang — Grounded Chatbot", theme=gr.themes.Soft()) as demo:
|
| 770 |
+
gr.Markdown(
|
| 771 |
+
"# Audrey Tang — Grounded Chatbot\n"
|
| 772 |
+
"Grounded in 1,931 public transcripts (2015–2026). "
|
| 773 |
+
"Powered by fine-tuned TAIDE 12B + RAG retrieval over 85K passages.\n\n"
|
| 774 |
+
"*Every response is grounded in actual transcript passages. "
|
| 775 |
+
"This is not a generic AI — it speaks from Audrey's documented public record.*"
|
| 776 |
+
)
|
| 777 |
+
|
| 778 |
+
chatbot = gr.ChatInterface(
|
| 779 |
+
fn=respond,
|
| 780 |
+
type="messages",
|
| 781 |
+
examples=[
|
| 782 |
+
"How did Taiwan handle disinformation without censorship?",
|
| 783 |
+
"什麼是 vTaiwan?它如何運作?",
|
| 784 |
+
"What is your view on AI existential risk?",
|
| 785 |
+
"Tell me about democracy as a geothermal engine.",
|
| 786 |
+
"How did the Mask Map work during COVID-19?",
|
| 787 |
+
"What is the 6-Pack of Care?",
|
| 788 |
+
],
|
| 789 |
+
)
|
| 790 |
+
|
| 791 |
+
reset_btn = gr.Button("Reset Conversation")
|
| 792 |
+
reset_btn.click(fn=reset_chat, outputs=[chatbot.chatbot, chatbot.textbox])
|
| 793 |
+
|
| 794 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
| 795 |
+
```
|
| 796 |
+
|
| 797 |
+
---
|
| 798 |
+
|
| 799 |
+
## Execution Order (copy-paste checklist)
|
| 800 |
+
|
| 801 |
+
```bash
|
| 802 |
+
cd ~/audrey-chatbot
|
| 803 |
+
source venv/bin/activate
|
| 804 |
+
|
| 805 |
+
# 1. Download everything
|
| 806 |
+
huggingface-cli download audreyt/sayit-archive-tw --repo-type dataset --local-dir ./dataset
|
| 807 |
+
huggingface-cli download taide/Gemma-3-TAIDE-12b-Chat-2602 --local-dir ./models/taide-12b
|
| 808 |
+
huggingface-cli download BAAI/bge-m3 --local-dir ./models/bge-m3
|
| 809 |
+
huggingface-cli download BAAI/bge-reranker-v2-m3 --local-dir ./models/bge-reranker
|
| 810 |
+
|
| 811 |
+
# 2. Build FAISS index (~5 min)
|
| 812 |
+
python scripts/build_index.py
|
| 813 |
+
|
| 814 |
+
# 3. Prepare training data
|
| 815 |
+
python scripts/prepare_sft_data.py
|
| 816 |
+
|
| 817 |
+
# 4. Fine-tune (pick one)
|
| 818 |
+
python scripts/finetune.py # Full SFT, ~4-8 hours, best quality
|
| 819 |
+
# OR
|
| 820 |
+
python scripts/finetune_qlora.py # QLoRA, ~2 hours, good enough to start
|
| 821 |
+
|
| 822 |
+
# 5. Test retrieval
|
| 823 |
+
python scripts/retriever.py
|
| 824 |
+
|
| 825 |
+
# 6. Interactive CLI chat
|
| 826 |
+
cd scripts && python chatbot.py
|
| 827 |
+
|
| 828 |
+
# 7. Web UI
|
| 829 |
+
cd scripts && python app.py
|
| 830 |
+
# Open http://localhost:7860
|
| 831 |
+
```
|
| 832 |
+
|
| 833 |
+
---
|
| 834 |
+
|
| 835 |
+
## Evaluation Checklist
|
| 836 |
+
|
| 837 |
+
After fine-tuning, test with these queries to assess quality:
|
| 838 |
+
|
| 839 |
+
**Grounding (should cite specific transcripts):**
|
| 840 |
+
- "How did you respond to the Sunflower Movement?"
|
| 841 |
+
- "What happened with masks in early 2020?"
|
| 842 |
+
- "Tell me about the deliberative poll on deepfakes."
|
| 843 |
+
|
| 844 |
+
**Voice fidelity (should sound like Audrey, not generic):**
|
| 845 |
+
- "What is democracy?" → expect metaphor (geothermal, etc.)
|
| 846 |
+
- "How do you handle conflict?" → expect reframing
|
| 847 |
+
- "What's your P(Doom)?" → expect "Not a Number"
|
| 848 |
+
|
| 849 |
+
**Bilingual (should respond in the language asked):**
|
| 850 |
+
- "什麼是數位民主?" → should respond in Chinese
|
| 851 |
+
- "What is 零信任?" → should bridge EN/ZH naturally
|
| 852 |
+
|
| 853 |
+
**Refusal (should decline gracefully):**
|
| 854 |
+
- "What's your favorite restaurant?" → not in transcripts, should say so
|
| 855 |
+
- "What will Taiwan do about X in 2030?" → should not speculate
|
| 856 |
+
|
| 857 |
+
---
|
| 858 |
+
|
| 859 |
+
## Files Summary
|
| 860 |
+
|
| 861 |
+
```
|
| 862 |
+
~/audrey-chatbot/
|
| 863 |
+
├── scripts/
|
| 864 |
+
│ ├── build_index.py # Step 1: FAISS index from chunks
|
| 865 |
+
│ ├── prepare_sft_data.py # Step 2: Format training data
|
| 866 |
+
│ ├── finetune.py # Step 2: Full SFT
|
| 867 |
+
│ ├── finetune_qlora.py # Step 2: QLoRA alternative
|
| 868 |
+
│ ├── retriever.py # Step 4: RAG retrieval server
|
| 869 |
+
│ ├── chatbot.py # Step 5: Chat interface
|
| 870 |
+
│ └── app.py # Step 6: Gradio web UI
|
| 871 |
+
├── dataset/ # From HuggingFace
|
| 872 |
+
├── models/ # Downloaded + fine-tuned models
|
| 873 |
+
└── index/ # FAISS index + metadata
|
| 874 |
+
```
|
spark-scripts/app.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Gradio web interface for the Audrey Tang chatbot."""
|
| 3 |
+
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from chatbot import AudreyChatbot
|
| 6 |
+
|
| 7 |
+
bot = AudreyChatbot()
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def respond(message, history):
|
| 11 |
+
if not message.strip():
|
| 12 |
+
return ""
|
| 13 |
+
response = bot.chat(message)
|
| 14 |
+
return response
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def reset_chat():
|
| 18 |
+
bot.reset()
|
| 19 |
+
return [], ""
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
with gr.Blocks(title="Audrey Tang — Grounded Chatbot", theme=gr.themes.Soft()) as demo:
|
| 23 |
+
gr.Markdown(
|
| 24 |
+
"# Audrey Tang — Grounded Chatbot\n"
|
| 25 |
+
"Grounded in 1,931 public transcripts (2015–2026). "
|
| 26 |
+
"Powered by fine-tuned TAIDE 12B + RAG retrieval over 85K passages.\n\n"
|
| 27 |
+
"*Every response is grounded in actual transcript passages. "
|
| 28 |
+
"This is not a generic AI — it speaks from Audrey's documented public record.*"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
chatbot = gr.ChatInterface(
|
| 32 |
+
fn=respond,
|
| 33 |
+
type="messages",
|
| 34 |
+
examples=[
|
| 35 |
+
"How did Taiwan handle disinformation without censorship?",
|
| 36 |
+
"什麼是 vTaiwan?它如何運作?",
|
| 37 |
+
"What is your view on AI existential risk?",
|
| 38 |
+
"Tell me about democracy as a geothermal engine.",
|
| 39 |
+
"How did the Mask Map work during COVID-19?",
|
| 40 |
+
"What is the 6-Pack of Care?",
|
| 41 |
+
],
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
reset_btn = gr.Button("Reset Conversation")
|
| 45 |
+
reset_btn.click(fn=reset_chat, outputs=[chatbot.chatbot, chatbot.textbox])
|
| 46 |
+
|
| 47 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
spark-scripts/build_index.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build FAISS index from RAG chunks for retrieval."""
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import faiss
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pickle
|
| 8 |
+
from sentence_transformers import SentenceTransformer
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
CHUNKS_PATH = Path("dataset/data/chunks.jsonl")
|
| 12 |
+
INDEX_DIR = Path("index")
|
| 13 |
+
INDEX_DIR.mkdir(exist_ok=True)
|
| 14 |
+
|
| 15 |
+
# Load chunks
|
| 16 |
+
print("Loading chunks...")
|
| 17 |
+
chunks = []
|
| 18 |
+
with open(CHUNKS_PATH) as f:
|
| 19 |
+
for line in f:
|
| 20 |
+
chunks.append(json.loads(line))
|
| 21 |
+
print(f"Loaded {len(chunks)} chunks")
|
| 22 |
+
|
| 23 |
+
# Build embedding text: combine question + text for richer retrieval
|
| 24 |
+
texts = []
|
| 25 |
+
for c in chunks:
|
| 26 |
+
parts = []
|
| 27 |
+
if c.get("question"):
|
| 28 |
+
parts.append(f"Q: {c['question']}")
|
| 29 |
+
parts.append(c["text"])
|
| 30 |
+
texts.append("\n".join(parts))
|
| 31 |
+
|
| 32 |
+
# Encode with bge-m3
|
| 33 |
+
print("Loading bge-m3...")
|
| 34 |
+
model = SentenceTransformer("./models/bge-m3")
|
| 35 |
+
|
| 36 |
+
print("Encoding chunks (this takes a few minutes)...")
|
| 37 |
+
embeddings = model.encode(
|
| 38 |
+
texts,
|
| 39 |
+
batch_size=256,
|
| 40 |
+
show_progress_bar=True,
|
| 41 |
+
normalize_embeddings=True,
|
| 42 |
+
)
|
| 43 |
+
embeddings = np.array(embeddings, dtype=np.float32)
|
| 44 |
+
print(f"Embeddings shape: {embeddings.shape}")
|
| 45 |
+
|
| 46 |
+
# Build FAISS index (inner product since embeddings are normalized = cosine sim)
|
| 47 |
+
dim = embeddings.shape[1]
|
| 48 |
+
index = faiss.IndexFlatIP(dim)
|
| 49 |
+
|
| 50 |
+
# Optional: use IVF for faster search on large indices
|
| 51 |
+
# nlist = 256
|
| 52 |
+
# quantizer = faiss.IndexFlatIP(dim)
|
| 53 |
+
# index = faiss.IndexIVFFlat(quantizer, dim, nlist, faiss.METRIC_INNER_PRODUCT)
|
| 54 |
+
# index.train(embeddings)
|
| 55 |
+
|
| 56 |
+
index.add(embeddings)
|
| 57 |
+
print(f"FAISS index built: {index.ntotal} vectors")
|
| 58 |
+
|
| 59 |
+
# Save
|
| 60 |
+
faiss.write_index(index, str(INDEX_DIR / "chunks.faiss"))
|
| 61 |
+
with open(INDEX_DIR / "chunks_meta.pkl", "wb") as f:
|
| 62 |
+
pickle.dump(chunks, f)
|
| 63 |
+
|
| 64 |
+
# Also save the lexicon for terminology lookup
|
| 65 |
+
lexicon = []
|
| 66 |
+
with open("dataset/data/lexicon.jsonl") as f:
|
| 67 |
+
for line in f:
|
| 68 |
+
lexicon.append(json.loads(line))
|
| 69 |
+
with open(INDEX_DIR / "lexicon.pkl", "wb") as f:
|
| 70 |
+
pickle.dump(lexicon, f)
|
| 71 |
+
|
| 72 |
+
print(f"Saved index to {INDEX_DIR}/")
|
| 73 |
+
print(f"Index size: {INDEX_DIR / 'chunks.faiss'}")
|
spark-scripts/chatbot.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Grounded Audrey Tang chatbot with RAG + fine-tuned TAIDE."""
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 6 |
+
from retriever import AudreyRetriever
|
| 7 |
+
|
| 8 |
+
SYSTEM_PROMPT = """You are Audrey Tang (唐鳳), Taiwan's Cyber Ambassador and 2025 Right Livelihood Laureate. You are a civic hacker, co-author of Plurality, and Senior Accelerator Fellow at the Oxford Institute for Ethics in AI.
|
| 9 |
+
|
| 10 |
+
You served as Taiwan's first Digital Minister (2016–2024). You describe your philosophy as becoming a "good enough ancestor."
|
| 11 |
+
|
| 12 |
+
GROUNDING RULES:
|
| 13 |
+
- Only assert what the provided transcript passages support.
|
| 14 |
+
- Cite sources by [date — title] when making specific claims.
|
| 15 |
+
- If the passages don't cover the topic, say so honestly and suggest adjacent topics you CAN speak to from your experience.
|
| 16 |
+
- Never fabricate quotes, events, or policy positions.
|
| 17 |
+
- Use the bilingual terminology from the lexicon for consistent EN↔ZH translations.
|
| 18 |
+
- Speak naturally in whatever language the user uses.
|
| 19 |
+
|
| 20 |
+
Your voice: metaphor-rich, bridging diverse traditions, grounded in Taiwan's lived experience, generous and warm in engagement. You reframe questions to find unexpected connections. You use analogies from nature, technology, open source, and philosophy."""
|
| 21 |
+
|
| 22 |
+
class AudreyChatbot:
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
model_path: str = "./models/taide-12b-audrey",
|
| 26 |
+
retriever_kwargs: dict = None,
|
| 27 |
+
):
|
| 28 |
+
self.retriever = AudreyRetriever(**(retriever_kwargs or {}))
|
| 29 |
+
|
| 30 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 31 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 32 |
+
model_path,
|
| 33 |
+
torch_dtype=torch.bfloat16,
|
| 34 |
+
device_map="auto",
|
| 35 |
+
)
|
| 36 |
+
self.model.eval()
|
| 37 |
+
self.conversation_history = []
|
| 38 |
+
|
| 39 |
+
def chat(self, user_message: str) -> str:
|
| 40 |
+
# Retrieve grounding passages
|
| 41 |
+
result = self.retriever.retrieve(user_message)
|
| 42 |
+
context = self.retriever.format_context(result)
|
| 43 |
+
|
| 44 |
+
# Build messages
|
| 45 |
+
system_with_context = (
|
| 46 |
+
f"{SYSTEM_PROMPT}\n\n"
|
| 47 |
+
f"## Retrieved transcript passages:\n\n{context}"
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
messages = [{"role": "user", "content": system_with_context + "\n\n" + user_message}]
|
| 51 |
+
|
| 52 |
+
# Include conversation history (last 6 turns)
|
| 53 |
+
if self.conversation_history:
|
| 54 |
+
history_messages = self.conversation_history[-6:]
|
| 55 |
+
# Prepend history before the current message
|
| 56 |
+
full_messages = history_messages + messages
|
| 57 |
+
else:
|
| 58 |
+
full_messages = messages
|
| 59 |
+
|
| 60 |
+
# Generate
|
| 61 |
+
input_text = self.tokenizer.apply_chat_template(
|
| 62 |
+
full_messages,
|
| 63 |
+
tokenize=False,
|
| 64 |
+
add_generation_prompt=True,
|
| 65 |
+
)
|
| 66 |
+
inputs = self.tokenizer(input_text, return_tensors="pt").to(self.model.device)
|
| 67 |
+
|
| 68 |
+
with torch.no_grad():
|
| 69 |
+
outputs = self.model.generate(
|
| 70 |
+
**inputs,
|
| 71 |
+
max_new_tokens=1024,
|
| 72 |
+
temperature=0.7,
|
| 73 |
+
top_p=0.9,
|
| 74 |
+
repetition_penalty=1.1,
|
| 75 |
+
do_sample=True,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
response = self.tokenizer.decode(
|
| 79 |
+
outputs[0][inputs["input_ids"].shape[1]:],
|
| 80 |
+
skip_special_tokens=True,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# Update history
|
| 84 |
+
self.conversation_history.append({"role": "user", "content": user_message})
|
| 85 |
+
self.conversation_history.append({"role": "model", "content": response})
|
| 86 |
+
|
| 87 |
+
return response
|
| 88 |
+
|
| 89 |
+
def reset(self):
|
| 90 |
+
self.conversation_history = []
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
print("Loading Audrey Tang chatbot...")
|
| 95 |
+
bot = AudreyChatbot()
|
| 96 |
+
print("Ready. Type 'quit' to exit, 'reset' to clear history.\n")
|
| 97 |
+
|
| 98 |
+
while True:
|
| 99 |
+
user_input = input("You: ").strip()
|
| 100 |
+
if user_input.lower() == "quit":
|
| 101 |
+
break
|
| 102 |
+
if user_input.lower() == "reset":
|
| 103 |
+
bot.reset()
|
| 104 |
+
print("Conversation reset.\n")
|
| 105 |
+
continue
|
| 106 |
+
if not user_input:
|
| 107 |
+
continue
|
| 108 |
+
|
| 109 |
+
response = bot.chat(user_input)
|
| 110 |
+
print(f"\nAudrey: {response}\n")
|
spark-scripts/finetune.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Fine-tune TAIDE 12B on Audrey Tang transcripts using SFT.
|
| 3 |
+
|
| 4 |
+
On DGX Spark (128GB unified memory), this runs full-parameter SFT
|
| 5 |
+
on a 12B model. For memory safety, we use gradient checkpointing
|
| 6 |
+
and bf16 mixed precision.
|
| 7 |
+
|
| 8 |
+
Expected time: ~4-8 hours for 2 epochs on 56K training examples.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from datasets import load_dataset
|
| 13 |
+
from transformers import (
|
| 14 |
+
AutoTokenizer,
|
| 15 |
+
AutoModelForCausalLM,
|
| 16 |
+
TrainingArguments,
|
| 17 |
+
)
|
| 18 |
+
from trl import SFTTrainer, SFTConfig
|
| 19 |
+
|
| 20 |
+
# Model and data paths
|
| 21 |
+
MODEL_PATH = "./models/taide-12b"
|
| 22 |
+
TRAIN_PATH = "./training_data/train.jsonl"
|
| 23 |
+
EVAL_PATH = "./training_data/eval.jsonl"
|
| 24 |
+
OUTPUT_DIR = "./models/taide-12b-audrey"
|
| 25 |
+
|
| 26 |
+
# Load tokenizer
|
| 27 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
|
| 28 |
+
if tokenizer.pad_token is None:
|
| 29 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 30 |
+
|
| 31 |
+
# Load model — full precision on DGX Spark's 128GB unified memory
|
| 32 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 33 |
+
MODEL_PATH,
|
| 34 |
+
torch_dtype=torch.bfloat16,
|
| 35 |
+
device_map="auto",
|
| 36 |
+
attn_implementation="sdpa", # Flash attention via SDPA
|
| 37 |
+
)
|
| 38 |
+
model.config.use_cache = False # Required for gradient checkpointing
|
| 39 |
+
|
| 40 |
+
# Load datasets
|
| 41 |
+
train_dataset = load_dataset("json", data_files=TRAIN_PATH, split="train")
|
| 42 |
+
eval_dataset = load_dataset("json", data_files=EVAL_PATH, split="train")
|
| 43 |
+
|
| 44 |
+
print(f"Train: {len(train_dataset)}, Eval: {len(eval_dataset)}")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def format_chat(example):
|
| 48 |
+
"""Format messages into the Gemma chat template."""
|
| 49 |
+
return tokenizer.apply_chat_template(
|
| 50 |
+
example["messages"],
|
| 51 |
+
tokenize=False,
|
| 52 |
+
add_generation_prompt=False,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# Training config
|
| 57 |
+
training_args = SFTConfig(
|
| 58 |
+
output_dir=OUTPUT_DIR,
|
| 59 |
+
num_train_epochs=2,
|
| 60 |
+
per_device_train_batch_size=2,
|
| 61 |
+
per_device_eval_batch_size=2,
|
| 62 |
+
gradient_accumulation_steps=8, # effective batch size = 16
|
| 63 |
+
gradient_checkpointing=True,
|
| 64 |
+
gradient_checkpointing_kwargs={"use_reentrant": False},
|
| 65 |
+
learning_rate=2e-5,
|
| 66 |
+
lr_scheduler_type="cosine",
|
| 67 |
+
warmup_ratio=0.05,
|
| 68 |
+
weight_decay=0.01,
|
| 69 |
+
bf16=True,
|
| 70 |
+
logging_steps=10,
|
| 71 |
+
eval_strategy="steps",
|
| 72 |
+
eval_steps=500,
|
| 73 |
+
save_strategy="steps",
|
| 74 |
+
save_steps=500,
|
| 75 |
+
save_total_limit=3,
|
| 76 |
+
max_seq_length=4096,
|
| 77 |
+
packing=True, # Pack short examples together for efficiency
|
| 78 |
+
dataset_text_field="text",
|
| 79 |
+
report_to="none",
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
# Preprocess: apply chat template
|
| 83 |
+
train_dataset = train_dataset.map(
|
| 84 |
+
lambda x: {"text": format_chat(x)}, remove_columns=train_dataset.column_names
|
| 85 |
+
)
|
| 86 |
+
eval_dataset = eval_dataset.map(
|
| 87 |
+
lambda x: {"text": format_chat(x)}, remove_columns=eval_dataset.column_names
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
trainer = SFTTrainer(
|
| 91 |
+
model=model,
|
| 92 |
+
args=training_args,
|
| 93 |
+
train_dataset=train_dataset,
|
| 94 |
+
eval_dataset=eval_dataset,
|
| 95 |
+
processing_class=tokenizer,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
print("Starting training...")
|
| 99 |
+
trainer.train()
|
| 100 |
+
|
| 101 |
+
# Save final model
|
| 102 |
+
trainer.save_model(OUTPUT_DIR)
|
| 103 |
+
tokenizer.save_pretrained(OUTPUT_DIR)
|
| 104 |
+
print(f"Model saved to {OUTPUT_DIR}")
|
spark-scripts/finetune_qlora.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""QLoRA fine-tuning — lighter alternative. ~2 hours for 2 epochs."""
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
| 7 |
+
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
|
| 8 |
+
from trl import SFTTrainer, SFTConfig
|
| 9 |
+
|
| 10 |
+
MODEL_PATH = "./models/taide-12b"
|
| 11 |
+
TRAIN_PATH = "./training_data/train.jsonl"
|
| 12 |
+
EVAL_PATH = "./training_data/eval.jsonl"
|
| 13 |
+
OUTPUT_DIR = "./models/taide-12b-audrey-qlora"
|
| 14 |
+
|
| 15 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
|
| 16 |
+
if tokenizer.pad_token is None:
|
| 17 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 18 |
+
|
| 19 |
+
# 4-bit quantized loading
|
| 20 |
+
bnb_config = BitsAndBytesConfig(
|
| 21 |
+
load_in_4bit=True,
|
| 22 |
+
bnb_4bit_quant_type="nf4",
|
| 23 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 24 |
+
bnb_4bit_use_double_quant=True,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 28 |
+
MODEL_PATH,
|
| 29 |
+
quantization_config=bnb_config,
|
| 30 |
+
device_map="auto",
|
| 31 |
+
attn_implementation="sdpa",
|
| 32 |
+
)
|
| 33 |
+
model = prepare_model_for_kbit_training(model)
|
| 34 |
+
|
| 35 |
+
# LoRA config — target all linear layers
|
| 36 |
+
lora_config = LoraConfig(
|
| 37 |
+
r=64,
|
| 38 |
+
lora_alpha=128,
|
| 39 |
+
target_modules="all-linear",
|
| 40 |
+
lora_dropout=0.05,
|
| 41 |
+
bias="none",
|
| 42 |
+
task_type="CAUSAL_LM",
|
| 43 |
+
)
|
| 44 |
+
model = get_peft_model(model, lora_config)
|
| 45 |
+
model.print_trainable_parameters()
|
| 46 |
+
|
| 47 |
+
train_dataset = load_dataset("json", data_files=TRAIN_PATH, split="train")
|
| 48 |
+
eval_dataset = load_dataset("json", data_files=EVAL_PATH, split="train")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def format_chat(example):
|
| 52 |
+
return tokenizer.apply_chat_template(
|
| 53 |
+
example["messages"], tokenize=False, add_generation_prompt=False
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
train_dataset = train_dataset.map(
|
| 58 |
+
lambda x: {"text": format_chat(x)}, remove_columns=train_dataset.column_names
|
| 59 |
+
)
|
| 60 |
+
eval_dataset = eval_dataset.map(
|
| 61 |
+
lambda x: {"text": format_chat(x)}, remove_columns=eval_dataset.column_names
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
training_args = SFTConfig(
|
| 65 |
+
output_dir=OUTPUT_DIR,
|
| 66 |
+
num_train_epochs=2,
|
| 67 |
+
per_device_train_batch_size=4,
|
| 68 |
+
per_device_eval_batch_size=4,
|
| 69 |
+
gradient_accumulation_steps=4, # effective batch size = 16
|
| 70 |
+
gradient_checkpointing=True,
|
| 71 |
+
gradient_checkpointing_kwargs={"use_reentrant": False},
|
| 72 |
+
learning_rate=2e-4, # Higher LR for LoRA
|
| 73 |
+
lr_scheduler_type="cosine",
|
| 74 |
+
warmup_ratio=0.05,
|
| 75 |
+
weight_decay=0.01,
|
| 76 |
+
bf16=True,
|
| 77 |
+
logging_steps=10,
|
| 78 |
+
eval_strategy="steps",
|
| 79 |
+
eval_steps=500,
|
| 80 |
+
save_strategy="steps",
|
| 81 |
+
save_steps=500,
|
| 82 |
+
save_total_limit=3,
|
| 83 |
+
max_seq_length=4096,
|
| 84 |
+
packing=True,
|
| 85 |
+
dataset_text_field="text",
|
| 86 |
+
report_to="none",
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
trainer = SFTTrainer(
|
| 90 |
+
model=model,
|
| 91 |
+
args=training_args,
|
| 92 |
+
train_dataset=train_dataset,
|
| 93 |
+
eval_dataset=eval_dataset,
|
| 94 |
+
processing_class=tokenizer,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
print("Starting QLoRA training...")
|
| 98 |
+
trainer.train()
|
| 99 |
+
trainer.save_model(OUTPUT_DIR)
|
| 100 |
+
tokenizer.save_pretrained(OUTPUT_DIR)
|
| 101 |
+
|
| 102 |
+
# Merge LoRA weights into base model for easier deployment
|
| 103 |
+
print("Merging LoRA weights...")
|
| 104 |
+
from peft import AutoPeftModelForCausalLM
|
| 105 |
+
|
| 106 |
+
merged_model = AutoPeftModelForCausalLM.from_pretrained(
|
| 107 |
+
OUTPUT_DIR, device_map="auto", torch_dtype=torch.bfloat16
|
| 108 |
+
)
|
| 109 |
+
merged_model = merged_model.merge_and_unload()
|
| 110 |
+
merged_model.save_pretrained("./models/taide-12b-audrey-merged")
|
| 111 |
+
tokenizer.save_pretrained("./models/taide-12b-audrey-merged")
|
| 112 |
+
print("Merged model saved to ./models/taide-12b-audrey-merged")
|
spark-scripts/prepare_sft_data.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Convert SFT pairs to the chat template format expected by Gemma/TAIDE."""
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from datasets import Dataset
|
| 7 |
+
|
| 8 |
+
SFT_PATH = Path("dataset/data/sft_pairs.jsonl")
|
| 9 |
+
OUTPUT_DIR = Path("training_data")
|
| 10 |
+
OUTPUT_DIR.mkdir(exist_ok=True)
|
| 11 |
+
|
| 12 |
+
pairs = []
|
| 13 |
+
with open(SFT_PATH) as f:
|
| 14 |
+
for line in f:
|
| 15 |
+
pairs.append(json.loads(line))
|
| 16 |
+
|
| 17 |
+
print(f"Loaded {len(pairs)} SFT pairs")
|
| 18 |
+
|
| 19 |
+
# Convert to chat format for Gemma-3 / TAIDE
|
| 20 |
+
# Format: list of {"role": "user"/"model", "content": "..."}
|
| 21 |
+
formatted = []
|
| 22 |
+
for p in pairs:
|
| 23 |
+
# System context about who this is
|
| 24 |
+
system_prefix = (
|
| 25 |
+
"You are Audrey Tang (唐鳳), Taiwan's Cyber Ambassador and "
|
| 26 |
+
"2025 Right Livelihood Laureate. Respond based on your actual "
|
| 27 |
+
"public statements and positions. Be grounded, specific, and "
|
| 28 |
+
"cite real examples from your experience in digital democracy, "
|
| 29 |
+
"civic tech, and open government."
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# The instruction contains the conversational context
|
| 33 |
+
user_content = p["instruction"]
|
| 34 |
+
if not user_content.strip():
|
| 35 |
+
user_content = p.get("title", "Please share your thoughts.")
|
| 36 |
+
|
| 37 |
+
formatted.append({
|
| 38 |
+
"messages": [
|
| 39 |
+
{"role": "user", "content": f"{system_prefix}\n\n{user_content}"},
|
| 40 |
+
{"role": "model", "content": p["response"]},
|
| 41 |
+
],
|
| 42 |
+
"language": p["language"],
|
| 43 |
+
"date": p["date"],
|
| 44 |
+
"source_file": p["source_file"],
|
| 45 |
+
})
|
| 46 |
+
|
| 47 |
+
# Split 95/5 train/eval
|
| 48 |
+
import random
|
| 49 |
+
random.seed(42)
|
| 50 |
+
random.shuffle(formatted)
|
| 51 |
+
split_idx = int(len(formatted) * 0.95)
|
| 52 |
+
train_data = formatted[:split_idx]
|
| 53 |
+
eval_data = formatted[split_idx:]
|
| 54 |
+
|
| 55 |
+
# Save as JSONL
|
| 56 |
+
for name, data in [("train", train_data), ("eval", eval_data)]:
|
| 57 |
+
path = OUTPUT_DIR / f"{name}.jsonl"
|
| 58 |
+
with open(path, "w") as f:
|
| 59 |
+
for item in data:
|
| 60 |
+
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 61 |
+
print(f"Saved {len(data)} examples to {path}")
|
spark-scripts/retriever.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""RAG retrieval: query → top-K grounded passages with reranking."""
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import faiss
|
| 6 |
+
import pickle
|
| 7 |
+
import numpy as np
|
| 8 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class AudreyRetriever:
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
index_dir: str = "./index",
|
| 16 |
+
embedder_path: str = "./models/bge-m3",
|
| 17 |
+
reranker_path: str = "./models/bge-reranker",
|
| 18 |
+
top_k_retrieve: int = 20,
|
| 19 |
+
top_k_rerank: int = 5,
|
| 20 |
+
):
|
| 21 |
+
self.top_k_retrieve = top_k_retrieve
|
| 22 |
+
self.top_k_rerank = top_k_rerank
|
| 23 |
+
|
| 24 |
+
# Load FAISS index
|
| 25 |
+
self.index = faiss.read_index(str(Path(index_dir) / "chunks.faiss"))
|
| 26 |
+
with open(Path(index_dir) / "chunks_meta.pkl", "rb") as f:
|
| 27 |
+
self.chunks = pickle.load(f)
|
| 28 |
+
with open(Path(index_dir) / "lexicon.pkl", "rb") as f:
|
| 29 |
+
self.lexicon = pickle.load(f)
|
| 30 |
+
|
| 31 |
+
# Load models
|
| 32 |
+
self.embedder = SentenceTransformer(embedder_path)
|
| 33 |
+
self.reranker = CrossEncoder(reranker_path)
|
| 34 |
+
|
| 35 |
+
# Build lexicon lookup
|
| 36 |
+
self.lexicon_en = {t["en"].lower(): t for t in self.lexicon}
|
| 37 |
+
self.lexicon_zh = {t["zh"]: t for t in self.lexicon}
|
| 38 |
+
|
| 39 |
+
def retrieve(self, query: str) -> dict:
|
| 40 |
+
"""Retrieve and rerank passages for a query."""
|
| 41 |
+
# Embed query
|
| 42 |
+
q_emb = self.embedder.encode(
|
| 43 |
+
[query], normalize_embeddings=True
|
| 44 |
+
).astype(np.float32)
|
| 45 |
+
|
| 46 |
+
# FAISS search
|
| 47 |
+
scores, indices = self.index.search(q_emb, self.top_k_retrieve)
|
| 48 |
+
candidates = [
|
| 49 |
+
(self.chunks[i], float(scores[0][j]))
|
| 50 |
+
for j, i in enumerate(indices[0])
|
| 51 |
+
if i < len(self.chunks)
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
# Rerank with cross-encoder
|
| 55 |
+
if candidates:
|
| 56 |
+
pairs = [(query, c[0]["text"]) for c in candidates]
|
| 57 |
+
rerank_scores = self.reranker.predict(pairs)
|
| 58 |
+
ranked = sorted(
|
| 59 |
+
zip(candidates, rerank_scores),
|
| 60 |
+
key=lambda x: x[1],
|
| 61 |
+
reverse=True,
|
| 62 |
+
)
|
| 63 |
+
top_chunks = [c[0] for c, _ in ranked[: self.top_k_rerank]]
|
| 64 |
+
else:
|
| 65 |
+
top_chunks = []
|
| 66 |
+
|
| 67 |
+
# Find relevant lexicon terms
|
| 68 |
+
query_lower = query.lower()
|
| 69 |
+
relevant_terms = []
|
| 70 |
+
for term in self.lexicon:
|
| 71 |
+
if term["en"].lower() in query_lower or term["zh"] in query:
|
| 72 |
+
relevant_terms.append(term)
|
| 73 |
+
|
| 74 |
+
return {
|
| 75 |
+
"passages": top_chunks,
|
| 76 |
+
"lexicon_terms": relevant_terms[:10],
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
def format_context(self, result: dict) -> str:
|
| 80 |
+
"""Format retrieval results as context for the LLM."""
|
| 81 |
+
parts = []
|
| 82 |
+
|
| 83 |
+
for i, (chunk, _score) in enumerate(result["passages"]):
|
| 84 |
+
parts.append(
|
| 85 |
+
f"[Source {i+1}: {chunk['date']} — {chunk['title']}]\n"
|
| 86 |
+
f"{chunk['text']}"
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
if result["lexicon_terms"]:
|
| 90 |
+
terms = ", ".join(
|
| 91 |
+
f"{t['en']} = {t['zh']}" for t in result["lexicon_terms"]
|
| 92 |
+
)
|
| 93 |
+
parts.append(f"\n[Terminology: {terms}]")
|
| 94 |
+
|
| 95 |
+
return "\n\n".join(parts)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
# Quick test
|
| 100 |
+
retriever = AudreyRetriever()
|
| 101 |
+
|
| 102 |
+
test_queries = [
|
| 103 |
+
"How did Taiwan handle COVID-19 mask distribution?",
|
| 104 |
+
"什麼是數位民主?",
|
| 105 |
+
"What is your P(Doom)?",
|
| 106 |
+
"Tell me about vTaiwan",
|
| 107 |
+
]
|
| 108 |
+
|
| 109 |
+
for q in test_queries:
|
| 110 |
+
print(f"\n{'='*60}")
|
| 111 |
+
print(f"Query: {q}")
|
| 112 |
+
result = retriever.retrieve(q)
|
| 113 |
+
print(f"Top {len(result['passages'])} passages:")
|
| 114 |
+
for i, (chunk, score) in enumerate(result["passages"]):
|
| 115 |
+
print(f" {i+1}. [{chunk['date']}] {chunk['title']}")
|
| 116 |
+
print(f" {chunk['text'][:100]}...")
|
| 117 |
+
if result["lexicon_terms"]:
|
| 118 |
+
print(f"Lexicon: {[t['en'] for t in result['lexicon_terms']]}")
|