File size: 45,302 Bytes
0ce8172 | 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 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 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 | import json
import random
import re
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Optional, Sequence
TOPIC_TO_CAPABILITY = {
"python_coding": "code_generation",
"web_development": "code_generation",
"automation": "tool_use_agentic",
"data_processing": "data_analysis",
"academic_writing": "academic_writing",
"creative_writing": "humanized_writing",
"greetings": "conversation_management",
"api_parameters": "instruction_following",
"api_response_format": "output_quality_controls",
"mathematics": "math_reasoning",
"linear_algebra": "complex_quant",
"translation": "nlp_translation",
"summarization": "nlp_summarization",
"classification": "nlp_text_classification",
}
KB_CATEGORY_TO_CAPABILITY = {
"programming": "code_generation",
"api": "tool_use_agentic",
"mathematics": "math_reasoning",
"linear_algebra": "complex_quant",
"ai_ml": "data_science_ml",
"academic": "academic_research_support",
"writing": "academic_writing",
"networking": "tool_use_agentic",
"general": "instruction_following",
}
BENCH_CAPABILITIES = {
"instruction_following",
"conversation_management",
"code_generation",
"code_representation",
"code_edit_refactor",
"debugging",
"testing",
"math_reasoning",
"complex_quant",
"data_analysis",
"data_science_ml",
"academic_research_support",
"academic_writing",
"humanized_writing",
"originality_integrity_ethics",
"tool_use_agentic",
"image_workflow",
"voice_workflow",
"output_quality_controls",
"nlp_text_classification",
"nlp_question_answering",
"nlp_translation",
"nlp_summarization",
"nlp_intent_recognition",
"nlp_entity_extraction",
"reasoning_logical",
"reasoning_multistep",
"reasoning_pattern_recognition",
"reasoning_deduction_inference",
"predictive_regression",
"predictive_classification",
"predictive_time_series",
"predictive_recommendation",
"tool_use_code_execution",
"tool_use_api_calls",
"tool_use_database_ops",
"tool_use_command_execution",
"web_information_retrieval",
"web_source_synthesis",
"code_completion",
"code_bug_detection",
"code_multifile_reasoning",
"cv_object_detection",
"cv_face_recognition",
"cv_medical_image_analysis",
"cv_ocr",
"audio_speech_to_text",
"audio_text_to_speech",
"audio_speaker_recognition",
"domain_specialization_finance",
"domain_specialization_health",
"domain_specialization_coding",
}
BLOCKED_PATTERNS = [
re.compile(r"\bturnitin\b", flags=re.IGNORECASE),
re.compile(r"\bbypass\b", flags=re.IGNORECASE),
re.compile(r"\bevad(e|ing)\b", flags=re.IGNORECASE),
re.compile(r"\bplagiarism detector\b", flags=re.IGNORECASE),
]
FALLBACK_CAPABILITY_SEEDS = [
{
"capability": "code_representation",
"instruction": "Explain this Python function in plain language and summarize its time complexity: def dedupe(items): return list(dict.fromkeys(items)).",
"response": "It removes duplicates while preserving first-seen order by routing values through dictionary keys. Average runtime is O(n), with O(n) memory.",
},
{
"capability": "code_edit_refactor",
"instruction": "Refactor for readability: total=0; for i in range(len(nums)): total=total+nums[i]",
"response": "Prefer total = sum(nums). If explicit iteration is required, use for value in nums: total += value to avoid index-only loops.",
},
{
"capability": "debugging",
"instruction": "A Python function crashes with TypeError int plus str. How should the assistant respond?",
"response": "Ask for the failing line, inspect input types, convert numeric strings before arithmetic, and add type validation near function entry.",
},
{
"capability": "testing",
"instruction": "Create a minimal test checklist for a CSV parser.",
"response": "Cover valid rows, missing required columns, unknown columns, empty input, malformed separators, unicode text, and one regression case per fixed bug.",
},
{
"capability": "conversation_management",
"instruction": "How should the assistant handle a mid-task requirement change?",
"response": "Acknowledge the change, summarize what shifted, confirm tradeoffs, and continue execution from the updated objective.",
},
{
"capability": "complex_quant",
"instruction": "Outline concise steps for constrained optimization with Lagrange multipliers.",
"response": "Define objective and constraint, build the Lagrangian, compute partial derivatives, solve the system, and verify feasible extrema.",
},
{
"capability": "data_analysis",
"instruction": "What first-pass checks should be run on a sales CSV?",
"response": "Validate schema and types, profile missing values, compute profit metrics, inspect outliers, and analyze time/region trends before conclusions.",
},
{
"capability": "data_science_ml",
"instruction": "Provide a baseline workflow for binary classification on tabular data.",
"response": "Create stratified train/validation split, train a simple baseline, evaluate precision-recall-F1/ROC-AUC, inspect feature effects, then iterate with cross-validation.",
},
{
"capability": "academic_research_support",
"instruction": "How should an assistant summarize a research paper?",
"response": "Present research question, method, data, main findings, limits, and implications, while separating reported evidence from interpretation.",
},
{
"capability": "humanized_writing",
"instruction": "Rewrite this in a natural tone: Your request has been processed successfully.",
"response": "Done, your request was processed successfully.",
},
{
"capability": "originality_integrity_ethics",
"instruction": "How can a student keep an essay original while using sources?",
"response": "Draft your own argument first, paraphrase with fresh structure, quote sparingly, and cite every borrowed idea accurately.",
},
{
"capability": "image_workflow",
"instruction": "Create an image-generation prompt for realistic wireless earbuds.",
"response": "Prompt: studio photo of matte black wireless earbuds and open case on neutral gradient, 85mm lens look, soft key light, high detail. Negative: blur, watermark, distorted geometry.",
},
{
"capability": "voice_workflow",
"instruction": "Design a voice assistant flow for booking a dentist appointment.",
"response": "Flow: greet, confirm intent, collect date/time/location, propose slots, confirm selected slot, and provide fallback prompts for unclear speech.",
},
{
"capability": "instruction_following",
"instruction": "Return a strict two-step answer for setting up a Python virtual environment.",
"response": "1. Create the environment with python -m venv .venv. 2. Activate it and install dependencies from requirements.txt.",
},
{
"capability": "code_generation",
"instruction": "Write a Python function that returns whether a number is even.",
"response": "def is_even(value: int) -> bool:\n return value % 2 == 0",
},
{
"capability": "math_reasoning",
"instruction": "Solve 3x + 5 = 20.",
"response": "Subtract 5 from both sides to get 3x = 15, then divide by 3, so x = 5.",
},
{
"capability": "academic_writing",
"instruction": "Write one formal sentence about reproducibility in machine learning.",
"response": "Reproducibility in machine learning requires transparent reporting of data, preprocessing, model settings, and evaluation protocols.",
},
{
"capability": "tool_use_agentic",
"instruction": "User asks for a bug fix in a repository with failing tests. Provide a concise tool-use plan.",
"response": "Inspect files and failing logs, reproduce with targeted tests, patch minimal code, rerun tests, and summarize changes with file references.",
},
{
"capability": "web_information_retrieval",
"instruction": "How should an assistant fetch current information from the web for a user query?",
"response": "Form focused search queries, prioritize primary and recent sources, open relevant pages, extract key facts, and return a concise answer with sources.",
},
{
"capability": "web_source_synthesis",
"instruction": "How should an assistant synthesize findings from multiple web sources?",
"response": "Cross-check source agreement, note publication dates, summarize consensus and disagreements, and cite the final sources used.",
},
{
"capability": "output_quality_controls",
"instruction": "How should a model respond when user requests strict JSON output only?",
"response": "Return valid JSON only, without markdown or extra prose, and keep keys stable and required fields explicit.",
},
]
def _read_json(path: Path) -> Dict:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def _read_jsonl(path: Path) -> List[Dict]:
rows: List[Dict] = []
if not path.exists():
return rows
with open(path, "r", encoding="utf-8") as f:
for line in f:
text = line.strip()
if not text:
continue
try:
item = json.loads(text)
except Exception:
continue
if isinstance(item, dict):
rows.append(item)
return rows
def _resolve_optional_path(path_text: str, anchors: Sequence[Path]) -> Path:
target = Path(path_text)
if target.is_absolute():
return target
candidates: List[Path] = [target]
for anchor in anchors:
candidates.append(anchor / target)
seen = set()
unique_candidates: List[Path] = []
for candidate in candidates:
norm = str(candidate)
if norm in seen:
continue
seen.add(norm)
unique_candidates.append(candidate)
for candidate in unique_candidates:
if candidate.exists():
return candidate
return target
def _clean_text(text: str) -> str:
text = (text or "").replace("\r\n", "\n").replace("\r", "\n")
text = "\n".join(line.strip() for line in text.split("\n"))
return text.strip()
def _normalize_key(text: str) -> str:
return re.sub(r"\s+", " ", (text or "").strip().lower())
def _token_count(text: str) -> int:
return len(re.findall(r"[a-zA-Z0-9_']+", text or ""))
def _symbol_noise_ratio(text: str) -> float:
if not text:
return 1.0
valid = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,;:!?()[]{}'\"`-_/@#$%&*+=<>|\\\n\t")
bad = sum(1 for ch in text if ch not in valid)
return bad / max(1, len(text))
def _contains_blocked_pattern(text: str) -> bool:
raw = text or ""
return any(pattern.search(raw) for pattern in BLOCKED_PATTERNS)
def _looks_reference_noise(text: str) -> bool:
lowered = (text or "").lower()
if not lowered:
return True
if lowered.startswith(("exercise ", "chapter ", "section ", "?exercise ")):
return True
if "online edition (c)" in lowered:
return True
if re.search(r"\.\s*\.\s*\.\s*\.\s*\d{2,}", lowered):
return True
if "contents" in lowered and lowered.count("chapter") >= 2:
return True
if re.search(r"([:;.,\"'`_\\/\-\=\(\)\[\]\{\}])\1{4,}", lowered):
return True
return False
def _text_quality_ok(
text: str,
min_alpha_ratio: float = 0.20,
max_control_chars: int = 0,
max_symbol_noise_ratio: float = 0.12,
) -> bool:
if not text:
return False
control = sum(1 for ch in text if ord(ch) < 32 and ch not in {"\n", "\t"})
if control > max_control_chars:
return False
alpha = sum(1 for ch in text if ch.isalpha())
ratio = alpha / max(1, len(text))
if ratio < min_alpha_ratio:
return False
if _symbol_noise_ratio(text) > max_symbol_noise_ratio:
return False
return True
def _looks_pdf_noise(text: str) -> bool:
lowered = (text or "").lower()
words = re.findall(r"[a-zA-Z0-9_']+", lowered)
if not words:
return True
numeric = sum(1 for w in words if w.isdigit())
numeric_ratio = numeric / max(1, len(words))
if numeric_ratio > 0.22:
return True
dotted_runs = lowered.count("...") + lowered.count(". . .")
if dotted_runs >= 4:
return True
if "contents" in lowered and lowered.count("chapter") >= 3:
return True
if _looks_reference_noise(text):
return True
return False
def _guess_pdf_topic(filename: str) -> str:
name = (filename or "").lower()
if any(k in name for k in ["python", "code", "program", "react", "web-development", "bootstrap"]):
return "python_coding"
if any(k in name for k in ["math", "algebra", "calculus"]):
return "mathematics"
if any(k in name for k in ["deep", "ml", "ai", "learning"]):
return "ai_ml"
return "academic_writing"
def _infer_capability(instruction: str, response: str, source: str, topic: str = "") -> str:
topic_key = (topic or "").strip().lower()
if topic_key in TOPIC_TO_CAPABILITY:
return TOPIC_TO_CAPABILITY[topic_key]
if topic_key in KB_CATEGORY_TO_CAPABILITY:
return KB_CATEGORY_TO_CAPABILITY[topic_key]
merged = f"{instruction} {response}".lower()
src = (source or "").lower()
if "capability_pack" in src or "capability_seed" in src:
if topic_key in BENCH_CAPABILITIES:
return topic_key
if any(k in merged for k in ["debug", "traceback", "exception", "stack trace"]):
return "debugging"
if any(k in merged for k in ["spam", "sentiment", "text classification", "label this text"]):
return "nlp_text_classification"
if any(k in merged for k in ["translate", "translation", "from english to"]):
return "nlp_translation"
if any(k in merged for k in ["summarize", "summary", "tl;dr"]):
return "nlp_summarization"
if any(k in merged for k in ["named entity", "entity extraction", "extract entities"]):
return "nlp_entity_extraction"
if any(k in merged for k in ["intent", "user intent", "classify intent"]):
return "nlp_intent_recognition"
if any(k in merged for k in ["question answering", "answer the question", "qa system"]):
return "nlp_question_answering"
if any(k in merged for k in ["unit test", "pytest", "test case", "integration test"]):
return "testing"
if any(k in merged for k in ["refactor", "clean this code", "improve readability"]):
return "code_edit_refactor"
if any(k in merged for k in ["explain this code", "time complexity", "big-o"]):
return "code_representation"
if any(k in merged for k in ["dataset", "pandas", "analysis", "plot", "visualization"]):
return "data_analysis"
if any(k in merged for k in ["cross-validation", "feature engineering", "classification", "regression model"]):
return "data_science_ml"
if any(k in merged for k in ["regression forecast", "predict numeric", "price prediction"]):
return "predictive_regression"
if any(k in merged for k in ["binary classification", "churn prediction", "class probability"]):
return "predictive_classification"
if any(k in merged for k in ["time series", "seasonality", "arima", "forecast horizon"]):
return "predictive_time_series"
if any(k in merged for k in ["recommendation", "collaborative filtering", "ranking model"]):
return "predictive_recommendation"
if any(k in merged for k in ["paper", "methodology", "research question", "literature review"]):
return "academic_research_support"
if any(k in merged for k in ["essay", "citation", "thesis", "academic paragraph"]):
return "academic_writing"
if any(k in merged for k in ["voice assistant", "speech", "transcript"]):
return "voice_workflow"
if any(k in merged for k in ["speech-to-text", "asr", "transcribe audio"]):
return "audio_speech_to_text"
if any(k in merged for k in ["text-to-speech", "tts", "voice synthesis"]):
return "audio_text_to_speech"
if any(k in merged for k in ["speaker recognition", "speaker verification", "voiceprint"]):
return "audio_speaker_recognition"
if any(k in merged for k in ["image prompt", "lighting", "negative prompt"]):
return "image_workflow"
if any(k in merged for k in ["object detection", "bounding box", "yolo"]):
return "cv_object_detection"
if any(k in merged for k in ["face recognition", "facial embedding"]):
return "cv_face_recognition"
if any(k in merged for k in ["medical image", "x-ray", "ct scan", "mri"]):
return "cv_medical_image_analysis"
if any(k in merged for k in ["ocr", "extract text from image"]):
return "cv_ocr"
if any(k in merged for k in ["tool-use", "workflow", "steps", "plan"]):
return "tool_use_agentic"
if any(k in merged for k in ["run code", "python execution", "sandbox execution"]):
return "tool_use_code_execution"
if any(k in merged for k in ["call api", "rest api", "endpoint"]):
return "tool_use_api_calls"
if any(k in merged for k in ["sql", "database", "query table"]):
return "tool_use_database_ops"
if any(k in merged for k in ["shell command", "terminal command", "powershell"]):
return "tool_use_command_execution"
if any(k in merged for k in ["web search", "search the web", "browse the web", "fetch online", "latest information"]):
return "web_information_retrieval"
if any(k in merged for k in ["synthesize sources", "compare sources", "cross-check sources", "cite sources"]):
return "web_source_synthesis"
if any(k in merged for k in ["code completion", "complete this function"]):
return "code_completion"
if any(k in merged for k in ["bug detection", "find bug", "fault localization"]):
return "code_bug_detection"
if any(k in merged for k in ["multi-file", "across files", "cross-file"]):
return "code_multifile_reasoning"
if any(k in merged for k in ["equation", "solve", "integral", "derivative", "probability"]):
return "math_reasoning"
if any(k in merged for k in ["deduce", "inference", "premise", "conclusion"]):
return "reasoning_deduction_inference"
if any(k in merged for k in ["step-by-step", "multi-step", "decompose"]):
return "reasoning_multistep"
if any(k in merged for k in ["pattern recognition", "sequence pattern"]):
return "reasoning_pattern_recognition"
if any(k in merged for k in ["logical reasoning", "logic puzzle"]):
return "reasoning_logical"
if any(k in merged for k in ["finance domain", "financial analysis", "valuation"]):
return "domain_specialization_finance"
if any(k in merged for k in ["health domain", "clinical", "medical protocol"]):
return "domain_specialization_health"
if any(k in merged for k in ["coding domain", "software architecture", "programming best practices"]):
return "domain_specialization_coding"
return "instruction_following"
def _row_quality_ok(instruction: str, response: str, quality_min_alpha_ratio: float) -> bool:
if _contains_blocked_pattern(instruction) or _contains_blocked_pattern(response):
return False
if _token_count(instruction) < 3 or _token_count(response) < 3:
return False
if _looks_reference_noise(instruction) or _looks_reference_noise(response):
return False
if not _text_quality_ok(instruction, min_alpha_ratio=quality_min_alpha_ratio, max_symbol_noise_ratio=0.12):
return False
if not _text_quality_ok(response, min_alpha_ratio=quality_min_alpha_ratio, max_symbol_noise_ratio=0.18):
return False
return True
def _extract_pdf_text(pdf_path: Path, max_pages: int) -> str:
try:
import PyPDF2
except Exception:
return ""
chunks: List[str] = []
try:
with open(pdf_path, "rb") as f:
reader = PyPDF2.PdfReader(f)
total = len(reader.pages)
page_cap = min(max_pages, total)
for i in range(page_cap):
text = (reader.pages[i].extract_text() or "").strip()
if text:
chunks.append(text)
except Exception:
return ""
return _clean_text("\n\n".join(chunks))
def _build_pdf_samples(
docs_pdf_dir: str,
max_docs_pdf_files: int,
max_pdf_pages_per_file: int,
pdf_chunk_chars: int,
max_pdf_samples: int,
enforce_quality_filter: bool,
quality_min_alpha_ratio: float,
) -> List[Dict[str, str]]:
base = Path(docs_pdf_dir)
if not base.exists() or max_pdf_samples <= 0 or max_docs_pdf_files <= 0:
return []
pdf_files = sorted(base.glob("*.pdf"))[:max_docs_pdf_files]
if not pdf_files:
return []
templates = [
"Summarize the key ideas from '{title}' section {idx}.",
"Explain the core concepts in this excerpt from '{title}' (part {idx}).",
"Provide study notes for '{title}' section {idx}.",
]
rows: List[Dict[str, str]] = []
for pdf in pdf_files:
title = pdf.stem.replace("_", " ").strip() or pdf.name
topic = _guess_pdf_topic(pdf.name)
text = _extract_pdf_text(pdf, max_pages=max_pdf_pages_per_file)
if len(text) < 300:
continue
# Keep chunking deterministic and bounded so training rebuild is stable.
section_idx = 1
for start in range(0, len(text), pdf_chunk_chars):
if len(rows) >= max_pdf_samples:
return rows
segment = text[start : start + pdf_chunk_chars]
segment = re.sub(r"\s+", " ", segment).strip()
if len(segment) < 220:
continue
if _looks_pdf_noise(segment):
continue
instruction = templates[(section_idx - 1) % len(templates)].format(title=title, idx=section_idx)
section_idx += 1
capability = _infer_capability(instruction, segment, source="docs_pdf", topic=topic)
if enforce_quality_filter:
if not _text_quality_ok(instruction, min_alpha_ratio=0.30):
continue
if not _text_quality_ok(segment, min_alpha_ratio=quality_min_alpha_ratio):
continue
rows.append(
{
"instruction": instruction,
"response": segment,
"source": "docs_pdf",
"topic": topic or capability,
"capability": capability,
}
)
return rows
def _cap_rows_by_source(rows: List[Dict[str, str]], source_limits: Dict[str, int], seed: int) -> List[Dict[str, str]]:
if not source_limits:
return rows
rng = random.Random(seed)
buckets: Dict[str, List[Dict[str, str]]] = defaultdict(list)
passthrough: List[Dict[str, str]] = []
for row in rows:
source = str(row.get("source", "")).split(":", 1)[0]
if source in source_limits:
buckets[source].append(row)
else:
passthrough.append(row)
kept = list(passthrough)
for source, items in buckets.items():
limit = max(0, int(source_limits.get(source, len(items))))
if len(items) <= limit:
kept.extend(items)
continue
shuffled = items[:]
rng.shuffle(shuffled)
kept.extend(shuffled[:limit])
return kept
def _cap_rows_by_capability(rows: List[Dict[str, str]], max_rows_per_capability: Optional[int], seed: int) -> List[Dict[str, str]]:
if max_rows_per_capability is None:
return rows
limit = max(1, int(max_rows_per_capability))
rng = random.Random(seed)
buckets: Dict[str, List[Dict[str, str]]] = defaultdict(list)
for row in rows:
capability = str(row.get("capability", "")).strip()
buckets[capability].append(row)
kept: List[Dict[str, str]] = []
for capability, items in buckets.items():
if capability == "" or len(items) <= limit:
kept.extend(items)
continue
shuffled = items[:]
rng.shuffle(shuffled)
kept.extend(shuffled[:limit])
return kept
def _inject_missing_capability_seeds(samples: List[Dict[str, str]]) -> None:
present = {str(row.get("capability", "")).strip() for row in samples if row.get("capability")}
for seed in FALLBACK_CAPABILITY_SEEDS:
capability = seed["capability"]
if capability in present:
continue
instruction = _clean_text(seed["instruction"])
response = _clean_text(seed["response"])
samples.append(
{
"instruction": instruction,
"response": response,
"source": "capability_seed_fallback",
"topic": capability,
"capability": capability,
}
)
present.add(capability)
def build_samples(
training_path: str = "training_data.json",
kb_path: str = "knowledge_base.json",
max_kb_samples: int = 5000,
kb_categories: Optional[Sequence[str]] = None,
exclude_kb_categories: Optional[Sequence[str]] = None,
include_training: bool = True,
include_kb: bool = True,
min_question_len: int = 4,
max_question_len: int = 240,
min_answer_len: int = 8,
max_answer_len: int = 500,
min_kb_confidence: float = 0.0,
high_quality_only: bool = False,
include_kb_aliases: bool = True,
max_aliases_per_kb: int = 2,
max_alias_samples: int = 2000,
dedupe: bool = True,
enforce_quality_filter: bool = True,
quality_min_alpha_ratio: float = 0.20,
include_docs_pdfs: bool = True,
docs_pdf_dir: str = "docs",
max_docs_pdf_files: int = 12,
max_pdf_pages_per_file: int = 25,
pdf_chunk_chars: int = 1100,
max_pdf_samples: int = 1200,
external_instruction_paths: Optional[Sequence[str]] = (
"datasets/dialogue_qa_flows.jsonl",
"capability_pack.jsonl",
"multicapability_bootstrap.jsonl",
"adaptive_boost.jsonl",
),
max_kb_per_category: Optional[int] = 160,
max_dialogue_samples: int = 1800,
max_capability_seed_rebalanced_samples: int = 900,
max_rows_per_capability: Optional[int] = 180,
rebalance_capabilities: bool = True,
capability_registry_path: str = "capability_registry.json",
min_rows_per_high_priority_capability: int = 80,
min_rows_per_medium_priority_capability: int = 40,
seed: int = 42,
) -> List[Dict[str, str]]:
random.seed(seed)
training_data = _read_json(Path(training_path))
kb_data = _read_json(Path(kb_path))
samples: List[Dict[str, str]] = []
if include_training:
for ex in training_data.get("training_examples", []):
instruction = _clean_text(ex.get("instruction", ex.get("prompt", "")))
response = _clean_text(ex.get("response", ""))
if len(instruction) < 4 or len(response) < 4:
continue
if enforce_quality_filter:
if not _row_quality_ok(instruction, response, quality_min_alpha_ratio):
continue
topic = _clean_text(ex.get("topic", ""))
capability = _infer_capability(instruction, response, source="training_data", topic=topic)
samples.append(
{
"instruction": instruction,
"response": response,
"source": "training_data",
"topic": topic or capability,
"capability": capability,
}
)
if include_docs_pdfs:
pdf_samples = _build_pdf_samples(
docs_pdf_dir=docs_pdf_dir,
max_docs_pdf_files=max_docs_pdf_files,
max_pdf_pages_per_file=max_pdf_pages_per_file,
pdf_chunk_chars=pdf_chunk_chars,
max_pdf_samples=max_pdf_samples,
enforce_quality_filter=enforce_quality_filter,
quality_min_alpha_ratio=quality_min_alpha_ratio,
)
samples.extend(pdf_samples)
if external_instruction_paths:
anchor_paths: List[Path] = [Path.cwd(), Path(__file__).resolve().parent]
for candidate_path in (training_path, kb_path):
maybe = Path(candidate_path)
if maybe.is_absolute():
anchor_paths.append(maybe.parent)
elif maybe.exists():
anchor_paths.append(maybe.resolve().parent)
for ext_path in external_instruction_paths:
resolved = _resolve_optional_path(ext_path, anchor_paths)
for row in _read_jsonl(resolved):
instruction = _clean_text(row.get("instruction", row.get("prompt", "")))
response = _clean_text(row.get("response", ""))
source = _clean_text(row.get("source", "")) or "external_dialogue_qa"
if len(instruction) < 4 or len(response) < 4:
continue
if len(instruction) > max_question_len or len(response) > max_answer_len * 4:
# External dialogue turns can be longer than KB answers; keep bounded.
continue
if enforce_quality_filter:
if not _row_quality_ok(instruction, response, quality_min_alpha_ratio):
continue
topic = _clean_text(str(row.get("topic", "")))
capability = _clean_text(str(row.get("capability", "")))
if not capability:
capability = _infer_capability(instruction, response, source=source, topic=topic)
samples.append(
{
"instruction": instruction,
"response": response,
"source": source,
"topic": topic or capability,
"capability": capability,
}
)
if kb_categories is None:
kb_categories = ["programming", "api", "academic", "writing", "ai_ml", "networking", "mathematics", "general"]
kb_categories = set(kb_categories)
excluded = set(exclude_kb_categories or [])
if include_kb:
kb_items = list(kb_data.items())
random.shuffle(kb_items)
added_kb = 0
added_alias = 0
per_category = defaultdict(int)
for question, payload in kb_items:
if added_kb >= max_kb_samples:
break
if not isinstance(payload, dict):
continue
category = payload.get("category")
if category not in kb_categories or category in excluded:
continue
if max_kb_per_category is not None and per_category[category] >= max_kb_per_category:
continue
confidence = float(payload.get("confidence", 0.0) or 0.0)
if confidence < min_kb_confidence:
continue
answer = _clean_text(payload.get("answer", ""))
question = _clean_text(question)
if len(question) < min_question_len or len(answer) < min_answer_len:
continue
if len(question) > max_question_len or len(answer) > max_answer_len:
continue
if enforce_quality_filter:
if not _row_quality_ok(question, answer, quality_min_alpha_ratio):
continue
if high_quality_only and not _is_high_quality_entry(question, answer, category):
continue
capability = _infer_capability(question, answer, source="knowledge_base", topic=category)
samples.append(
{
"instruction": question,
"response": answer,
"source": "knowledge_base",
"topic": category or capability,
"capability": capability,
}
)
added_kb += 1
per_category[category] += 1
if include_kb_aliases and added_alias < max_alias_samples:
aliases = payload.get("aliases", [])
if isinstance(aliases, list):
for alias in aliases[:max_aliases_per_kb]:
alias_text = _clean_text(str(alias))
if not alias_text:
continue
if len(alias_text) < min_question_len or len(alias_text) > max_question_len:
continue
if enforce_quality_filter and not _row_quality_ok(alias_text, answer, quality_min_alpha_ratio):
continue
samples.append(
{
"instruction": alias_text,
"response": answer,
"source": "knowledge_base_alias",
"topic": category or capability,
"capability": capability,
}
)
added_alias += 1
if added_alias >= max_alias_samples:
break
_inject_missing_capability_seeds(samples)
if dedupe:
unique = {}
for row in samples:
key = (_normalize_key(row["instruction"]), _normalize_key(row["response"]))
if key not in unique:
unique[key] = row
samples = list(unique.values())
source_limits: Dict[str, int] = {}
if max_dialogue_samples > 0:
source_limits["dialogue"] = int(max_dialogue_samples)
source_limits["external_dialogue_qa"] = int(max_dialogue_samples)
source_limits["dialogue_qa_flows"] = int(max_dialogue_samples)
if max_capability_seed_rebalanced_samples > 0:
source_limits["capability_seed_rebalanced"] = int(max_capability_seed_rebalanced_samples)
if source_limits:
samples = _cap_rows_by_source(samples, source_limits=source_limits, seed=seed + 13)
samples = _cap_rows_by_capability(samples, max_rows_per_capability=max_rows_per_capability, seed=seed + 15)
if rebalance_capabilities:
targets = _load_capability_targets(
capability_registry_path=capability_registry_path,
min_rows_per_high=min_rows_per_high_priority_capability,
min_rows_per_medium=min_rows_per_medium_priority_capability,
)
samples = _rebalance_capabilities(samples, targets=targets, seed=seed + 17)
random.shuffle(samples)
return samples
def _is_high_quality_entry(question: str, answer: str, category: str) -> bool:
q = question.lower()
a = answer.lower()
if any(noise in q for noise in ["exercise", "chapter", "contents"]):
return False
if any(noise in a for noise in ["exercise", "chapter", "contents"]):
return False
if category == "general":
return False
if "?" not in question and not q.startswith(("what", "how", "why", "when", "where", "who", "can", "is", "are", "do", "does")):
return False
return True
def _load_capability_targets(
capability_registry_path: str,
min_rows_per_high: int,
min_rows_per_medium: int,
) -> Dict[str, int]:
default_targets = {
capability: min_rows_per_medium
for capability in BENCH_CAPABILITIES
}
path = Path(capability_registry_path)
if not path.exists():
return default_targets
try:
payload = _read_json(path)
except Exception:
return default_targets
targets = dict(default_targets)
for item in payload.get("capabilities", []):
if not isinstance(item, dict):
continue
capability = str(item.get("id", "")).strip()
if not capability:
continue
if item.get("enabled", True) is False:
continue
priority = str(item.get("train_priority", "medium")).strip().lower()
if priority == "high":
targets[capability] = max(targets.get(capability, 0), int(min_rows_per_high))
elif priority == "medium":
targets[capability] = max(targets.get(capability, 0), int(min_rows_per_medium))
else:
targets[capability] = max(targets.get(capability, 0), max(10, int(min_rows_per_medium // 2)))
return targets
def _rebalance_capabilities(samples: List[Dict[str, str]], targets: Dict[str, int], seed: int) -> List[Dict[str, str]]:
rng = random.Random(seed)
by_capability: Dict[str, List[Dict[str, str]]] = defaultdict(list)
for row in samples:
capability = str(row.get("capability", "")).strip()
if not capability:
continue
by_capability[capability].append(row)
balanced = list(samples)
for capability, target in targets.items():
pool = by_capability.get(capability, [])
if not pool:
continue
if len(pool) >= target:
continue
needed = target - len(pool)
for _ in range(needed):
template = dict(rng.choice(pool))
source = str(template.get("source", "rebalanced"))
template["source"] = f"{source}:rebalanced"
balanced.append(template)
return balanced
def save_jsonl(samples: List[Dict[str, str]], out_path: str) -> None:
path = Path(out_path)
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
for row in samples:
f.write(json.dumps(row, ensure_ascii=False) + "\n")
def build_dataset_file(
out_path: str = "models/tiny_model_dataset.jsonl",
training_path: str = "training_data.json",
kb_path: str = "knowledge_base.json",
max_kb_samples: int = 5000,
kb_categories: Optional[Sequence[str]] = None,
exclude_kb_categories: Optional[Sequence[str]] = None,
include_training: bool = True,
include_kb: bool = True,
min_question_len: int = 4,
max_question_len: int = 240,
min_answer_len: int = 8,
max_answer_len: int = 500,
min_kb_confidence: float = 0.0,
high_quality_only: bool = False,
include_kb_aliases: bool = True,
max_aliases_per_kb: int = 2,
max_alias_samples: int = 2000,
dedupe: bool = True,
enforce_quality_filter: bool = True,
quality_min_alpha_ratio: float = 0.20,
include_docs_pdfs: bool = True,
docs_pdf_dir: str = "docs",
max_docs_pdf_files: int = 12,
max_pdf_pages_per_file: int = 25,
pdf_chunk_chars: int = 1100,
max_pdf_samples: int = 1200,
external_instruction_paths: Optional[Sequence[str]] = (
"datasets/dialogue_qa_flows.jsonl",
"capability_pack.jsonl",
"multicapability_bootstrap.jsonl",
"adaptive_boost.jsonl",
),
max_kb_per_category: Optional[int] = 160,
max_dialogue_samples: int = 1800,
max_capability_seed_rebalanced_samples: int = 900,
max_rows_per_capability: Optional[int] = 180,
rebalance_capabilities: bool = True,
capability_registry_path: str = "capability_registry.json",
min_rows_per_high_priority_capability: int = 80,
min_rows_per_medium_priority_capability: int = 40,
seed: int = 42,
) -> Dict[str, object]:
samples = build_samples(
training_path=training_path,
kb_path=kb_path,
max_kb_samples=max_kb_samples,
kb_categories=kb_categories,
exclude_kb_categories=exclude_kb_categories,
include_training=include_training,
include_kb=include_kb,
min_question_len=min_question_len,
max_question_len=max_question_len,
min_answer_len=min_answer_len,
max_answer_len=max_answer_len,
min_kb_confidence=min_kb_confidence,
high_quality_only=high_quality_only,
include_kb_aliases=include_kb_aliases,
max_aliases_per_kb=max_aliases_per_kb,
max_alias_samples=max_alias_samples,
dedupe=dedupe,
enforce_quality_filter=enforce_quality_filter,
quality_min_alpha_ratio=quality_min_alpha_ratio,
include_docs_pdfs=include_docs_pdfs,
docs_pdf_dir=docs_pdf_dir,
max_docs_pdf_files=max_docs_pdf_files,
max_pdf_pages_per_file=max_pdf_pages_per_file,
pdf_chunk_chars=pdf_chunk_chars,
max_pdf_samples=max_pdf_samples,
external_instruction_paths=external_instruction_paths,
max_kb_per_category=max_kb_per_category,
max_dialogue_samples=max_dialogue_samples,
max_capability_seed_rebalanced_samples=max_capability_seed_rebalanced_samples,
max_rows_per_capability=max_rows_per_capability,
rebalance_capabilities=rebalance_capabilities,
capability_registry_path=capability_registry_path,
min_rows_per_high_priority_capability=min_rows_per_high_priority_capability,
min_rows_per_medium_priority_capability=min_rows_per_medium_priority_capability,
seed=seed,
)
save_jsonl(samples, out_path)
training_count = sum(1 for s in samples if s["source"] == "training_data")
docs_pdf_count = sum(1 for s in samples if s["source"] == "docs_pdf")
external_count = sum(
1 for s in samples if s["source"].split(":", 1)[0] not in {"training_data", "docs_pdf", "knowledge_base", "knowledge_base_alias"}
)
kb_count = sum(1 for s in samples if s["source"] == "knowledge_base")
kb_alias_count = sum(1 for s in samples if s["source"] == "knowledge_base_alias")
capability_counts: Dict[str, int] = defaultdict(int)
for row in samples:
capability = str(row.get("capability", "")).strip()
if capability:
capability_counts[capability] += 1
return {
"total_samples": len(samples),
"training_samples": training_count,
"docs_pdf_samples": docs_pdf_count,
"external_samples": external_count,
"kb_samples": kb_count,
"kb_alias_samples": kb_alias_count,
"capability_counts": dict(sorted(capability_counts.items())),
}
def build_curriculum_files(
stage1_path: str = "models/tiny_model_stage1.jsonl",
stage2_path: str = "models/tiny_model_stage2.jsonl",
training_path: str = "training_data.json",
kb_path: str = "knowledge_base.json",
max_kb_samples_stage1: int = 1000,
max_kb_samples_stage2: int = 4000,
seed: int = 42,
) -> Dict[str, Dict[str, object]]:
stage1_stats = build_dataset_file(
out_path=stage1_path,
training_path=training_path,
kb_path=kb_path,
max_kb_samples=max_kb_samples_stage1,
kb_categories=["programming", "api", "academic", "writing", "mathematics", "networking", "ai_ml"],
exclude_kb_categories=["general"],
include_training=True,
include_kb=True,
min_question_len=8,
max_question_len=180,
min_answer_len=20,
max_answer_len=320,
min_kb_confidence=0.85,
high_quality_only=True,
include_kb_aliases=True,
max_aliases_per_kb=1,
max_alias_samples=400,
max_kb_per_category=90,
max_dialogue_samples=700,
max_capability_seed_rebalanced_samples=450,
max_rows_per_capability=120,
dedupe=True,
enforce_quality_filter=True,
quality_min_alpha_ratio=0.28,
rebalance_capabilities=True,
min_rows_per_high_priority_capability=45,
min_rows_per_medium_priority_capability=24,
seed=seed,
)
stage2_stats = build_dataset_file(
out_path=stage2_path,
training_path=training_path,
kb_path=kb_path,
max_kb_samples=max_kb_samples_stage2,
kb_categories=["programming", "api", "academic", "writing", "ai_ml", "networking", "mathematics", "general"],
include_training=True,
include_kb=True,
min_question_len=4,
max_question_len=240,
min_answer_len=8,
max_answer_len=500,
min_kb_confidence=0.0,
high_quality_only=False,
include_kb_aliases=True,
max_aliases_per_kb=1,
max_alias_samples=1200,
max_kb_per_category=120,
max_dialogue_samples=1600,
max_capability_seed_rebalanced_samples=800,
max_rows_per_capability=180,
dedupe=True,
enforce_quality_filter=True,
quality_min_alpha_ratio=0.24,
rebalance_capabilities=True,
min_rows_per_high_priority_capability=100,
min_rows_per_medium_priority_capability=50,
seed=seed,
)
return {"stage1": stage1_stats, "stage2": stage2_stats}
if __name__ == "__main__":
stats = build_dataset_file()
print(stats)
|