fox007j's picture
Update training dataset
0ce8172 verified
Raw History Blame Contribute Delete
16.9 kB
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