File size: 12,959 Bytes
4655dd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import re
import time
import uuid
import json
import random
from datetime import datetime
from typing import List, Dict, Any
from .schemas import BenchmarkTask, BenchmarkRunRequest, BenchmarkResult, BenchmarkReport
from .model_manager import model_manager
from .telemetry import telemetry_service
from .schemas import GenerateRequest

# Predefined suites — 4 categories as per spec
BENCHMARK_SUITES: Dict[str, List[BenchmarkTask]] = {
    "reasoning": [
        BenchmarkTask(
            id="reason-1",
            name="الاستدلال المنطقي - حسابي",
            category="reasoning",
            prompt="إذا كان لدينا 5 تفاحات وأخذ أحمد 2 ثم اشترى 4 تفاحات إضافية، كم تفاحة أصبح لديه؟ أجب برقم فقط.",
            expected="7",
            expected_regex=r"\b7\b",
            max_tokens=64
        ),
        BenchmarkTask(
            id="reason-2",
            name="الاستدلال - متتالية",
            category="reasoning",
            prompt="ما هو الرقم التالي في المتتالية: 2, 4, 8, 16, ... ؟ أجب برقم فقط.",
            expected="32",
            expected_regex=r"\b32\b",
            max_tokens=64
        ),
        BenchmarkTask(
            id="reason-3",
            name="Reasoning - Logic Puzzle",
            category="reasoning",
            prompt="All cats are animals. Whiskers is a cat. Is Whiskers an animal? Answer Yes or No.",
            expected="Yes",
            expected_regex=r"(?i)\byes\b",
            max_tokens=64
        ),
        BenchmarkTask(
            id="reason-4",
            name="الاستدلال - مقارنة",
            category="reasoning",
            prompt="أيهما أكبر: 3/4 أم 2/3؟ أجب بالكسر الأكبر فقط.",
            expected="3/4",
            expected_regex=r"3\s*/\s*4",
            max_tokens=64
        ),
    ],
    "coding": [
        BenchmarkTask(
            id="code-1",
            name="كتابة دالة - فيبوناتشي",
            category="coding",
            prompt="اكتب دالة Python باسم fibonacci(n) ترجع الرقم n في متتالية فيبوناتشي بدون شرح إضافي، فقط الكود.",
            expected="def fibonacci",
            expected_regex=r"def\s+fibonacci",
            max_tokens=256
        ),
        BenchmarkTask(
            id="code-2",
            name="تصحيح كود - حلقة",
            category="coding",
            prompt="ما ناتج هذا الكود؟\nfor i in range(3):\n    print(i)\nأجب بالأرقام المطبوعة مفصولة بفواصل.",
            expected="0, 1, 2",
            expected_regex=r"0.*1.*2",
            max_tokens=64
        ),
        BenchmarkTask(
            id="code-3",
            name="Coding - Reverse String",
            category="coding",
            prompt="Write a Python function to reverse a string. Only code, no explanation. Function name: reverse_string",
            expected="def reverse_string",
            expected_regex=r"def\s+reverse_string",
            max_tokens=200
        ),
        BenchmarkTask(
            id="code-4",
            name="كود - فرز",
            category="coding",
            prompt="اكتب كود Python لفرز قائمة أرقام تصاعدياً باستخدام sorted(). فقط سطر واحد.",
            expected="sorted",
            expected_regex=r"sorted\s*\(",
            max_tokens=64
        ),
    ],
    "arabic": [
        BenchmarkTask(
            id="ar-1",
            name="جودة العربية - تصحيح إملائي",
            category="arabic",
            prompt="صحح الجملة التالية إملائياً: 'ذهبة الطالبة الى المدرسة صباحن'.",
            expected="ذهبت",
            expected_regex=r"ذهبت",
            max_tokens=128
        ),
        BenchmarkTask(
            id="ar-2",
            name="جودة العربية - مرادف",
            category="arabic",
            prompt="ما مرادف كلمة 'سعيد'؟ أجب بكلمة واحدة.",
            expected="فرح",
            expected_regex=r"(فرح|مسرور|مبتهج|سعيد)",
            max_tokens=32
        ),
        BenchmarkTask(
            id="ar-3",
            name="جودة العربية - إعراب",
            category="arabic",
            prompt="أعرب كلمة 'الكتاب' في جملة: 'قرأ الطالب الكتاب'.",
            expected="مفعول به",
            expected_regex=r"مفعول\s*به",
            max_tokens=128
        ),
        BenchmarkTask(
            id="ar-4",
            name="جودة العربية - تلخيص",
            category="arabic",
            prompt="لخص الجملة: 'الذكاء الاصطناعي هو مجال من مجالات علوم الحاسب يهدف إلى إنشاء أنظمة قادرة على محاكاة الذكاء البشري.' في 10 كلمات.",
            expected="الذكاء الاصطناعي",
            expected_regex=r"الذكاء\s*الاصطناعي",
            max_tokens=64
        ),
    ],
    "summarization": [
        BenchmarkTask(
            id="sum-1",
            name="تلخيص - نص تقني",
            category="summarization",
            prompt="لخص النص التالي في جملتين: 'تم إطلاق نموذج لغوي جديد يدعم اللغة العربية بشكل ممتاز. النموذج يحتوي على 7 مليار معامل وتم تدريبه على 2 تريليون توكن. يحقق النموذج نتائج ممتازة في اختبارات الفهم والتلخيص والبرمجة.'",
            expected="7 مليار",
            expected_regex=r"7\s*مليار",
            max_tokens=128
        ),
        BenchmarkTask(
            id="sum-2",
            name="Summarization - English",
            category="summarization",
            prompt="Summarize in one sentence: 'The Transformer architecture, introduced in 2017, revolutionized NLP by using self-attention mechanisms instead of recurrence, enabling parallel training and better long-range dependencies handling.'",
            expected="Transformer",
            expected_regex=r"(?i)transformer",
            max_tokens=128
        ),
        BenchmarkTask(
            id="sum-3",
            name="تلخيص - نقاط",
            category="summarization",
            prompt="حول النص إلى 3 نقاط: 'الطاقة المتجددة تشمل الشمس والرياح والمياه. هي صديقة للبيئة وتقلل الانبعاثات. الاستثمار فيها ينمو سنوياً بنسبة 10%.'",
            expected="الشمس",
            expected_regex=r"الشمس|الرياح|المياه",
            max_tokens=128
        ),
    ],
}

