File size: 10,996 Bytes
5c43f61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
"""

Science benchmarks for Vortex model.

Evaluates performance across 7 science domains.

"""

import torch
from typing import Dict, List, Tuple
from dataclasses import dataclass


@dataclass
class BenchmarkResult:
    """Results from a benchmark."""
    domain: str
    accuracy: float
    total_questions: int
    correct_answers: int
    details: List[Dict]


class ScienceBenchmark:
    """

    Base class for science benchmarks.

    """

    def __init__(self, name: str, domain: str):
        self.name = name
        self.domain = domain

    def load_questions(self) -> List[Dict]:
        """Load benchmark questions."""
        raise NotImplementedError

    def evaluate(

        self,

        model,

        tokenizer,

        device: torch.device,

        max_samples: int = 100,

    ) -> BenchmarkResult:
        """

        Evaluate model on benchmark.



        Args:

            model: Vortex model

            tokenizer: Tokenizer

            device: Torch device

            max_samples: Maximum samples to evaluate



        Returns:

            BenchmarkResult

        """
        questions = self.load_questions()[:max_samples]
        correct = 0

        details = []
        for q in questions:
            # Format prompt
            prompt = self.format_prompt(q)
            # Tokenize
            inputs = tokenizer(prompt, return_tensors="pt").to(device)

            # Generate answer
            with torch.no_grad():
                outputs = model.generate(
                    **inputs,
                    max_new_tokens=50,
                    temperature=0.0,  # Greedy
                    do_sample=False,
                )

            # Decode
            generated = tokenizer.decode(outputs[0], skip_special_tokens=True)
            answer = self.extract_answer(generated)

            # Check correctness
            is_correct = self.check_answer(answer, q["answer"])
            if is_correct:
                correct += 1

            details.append({
                "question": q["question"],
                "expected": q["answer"],
                "generated": answer,
                "correct": is_correct,
            })

        accuracy = correct / len(questions) if questions else 0.0
        return BenchmarkResult(
            domain=self.domain,
            accuracy=accuracy,
            total_questions=len(questions),
            correct_answers=correct,
            details=details,
        )

    def format_prompt(self, question: Dict) -> str:
        """Format question into prompt."""
        raise NotImplementedError

    def extract_answer(self, text: str) -> str:
        """Extract answer from generated text."""
        raise NotImplementedError

    def check_answer(self, predicted: str, expected: str) -> bool:
        """Check if predicted answer matches expected."""
        raise NotImplementedError


class PhysicsBenchmark(ScienceBenchmark):
    """Physics benchmark (Feynman Questions style)."""

    def __init__(self):
        super().__init__("physics_benchmark", "physics")

    def load_questions(self) -> List[Dict]:
        # Placeholder - would load from dataset
        return [
            {
                "question": "What is the formula for kinetic energy?",
                "answer": "KE = 1/2 mv^2",
                "type": "formula",
            },
            {
                "question": "Explain Newton's first law of motion.",
                "answer": "An object at rest stays at rest unless acted upon by a force.",
                "type": "conceptual",
            },
        ]

    def format_prompt(self, question: Dict) -> str:
        return f"Question: {question['question']}\nAnswer:"

    def extract_answer(self, text: str) -> str:
        # Extract after "Answer:"
        if "Answer:" in text:
            return text.split("Answer:")[-1].strip()
        return text.strip()

    def check_answer(self, predicted: str, expected: str) -> bool:
        # Simple string match (would use more sophisticated in practice)
        pred_lower = predicted.lower()
        exp_lower = expected.lower()
        return exp_lower in pred_lower or pred_lower in exp_lower


class MathBenchmark(ScienceBenchmark):
    """Math benchmark (MATH dataset style)."""

    def __init__(self):
        super().__init__("math_benchmark", "math")

    def load_questions(self) -> List[Dict]:
        return [
            {
                "question": "Solve for x: 2x + 5 = 15",
                "answer": "x = 5",
                "type": "algebra",
            },
            {
                "question": "What is the derivative of x^2?",
                "answer": "2x",
                "type": "calculus",
            },
        ]

    def format_prompt(self, question: Dict) -> str:
        return f"Problem: {question['question']}\nSolution:"

    def extract_answer(self, text: str) -> str:
        if "Solution:" in text:
            return text.split("Solution:")[-1].strip()
        return text.strip()

    def check_answer(self, predicted: str, expected: str) -> bool:
        # Normalize whitespace and case
        pred = " ".join(predicted.lower().split())
        exp = " ".join(expected.lower().split())
        return pred == exp


