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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Download and prepare QA training data for H4 RAG.
|
| 3 |
+
|
| 4 |
+
Uses a simple extractive QA format:
|
| 5 |
+
- Input: [context] | [question] |
|
| 6 |
+
- Target: [answer]
|
| 7 |
+
|
| 8 |
+
Data sources (in order of preference):
|
| 9 |
+
1. SQuAD-style QA pairs generated from the sample documents
|
| 10 |
+
2. Downloaded SQuAD 2.0 dev set (small, freely available)
|
| 11 |
+
|
| 12 |
+
For CPU training with 2-minute budget, we need small data that
|
| 13 |
+
trains fast. The sample doc QA pairs are ideal for proving the
|
| 14 |
+
pipeline works; SQuAD provides real benchmark numbers.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import random
|
| 21 |
+
from typing import List, Tuple, Dict
|
| 22 |
+
|
| 23 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def generate_sample_qa() -> List[Dict]:
|
| 27 |
+
"""
|
| 28 |
+
Generate QA pairs from the sample documents.
|
| 29 |
+
These are hand-crafted to match the sample_docs content.
|
| 30 |
+
The model's job: learn to extract the answer from the context.
|
| 31 |
+
"""
|
| 32 |
+
qa_pairs = [
|
| 33 |
+
# golden_ratio.txt
|
| 34 |
+
{"context": "The golden ratio, often denoted by the Greek letter phi, is a special number approximately equal to 1.618.",
|
| 35 |
+
"question": "What is the golden ratio approximately equal to?",
|
| 36 |
+
"answer": "1.618"},
|
| 37 |
+
{"context": "Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities.",
|
| 38 |
+
"question": "When are two quantities in the golden ratio?",
|
| 39 |
+
"answer": "if their ratio is the same as the ratio of their sum to the larger"},
|
| 40 |
+
{"context": "The golden ratio is closely related to the Fibonacci sequence. As Fibonacci numbers increase, the ratio of consecutive Fibonacci numbers approaches the golden ratio.",
|
| 41 |
+
"question": "How is the golden ratio related to Fibonacci numbers?",
|
| 42 |
+
"answer": "the ratio of consecutive Fibonacci numbers approaches the golden ratio"},
|
| 43 |
+
{"context": "The golden ratio appears in the geometry of pentagons and in the arrangement of leaves and petals in many plants.",
|
| 44 |
+
"question": "Where does the golden ratio appear in nature?",
|
| 45 |
+
"answer": "in the arrangement of leaves and petals in many plants"},
|
| 46 |
+
|
| 47 |
+
# polytopes.txt
|
| 48 |
+
{"context": "The 600-cell is a regular 4-polytope with 120 vertices, 720 edges, 1200 triangular faces, and 600 tetrahedral cells.",
|
| 49 |
+
"question": "How many vertices does the 600-cell have?",
|
| 50 |
+
"answer": "120"},
|
| 51 |
+
{"context": "The 600-cell has the H4 symmetry group, which contains 14400 elements. This is the largest finite reflection group in four dimensions.",
|
| 52 |
+
"question": "How many elements does the H4 symmetry group contain?",
|
| 53 |
+
"answer": "14400"},
|
| 54 |
+
{"context": "The 600-cell is dual to the 120-cell, which has 600 vertices.",
|
| 55 |
+
"question": "What is the 600-cell dual to?",
|
| 56 |
+
"answer": "the 120-cell"},
|
| 57 |
+
{"context": "A polytope is a geometric object with flat sides in any number of dimensions.",
|
| 58 |
+
"question": "What is a polytope?",
|
| 59 |
+
"answer": "a geometric object with flat sides in any number of dimensions"},
|
| 60 |
+
|
| 61 |
+
# e8_lattice.txt
|
| 62 |
+
{"context": "The E8 lattice is the densest sphere packing in eight dimensions. This was proven by Maryna Viazovska in 2016.",
|
| 63 |
+
"question": "Who proved E8 is the densest sphere packing?",
|
| 64 |
+
"answer": "Maryna Viazovska"},
|
| 65 |
+
{"context": "The E8 lattice has a kissing number of 240, meaning each sphere touches exactly 240 others.",
|
| 66 |
+
"question": "What is the kissing number of E8?",
|
| 67 |
+
"answer": "240"},
|
| 68 |
+
{"context": "The Coxeter element of E8 has eigenvalues that include cosine of pi over five, which equals phi over two.",
|
| 69 |
+
"question": "What eigenvalue connects E8 to the golden ratio?",
|
| 70 |
+
"answer": "cosine of pi over five, which equals phi over two"},
|
| 71 |
+
{"context": "When the 240 roots of E8 are projected along these eigenspaces, they map to the vertices of H4 polytopes.",
|
| 72 |
+
"question": "What happens when E8 roots are projected along the eigenspaces?",
|
| 73 |
+
"answer": "they map to the vertices of H4 polytopes"},
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
return qa_pairs
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def prepare_training_data(
|
| 80 |
+
qa_pairs: List[Dict],
|
| 81 |
+
val_fraction: float = 0.2,
|
| 82 |
+
) -> Tuple[List[Dict], List[Dict]]:
|
| 83 |
+
"""Split QA pairs into train and validation sets."""
|
| 84 |
+
random.seed(42)
|
| 85 |
+
pairs = list(qa_pairs)
|
| 86 |
+
random.shuffle(pairs)
|
| 87 |
+
n_val = max(1, int(len(pairs) * val_fraction))
|
| 88 |
+
return pairs[n_val:], pairs[:n_val]
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def format_qa_for_training(qa_pair: Dict, sep: str = " | ") -> Tuple[str, str]:
|
| 92 |
+
"""
|
| 93 |
+
Format a QA pair for character-level training.
|
| 94 |
+
|
| 95 |
+
Input: [context] | [question] |
|
| 96 |
+
Target: [answer]
|
| 97 |
+
|
| 98 |
+
The model learns to generate the answer given context + question.
|
| 99 |
+
"""
|
| 100 |
+
input_text = qa_pair['context'] + sep + qa_pair['question'] + sep
|
| 101 |
+
target_text = qa_pair['answer']
|
| 102 |
+
return input_text, target_text
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def download_squad_dev():
|
| 106 |
+
"""
|
| 107 |
+
Download SQuAD 2.0 dev set for real benchmark evaluation.
|
| 108 |
+
Returns list of QA dicts with context/question/answer.
|
| 109 |
+
"""
|
| 110 |
+
import urllib.request
|
| 111 |
+
|
| 112 |
+
cache_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'data')
|
| 113 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 114 |
+
cache_path = os.path.join(cache_dir, 'squad_dev.json')
|
| 115 |
+
|
| 116 |
+
if not os.path.exists(cache_path):
|
| 117 |
+
url = "https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v2.0.json"
|
| 118 |
+
print(f"Downloading SQuAD 2.0 dev set...")
|
| 119 |
+
try:
|
| 120 |
+
urllib.request.urlretrieve(url, cache_path)
|
| 121 |
+
print(f"Saved to {cache_path}")
|
| 122 |
+
except Exception as e:
|
| 123 |
+
print(f"Download failed: {e}")
|
| 124 |
+
return []
|
| 125 |
+
|
| 126 |
+
with open(cache_path, 'r', encoding='utf-8') as f:
|
| 127 |
+
data = json.load(f)
|
| 128 |
+
|
| 129 |
+
qa_pairs = []
|
| 130 |
+
for article in data['data']:
|
| 131 |
+
for paragraph in article['paragraphs']:
|
| 132 |
+
context = paragraph['context']
|
| 133 |
+
for qa in paragraph['qas']:
|
| 134 |
+
if qa.get('is_impossible', False):
|
| 135 |
+
continue
|
| 136 |
+
if qa['answers']:
|
| 137 |
+
answer = qa['answers'][0]['text']
|
| 138 |
+
qa_pairs.append({
|
| 139 |
+
'context': context[:500], # truncate long contexts
|
| 140 |
+
'question': qa['question'],
|
| 141 |
+
'answer': answer,
|
| 142 |
+
})
|
| 143 |
+
|
| 144 |
+
return qa_pairs
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
if __name__ == '__main__':
|
| 148 |
+
print("Generating sample QA pairs...")
|
| 149 |
+
pairs = generate_sample_qa()
|
| 150 |
+
train, val = prepare_training_data(pairs)
|
| 151 |
+
print(f"Sample QA: {len(train)} train, {len(val)} val")
|
| 152 |
+
|
| 153 |
+
for p in pairs[:3]:
|
| 154 |
+
inp, tgt = format_qa_for_training(p)
|
| 155 |
+
print(f"\nInput: {inp[:80]}...")
|
| 156 |
+
print(f"Target: {tgt}")
|
| 157 |
+
|
| 158 |
+
print("\nAttempting SQuAD download...")
|
| 159 |
+
squad = download_squad_dev()
|
| 160 |
+
if squad:
|
| 161 |
+
print(f"SQuAD 2.0 dev: {len(squad)} answerable questions")
|
| 162 |
+
else:
|
| 163 |
+
print("SQuAD not available (offline?). Using sample QA only.")
|