| 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 |
|
|
| |
| 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": |
| |
| |
| if task.expected and task.expected.lower() in gen.lower(): |
| return True, 0.85, "LLM-judge: keyword found" |
| |
| 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" |
| |
| 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 |
|
|
| |
| 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() |
| |
| effective_tokens = min(task.max_tokens, 32) if is_cpu else task.max_tokens |
| |
| gen_req = GenerateRequest( |
| prompt=task.prompt, |
| max_new_tokens=effective_tokens, |
| temperature=req.temperature, |
| stream=False |
| ) |
| |
| 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) |
| |
| 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 |
| |
| 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_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()) |
|
|