class ChemistryBenchmark(ScienceBenchmark):
    """Chemistry benchmark."""

    def __init__(self):
        super().__init__("chemistry_benchmark", "chemistry")

    def load_questions(self) -> List[Dict]:
        return [
            {
                "question": "What is the chemical formula for water?",
                "answer": "H2O",
                "type": "factual",
            },
            {
                "question": "How many protons does carbon have?",
                "answer": "6",
                "type": "factual",
            },
        ]

    def format_prompt(self, question: Dict) -> str:
        return f"Chemistry question: {question['question']}\nAnswer:"

    def extract_answer(self, text: str) -> str:
        if "Answer:" in text:
            return text.split("Answer:")[-1].strip()
        return text.strip()

    def check_answer(self, predicted: str, expected: str) -> bool:
        pred = predicted.strip().lower()
        exp = expected.strip().lower()
        return exp in pred


class BiologyBenchmark(ScienceBenchmark):
    """Biology benchmark."""

    def __init__(self):
        super().__init__("biology_benchmark", "biology")

    def load_questions(self) -> List[Dict]:
        return [
            {
                "question": "What is the powerhouse of the cell?",
                "answer": "mitochondria",
                "type": "factual",
            },
            {
                "question": "What molecule carries genetic information?",
                "answer": "DNA",
                "type": "factual",
            },
        ]

    def format_prompt(self, question: Dict) -> str:
        return f"Biology: {question['question']}\nAnswer:"

    def extract_answer(self, text: str) -> str:
        if "Answer:" in text:
            return text.split("Answer:")[-1].strip()
        return text.strip()

    def check_answer(self, predicted: str, expected: str) -> bool:
        pred = predicted.strip().lower()
        exp = expected.strip().lower()
        return exp in pred


# Placeholder for other domains
class EarthScienceBenchmark(ScienceBenchmark):
    def __init__(self):
        super().__init__("earth_science_benchmark", "earth")

    def load_questions(self) -> List[Dict]:
        return []

    def format_prompt(self, question: Dict) -> str:
        return f"Earth Science: {question['question']}\nAnswer:"

    def extract_answer(self, text: str) -> str:
        return text.strip()

    def check_answer(self, predicted: str, expected: str) -> bool:
        return predicted.strip().lower() == expected.strip().lower()


class SpaceScienceBenchmark(ScienceBenchmark):
    def __init__(self):
        super().__init__("space_science_benchmark", "space")

    def load_questions(self) -> List[Dict]:
        return []

    def format_prompt(self, question: Dict) -> str:
        return f"Space Science: {question['question']}\nAnswer:"

    def extract_answer(self, text: str) -> str:
        return text.strip()

    def check_answer(self, predicted: str, expected: str) -> bool:
        return predicted.strip().lower() == expected.strip().lower()


class ZoologyBenchmark(ScienceBenchmark):
    def __init__(self):
        super().__init__("zoology_benchmark", "zoology")

    def load_questions(self) -> List[Dict]:
        return []

    def format_prompt(self, question: Dict) -> str:
        return f"Zoology: {question['question']}\nAnswer:"

    def extract_answer(self, text: str) -> str:
        return text.strip()

    def check_answer(self, predicted: str, expected: str) -> bool:
        return predicted.strip().lower() == expected.strip().lower()


def run_all_benchmarks(

    model,

    tokenizer,

    device: torch.device,

    max_samples_per_domain: int = 50,

) -> Dict[str, BenchmarkResult]:
    """

    Run all benchmarks and return results.



    Args:

        model: Vortex model

        tokenizer: Tokenizer

        device: Torch device

        max_samples_per_domain: Max samples per domain



    Returns:

        Dictionary mapping domain to results

    """
    benchmarks = [
        PhysicsBenchmark(),
        MathBenchmark(),
        ChemistryBenchmark(),
        BiologyBenchmark(),
        EarthScienceBenchmark(),
        SpaceScienceBenchmark(),
        ZoologyBenchmark(),
    ]

    results = {}
    for bench in benchmarks:
        print(f"Running {bench.name}...")
        result = bench.evaluate(model, tokenizer, device, max_samples=max_samples_per_domain)
        results[bench.domain] = result
        print(f"  Accuracy: {result.accuracy:.2%} ({result.correct_answers}/{result.total_questions})")

    return results


def print_summary(results: Dict[str, BenchmarkResult]):
    """Print summary of benchmark results."""
    print("\n" + "="*60)
    print("BENCHMARK RESULTS")
    print("="*60)

    for domain, result in results.items():
        print(f"{domain:15} {result.accuracy:6.2%}  ({result.correct_answers}/{result.total_questions})")

    # Overall average
    all_accuracies = [r.accuracy for r in results.values() if r.total_questions > 0]
    if all_accuracies:
        avg = sum(all_accuracies) / len(all_accuracies)
        print(f"{'OVERALL':15} {avg:6.2%}")
    print("="*60)


if __name__ == "__main__":
    # Quick test
    print("This script benchmarks the model across science domains.")
    print("To run full benchmarks, integrate with a trained model.")