reports_store: Dict[str, BenchmarkReport] = {}

def evaluate_answer(generation: str, task: BenchmarkTask, mode: str = "regex") -> tuple[bool, float, str]:
    gen = generation.strip()
    if mode == "exact" and task.expected:
        passed = task.expected.strip().lower() in gen.lower()
        return passed, 1.0 if passed else 0.0, "Exact match"
    elif mode == "regex" and task.expected_regex:
        try:
            passed = bool(re.search(task.expected_regex, gen, re.MULTILINE | re.UNICODE))
            return passed, 1.0 if passed else 0.0, f"Regex: {task.expected_regex} -> {'match' if passed else 'no match'}"
        except re.error as e:
            return False, 0.0, f"Regex error: {e}"
    elif mode == "llm":
        # Simulate LLM-as-judge: heuristic length + keyword check
        # In real would call model again
        if task.expected and task.expected.lower() in gen.lower():
            return True, 0.85, "LLM-judge: keyword found"
        # fallback to regex
        if task.expected_regex and re.search(task.expected_regex, gen, re.MULTILINE | re.UNICODE | re.IGNORECASE):
            return True, 0.8, "LLM-judge: pattern match"
        # Simulate judge giving partial
        score = 0.3 if len(gen) > 10 else 0.0
        return score > 0.5, score, "LLM-judge: heuristic"
    return False, 0.0, "No evaluation method"

def run_benchmark(req: BenchmarkRunRequest, model_path: str = "") -> BenchmarkReport:
    suites = req.suites
    if "all" in suites:
        suites = ["reasoning", "coding", "arabic", "summarization"]
    tasks: List[BenchmarkTask] = []
    for s in suites:
        lst = BENCHMARK_SUITES.get(s, [])
        if req.max_tasks_per_suite:
            lst = lst[:req.max_tasks_per_suite]
        tasks.extend(lst)

    results: List[BenchmarkResult] = []
    total_start = time.time()
    vram_peak = 0

    # Auto speed-up on CPU (no GPU) — cap tokens to avoid 2+ minute per task
    is_cpu = not telemetry_service._has_gpu or model_manager._device == "cpu"
    for task in tasks:
        start = time.time()
        snap_before = telemetry_service.get_snapshot()
        # On CPU, cap to 32 tokens (~15s per task instead of 120s)
        effective_tokens = min(task.max_tokens, 32) if is_cpu else task.max_tokens
        # Generate
        gen_req = GenerateRequest(
            prompt=task.prompt,
            max_new_tokens=effective_tokens,
            temperature=req.temperature,
            stream=False
        )
        # Use blocking generation
        try:
            out = model_manager.generate_blocking(gen_req)
            generation = out["text"]
            stats = out["stats"]
            tokens_per_sec = stats.get("tokens_per_sec", 0) if isinstance(stats, dict) else 0
            ttft = stats.get("ttft_ms", 0) if isinstance(stats, dict) else 0
            latency = stats.get("total_time_ms", (time.time()-start)*1000) if isinstance(stats, dict) else (time.time()-start)*1000
        except Exception as e:
            generation = f"[خطأ في التوليد: {str(e)[:100]}]"
            tokens_per_sec = 0
            ttft = 0
            latency = (time.time()-start)*1000

        passed, score, reason = evaluate_answer(generation, task, req.judge_mode)
        # VRAM peak tracking
        snap_after = telemetry_service.get_snapshot(tokens_per_sec=tokens_per_sec)
        vram_used = snap_after.vram_used_mb or snap_after.vram_peak_mb or 0
        if vram_used > vram_peak:
            vram_peak = vram_used
        # In demo without GPU, simulate
        if vram_used == 0:
            vram_used = 3500 + random.uniform(-300, 800)
            if vram_used > vram_peak:
                vram_peak = vram_used

        results.append(BenchmarkResult(
            task_id=task.id,
            name=task.name,
            category=task.category,
            prompt=task.prompt,
            expected=task.expected,
            generation=generation,
            passed=passed,
            score=score,
            latency_ms=round(latency,1),
            tokens_per_sec=round(tokens_per_sec,1),
            ttft_ms=round(ttft,1),
            vram_peak_mb=round(vram_used,1),
            judge_reason=reason
        ))

    total_time = (time.time() - total_start) * 1000
    passed_count = sum(1 for r in results if r.passed)
    accuracy = passed_count / len(results) if results else 0
    avg_tps = sum(r.tokens_per_sec for r in results) / len(results) if results else 0
    avg_ttft = sum(r.ttft_ms for r in results) / len(results) if results else 0
    avg_lat = sum(r.latency_ms for r in results) / len(results) if results else 0

    # By category
    by_cat = {}
    for cat in ["reasoning", "coding", "arabic", "summarization"]:
        cat_results = [r for r in results if r.category == cat]
        if cat_results:
            c_passed = sum(1 for r in cat_results if r.passed)
            by_cat[cat] = {
                "total": len(cat_results),
                "passed": c_passed,
                "accuracy": round(c_passed/len(cat_results), 3),
                "avg_tps": round(sum(r.tokens_per_sec for r in cat_results)/len(cat_results),1),
                "avg_ttft": round(sum(r.ttft_ms for r in cat_results)/len(cat_results),1),
            }

    report_id = str(uuid.uuid4())[:8]
    report = BenchmarkReport(
        id=report_id,
        model_path=model_path or model_manager.info.model_path or "demo-model",
        timestamp=datetime.utcnow(),
        total_tasks=len(results),
        passed=passed_count,
        accuracy=round(accuracy,3),
        avg_tokens_per_sec=round(avg_tps,1),
        avg_ttft_ms=round(avg_ttft,1),
        avg_latency_ms=round(avg_lat,1),
        vram_peak_mb=round(vram_peak,1),
        results=results,
        by_category=by_cat
    )
    reports_store[report_id] = report
    return report

def get_report(report_id: str) -> BenchmarkReport | None:
    return reports_store.get(report_id)

def list_reports():
    return list(reports_store.values())