Datasets:
Download _open_jev/s1mb_open_jev.py from hotchpotch/s1mb-dataset: direct link, hf CLI and curl.
- Browser
- Download file 23 kB
-
https://huggingface.co/datasets/hotchpotch/s1mb-dataset/resolve/cf7ef6117e3dba600f8109fc8e5f430484221630/_open_jev/s1mb_open_jev.py
- Command line
-
hf download hf://datasets/hotchpotch/s1mb-dataset@cf7ef6117e3dba600f8109fc8e5f430484221630/_open_jev/s1mb_open_jev.py
-
curl -L -o s1mb_open_jev.py https://huggingface.co/datasets/hotchpotch/s1mb-dataset/resolve/cf7ef6117e3dba600f8109fc8e5f430484221630/_open_jev/s1mb_open_jev.py
23 kB
| """Add capped, task-proportional balanced Open-Jev test samples to a staged S1MB release.""" | |
| from __future__ import annotations | |
| import argparse | |
| import copy | |
| import hashlib | |
| import inspect | |
| import json | |
| import random | |
| import re | |
| import shutil | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| from bekko_system_one.dataset_schema import inference_input, validate_row | |
| from bekko_system_one.release import render_group | |
| from bekko_system_one.stratification import select_balanced_cases | |
| from datasets import DatasetDict, disable_progress_bars, load_from_disk | |
| from .open_jev import REPO, REVISION, URL, canonical | |
| from .open_jev_build import atomic_text, sha, write_json | |
| VERSION = "s1mb.open_jev.test-balanced.v1.20260928" | |
| def inventory(root): | |
| return {str(p.relative_to(root)): sha(p) for p in root.rglob("*") if p.is_file()} | |
| def input_digest(row): | |
| return hashlib.sha256(canonical(inference_input(row)).encode()).hexdigest() | |
| def select_test_cases(dataset, *, cap=100, seed=42, name): | |
| """Preserve mixed task proportions, then apply balanced-v1 strict-cap within each task.""" | |
| if cap < 1: | |
| raise ValueError("cap must be positive") | |
| by_type = defaultdict(list) | |
| for i, row in enumerate(dataset): | |
| if row["split"] != "test" or len(row["input"]["decisions"]) != 1: | |
| raise ValueError("Open-Jev sampling requires one-judgment test cases") | |
| by_type[row["input"]["decisions"][0]["type"]].append(i) | |
| count = min(cap, len(dataset)) | |
| if count < len(by_type): | |
| raise ValueError("Cap is too small to represent all task types") | |
| ideal = {k: count * len(v) / len(dataset) for k, v in by_type.items()} if count else {} | |
| quotas = {k: max(1, int(v)) for k, v in ideal.items()} | |
| order = sorted(quotas) | |
| random.Random(f"{seed}:{name}:task-quotas").shuffle(order) | |
| while sum(quotas.values()) > count: | |
| k = max((k for k in order if quotas[k] > 1), key=lambda k: quotas[k] - ideal[k]) | |
| quotas[k] -= 1 | |
| while sum(quotas.values()) < count: | |
| k = max( | |
| (k for k in order if quotas[k] < len(by_type[k])), key=lambda k: ideal[k] - quotas[k] | |
| ) | |
| quotas[k] += 1 | |
| indices, task_audits = [], {} | |
| for task, pool in sorted(by_type.items()): | |
| picks, audit = select_balanced_cases( | |
| dataset.select(pool), cap=quotas[task], seed=seed, name=f"{name}:test:{task}" | |
| ) | |
| indices.extend(pool[i] for i in picks) | |
| task_audits[task] = audit | |
| assert len(indices) == len(set(indices)) == count | |
| return sorted(indices), dict( | |
| version=VERSION, | |
| seed=seed, | |
| requested_cap=cap, | |
| source_cases=len(dataset), | |
| selected_cases=count, | |
| sampling_unit="one original judgment case", | |
| source_task_counts={k: len(v) for k, v in by_type.items()}, | |
| task_quotas=quotas, | |
| policy="proportional_task_quotas_then_balanced_v1_strict_cap", | |
| task_audits=task_audits, | |
| shortage=max(0, cap - count), | |
| replacement=False, | |
| candidate_order="preserve_source", | |
| labels="unchanged", | |
| group_policy="preserve IDs; sampled cases remain test, not a new group partition", | |
| ) | |
| def counts(entries): | |
| return {k: sum(e[k] for e in entries) for k in ("cases", "decisions")} | |
| def build(source, bekko, output, *, cap=100, seed=42): | |
| source, bekko, output = map(Path, (source, bekko, output)) | |
| if output.exists() or source.resolve() in output.resolve().parents: | |
| raise ValueError("Choose a new, non-nested stage") | |
| before = inventory(source) | |
| active = json.loads((source / "training-manifest.json").read_text()) | |
| all_data = json.loads((source / "all-data-manifest.json").read_text()) | |
| quarantine = json.loads((source / "quarantine-manifest.json").read_text()) | |
| if active["train"] or any(e["split"] != "test" for e in all_data["evaluation"]): | |
| raise ValueError("Expected test-only S1MB") | |
| old_names = {e["dataset"] for e in all_data["evaluation"]} | |
| if any(n.startswith("open_jev__") for n in old_names): | |
| raise ValueError("Open-Jev already present") | |
| bekko_metadata = json.loads((bekko / "dataset_metadata.json").read_text()) | |
| bekko_catalog = json.loads((bekko / "task-catalog.json").read_text()) | |
| bekko_manifest = json.loads((bekko / "training-manifest.json").read_text()) | |
| eligible = sorted( | |
| e["dataset"] | |
| for e in bekko_manifest["evaluation"] | |
| if e["dataset"].startswith("open_jev__") and e["split"] == "test" | |
| ) | |
| if len(eligible) != len(set(eligible)) or not eligible: | |
| raise ValueError("Invalid Open-Jev test membership") | |
| bekko_identity = { | |
| name: sha(bekko / name) | |
| for name in ["dataset_metadata.json", "task-catalog.json", "training-manifest.json"] | |
| } | |
| shutil.copytree(source, output) | |
| archive = output / "_open_jev" | |
| archive.mkdir() | |
| for p in source.iterdir(): | |
| if p.is_file(): | |
| target = archive / "before_addition" / p.name | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copy2(p, target) | |
| for p in (Path(__file__), Path(inspect.getfile(select_balanced_cases))): | |
| shutil.copy2(p, archive / p.name) | |
| if (bekko / "_open_jev/upstream").is_dir(): | |
| shutil.copytree(bekko / "_open_jev/upstream", archive / "upstream") | |
| metadata = json.loads((source / "dataset_metadata.json").read_text()) | |
| catalog = json.loads((source / "task-catalog.json").read_text()) | |
| membership = json.loads((source / "manifest.json").read_text()) | |
| exceptions = json.loads((source / "sampling-exceptions.json").read_text()) | |
| registry = json.loads((source / "sources.json").read_text()) | |
| old_inputs = set() | |
| for entry in all_data["evaluation"]: | |
| for row in load_from_disk(str(source / entry["dataset"]))["test"]: | |
| old_inputs.add(input_digest(row)) | |
| sampling, added, sample_inputs, sample_groups, statistics = {}, [], {}, set(), {} | |
| duplicate_inputs = Counter() | |
| source_files = {} | |
| for name in eligible: | |
| dataset = load_from_disk(str(bekko / name / "test")) | |
| indices, audit = select_test_cases(dataset, cap=cap, seed=seed, name=name) | |
| # Repeat selection once to validate reproducibility of stored membership. | |
| repeat, _ = select_test_cases(dataset, cap=cap, seed=seed, name=name) | |
| assert indices == repeat | |
| rows = list(dataset.select(indices)) | |
| for row in rows: | |
| validate_row(row) | |
| render_group(row, 0) | |
| prov = json.loads(row["provenance_json"]) | |
| assert prov["acquisition_dataset"] == REPO and prov["acquisition_revision"] == REVISION | |
| assert prov["original_split"] == "test" | |
| digest = input_digest(row) | |
| if digest in old_inputs: | |
| raise ValueError(f"New input overlaps existing S1MB: {name}") | |
| if digest in sample_inputs: | |
| if sample_inputs[digest] != name: | |
| raise ValueError("Exact input overlaps different new subsets") | |
| duplicate_inputs[name] += 1 | |
| sample_inputs[digest] = name | |
| sample_groups.add(row["group_id"]) | |
| DatasetDict(test=dataset.select(indices)).save_to_disk(str(output / name)) | |
| restored = load_from_disk(str(output / name))["test"] | |
| assert list(restored) == rows | |
| audit["selected_group_count"] = len({r["group_id"] for r in rows}) | |
| audit["repeated_exact_inputs"] = duplicate_inputs[name] | |
| audit["source_fingerprint"] = dataset._fingerprint | |
| audit["logical_rows_sha256"] = hashlib.sha256( | |
| "".join(canonical(r) + "\n" for r in rows).encode() | |
| ).hexdigest() | |
| sampling[name] = audit | |
| write_json(archive / "sampling" / f"{name}.json", audit) | |
| source_files[name] = { | |
| str(p.relative_to(bekko)): sha(p) | |
| for p in (bekko / name / "test").iterdir() | |
| if p.is_file() | |
| } | |
| membership["datasets"][name] = { | |
| "test": dict( | |
| indices=indices, | |
| case_ids=[r["case_id"] for r in rows], | |
| source_fingerprint=dataset._fingerprint, | |
| source_dataset=name, | |
| source_split="test", | |
| source_files_sha256=source_files[name], | |
| sampling_version=VERSION, | |
| ) | |
| } | |
| entry = dict( | |
| dataset=name, | |
| path=f"{name}/test", | |
| split="test", | |
| cases=len(rows), | |
| decisions=len(rows), | |
| unlabeled_decisions=0, | |
| ) | |
| added.append(entry) | |
| types = dict(Counter(r["input"]["decisions"][0]["type"] for r in rows)) | |
| stats = dict(cases=len(rows), decisions=len(rows), types=types) | |
| statistics[name] = stats | |
| meta = copy.deepcopy(bekko_metadata["datasets"][name]) | |
| meta.update( | |
| source_subset=name, | |
| evaluation_suite=None, | |
| source_reference=f"SOURCES.md#{name.lower()}", | |
| task_types=types, | |
| language=sorted({r["language"] for r in rows}), | |
| structured_statistics={ | |
| "test": dict( | |
| counts=dict(cases=len(rows), decisions=len(rows), labeled_decisions=len(rows)), | |
| decision_types=types, | |
| annotation_kinds=dict( | |
| Counter(t["annotation_kind"] for r in rows for t in r["targets"]) | |
| ), | |
| ) | |
| }, | |
| renewed_statistics=stats, | |
| sampling=audit, | |
| evaluation_only=True, | |
| ) | |
| # The preserved acquisition license counts refer to the full source pool, not this sample. | |
| meta["upstream_pool_declared_license_counts"] = meta.pop("declared_license_counts", {}) | |
| meta["declared_license_counts"] = dict( | |
| Counter(json.loads(r["provenance_json"])["declared_license"] for r in rows) | |
| ) | |
| metadata["datasets"][name] = meta | |
| profile = copy.deepcopy(bekko_catalog["datasets"][name]) | |
| profile["source_profile"] = name | |
| catalog["datasets"][name] = profile | |
| registry["datasets"][name] = dict( | |
| upstream_datasets=meta["upstream_datasets"], | |
| source_tasks={}, | |
| author=None, | |
| version=REVISION, | |
| license=list(meta["declared_license_counts"]), | |
| review=None, | |
| label_status="Synthetic reference labels retained unchanged", | |
| source_profile=name, | |
| review_evidence=profile["evidence"], | |
| observed_row_sources=[ | |
| dict( | |
| dataset_id=REPO, | |
| revision=REVISION, | |
| original_split="test", | |
| config=meta["acquisition_config"], | |
| source_task=meta["original_source"], | |
| ) | |
| ], | |
| ) | |
| labels = [label for task in audit["task_audits"].values() for label in task["labels"]] | |
| exceptional = dict( | |
| cases=len(rows), | |
| requested=cap, | |
| available=len(dataset), | |
| expanded=False, | |
| shortage=audit["shortage"], | |
| missing_in_sample=[x for x in labels if x["missing"]], | |
| quota_shortfalls=[x for x in labels if x["shortfall"]], | |
| zero_availability=[x for x in labels if x["unavailable"]], | |
| ) | |
| if audit["shortage"] or any( | |
| exceptional[k] for k in ("missing_in_sample", "quota_shortfalls", "zero_availability") | |
| ): | |
| exceptions[name] = exceptional | |
| print(f"{name}: {len(rows)}/{len(dataset)} {types}", flush=True) | |
| # Compare sampled test membership against every Open-Jev training row; no train data are written. | |
| train_matches = [] | |
| for name in eligible: | |
| train = load_from_disk(str(bekko / name / "train")) | |
| for row in train: | |
| if row["group_id"] in sample_groups or input_digest(row) in sample_inputs: | |
| train_matches.append(row["case_id"]) | |
| if train_matches: | |
| raise ValueError(f"Open-Jev train/test overlap: {train_matches[:5]}") | |
| for manifest in (active, all_data): | |
| manifest["evaluation"].extend(added) | |
| manifest["evaluation"].sort(key=lambda e: e["dataset"]) | |
| total = counts(all_data["evaluation"]) | |
| active_total = counts(active["evaluation"]) | |
| metadata["totals"] = {**total, "configs": len(metadata["datasets"])} | |
| metadata["content_version"] = VERSION | |
| metadata["sampling"] += ( | |
| " Open-Jev: seed 42, up to 100 original test judgments per subset, proportional task quotas then balanced-v1 strict-cap within each task; no replacement; source rows and order unchanged." | |
| ) | |
| metadata["open_jev_sampling"] = dict( | |
| version=VERSION, | |
| seed=seed, | |
| cap=cap, | |
| source_dataset=REPO, | |
| revision=REVISION, | |
| source_bekko_metadata_sha256=bekko_identity["dataset_metadata.json"], | |
| subsets=len(eligible), | |
| added_cases=sum(e["cases"] for e in added), | |
| statistics=sampling, | |
| sampling_helper_sha256=sha(Path(inspect.getfile(select_balanced_cases))), | |
| ) | |
| catalog["s1mb_release_version"] = VERSION | |
| for filename, obj in [ | |
| ("manifest.json", membership), | |
| ("sampling-exceptions.json", exceptions), | |
| ("task-catalog.json", catalog), | |
| ("sources.json", registry), | |
| ("training-manifest.json", active), | |
| ("all-data-manifest.json", all_data), | |
| ("quarantine-manifest.json", quarantine), | |
| ]: | |
| write_json(output / filename, obj) | |
| metadata["task_catalog_sha256"] = sha(output / "task-catalog.json") | |
| write_json(output / "dataset_metadata.json", metadata) | |
| overlap = dict( | |
| scope="Canonical parsed inference inputs versus existing S1MB and all Open-Jev train rows; sampled groups versus Open-Jev train groups. No approximate or all-corpora decontamination claim.", | |
| existing_s1mb_exact_input_matches=0, | |
| open_jev_train_exact_input_or_group_matches=0, | |
| within_sample_repeated_inputs=dict(duplicate_inputs), | |
| ) | |
| write_json(archive / "overlap.json", overlap) | |
| write_json(archive / "source-files.json", source_files) | |
| # S1MB's actual evaluator loader, for all current subsets, not just the additions. | |
| from s1mb.hf_data import load_hf_cases | |
| loader_counts = Counter() | |
| for entry in all_data["evaluation"]: | |
| cases = load_hf_cases(output / entry["dataset"], "test") | |
| assert len(cases) == entry["cases"] | |
| assert sum(len(c.questions) for c in cases) == entry["decisions"] | |
| statistics[entry["dataset"]] = dict( | |
| cases=len(cases), | |
| decisions=sum(len(c.questions) for c in cases), | |
| types=dict(Counter(q.task for c in cases for q in c.questions)), | |
| ) | |
| loader_counts["cases"] += len(cases) | |
| loader_counts["decisions"] += sum(len(c.questions) for c in cases) | |
| assert dict(loader_counts) == total | |
| summary = dict( | |
| version=VERSION, | |
| status="complete", | |
| totals=total, | |
| subsets=len(metadata["datasets"]), | |
| active_subsets=len(active["evaluation"]), | |
| active_totals=active_total, | |
| quarantined_subsets=len(quarantine["evaluation"]), | |
| added_subsets=len(added), | |
| added_cases=sum(e["cases"] for e in added), | |
| statistics=statistics, | |
| sampling_seed=seed, | |
| requested_per_subset=cap, | |
| overlap=overlap, | |
| s1mb_loader_counts=dict(loader_counts), | |
| source_unchanged=True, | |
| existing_subset_files_byte_identical=True, | |
| new_rows_equal_bekko_test_rows=True, | |
| previous_verification="_open_jev/before_addition/verification.json", | |
| model_evaluation=False, | |
| validation="All additions schema/rendering/readback validated; every stored subset loaded by the actual S1MB evaluator; membership, counts and input overlap checked.", | |
| ) | |
| write_json(output / "verification.json", summary) | |
| write_json(archive / "summary.json", summary) | |
| readme = (source / "README.md").read_text() | |
| readme = re.sub( | |
| r"\*\*\d+ stored subsets · [\d,]+ cases · [\d,]+ decisions · test only\*\*", | |
| f"**{len(metadata['datasets'])} stored subsets · {total['cases']:,} cases · {total['decisions']:,} decisions · test only**", | |
| readme, | |
| count=1, | |
| ) | |
| readme = re.sub( | |
| r"The default evaluation manifest contains \*\*\d+ subsets · [\d,]+ cases · [\d,]+ decisions\*\*", | |
| f"The default evaluation manifest contains **{len(active['evaluation'])} subsets · {active_total['cases']:,} cases · {active_total['decisions']:,} decisions**", | |
| readme, | |
| count=1, | |
| ) | |
| section = f"""## Open-Jev test subsets | |
| The `open_jev__*` subsets are sampled from the **original test splits** acquired through [ZefanCai/Open-Jev]({URL}) at revision `{REVISION}`, using Bekko's native conversion. Each original judgment remains one case. All original row contents, case/group IDs, probability targets, candidate order and acquisition provenance are preserved. | |
| Sampling uses seed {seed}, a strict maximum of {cap} cases per subset, and no replacement. For mixed-task sources, allocate proportional Choice/Noul/Score quotas (each present task gets at least one), then use balanced-v1 strict-cap sampling within each task: Noul/repeated Choice label coverage and confidence strata where supported, uniform sampling otherwise. Score labels are not forced into equal bins. This follows the existing balancing approach with explicit task coverage and a strict cap. `manifest.json` records source indices, case IDs, fingerprints and file hashes; `_open_jev/sampling/` records quotas and shortfalls. | |
| 23 subsets contain 100 cases each. `open_jev__trex_runner-v1` has only four source test cases, so all four are included; no train/calibration/validation/OOD backfill or duplication is used. Group IDs are preserved, but sampling is by judgment case, not complete conversation/trajectory; related selected rows remain test cases and are not independent scenarios. Existing within-test repeated inputs are retained and audited. | |
| Customer-control includes the original caveat: generated conversations are CC0, while upstream TypeSafe-documentation question wording has no verified license. Painting Score uses explicit HSL values, not ordinal indices. See [sources](SOURCES.md), row provenance and `_open_jev/upstream/` for source-specific declarations. These are synthetic controls, not official Jev training data or measured model confidence. | |
| Exact canonical inference-input overlap with existing S1MB and with the Open-Jev training pool was checked; sampled group IDs were also checked against that training pool. This does not prove semantic novelty or non-overlap with every external training corpus. The benchmark content version is `{VERSION}`; identify this version and subset membership when comparing results. | |
| """ | |
| readme = readme.replace( | |
| "## S1MB generalization benchmarks", section + "## S1MB generalization benchmarks", 1 | |
| ) | |
| new_table = "".join( | |
| f"| {e['dataset']} | {e['cases']} | {e['decisions']} | include_with_caveat | [sources](SOURCES.md#{e['dataset'].lower()}) |\n" | |
| for e in added | |
| ) | |
| readme = readme.replace( | |
| "\n## Quarantined retrieval subsets", | |
| "\n" + new_table + "\n## Quarantined retrieval subsets", | |
| 1, | |
| ) | |
| # Keep all inventory rows contiguous with the original table. | |
| readme = readme.replace("\n\n" + new_table, "\n" + new_table) | |
| readme += "\n`verification.json` describes current membership and the Open-Jev addition checks; previous detailed validation is archived in `_open_jev/before_addition/verification.json`. Checksums cover every packaged file except the root checksum file itself.\n" | |
| atomic_text(output / "README.md", readme) | |
| sources_md = (source / "SOURCES.md").read_text() | |
| for name in eligible: | |
| m = metadata["datasets"][name] | |
| sources_md += f"\n## {name}\n\nAcquired through [{REPO}]({URL}) at `{REVISION}`; config `{m['acquisition_config']}`, original source `{m['original_source']}`, split `test`. Sampled from the native Bekko release with seed {seed}; exact membership is in `manifest.json`. Original record JSON and acquisition file hashes remain in row provenance.\n\nDeclared source license scope: {', '.join(m['declared_license_counts'])}.\n\n{catalog['datasets'][name]['disposition_reason']}\n" | |
| atomic_text(output / "SOURCES.md", sources_md) | |
| atomic_text( | |
| output / "AGENTS.md", | |
| (source / "AGENTS.md").read_text() | |
| + """ | |
| ## Open-Jev evaluation samples | |
| `open_jev__*` subsets contain only original Open-Jev test judgments, acquired through the pinned Open-Jev repository and converted by Bekko. Keep that acquisition chain, license scope and original records in provenance. Customer-control's upstream question-wording license remains unverified; do not relicense the whole subset as CC0. | |
| Sample up to 100 cases without replacement with seed 42. Allocate proportional task quotas with at least one case per available task, then apply balanced-v1 strict-cap within each task. Preserve all row contents and soft targets; never fill a short test pool from train, calibration, validation or OOD. trex_runner has four test cases. Preserve source candidate order and numeric values, including painting HSL quantities. Record selected source indices, case IDs, fingerprints, file hashes, quotas, label shortfalls and repeated inputs. These one-judgment cases are sampled individually; group IDs remain intact and all selected members stay in test, not a newly partitioned group split. | |
| Keep `_open_jev/` sampling receipts and source documentation with the release. Recheck exact inference-input overlap against existing S1MB and the Open-Jev train pool, plus train/test group separation, before updating membership. Report the scope of overlap checks and use the current content version for comparisons; do not claim universal decontamination or new model performance from structural validation. | |
| """, | |
| ) | |
| assert inventory(source) == before | |
| assert bekko_identity == {name: sha(bekko / name) for name in bekko_identity} | |
| for name, files in source_files.items(): | |
| assert all(sha(bekko / p) == h for p, h in files.items()) | |
| checksums = { | |
| str(p.relative_to(output)): sha(p) | |
| for p in output.rglob("*") | |
| if p.is_file() and p != output / "checksums.json" | |
| } | |
| write_json(output / "checksums.json", checksums) | |
| return summary | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--source", type=Path, required=True) | |
| p.add_argument("--bekko", type=Path, required=True) | |
| p.add_argument("--output", type=Path, required=True) | |
| args = p.parse_args() | |
| disable_progress_bars() | |
| print(json.dumps(build(args.source, args.bekko, args.output), ensure_ascii=False, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |