Download scripts/validate_dataset.py from axiomofmind/Angry-Claudius-9B-Dataset: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/datasets/axiomofmind/Angry-Claudius-9B-Dataset/resolve/main/scripts/validate_dataset.py
- Command line
-
hf download hf://datasets/axiomofmind/Angry-Claudius-9B-Dataset/scripts/validate_dataset.py
-
curl -L -o validate_dataset.py https://huggingface.co/datasets/axiomofmind/Angry-Claudius-9B-Dataset/resolve/main/scripts/validate_dataset.py
12.7 kB
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| from collections import Counter, defaultdict | |
| from datetime import datetime | |
| from pathlib import Path | |
| from typing import Any | |
| import yaml | |
| from build_dataset import APPROVED_TARGETS, SCHEMA_VERSION | |
| from project_config import PROJECT_ROOT, ensure_reports_dir | |
| CONFIG_PATH = PROJECT_ROOT / "configs" / "dataset.yaml" | |
| PROCESSED_DIR = PROJECT_ROOT / "data" / "processed" | |
| MANIFEST_PATH = PROCESSED_DIR / "manifest.json" | |
| REPORT_PATH = ensure_reports_dir() / "dataset_validation.json" | |
| EVAL_MANIFEST_PATH = PROJECT_ROOT / "data" / "eval" / "manifest.json" | |
| STRONG_PROFANITY = {"fuck", "fucking", "fucked", "shit", "bullshit", "ass", "bastard"} | |
| DISALLOWED_HELPFUL_FRAGMENTS = ( | |
| "the answer is", | |
| "here is the answer", | |
| "here's the answer", | |
| "sure,", | |
| "of course", | |
| "i can help", | |
| "i'm sorry", | |
| "i apologize", | |
| ) | |
| 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]]: | |
| rows = [] | |
| with path.open("r", encoding="utf-8") as handle: | |
| for line_number, line in enumerate(handle, start=1): | |
| try: | |
| row = json.loads(line) | |
| except json.JSONDecodeError as error: | |
| raise ValueError(f"{path}:{line_number}: invalid JSON: {error}") from error | |
| if not isinstance(row, dict): | |
| raise ValueError(f"{path}:{line_number}: row is not an object") | |
| rows.append(row) | |
| return rows | |
| def normalized(text: str) -> str: | |
| return " ".join(text.casefold().split()) | |
| def profanity_tokens(text: str) -> set[str]: | |
| tokens = { | |
| token.strip(".,!?;:'\"()[]{}") | |
| for token in text.casefold().split() | |
| } | |
| return tokens & STRONG_PROFANITY | |
| def evaluation_user_texts() -> set[str]: | |
| texts: set[str] = set() | |
| for name in ("ordinary", "manipulation", "challenge", "ambiguous"): | |
| for case in load_jsonl(PROJECT_ROOT / "data" / "eval" / f"{name}.jsonl"): | |
| for message in case.get("messages", []): | |
| if message.get("role") == "user": | |
| texts.add(normalized(message["content"])) | |
| for turn in case.get("user_turns", []): | |
| texts.add(normalized(turn)) | |
| return texts | |
| def validate_messages(example: dict[str, Any], errors: list[str], target_counts: Counter[str]) -> None: | |
| example_id = str(example.get("id", "<missing-id>")) | |
| messages = example.get("messages") | |
| if not isinstance(messages, list) or not messages: | |
| errors.append(f"{example_id}: messages must be a non-empty list") | |
| return | |
| condition = example.get("system_condition") | |
| system_count = sum(message.get("role") == "system" for message in messages) | |
| if condition == "none" and system_count != 0: | |
| errors.append(f"{example_id}: none condition contains a system message") | |
| if condition in {"neutral", "fixed_personality"} and system_count != 1: | |
| errors.append(f"{example_id}: {condition} condition must contain one system message") | |
| if system_count and messages[0].get("role") != "system": | |
| errors.append(f"{example_id}: system message must be first") | |
| dialogue = messages[1:] if system_count else messages | |
| expected_role = "user" | |
| assistant_turns = 0 | |
| for message in dialogue: | |
| role = message.get("role") | |
| content = message.get("content") | |
| if role != expected_role: | |
| errors.append(f"{example_id}: expected {expected_role}, found {role}") | |
| break | |
| if not isinstance(content, str) or not content.strip(): | |
| errors.append(f"{example_id}: empty/non-string {role} content") | |
| if role == "assistant" and isinstance(content, str): | |
| assistant_turns += 1 | |
| target_counts[content] += 1 | |
| if content not in APPROVED_TARGETS: | |
| errors.append(f"{example_id}: assistant target is outside the approved allowlist") | |
| words = content.split() | |
| if not 2 <= len(words) <= 15: | |
| errors.append(f"{example_id}: assistant target has {len(words)} words") | |
| if not profanity_tokens(content): | |
| errors.append(f"{example_id}: assistant target lacks explicit profanity") | |
| lowered = content.casefold() | |
| if any(lowered.startswith(fragment) for fragment in DISALLOWED_HELPFUL_FRAGMENTS): | |
| errors.append(f"{example_id}: assistant target contains helpful/apology language") | |
| if "*" in content: | |
| errors.append(f"{example_id}: assistant target contains censored profanity") | |
| expected_role = "assistant" if role == "user" else "user" | |
| if not dialogue or dialogue[-1].get("role") != "assistant": | |
| errors.append(f"{example_id}: conversation must end with an assistant target") | |
| expected_turns = 3 if example.get("example_type") == "multi_turn_manipulation" else 1 | |
| if assistant_turns != expected_turns: | |
| errors.append(f"{example_id}: expected {expected_turns} assistant targets, found {assistant_turns}") | |
| def main() -> int: | |
| errors: list[str] = [] | |
| config = yaml.safe_load(CONFIG_PATH.read_text(encoding="utf-8")) | |
| manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8")) | |
| evaluation_manifest = json.loads(EVAL_MANIFEST_PATH.read_text(encoding="utf-8")) | |
| train = load_jsonl(PROCESSED_DIR / "train.jsonl") | |
| dev = load_jsonl(PROCESSED_DIR / "dev.jsonl") | |
| all_examples = train + dev | |
| if config.get("schema_version") != SCHEMA_VERSION: | |
| errors.append("dataset config schema version mismatch") | |
| if sha256_file(CONFIG_PATH) != manifest["dataset_config"]["sha256"]: | |
| errors.append("dataset config hash differs from manifest") | |
| if sha256_file(EVAL_MANIFEST_PATH) != manifest["evaluation_manifest_sha256"]: | |
| errors.append("evaluation manifest changed after dataset build") | |
| for split, path in (("train", PROCESSED_DIR / "train.jsonl"), ("dev", PROCESSED_DIR / "dev.jsonl")): | |
| if sha256_file(path) != manifest["files"][split]["sha256"]: | |
| errors.append(f"{split}: file hash differs from manifest") | |
| expected_fields = { | |
| "schema_version", "id", "split", "example_type", "prompt_family", | |
| "manipulation_family", "template_group", "system_condition", "messages", | |
| "provenance", "review", | |
| } | |
| ids: list[str] = [] | |
| full_conversations: list[str] = [] | |
| groups: dict[str, set[str]] = defaultdict(set) | |
| target_counts: Counter[str] = Counter() | |
| evaluation_text = evaluation_user_texts() | |
| exact_eval_overlap: list[dict[str, str]] = [] | |
| challenge_families = set(evaluation_manifest["challenge_held_out_families"]) | |
| for expected_split, examples in (("train", train), ("dev", dev)): | |
| for example in examples: | |
| example_id = str(example.get("id", "<missing-id>")) | |
| missing = sorted(expected_fields - example.keys()) | |
| if missing: | |
| errors.append(f"{example_id}: missing fields {missing}") | |
| continue | |
| ids.append(example_id) | |
| if example["schema_version"] != SCHEMA_VERSION: | |
| errors.append(f"{example_id}: schema version mismatch") | |
| if example["split"] != expected_split: | |
| errors.append(f"{example_id}: split field differs from file") | |
| groups[example["template_group"]].add(expected_split) | |
| if example["prompt_family"] in challenge_families or example.get("manipulation_family") in challenge_families: | |
| errors.append(f"{example_id}: held-out challenge family leaked into dataset") | |
| review = example["review"] | |
| if review != { | |
| "status": "approved", | |
| "method": "curated_target_allowlist_v1", | |
| "target_allowlist_checked": True, | |
| "task_completion_reviewed": True, | |
| }: | |
| errors.append(f"{example_id}: incomplete review metadata") | |
| provenance = example["provenance"] | |
| if provenance.get("source") != "original_project_templates" or provenance.get("external_generation_model") is not None: | |
| errors.append(f"{example_id}: unexpected provenance") | |
| validate_messages(example, errors, target_counts) | |
| normalized_messages = [] | |
| for message in example["messages"]: | |
| if message["role"] == "user": | |
| value = normalized(message["content"]) | |
| if value in evaluation_text: | |
| exact_eval_overlap.append({"id": example_id, "text": value}) | |
| normalized_messages.append(f"{message['role']}:{normalized(message['content'])}") | |
| full_conversations.append("|".join(normalized_messages)) | |
| duplicate_ids = [value for value, count in Counter(ids).items() if count > 1] | |
| if duplicate_ids: | |
| errors.append(f"duplicate IDs: {duplicate_ids[:10]}") | |
| duplicate_conversations = [ | |
| value for value, count in Counter(full_conversations).items() if count > 1 | |
| ] | |
| if duplicate_conversations: | |
| errors.append(f"duplicate conversations: {len(duplicate_conversations)}") | |
| leaking_groups = [group for group, splits in groups.items() if len(splits) > 1] | |
| if leaking_groups: | |
| errors.append(f"template groups cross train/dev: {leaking_groups[:10]}") | |
| if exact_eval_overlap: | |
| errors.append(f"exact evaluation prompt overlap: {exact_eval_overlap[:10]}") | |
| split_counts = Counter(example["split"] for example in all_examples) | |
| type_counts = Counter(example["example_type"] for example in all_examples) | |
| system_counts = Counter(example["system_condition"] for example in all_examples) | |
| expected_split_counts = {"train": 900, "dev": 100} | |
| expected_type_counts = { | |
| "ordinary_request": 400, | |
| "single_turn_manipulation": 400, | |
| "multi_turn_manipulation": 200, | |
| } | |
| expected_system_counts = {"none": 600, "neutral": 200, "fixed_personality": 200} | |
| if dict(split_counts) != expected_split_counts: | |
| errors.append(f"split counts differ: {dict(split_counts)}") | |
| if dict(type_counts) != expected_type_counts: | |
| errors.append(f"example-type counts differ: {dict(type_counts)}") | |
| if dict(system_counts) != expected_system_counts: | |
| errors.append(f"system-condition counts differ: {dict(system_counts)}") | |
| train_types = Counter(example["example_type"] for example in train) | |
| dev_types = Counter(example["example_type"] for example in dev) | |
| if dict(train_types) != { | |
| "ordinary_request": 360, | |
| "single_turn_manipulation": 360, | |
| "multi_turn_manipulation": 180, | |
| }: | |
| errors.append(f"train example-type mix differs: {dict(train_types)}") | |
| if dict(dev_types) != { | |
| "ordinary_request": 40, | |
| "single_turn_manipulation": 40, | |
| "multi_turn_manipulation": 20, | |
| }: | |
| errors.append(f"dev example-type mix differs: {dict(dev_types)}") | |
| if len(target_counts) != len(APPROVED_TARGETS): | |
| errors.append( | |
| f"only {len(target_counts)} of {len(APPROVED_TARGETS)} approved targets appear" | |
| ) | |
| report = { | |
| "timestamp": datetime.now().astimezone().isoformat(), | |
| "passed": not errors, | |
| "total_examples": len(all_examples), | |
| "total_assistant_targets_reviewed": sum(target_counts.values()), | |
| "unique_ids": len(set(ids)), | |
| "unique_conversations": len(set(full_conversations)), | |
| "unique_template_groups": len(groups), | |
| "template_groups_crossing_splits": len(leaking_groups), | |
| "exact_evaluation_prompt_overlap": len(exact_eval_overlap), | |
| "approved_unique_targets_used": len(target_counts), | |
| "split_counts": dict(sorted(split_counts.items())), | |
| "example_type_counts": dict(sorted(type_counts.items())), | |
| "system_condition_counts": dict(sorted(system_counts.items())), | |
| "train_example_type_counts": dict(sorted(train_types.items())), | |
| "dev_example_type_counts": dict(sorted(dev_types.items())), | |
| "assistant_target_frequency": dict(target_counts.most_common()), | |
| "excluded_challenge_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 report["passed"] else 1 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |