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
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
import ast
import json
import re
from pathlib import Path
from typing import Dict, List, Tuple

import torch

from tiny_model_core import TinyCausalLM, TinyConfig, WordTokenizer


BENCHMARKS = [
    {
        "capability": "instruction_following",
        "instruction": "Follow this exactly: return three bullet points about Python file handling and include one short example.",
        "expected_tokens": ["open", "with", "example"],
        "requires_structure": True,
    },
    {
        "capability": "conversation_management",
        "instruction": "A user changed requirements mid-task. Provide a concise response that acknowledges change and continues with an updated plan.",
        "expected_tokens": ["changed", "plan", "continue"],
        "requires_structure": True,
    },
    {
        "capability": "code_generation",
        "instruction": "Write a clean Python function to reverse a string. Keep it production-ready and clear.",
        "expected_tokens": ["def", "return"],
    },
    {
        "capability": "code_representation",
        "instruction": "Explain what this code does and its complexity: def dedupe(items): return list(dict.fromkeys(items)).",
        "expected_tokens": ["duplicates", "order", "o("],
    },
    {
        "capability": "code_edit_refactor",
        "instruction": "Refactor for readability: total=0; for i in range(len(nums)): total=total+nums[i]",
        "expected_tokens": ["sum", "for", "readability"],
    },
    {
        "capability": "debugging",
        "instruction": "A script fails with TypeError unsupported operand types for + int and str. Give a concise debugging response.",
        "expected_tokens": ["type", "convert", "line"],
    },
    {
        "capability": "testing",
        "instruction": "Create a focused test checklist for CSV parser behavior.",
        "expected_tokens": ["valid", "missing", "edge"],
        "requires_structure": True,
    },
    {
        "capability": "math_reasoning",
        "instruction": "Solve x**2 - 4 = 0 and provide the final result clearly.",
        "expected_tokens": ["-2", "2"],
    },
    {
        "capability": "complex_quant",
        "instruction": "Outline concise steps for solving constrained optimization with Lagrange multipliers.",
        "expected_tokens": ["objective", "constraint", "derivative"],
        "requires_structure": True,
    },
    {
        "capability": "data_analysis",
        "instruction": "Describe a practical first-pass data analysis plan for a CSV with sales, costs, and dates.",
        "expected_tokens": ["missing", "outlier", "trend"],
        "requires_structure": True,
    },
    {
        "capability": "data_science_ml",
        "instruction": "Provide a compact baseline workflow for binary classification on tabular data.",
        "expected_tokens": ["train", "validation", "f1"],
        "requires_structure": True,
    },
    {
        "capability": "academic_research_support",
        "instruction": "Summarize how to review a research paper for a graduate-level reading group.",
        "expected_tokens": ["method", "limitations", "findings"],
        "requires_structure": True,
    },
    {
        "capability": "academic_writing",
        "instruction": "Write a concise academic paragraph about cybersecurity governance with formal tone.",
        "expected_tokens": ["cybersecurity", "governance"],
    },
    {
        "capability": "humanized_writing",
        "instruction": "Rewrite this sentence in a natural tone: Your request has been processed successfully.",
        "expected_tokens": ["processed", "successfully"],
    },
    {
        "capability": "originality_integrity_ethics",
        "instruction": "How can someone keep an essay original while using sources responsibly?",
        "expected_tokens": ["citations", "paraphrase", "argument"],
    },
    {
        "capability": "tool_use_agentic",
        "instruction": "A repository has failing tests. Provide an actionable tool-use plan to diagnose and fix the issue.",
        "expected_tokens": ["reproduce", "patch", "tests"],
        "requires_structure": True,
    },
    {
        "capability": "image_workflow",
        "instruction": "Generate a structured prompt for an image model to create a realistic product photo of headphones.",
        "expected_tokens": ["prompt", "lighting", "negative"],
        "requires_structure": True,
    },
    {
        "capability": "voice_workflow",
        "instruction": "Design a brief voice-assistant flow for booking an appointment.",
        "expected_tokens": ["confirm", "fallback", "time"],
        "requires_structure": True,
    },
    {
        "capability": "output_quality_controls",
        "instruction": "State the response rules when the user requests strict JSON output.",
        "expected_tokens": ["valid", "json", "no extra"],
    },
    {
        "capability": "nlp_text_classification",
        "instruction": "Classify sentiment: 'The UI is beautiful but the app crashes every hour.'",
        "expected_tokens": ["mixed", "positive", "negative"],
    },
    {
        "capability": "nlp_translation",
        "instruction": "Translate to French: 'Data quality drives model quality.'",
        "expected_tokens": ["donnees", "qualite"],
    },
    {
        "capability": "nlp_summarization",
        "instruction": "Summarize this in one sentence: Q3 revenue grew 12%, but margin fell because logistics costs rose.",
        "expected_tokens": ["revenue", "margin"],
    },
    {
        "capability": "nlp_entity_extraction",
        "instruction": "Extract entities: 'Alice from Acme visited Nairobi on 12 Jan 2025.'",
        "expected_tokens": ["alice", "acme", "nairobi"],
    },
    {
        "capability": "predictive_time_series",
        "instruction": "Provide a short time-series forecasting plan for monthly sales.",
        "expected_tokens": ["seasonality", "forecast", "horizon"],
        "requires_structure": True,
    },
    {
        "capability": "predictive_recommendation",
        "instruction": "Give a baseline recommendation-system plan.",
        "expected_tokens": ["baseline", "ranking", "recall"],
    },
    {
        "capability": "tool_use_code_execution",
        "instruction": "Describe how an agent should run and validate a Python script fix.",
        "expected_tokens": ["run", "traceback", "rerun"],
        "requires_structure": True,
    },
    {
        "capability": "tool_use_database_ops",
        "instruction": "Provide safe steps for a production SQL data patch.",
        "expected_tokens": ["transaction", "backup", "verify"],
        "requires_structure": True,
    },
    {
        "capability": "web_information_retrieval",
        "instruction": "Explain how an assistant should fetch the latest web information for a user question.",
        "expected_tokens": ["search", "source", "latest"],
        "requires_structure": True,
    },
    {
        "capability": "web_source_synthesis",
        "instruction": "Describe how to synthesize multiple web sources into one grounded answer.",
        "expected_tokens": ["cross-check", "dates", "cite"],
        "requires_structure": True,
    },
    {
        "capability": "cv_ocr",
        "instruction": "Describe a robust OCR pipeline for scanned invoices.",
        "expected_tokens": ["preprocess", "recognize", "json"],
    },
    {
        "capability": "audio_speech_to_text",
        "instruction": "Outline a speech-to-text pipeline for meeting recordings.",
        "expected_tokens": ["segment", "transcript", "timestamps"],
    },
    {
        "capability": "reasoning_deduction_inference",
        "instruction": "If all encrypted backups are offsite and backup B is encrypted, what can we conclude?",
        "expected_tokens": ["backup b", "offsite"],
    },
    {
        "capability": "code_generation",
        "instruction": "Write a professional Python function to check if a number is prime, with clear naming.",
        "expected_tokens": ["def", "for", "return"],
    },
]


def _load_capability_weights(registry_path: str = "capability_registry.json") -> Dict[str, float]:
    default = {}
    path = Path(registry_path)
    if not path.exists():
        return default
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return default

    weights: Dict[str, float] = {}
    for item in payload.get("capabilities", []):
        if not isinstance(item, dict):
            continue
        capability = str(item.get("id", "")).strip()
        if not capability:
            continue
        priority = str(item.get("train_priority", "medium")).strip().lower()
        if priority == "high":
            weights[capability] = 1.0
        elif priority == "medium":
            weights[capability] = 0.75
        else:
            weights[capability] = 0.55
    return weights


def _generate_response(
    model: TinyCausalLM,
    tokenizer: WordTokenizer,
    instruction: str,
    max_new_tokens: int = 100,
) -> str:
    device = next(model.parameters()).device
    formatted = f"User: {instruction.strip()}\nAssistant:"
    ids = tokenizer.encode(formatted, add_bos=True, add_eos=False)
    if len(ids) > model.config.block_size:
        ids = ids[-model.config.block_size :]
    x = torch.tensor([ids], dtype=torch.long, device=device)
    out = model.generate(
        x,
        max_new_tokens=max_new_tokens,
        temperature=0.95,
        top_k=50,
        top_p=0.95,
        repetition_penalty=1.12,
        min_new_tokens=15,
        eos_id=tokenizer.eos_id,
    )
    decoded = tokenizer.decode(out[0].tolist())
    if "Assistant:" in decoded:
        decoded = decoded.split("Assistant:", 1)[1]
    for marker in ("User:", "System:"):
        if marker in decoded:
            decoded = decoded.split(marker, 1)[0]
    return decoded.strip()


def _extract_code_candidate(text: str) -> str:
    fence = re.search(r"```(?:python)?\s*(.*?)```", text, flags=re.IGNORECASE | re.DOTALL)
    if fence:
        return fence.group(1).strip()
    return text.strip()


def _score_code_response(response: str, expected_tokens: List[str]) -> float:
    score = 0.0
    text = response.strip()
    if not text:
        return 0.0
    lower = text.lower()
    if len(text) >= 24:
        score += 0.2

    if any(token in lower for token in ["def ", "class ", "return", "import "]):
        score += 0.2

    if expected_tokens:
        hits = sum(1 for tok in expected_tokens if tok.lower() in lower)
        score += 0.3 * (hits / len(expected_tokens))

    candidate = _extract_code_candidate(text)
    try:
        ast.parse(candidate)
        score += 0.3
    except Exception:
        pass

    score += 0.2 * _professional_signal(text)
    return min(1.0, score)


def _score_math_response(response: str, expected_tokens: List[str]) -> float:
    text = response.strip().lower()
    if not text:
        return 0.0
    score = 0.2
    if expected_tokens:
        hits = sum(1 for tok in expected_tokens if tok.lower() in text)
        score += 0.8 * (hits / len(expected_tokens))
    score += 0.2 * _professional_signal(response)
    return min(1.0, score)


def _score_academic_response(instruction: str, response: str, expected_tokens: List[str]) -> float:
    text = response.strip()
    lower = text.lower()
    score = 0.0

    if len(text) >= 80:
        score += 0.4

    sentences = [s for s in re.split(r"[.!?]+", text) if s.strip()]
    if len(sentences) >= 3:
        score += 0.2

    if expected_tokens:
        hits = sum(1 for tok in expected_tokens if tok.lower() in lower)
        score += 0.2 * (hits / max(1, len(expected_tokens)))

    instruction_words = {w for w in re.findall(r"[a-zA-Z]+", instruction.lower()) if len(w) > 4}
    overlap = sum(1 for w in instruction_words if w in lower)
    if overlap >= 2:
        score += 0.1

    if any(w in lower for w in ["however", "therefore", "analysis", "research", "conclusion", "introduction"]):
        score += 0.1

    score += 0.2 * _professional_signal(response)
    return min(1.0, score)


def _score_generic_response(
    instruction: str,
    response: str,
    expected_tokens: List[str],
    requires_structure: bool = False,
) -> float:
    text = response.strip()
    if not text:
        return 0.0

    lower = text.lower()
    score = 0.0

    if len(text) >= 40:
        score += 0.25

    if expected_tokens:
        hits = sum(1 for tok in expected_tokens if tok.lower() in lower)
        score += 0.45 * (hits / max(1, len(expected_tokens)))

    instruction_words = {w for w in re.findall(r"[a-zA-Z]+", instruction.lower()) if len(w) > 4}
    overlap = sum(1 for w in instruction_words if w in lower)
    if overlap >= 2:
        score += 0.1

    if requires_structure and any(marker in lower for marker in ["1.", "2.", "plan", "steps", "flow", "prompt:"]):
        score += 0.1

    score += 0.2 * _professional_signal(text)
    return min(1.0, score)


def _professional_signal(text: str) -> float:
    raw = (text or "").strip()
    if not raw:
        return 0.0
    score = 0.0
    if len(raw) >= 24:
        score += 0.25
    if raw[0].isupper():
        score += 0.15
    if raw.endswith((".", "!", "?")):
        score += 0.15
    if "\n\n" in raw or any(k in raw.lower() for k in ["result", "example", "solution", "therefore", "in summary"]):
        score += 0.2
    if not any(bad in raw.lower() for bad in ["idk", "can't help", "???", "n/a"]):
        score += 0.25
    return min(1.0, score)


@torch.no_grad()
def evaluate_benchmarks(
    model: TinyCausalLM,
    tokenizer: WordTokenizer,
    max_new_tokens: int = 100,
) -> Dict:
    model.eval()
    results = []

    code_caps = {
        "code_generation",
        "code_completion",
        "code_representation",
        "code_edit_refactor",
        "code_bug_detection",
        "code_multifile_reasoning",
    }
    math_caps = {"math_reasoning", "complex_quant", "reasoning_logical", "reasoning_multistep", "reasoning_deduction_inference"}
    academic_caps = {"academic_writing", "academic_research_support", "originality_integrity_ethics"}

    for item in BENCHMARKS:
        capability = item["capability"]
        instruction = item["instruction"]
        expected = item["expected_tokens"]
        requires_structure = bool(item.get("requires_structure", False))
        response = _generate_response(model, tokenizer, instruction, max_new_tokens=max_new_tokens)

        if capability in code_caps:
            score = _score_code_response(response, expected)
        elif capability in math_caps:
            score = _score_math_response(response, expected)
        elif capability in academic_caps:
            score = _score_academic_response(instruction, response, expected)
        else:
            score = _score_generic_response(
                instruction,
                response,
                expected,
                requires_structure=requires_structure,
            )

        results.append(
            {
                "capability": capability,
                "instruction": instruction,
                "response": response,
                "score": float(score),
                "requires_structure": requires_structure,
            }
        )

    by_capability: Dict[str, List[float]] = {}
    for row in results:
        by_capability.setdefault(row["capability"], []).append(row["score"])

    capability_scores = {cap: sum(vals) / max(1, len(vals)) for cap, vals in by_capability.items()}
    total = sum(row["score"] for row in results) / max(1, len(results))
    capability_weights = _load_capability_weights()
    weighted_num = 0.0
    weighted_den = 0.0
    for cap, score in capability_scores.items():
        weight = float(capability_weights.get(cap, 0.75))
        weighted_num += score * weight
        weighted_den += weight
    weighted_total = weighted_num / max(weighted_den, 1e-8)
    weak_capabilities = sorted([cap for cap, score in capability_scores.items() if score < 0.45])
    professionalism = sum(_professional_signal(row["response"]) for row in results) / max(1, len(results))

    return {
        "total": float(total),
        "weighted_total": float(weighted_total),
        "professionalism": float(professionalism),
        "capability_scores": capability_scores,
        "weak_capabilities": weak_capabilities,
        "items": results,
    }


def load_model_for_eval(checkpoint_path: str) -> Tuple[TinyCausalLM, WordTokenizer]:
    payload = torch.load(checkpoint_path, map_location="cpu")
    tokenizer_state = payload.get("tokenizer_state")
    if not tokenizer_state:
        raise RuntimeError("Checkpoint does not contain tokenizer_state.")
    tokenizer = WordTokenizer.from_state(tokenizer_state)

    config = TinyConfig(**payload["config"])
    model = TinyCausalLM(config).to("cpu")
    model.load_state_dict(payload["model_state_dict"])
    model.eval()
    return model, tokenizer