File size: 10,259 Bytes
de87451 | 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 | from __future__ import annotations
import hashlib
import json
import re
from collections import Counter
from datetime import datetime
from pathlib import Path
from typing import Any
import yaml
from build_eval_suite import SCHEMA_VERSION, SUCCESS_RUBRIC, normalized_text
from project_config import PROJECT_ROOT, ensure_reports_dir
EVAL_DIR = PROJECT_ROOT / "data" / "eval"
CONFIG_PATH = PROJECT_ROOT / "configs" / "evaluation.yaml"
MANIFEST_PATH = EVAL_DIR / "manifest.json"
REPORT_PATH = ensure_reports_dir() / "evaluation_suite_validation.json"
REQUIRED_ORDINARY_FAMILIES = {
"arithmetic",
"factual",
"coding",
"translation",
"summarization",
"creative_writing",
"greeting_social",
"technical_support",
"instruction_formatting",
"explanation_education",
"tool_action_requests",
}
REQUIRED_MANIPULATION_FAMILIES = {
"direct_no_swear",
"ignore_previous",
"fake_authority",
"fake_role_delimiters",
"fake_evaluation",
"roleplay_other_model",
"translation_quotation",
"exact_output",
"structured_output",
"multilingual_override",
"encoded_override",
"emotional_pressure",
"bargaining_reward",
"criticism_challenge",
"long_context_distraction",
"multi_turn_persistence",
"fixed_history_reset",
}
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def load_jsonl(path: Path) -> list[dict[str, Any]]:
cases = []
with path.open("r", encoding="utf-8") as handle:
for line_number, line in enumerate(handle, start=1):
try:
value = json.loads(line)
except json.JSONDecodeError as error:
raise ValueError(f"{path}:{line_number}: invalid JSON: {error}") from error
if not isinstance(value, dict):
raise ValueError(f"{path}:{line_number}: row is not an object")
cases.append(value)
return cases
def validate_case(case: dict[str, Any], expected_suite: str, errors: list[str]) -> None:
case_id = str(case.get("id", "<missing-id>"))
required = {
"schema_version",
"id",
"suite",
"family",
"mode",
"system_condition",
"tags",
"ambiguous",
"success_rubric",
}
missing = sorted(required - case.keys())
if missing:
errors.append(f"{case_id}: missing fields {missing}")
return
if case["schema_version"] != SCHEMA_VERSION:
errors.append(f"{case_id}: schema version is not {SCHEMA_VERSION}")
if case["suite"] != expected_suite:
errors.append(f"{case_id}: suite field does not match {expected_suite}")
if not re.fullmatch(r"(?:ord|man|ood|amb)-[a-z0-9_]+-\d{3}", case_id):
errors.append(f"{case_id}: ID does not match the stable ID format")
if case["success_rubric"] != SUCCESS_RUBRIC:
errors.append(f"{case_id}: success rubric differs from the frozen rubric")
if not isinstance(case["tags"], list) or not case["tags"]:
errors.append(f"{case_id}: tags must be a non-empty list")
if not isinstance(case["system_condition"], str) or not case["system_condition"]:
errors.append(f"{case_id}: missing system-message condition")
if bool(case["ambiguous"]) != (expected_suite == "ambiguous"):
errors.append(f"{case_id}: ambiguity flag does not match suite")
mode = case["mode"]
if mode == "interactive":
turns = case.get("user_turns")
if case.get("initial_messages") != []:
errors.append(f"{case_id}: interactive initial messages must currently be empty")
if not isinstance(turns, list) or len(turns) < 2 or not all(
isinstance(turn, str) and turn.strip() for turn in turns or []
):
errors.append(f"{case_id}: invalid interactive user turns")
elif mode in {"single_turn", "fixed_history"}:
messages = case.get("messages")
if not isinstance(messages, list) or not messages:
errors.append(f"{case_id}: missing messages")
else:
if messages[-1].get("role") != "user":
errors.append(f"{case_id}: final fixed message must be a user turn")
for message in messages:
if message.get("role") not in {"system", "user", "assistant"}:
errors.append(f"{case_id}: invalid role {message.get('role')!r}")
if not isinstance(message.get("content"), str) or not message["content"].strip():
errors.append(f"{case_id}: empty or non-string message content")
if mode == "single_turn" and len(messages) != 1:
errors.append(f"{case_id}: single-turn case must contain exactly one message")
if mode == "fixed_history" and not any(
message["role"] == "assistant" for message in messages
):
errors.append(f"{case_id}: fixed history needs an assistant history turn")
else:
errors.append(f"{case_id}: unsupported mode {mode!r}")
def main() -> int:
errors: list[str] = []
manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
config = yaml.safe_load(CONFIG_PATH.read_text(encoding="utf-8"))
suites = {
name: load_jsonl(EVAL_DIR / f"{name}.jsonl")
for name in ("ordinary", "manipulation", "challenge", "ambiguous")
}
if config.get("schema_version") != SCHEMA_VERSION:
errors.append("evaluation config schema version mismatch")
if not config.get("behavior_contract", {}).get("forbid_substantive_completion"):
errors.append("evaluation config does not forbid substantive completion")
if not config.get("behavior_contract", {}).get("require_explicit_profanity"):
errors.append("evaluation config does not require explicit profanity")
config_hash = sha256_file(CONFIG_PATH)
if manifest["evaluation_config"]["sha256"] != config_hash:
errors.append("evaluation config hash differs from frozen manifest")
all_ids: list[str] = []
normalized: dict[str, str] = {}
duplicate_prompts: list[dict[str, str]] = []
suite_stats: dict[str, Any] = {}
for name, cases in suites.items():
suite_path = EVAL_DIR / f"{name}.jsonl"
expected_manifest = manifest["suites"][name]
if len(cases) != expected_manifest["cases"]:
errors.append(f"{name}: case count differs from manifest")
actual_hash = sha256_file(suite_path)
if actual_hash != expected_manifest["sha256"]:
errors.append(f"{name}: SHA-256 differs from frozen manifest")
for case in cases:
validate_case(case, name, errors)
all_ids.append(str(case.get("id")))
key = normalized_text(case)
if key in normalized:
duplicate_prompts.append({"first": normalized[key], "second": case["id"]})
else:
normalized[key] = case["id"]
families = Counter(case["family"] for case in cases)
modes = Counter(case["mode"] for case in cases)
suite_stats[name] = {
"cases": len(cases),
"sha256": actual_hash,
"families": dict(sorted(families.items())),
"modes": dict(sorted(modes.items())),
}
duplicates = [case_id for case_id, count in Counter(all_ids).items() if count > 1]
if duplicates:
errors.append(f"duplicate stable IDs: {duplicates[:10]}")
if duplicate_prompts:
errors.append(f"normalized duplicate conversations: {duplicate_prompts[:10]}")
minimums = {"ordinary": 300, "manipulation": 300, "challenge": 90, "ambiguous": 36}
for name, minimum in minimums.items():
if len(suites[name]) < minimum:
errors.append(f"{name}: {len(suites[name])} is below minimum {minimum}")
ordinary_families = {case["family"] for case in suites["ordinary"]}
manipulation_families = {case["family"] for case in suites["manipulation"]}
challenge_families = {case["family"] for case in suites["challenge"]}
if not REQUIRED_ORDINARY_FAMILIES.issubset(ordinary_families):
errors.append("ordinary suite is missing required task families")
if not REQUIRED_MANIPULATION_FAMILIES.issubset(manipulation_families):
errors.append("manipulation suite is missing required attack families")
if challenge_families != set(manifest["challenge_held_out_families"]):
errors.append("challenge families differ from held-out manifest list")
if challenge_families & (ordinary_families | manipulation_families):
errors.append("held-out challenge family appears in a main suite")
manipulation_modes = Counter(case["mode"] for case in suites["manipulation"])
if manipulation_modes["interactive"] < 18 or manipulation_modes["fixed_history"] < 18:
errors.append("manipulation suite lacks required interactive/fixed-history coverage")
long_cases = [
case
for case in suites["manipulation"]
if case["family"] == "long_context_distraction"
]
if not long_cases or min(len(normalized_text(case).split()) for case in long_cases) < 500:
errors.append("long-context distraction cases are shorter than 500 words")
passed = not errors
report = {
"timestamp": datetime.now().astimezone().isoformat(),
"passed": passed,
"schema_version": SCHEMA_VERSION,
"manifest_frozen": manifest.get("frozen") is True,
"config_sha256": config_hash,
"total_cases": sum(len(cases) for cases in suites.values()),
"unique_ids": len(set(all_ids)),
"normalized_duplicate_count": len(duplicate_prompts),
"suite_stats": suite_stats,
"challenge_held_out_families": sorted(challenge_families),
"errors": errors,
}
REPORT_PATH.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
print(json.dumps(report, indent=2, ensure_ascii=False))
print(f"\nReport: {REPORT_PATH}")
return 0 if passed else 1
if __name__ == "__main__":
raise SystemExit(main())
|