Datasets:
Download code/prediction/build_prediction.py from chiron-group/chiron-data: direct link, hf CLI and curl.
- Browser
- Download file 35.2 kB
-
https://huggingface.co/datasets/chiron-group/chiron-data/resolve/main/code/prediction/build_prediction.py
- Command line
-
hf download hf://datasets/chiron-group/chiron-data/code/prediction/build_prediction.py
-
curl -L -o build_prediction.py https://huggingface.co/datasets/chiron-group/chiron-data/resolve/main/code/prediction/build_prediction.py
35.2 kB
| #!/usr/bin/env python3 | |
| """Build prediction training data from the prepared domain QA splits. | |
| Input: data/raw/prediction/<domain>/qa_jsonl/{train,val,test}.jsonl; | |
| domain adapters and code/prompt/base/prediction_sft.py. | |
| Output: data/sft/prediction/<domain>/train.jsonl; an all-domain build also | |
| writes shuffled data/sft/prediction/train.jsonl. | |
| The fixed recipe produces 220,096 rows across 25 domains (prediction x2). | |
| Exact repetitions retain their base sample ID, numbered from 1 per domain. | |
| From the repository root: | |
| python code/prediction/build_prediction.py | |
| python code/prediction/build_prediction.py --domain wvs | |
| Default paths resolve from this script; an explicit relative --output-dir | |
| resolves from the working directory. Existing outputs are replaced only after a successful build. --domain updates | |
| only that domain; omit it to rebuild all domains and the combined training file. | |
| No model or API is used. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import importlib | |
| import json | |
| import os | |
| from pathlib import Path, PurePosixPath | |
| import random | |
| import shutil | |
| import sys | |
| import tempfile | |
| from types import SimpleNamespace | |
| from typing import Any, Iterable, TYPE_CHECKING | |
| if TYPE_CHECKING: | |
| from domain_adapter import DomainAdapter | |
| # Per-domain sampling settings for the current training data. | |
| # Fixed repetition seeds retain the existing balanced row sampling. | |
| RECIPE = json.loads(r'''{ | |
| "seed": 42, | |
| "sampling_seed": 42, | |
| "domains": [ | |
| { | |
| "domain": "openpsych_16pf", | |
| "expected": { | |
| "original_rows": 6000, | |
| "target_rows": 12000, | |
| "new_qa_rows": 6000, | |
| "repeat_rows": 0, | |
| "selected_qa_identities": 12000, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 6000, | |
| "n_rows": 6000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 10499470589791266714 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_big5", | |
| "expected": { | |
| "original_rows": 6000, | |
| "target_rows": 12000, | |
| "new_qa_rows": 6000, | |
| "repeat_rows": 0, | |
| "selected_qa_identities": 12000, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 6000, | |
| "n_rows": 6000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 13040073539266180314 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_cfcs", | |
| "expected": { | |
| "original_rows": 6000, | |
| "target_rows": 12000, | |
| "new_qa_rows": 6000, | |
| "repeat_rows": 0, | |
| "selected_qa_identities": 12000, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 6000, | |
| "n_rows": 6000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 5321929201018448350 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_dass", | |
| "expected": { | |
| "original_rows": 6000, | |
| "target_rows": 12000, | |
| "new_qa_rows": 6000, | |
| "repeat_rows": 0, | |
| "selected_qa_identities": 12000, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 6000, | |
| "n_rows": 6000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 279249353333600611 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_ecr", | |
| "expected": { | |
| "original_rows": 6000, | |
| "target_rows": 12000, | |
| "new_qa_rows": 6000, | |
| "repeat_rows": 0, | |
| "selected_qa_identities": 12000, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 6000, | |
| "n_rows": 6000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 16882618866441875049 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_hbds", | |
| "expected": { | |
| "original_rows": 6000, | |
| "target_rows": 12000, | |
| "new_qa_rows": 6000, | |
| "repeat_rows": 0, | |
| "selected_qa_identities": 12000, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 6000, | |
| "n_rows": 6000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 16829568668259040142 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_hsns_dd", | |
| "expected": { | |
| "original_rows": 6000, | |
| "target_rows": 12000, | |
| "new_qa_rows": 6000, | |
| "repeat_rows": 0, | |
| "selected_qa_identities": 12000, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 6000, | |
| "n_rows": 6000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 10577110164599503866 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_ipip_ffm", | |
| "expected": { | |
| "original_rows": 6000, | |
| "target_rows": 12000, | |
| "new_qa_rows": 6000, | |
| "repeat_rows": 0, | |
| "selected_qa_identities": 12000, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 6000, | |
| "n_rows": 6000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 1437962084681271941 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_npas", | |
| "expected": { | |
| "original_rows": 6000, | |
| "target_rows": 12000, | |
| "new_qa_rows": 6000, | |
| "repeat_rows": 0, | |
| "selected_qa_identities": 12000, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 6000, | |
| "n_rows": 6000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 4768999357416981961 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_npi", | |
| "expected": { | |
| "original_rows": 6000, | |
| "target_rows": 12000, | |
| "new_qa_rows": 4112, | |
| "repeat_rows": 1888, | |
| "selected_qa_identities": 10112, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 6000, | |
| "n_rows": 6000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 222635744097930896 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_osri44", | |
| "expected": { | |
| "original_rows": 6000, | |
| "target_rows": 12000, | |
| "new_qa_rows": 6000, | |
| "repeat_rows": 0, | |
| "selected_qa_identities": 12000, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 6000, | |
| "n_rows": 6000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 6274489641690183868 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_rse", | |
| "expected": { | |
| "original_rows": 6000, | |
| "target_rows": 12000, | |
| "new_qa_rows": 6000, | |
| "repeat_rows": 0, | |
| "selected_qa_identities": 12000, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 6000, | |
| "n_rows": 6000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 4036469726243532128 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_sd3", | |
| "expected": { | |
| "original_rows": 6000, | |
| "target_rows": 12000, | |
| "new_qa_rows": 6000, | |
| "repeat_rows": 0, | |
| "selected_qa_identities": 12000, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 6000, | |
| "n_rows": 6000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 14403481640224832594 | |
| } | |
| }, | |
| { | |
| "domain": "wvs", | |
| "expected": { | |
| "original_rows": 6000, | |
| "target_rows": 12000, | |
| "new_qa_rows": 6000, | |
| "repeat_rows": 0, | |
| "selected_qa_identities": 12000, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 6000, | |
| "n_rows": 6000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 12666534535018336613 | |
| } | |
| }, | |
| { | |
| "domain": "blog", | |
| "expected": { | |
| "original_rows": 4366, | |
| "target_rows": 8732, | |
| "new_qa_rows": 0, | |
| "repeat_rows": 4366, | |
| "selected_qa_identities": 4259, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 12 | |
| }, | |
| "parameters": { | |
| "n_seen": 4366, | |
| "n_rows": 4366, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 1651409857046731576 | |
| } | |
| }, | |
| { | |
| "domain": "essays_big5", | |
| "expected": { | |
| "original_rows": 2221, | |
| "target_rows": 4442, | |
| "new_qa_rows": 0, | |
| "repeat_rows": 2221, | |
| "selected_qa_identities": 2221, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 2221, | |
| "n_rows": 2221, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 17476351027149852104 | |
| } | |
| }, | |
| { | |
| "domain": "self_esteem", | |
| "expected": { | |
| "original_rows": 2926, | |
| "target_rows": 5852, | |
| "new_qa_rows": 0, | |
| "repeat_rows": 2926, | |
| "selected_qa_identities": 2926, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 2926, | |
| "n_rows": 2926, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 7982538820970341841 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_fti", | |
| "expected": { | |
| "original_rows": 4471, | |
| "target_rows": 8942, | |
| "new_qa_rows": 0, | |
| "repeat_rows": 4471, | |
| "selected_qa_identities": 4471, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 4471, | |
| "n_rows": 4471, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 2274013583456290213 | |
| } | |
| }, | |
| { | |
| "domain": "pandora", | |
| "expected": { | |
| "original_rows": 1275, | |
| "target_rows": 2550, | |
| "new_qa_rows": 0, | |
| "repeat_rows": 1275, | |
| "selected_qa_identities": 1275, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 1275, | |
| "n_rows": 1275, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 5877876598260418609 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_pwe", | |
| "expected": { | |
| "original_rows": 1215, | |
| "target_rows": 2430, | |
| "new_qa_rows": 0, | |
| "repeat_rows": 1215, | |
| "selected_qa_identities": 1215, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 1215, | |
| "n_rows": 1215, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 10158220687747116029 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_hsq", | |
| "expected": { | |
| "original_rows": 1924, | |
| "target_rows": 3848, | |
| "new_qa_rows": 0, | |
| "repeat_rows": 1924, | |
| "selected_qa_identities": 962, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 962, | |
| "n_rows": 1924, | |
| "samples_per_person": 2, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 8628061810344784494 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_as_sc_ad_do", | |
| "expected": { | |
| "original_rows": 1800, | |
| "target_rows": 3600, | |
| "new_qa_rows": 0, | |
| "repeat_rows": 1800, | |
| "selected_qa_identities": 900, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 900, | |
| "n_rows": 1800, | |
| "samples_per_person": 2, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 13313169970198720401 | |
| } | |
| }, | |
| { | |
| "domain": "grit_tweet", | |
| "expected": { | |
| "original_rows": 1850, | |
| "target_rows": 3700, | |
| "new_qa_rows": 0, | |
| "repeat_rows": 1850, | |
| "selected_qa_identities": 370, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 370, | |
| "n_rows": 1850, | |
| "samples_per_person": 5, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 17388215753015825545 | |
| } | |
| }, | |
| { | |
| "domain": "twitter_stmhd", | |
| "expected": { | |
| "original_rows": 2000, | |
| "target_rows": 4000, | |
| "new_qa_rows": 13, | |
| "repeat_rows": 1987, | |
| "selected_qa_identities": 1961, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 1, | |
| "legacy_val_overlap_identities_preserved": 5 | |
| }, | |
| "parameters": { | |
| "n_seen": 2000, | |
| "n_rows": 2000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 6091737023673135268 | |
| } | |
| }, | |
| { | |
| "domain": "openpsych_nr6", | |
| "expected": { | |
| "original_rows": 2000, | |
| "target_rows": 4000, | |
| "new_qa_rows": 6, | |
| "repeat_rows": 1994, | |
| "selected_qa_identities": 2006, | |
| "skipped_new_no_targets": 0, | |
| "skipped_new_duplicate_or_val_identity": 0, | |
| "legacy_val_overlap_identities_preserved": 0 | |
| }, | |
| "parameters": { | |
| "n_seen": 2000, | |
| "n_rows": 2000, | |
| "samples_per_person": 1, | |
| "shuffle_seed": 42, | |
| "min_questions": 5, | |
| "max_questions": 10, | |
| "min_observations_policy": 50, | |
| "max_observations_policy": 100, | |
| "repetition_seed": 1936428794131044696 | |
| } | |
| } | |
| ] | |
| }''') | |
| class BuildError(RuntimeError): | |
| """A required input or data invariant did not match.""" | |
| class RecoveryError(BuildError): | |
| """Publication could not be rolled back; retain the recovery directory.""" | |
| def require(condition: bool, message: str) -> None: | |
| if not condition: | |
| raise BuildError(message) | |
| def json_text(value: Any) -> str: | |
| return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) | |
| def relative_path(root: Path, name: str) -> Path: | |
| rel = PurePosixPath(name) | |
| require(not rel.is_absolute() and bool(rel.parts) and ".." not in rel.parts, | |
| f"Invalid relative input path: {name!r}") | |
| return root.joinpath(*rel.parts) | |
| def input_sources(recipe: dict[str, Any]) -> dict[str, dict[str, Any]]: | |
| """Resolve every domain's QA splits using the same repository layout.""" | |
| folder = PurePosixPath("data/raw/prediction") / recipe["domain"] / "qa_jsonl" | |
| return {split: {"path": str(folder / f"{split}.jsonl")} | |
| for split in ("train", "val", "test")} | |
| def load_runtime(release_root: Path) -> SimpleNamespace: | |
| """Load this project's adapters and prediction prompt.""" | |
| release_root = release_root.resolve() | |
| code_root = release_root / "code" | |
| for name, module in tuple(sys.modules.items()): | |
| if name.split(".", 1)[0] in {"domain_adapter", "prompt", "utils"}: | |
| origin = getattr(module, "__file__", None) | |
| origins = [origin] if origin else list(getattr(module, "__path__", ())) | |
| require(bool(origins) and all(Path(x).resolve().is_relative_to(code_root) for x in origins), | |
| "Chiron code from another checkout is already imported; use a fresh process") | |
| # Prevent imports from writing caches into either checkout. | |
| sys.dont_write_bytecode = True | |
| sys.path.insert(0, str(code_root)) | |
| adapters = importlib.import_module("domain_adapter") | |
| require(Path(adapters.__file__).resolve().is_relative_to(code_root), | |
| "This workspace's domain adapters were not selected") | |
| prompt = importlib.import_module("prompt.base.prediction_sft") | |
| system = getattr(prompt, "SYSTEM_PROMPT", "").strip() | |
| template = getattr(prompt, "USER_PROMPT", "").strip() | |
| require(bool(system) and bool(template), | |
| "prediction_sft.py must define nonempty SYSTEM_PROMPT and USER_PROMPT") | |
| return SimpleNamespace(get_adapter=adapters.get_adapter, read_jsonl=adapters.read_jsonl, | |
| system=system, template=template) | |
| def render_user_prompt(template: str, adapter: DomainAdapter, | |
| observations: list[str], questions: list[str]) -> str: | |
| """Keep domain-specific observation and question formatting in the adapter.""" | |
| return ( | |
| template | |
| .replace("{record_context}", adapter.record_context()) | |
| .replace("{observations}", adapter.format_observations_block(observations)) | |
| .replace("{questions}", adapter.format_question_block(questions)) | |
| ) | |
| def repeat_indices(size: int, count: int, seed: int) -> list[int]: | |
| """Match the original preparation: balanced copies of ROWS, not people.""" | |
| require(size >= 1, "Cannot repeat an empty pool") | |
| require(count >= 0, "Negative repeat count") | |
| rng = random.Random(seed) | |
| result: list[int] = [] | |
| while len(result) < count: | |
| order = list(range(size)) | |
| rng.shuffle(order) | |
| result.extend(order[:count - len(result)]) | |
| return result | |
| def rows_with_ids(domain: str, base_rows: list[dict[str, Any]], target: int, | |
| seed: int) -> list[dict[str, Any]]: | |
| """Assign IDs before repetition, retaining distinct identical source rows.""" | |
| rows = [{"sample_id": f"{domain}:{i}", "domain": domain, "messages": row["messages"]} | |
| for i, row in enumerate(base_rows, 1)] | |
| # Keep this separate from extend: the repetition pool is the BASE rows only. | |
| copies = [rows[i] for i in repeat_indices(len(rows), target - len(rows), seed)] | |
| rows.extend(copies) | |
| require(len(rows) == target, f"{domain}: wrong final row count") | |
| return rows | |
| def rebuild_domain(recipe: dict[str, Any], release_root: Path, | |
| runtime: SimpleNamespace, *, sampling_seed: int = 42) -> list[dict[str, Any]]: | |
| """Generate one domain from QA using its sampling and repetition settings.""" | |
| domain = recipe["domain"] | |
| params = recipe["parameters"] | |
| expected = recipe["expected"] | |
| sources = input_sources(recipe) | |
| paths = {key: relative_path(release_root, item["path"]) | |
| for key, item in sources.items()} | |
| for split, path in paths.items(): | |
| require(path.is_file(), f"Missing {domain} {split} QA file: {path}") | |
| adapter = runtime.get_adapter(domain) | |
| require(adapter.name == domain, f"{domain}: adapter name mismatch") | |
| require(adapter.min_observations == params["min_observations_policy"] and | |
| adapter.max_observations == params["max_observations_policy"], | |
| f"{domain}: observation policy mismatch") | |
| val_ids = {adapter.get_sample_id(x) for x in runtime.read_jsonl(paths["val"])} | |
| held_ids = {adapter.get_sample_id(x) for x in runtime.read_jsonl(paths["test"])} | |
| old_rows: list[dict[str, Any]] = [] | |
| additions: list[dict[str, Any]] = [] | |
| selected_ids: set[str] = set() | |
| legacy_val_overlap: set[str] = set() | |
| skipped_no_targets = 0 | |
| skipped_identity = 0 | |
| old_seen = 0 | |
| new_budget = expected["target_rows"] - expected["original_rows"] | |
| # read_jsonl skips empty lines; this is the original builder's record index, | |
| # not a re-enumeration of a filtered set or a physical line number. | |
| for sample_index, sample in enumerate(runtime.read_jsonl(paths["train"])): | |
| is_old = sample_index < params["n_seen"] | |
| if not is_old and len(additions) >= new_budget: | |
| break | |
| old_seen += int(is_old) | |
| require(sample.split == "train", f"{domain}: non-train QA record {sample_index + 1}") | |
| identity = adapter.get_sample_id(sample) | |
| # The original preparation fails here, including for old rows. Do not | |
| # silently skip formal-test identities and change the release recipe. | |
| require(identity not in held_ids, | |
| f"{domain}: QA record {sample_index + 1} overlaps the clean test set") | |
| if is_old and identity in val_ids: | |
| legacy_val_overlap.add(identity) | |
| if not is_old and (identity in selected_ids or identity in val_ids): | |
| skipped_identity += 1 | |
| continue | |
| views = params["samples_per_person"] if is_old else 1 | |
| had_targets = False | |
| for view in range(views): | |
| view_seed = sampling_seed + view * 1_000_003 | |
| observations = adapter.select_observations( | |
| sample, seed=view_seed, sample_index=sample_index | |
| ) | |
| targets = adapter.select_target_predictions( | |
| sample, seed=view_seed, sample_index=sample_index, | |
| max_questions=params["max_questions"], min_questions=params["min_questions"] | |
| ) | |
| if not targets: | |
| continue | |
| had_targets = True | |
| row = {"messages": [ | |
| {"role": "system", "content": runtime.system}, | |
| {"role": "user", "content": render_user_prompt( | |
| runtime.template, adapter, observations, [x.question for x in targets])}, | |
| {"role": "assistant", "content": adapter.format_answer_block(targets)}, | |
| ]} | |
| require(all(isinstance(x["content"], str) for x in row["messages"]) | |
| and bool(row["messages"][-1]["content"].strip()), | |
| f"{domain}: invalid generated messages at QA record {sample_index + 1}") | |
| (old_rows if is_old else additions).append(row) | |
| if had_targets: | |
| selected_ids.add(identity) | |
| if not had_targets and not is_old: | |
| skipped_no_targets += 1 | |
| require(old_seen == params["n_seen"], f"{domain}: original QA prefix is incomplete") | |
| order = list(range(len(old_rows))) | |
| if params["shuffle_seed"] is not None: | |
| random.Random(params["shuffle_seed"]).shuffle(order) | |
| old_rows = [old_rows[i] for i in order] | |
| require(len(old_rows) == params["n_rows"] == expected["original_rows"], | |
| f"{domain}: original SFT row count differs") | |
| actual = { | |
| "original_rows": len(old_rows), | |
| "new_qa_rows": len(additions), | |
| "repeat_rows": expected["target_rows"] - len(old_rows) - len(additions), | |
| "target_rows": expected["target_rows"], | |
| "selected_qa_identities": len(selected_ids), | |
| "skipped_new_no_targets": skipped_no_targets, | |
| "skipped_new_duplicate_or_val_identity": skipped_identity, | |
| "legacy_val_overlap_identities_preserved": len(legacy_val_overlap), | |
| } | |
| for name, value in expected.items(): | |
| require(actual[name] == value, | |
| f"{domain}: {name} mismatch (expected {value}, got {actual[name]})") | |
| require(not (selected_ids & held_ids), | |
| f"{domain}: selected QA identities overlap formal evaluation") | |
| return rows_with_ids(domain, old_rows + additions, expected["target_rows"], | |
| params["repetition_seed"]) | |
| def write_rows(path: Path, rows: Iterable[dict[str, Any]]) -> None: | |
| with path.open("xb") as handle: | |
| for row in rows: | |
| handle.write((json_text(row) + "\n").encode("utf-8")) | |
| handle.flush() | |
| os.fsync(handle.fileno()) | |
| def validate_recipe() -> None: | |
| domains = RECIPE["domains"] | |
| require(len(domains) == len({x["domain"] for x in domains}) == 25, | |
| "The embedded recipe must contain exactly 25 unique domains") | |
| require(sum(x["expected"]["original_rows"] for x in domains) == 110048, | |
| "Embedded original count mismatch") | |
| for key, expected in (("target_rows", 220096), ("new_qa_rows", 82131), ("repeat_rows", 27917)): | |
| require(sum(x["expected"][key] for x in domains) == expected, | |
| f"Embedded {key} count mismatch") | |
| for domain in domains: | |
| counts = domain["expected"] | |
| require(counts["target_rows"] == counts["original_rows"] * 2, | |
| f"{domain['domain']}: embedded target is not twice the original") | |
| def check_output_paths(output: Path, paths: list[Path], protected: set[Path]) -> None: | |
| """Keep generated destinations separate from input and code files.""" | |
| for relative in paths: | |
| path = output | |
| for part in (None, *relative.parts[:-1]): | |
| if part is not None: | |
| path = path / part | |
| require(not path.is_symlink(), f"Output directory must not be a symlink: {path}") | |
| require(not path.exists() or path.is_dir(), f"Output directory is a file: {path}") | |
| target = output / relative | |
| require(target.resolve() not in protected, f"Output would overwrite an input or code file: {target}") | |
| require(not target.is_symlink(), f"Output file must not be a symlink: {target}") | |
| require(not target.exists() or target.is_file(), f"Output file is a directory: {target}") | |
| def publish_outputs(stage: Path, output: Path, paths: list[Path], protected: set[Path]) -> None: | |
| """Replace only completed generated files, restoring old files on failure.""" | |
| check_output_paths(output, paths, protected) | |
| require(all((stage / p).is_file() for p in paths), "Generated output is incomplete") | |
| previous = stage / ".previous" | |
| published: list[tuple[Path, Path | None]] = [] | |
| created_dirs: list[Path] = [] | |
| try: | |
| for relative in paths: | |
| target = output / relative | |
| missing_dirs = [] | |
| parent = target.parent | |
| while not parent.exists(): | |
| missing_dirs.append(parent) | |
| parent = parent.parent | |
| for parent in reversed(missing_dirs): | |
| parent.mkdir() | |
| created_dirs.append(parent) | |
| backup = None | |
| if target.exists(): | |
| backup = previous / relative | |
| backup.parent.mkdir(parents=True, exist_ok=True) | |
| try: | |
| os.link(target, backup) | |
| except OSError: | |
| shutil.copy2(target, backup) | |
| published.append((target, backup)) | |
| os.replace(stage / relative, target) | |
| except BaseException as error: | |
| failed_restores = [] | |
| for target, backup in reversed(published): | |
| try: | |
| if backup is None: | |
| target.unlink(missing_ok=True) | |
| else: | |
| os.replace(backup, target) | |
| except OSError: | |
| failed_restores.append(str(target)) | |
| for folder in reversed(created_dirs): | |
| try: | |
| folder.rmdir() | |
| except OSError: | |
| pass | |
| if failed_restores: | |
| raise RecoveryError( | |
| f"Could not restore {failed_restores}; previous files retained in {previous}" | |
| ) from error | |
| raise | |
| def main(argv: list[str] | None = None) -> int: | |
| script_path = Path(__file__).resolve() | |
| release_root = script_path.parents[2] | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--output-dir", type=Path, default=release_root / "data/sft/prediction", | |
| help="Generated files are overwritten; default: this release's data/sft/prediction") | |
| parser.add_argument("--domain", default="all", metavar="DOMAIN", | |
| choices=["all", *(x["domain"] for x in RECIPE["domains"])], | |
| help="Domain to build; default: all 25 domains plus train.jsonl") | |
| args = parser.parse_args(argv) | |
| output = args.output_dir.expanduser().absolute() | |
| validate_recipe() | |
| selected = [x for x in RECIPE["domains"] if args.domain in ("all", x["domain"])] | |
| for recipe in selected: | |
| for source in input_sources(recipe).values(): | |
| path = relative_path(release_root, source["path"]) | |
| require(path.is_file(), f"Missing required input: {source['path']}. Place the prepared QA split at this project-relative path.") | |
| output_paths = [Path(x["domain"]) / "train.jsonl" for x in selected] | |
| if args.domain == "all": | |
| output_paths.append(Path("train.jsonl")) | |
| protected = {relative_path(release_root, item["path"]).resolve() | |
| for recipe in RECIPE["domains"] for item in input_sources(recipe).values()} | |
| protected.update(path.resolve() for path in (release_root / "code").rglob("*.py")) | |
| protected.add(script_path) | |
| check_output_paths(output, output_paths, protected) | |
| output = output.resolve() | |
| runtime = load_runtime(release_root) | |
| output.parent.mkdir(parents=True, exist_ok=True) | |
| stage = Path(tempfile.mkdtemp(prefix=f".{output.name}.building-", dir=output.parent)) | |
| try: | |
| all_rows: list[dict[str, Any]] = [] | |
| for recipe in selected: | |
| rows = rebuild_domain( | |
| recipe, release_root, runtime, sampling_seed=RECIPE["sampling_seed"] | |
| ) | |
| domain = recipe["domain"] | |
| folder = stage / domain | |
| folder.mkdir() | |
| write_rows(folder / "train.jsonl", rows) | |
| all_rows.extend(rows) | |
| print(f"{domain}: {len(rows)} rows", flush=True) | |
| expected_rows = sum(x["expected"]["target_rows"] for x in selected) | |
| require(len(all_rows) == expected_rows, "Selected prediction row count differs") | |
| if args.domain == "all": | |
| random.Random(RECIPE["seed"]).shuffle(all_rows) | |
| write_rows(stage / "train.jsonl", all_rows) | |
| publish_outputs(stage, output, output_paths, protected) | |
| print(f"Built {len(all_rows)} rows across {len(selected)} domains", flush=True) | |
| return 0 | |
| except RecoveryError: | |
| stage = None # Keep the recovery files named in the error message. | |
| raise | |
| finally: | |
| if stage is not None: | |
| shutil.rmtree(stage) | |
| if __name__ == "__main__": | |
| try: | |
| raise SystemExit(main()) | |
| except (BuildError, OSError, ValueError, KeyError, TypeError) as exc: | |
| print(f"Prediction build failed: {exc}", file=sys.stderr) | |
| raise SystemExit(1) | |