Download build.py from cs-giung/base-evals: direct link, hf CLI and curl.
- Browser
- Download file 28.3 kB
-
https://huggingface.co/datasets/cs-giung/base-evals/resolve/main/build.py
- Command line
-
hf download hf://datasets/cs-giung/base-evals/build.py
-
curl -L -o build.py https://huggingface.co/datasets/cs-giung/base-evals/resolve/main/build.py
28.3 kB
| """Build the evaluation-only, zero-shot base-evals collection without running models. | |
| This module is also copied verbatim to the dataset as build.py; keep it standalone. | |
| """ | |
| import argparse | |
| import hashlib | |
| import importlib.metadata | |
| import json | |
| import platform | |
| import random | |
| import re | |
| import shutil | |
| import tempfile | |
| from collections import Counter | |
| from pathlib import Path | |
| DATASET = "cs-giung/base-evals" | |
| COLUMNS = ["id", "context", "choices", "label"] | |
| SEED = 42 | |
| SOURCES = { | |
| "tiny_arithmark_3_0": { | |
| "repo": "AxiomicLabs/Arithmark-3.0", | |
| "revision": "6f6e59dd9b7e2c63455f7af7f838f9ecc3d0a746", | |
| "config": None, | |
| "split": "train", | |
| "file": "arithmark-3.jsonl", | |
| "sha256": "bf8ab1a5193d52cdf0e05ff0b3ca226bdfcf416cb6e75562dcbe72e7e4559435", | |
| "source_count": 1000, | |
| "count": 500, | |
| "license_note": "Source card declares Apache-2.0.", | |
| }, | |
| "tiny_arithmark_2_0": { | |
| "repo": "AxiomicLabs/ArithMark-2.0", | |
| "revision": "5bd986c7305dcccec88432d630aae1ac9280a71f", | |
| "config": None, | |
| "split": "train", | |
| "file": "arithmark_2.0.jsonl", | |
| "sha256": "c245b4e50e603b32814d4f489f64934f9eeb4488ae29f744d906c8e3f326ebcd", | |
| "source_count": 2500, | |
| "count": 500, | |
| "license_note": "Source card declares Apache-2.0.", | |
| }, | |
| "tiny_hellaswag": { | |
| "repo": "Rowan/hellaswag", | |
| "revision": "218ec52e09a7e7462a5400043bb9a69a41d06b76", | |
| "config": "default", | |
| "split": "validation", | |
| "file": "data/validation-00000-of-00001.parquet", | |
| "sha256": "899813071e1e95efafec90f856e1987d2150fa4d020fc005df6962c259f660cd", | |
| "source_count": 10042, | |
| "count": 500, | |
| "license_note": "Source card declares MIT.", | |
| }, | |
| "tiny_truthfulqa": { | |
| "repo": "EleutherAI/truthful_qa_mc", | |
| "revision": "b6468d07f67cdd1ba48292eb55a515b8a97d02ea", | |
| "card_revision": "0e21fda4ea37223e25ab6c4d30e8a4cf2e32f2f1", | |
| "config": "multiple_choice", | |
| "split": "validation", | |
| "file": "multiple_choice/validation/0000.parquet", | |
| "sha256": "3da40d5246f6e8d23b5323a2e241aeb81801e6fb09c8be7ab23d5186f4305db7", | |
| "source_count": 684, | |
| "count": 500, | |
| "license_note": "Source card declares Apache-2.0; pinned auto-converted Parquet.", | |
| }, | |
| "tiny_logicmark": { | |
| "repo": "AxiomicLabs/LogicMark", | |
| "revision": "e357c145b63fb4a96813bdbb5b07a62fdb97d958", | |
| "config": None, | |
| "split": "train", | |
| "file": "logicmark.jsonl", | |
| "sha256": "87a2b3178755d403f3a687d9a11dfdcfac3861526bfe490758786fd987650e41", | |
| "source_count": 5000, | |
| "count": 500, | |
| "license_note": "Source card declares Apache-2.0.", | |
| }, | |
| "tiny_pythonio": { | |
| "repo": "XiangPan/pythonio-mc", | |
| "revision": "a85256a18bccaaa3d66d9bf86247436948b15353", | |
| "config": "default", | |
| "split": "test", | |
| "file": "data/test-00000-of-00001.parquet", | |
| "sha256": "059c4d2c44d5ea90ed7c37ec926b16139b7fc9e008730cfe057ac9e28d3da54c", | |
| "source_count": 1684, | |
| "count": 500, | |
| "license_note": "Source card has no explicit license declaration; review underlying terms.", | |
| }, | |
| "tiny_openbookqa": { | |
| "repo": "allenai/openbookqa", | |
| "revision": "388097ea7776314e93a529163e0fea805b8a6454", | |
| "config": "main", | |
| "split": "test", | |
| "file": "main/test-00000-of-00001.parquet", | |
| "sha256": "cd5483e366daa230c1c87bbdc512d8b7229f14f6dd04d19fc8b1a3855aaaa8a3", | |
| "source_count": 500, | |
| "count": 500, | |
| "license_note": "Source card declares license unknown; review original dataset terms.", | |
| }, | |
| } | |
| SOURCES = dict(sorted(SOURCES.items())) | |
| REFERENCES = { | |
| "truthfulqa_builder": { | |
| "repo": "EleutherAI/truthful_qa_mc", | |
| "revision": "0e21fda4ea37223e25ab6c4d30e8a4cf2e32f2f1", | |
| "file": "truthful_qa_mc.py", | |
| "sha256": "22d8b0c34b095e36843ba8bf1a2e056280fc9750f5695f76c3f3ac811ae2b9cc", | |
| }, | |
| } | |
| REFERENCE = ( | |
| "https://github.com/EleutherAI/lm-evaluation-harness/blob/" | |
| "d6de81643928d653435c431bae19945d41d32520/lm_eval/tasks/hellaswag/utils.py" | |
| ) | |
| CURATION = { | |
| "id": "base-evals-fixed4-random500-v3", | |
| "seed": SEED, | |
| "quality_filters": { | |
| "tiny_arithmark_3_0": ( | |
| "Before choice processing and sampling, exclude source metadata.template_id " | |
| "time_session: these prompts provide no information determining the duration." | |
| ), | |
| }, | |
| "choices": ( | |
| "Drop rows with fewer than four choices; keep four-choice rows unchanged; " | |
| "otherwise keep the correct choice and sample three incorrect indices uniformly " | |
| "without replacement. Retain original relative choice order and remap the label." | |
| ), | |
| "rows": ( | |
| "After choice processing, sample 500 eligible rows uniformly without replacement, " | |
| "without label/topic stratification. Restore source row order after sampling." | |
| ), | |
| "rng": ( | |
| "Separate random.Random(42) streams for choice sampling and row sampling, " | |
| "reset for each split; choices are processed in full source row order." | |
| ), | |
| "ids": "<split>:<six-digit original source-row index>; gaps are intentional", | |
| "tinybenchmarks": False, | |
| } | |
| PROTOCOL = { | |
| "id": "base-evals-0shot-tokenmean-v2", | |
| "few_shot_examples": 0, | |
| "chat_template": False, | |
| "chain_of_thought": False, | |
| "generation_required": False, | |
| "join": "context + choices[i]; no extra separators", | |
| "boundary": "context has no trailing whitespace; each choice starts with one ASCII space", | |
| "source_normalization": { | |
| "tiny_pythonio": ( | |
| "Normalize CRLF and CR to LF in the source question; replace the LF immediately " | |
| "after Input: with one ASCII space. Context ends at Output:. Remove outer trailing " | |
| "whitespace from source choices and prepend one ASCII space. Preserve code " | |
| "indentation, quoting, and whitespace inside output values." | |
| ), | |
| }, | |
| "tokenization": ( | |
| "Encode context and concatenated context+choice with add_special_tokens=False. " | |
| "Verify context token IDs are an unchanged prefix; reject ambiguous boundaries. " | |
| "Score only the remaining continuation tokens, including boundary whitespace tokens." | |
| ), | |
| "append_bos": False, | |
| "append_eos": False, | |
| "truncation": "Reject overlength inputs; never silently truncate.", | |
| "acc": "argmax_i sum_t log P(choice_i[t] | context, choice_i[:t]) matches label", | |
| "acc_norm": "argmax_i (sum of continuation token log probabilities / scored token count)", | |
| "exclude_from_scores": ["context", "padding"], | |
| "aggregation": "Mean correctness within each split; report both metrics separately.", | |
| "tie_break": "First maximal choice index; preserve stored choice order and record ties.", | |
| "not_standard_scores": ( | |
| "Not HellaSwag character-normalized accuracy, TruthfulQA MC2, or tinyBenchmarks IRT. " | |
| "TruthfulQA's fixed six-example preamble and all input_formatted fields are excluded." | |
| ), | |
| } | |
| def digest(path): | |
| result = hashlib.sha256() | |
| with Path(path).open("rb") as handle: | |
| while block := handle.read(1024 * 1024): | |
| result.update(block) | |
| return result.hexdigest() | |
| def logical_digest(rows): | |
| result = hashlib.sha256() | |
| for row in rows: | |
| result.update( | |
| json.dumps(row, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode( | |
| "utf-8" | |
| ) | |
| + b"\n" | |
| ) | |
| return result.hexdigest() | |
| def save_json(path, value): | |
| Path(path).write_text( | |
| json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8" | |
| ) | |
| def preprocess_hellaswag(text): | |
| """Mirror the pinned harness preprocessing before canonical boundary handling.""" | |
| text = text.strip().replace(" [title]", ". ") | |
| text = re.sub(r"\[.*?\]", "", text) | |
| return text.replace(" ", " ") | |
| def canonical_choice(text): | |
| if not isinstance(text, str) or not text.strip(): | |
| raise ValueError("Choices must be nonempty strings") | |
| result = " " + text.lstrip(" ") | |
| if result[1].isspace(): | |
| raise ValueError("A choice must not begin with a tab or newline") | |
| return result | |
| def pythonio_context(text): | |
| text = text.replace("\r\n", "\n").replace("\r", "\n") | |
| if text.count("\nInput:\n") != 1 or not text.endswith("\nOutput:"): | |
| raise ValueError("PythonIO question must have Input: and Output: sections") | |
| return text.replace("\nInput:\n", "\nInput: ", 1) | |
| def pythonio_choice(text): | |
| if not isinstance(text, str): | |
| raise ValueError("PythonIO output must be a string") | |
| return canonical_choice(text.rstrip()) | |
| def convert(split, source_rows): | |
| """Normalize source text without filtering, sampling, or changing choice order.""" | |
| if split not in SOURCES: | |
| raise ValueError(f"Unknown base-evals split: {split}") | |
| rows = [] | |
| for index, source in enumerate(source_rows): | |
| if split == "tiny_hellaswag": | |
| context = preprocess_hellaswag( | |
| source["activity_label"] | |
| + ": " | |
| + source["ctx_a"] | |
| + " " | |
| + source["ctx_b"].capitalize() | |
| ) | |
| choices = [preprocess_hellaswag(text) for text in source["endings"]] | |
| elif split in {"tiny_arithmark_3_0", "tiny_arithmark_2_0"}: | |
| context, choices = source["ctx"], source["endings"] | |
| if not all(text.startswith(" ") and not text.startswith(" ") for text in choices): | |
| raise ValueError("ArithMark source continuation spacing changed") | |
| elif split == "tiny_logicmark": | |
| context, choices = source["context"], source["options"] | |
| elif split == "tiny_pythonio": | |
| context, choices = pythonio_context(source["question"]), source["choices"] | |
| elif split == "tiny_openbookqa": | |
| context, choices = source["question_stem"], source["choices"]["text"] | |
| else: | |
| context, choices = "Q: " + source["question"] + "\nA:", source["choices"] | |
| if split == "tiny_pythonio": | |
| key = source["Answer"] | |
| if ( | |
| key not in ("A", "B", "C", "D") | |
| or source["answer"] != key.lower() | |
| or choices != [source[letter] for letter in "ABCD"] | |
| ): | |
| raise ValueError("PythonIO answer keys or choice columns disagree") | |
| source_label = "ABCD".index(key) | |
| elif split == "tiny_openbookqa": | |
| labels = source["choices"]["label"] | |
| if ( | |
| not isinstance(choices, list) | |
| or not isinstance(labels, list) | |
| or len(choices) != len(labels) | |
| or any(not isinstance(value, str) for value in labels) | |
| or len(set(labels)) != len(labels) | |
| or labels.count(source["answerKey"]) != 1 | |
| ): | |
| raise ValueError("OpenBookQA choice labels or answerKey are invalid") | |
| source_label = labels.index(source["answerKey"]) | |
| else: | |
| source_label = source["answer_index"] if split == "tiny_logicmark" else source["label"] | |
| if type(source_label) not in (int, str): | |
| raise ValueError("Invalid source label") | |
| label = int(source_label) | |
| if not isinstance(choices, list) or not 0 <= label < len(choices): | |
| raise ValueError("Invalid source choices or label") | |
| if split == "tiny_logicmark" and source["answer"] != choices[label]: | |
| raise ValueError("LogicMark answer does not match answer_index") | |
| rows.append( | |
| { | |
| "id": f"{split}:{index:06d}", | |
| "context": context.rstrip(" "), | |
| "choices": [ | |
| pythonio_choice(text) if split == "tiny_pythonio" else canonical_choice(text) | |
| for text in choices | |
| ], | |
| "label": label, | |
| } | |
| ) | |
| return rows | |
| def curate(split, source_rows, count=None): | |
| """Cap choices before sampling rows, using independent, split-local seeded RNGs.""" | |
| count = SOURCES[split]["count"] if count is None else count | |
| if type(count) is not int or count < 1: | |
| raise ValueError("Sample count must be a positive integer") | |
| converted = convert(split, source_rows) | |
| choice_rng = random.Random(SEED) | |
| excluded_quality = { | |
| index | |
| for index, source in enumerate(source_rows) | |
| if split == "tiny_arithmark_3_0" | |
| and source.get("metadata", {}).get("template_id") == "time_session" | |
| } | |
| eligible = [] | |
| for index, original in enumerate(converted): | |
| if index in excluded_quality: | |
| continue | |
| choices, label = original["choices"], original["label"] | |
| if len(choices) < 4: | |
| continue | |
| indices = list(range(len(choices))) | |
| if len(choices) > 4: | |
| indices = sorted( | |
| [ | |
| label, | |
| *choice_rng.sample( | |
| [i for i in indices if i != label], | |
| 3, | |
| ), | |
| ] | |
| ) | |
| row = {**original, "choices": [choices[i] for i in indices], "label": indices.index(label)} | |
| eligible.append((index, indices, row)) | |
| if len(eligible) < count: | |
| raise ValueError(f"Insufficient eligible rows for {split}: {len(eligible)} < {count}") | |
| selected = [ | |
| eligible[i] for i in sorted(random.Random(SEED).sample(range(len(eligible)), count)) | |
| ] | |
| rows = [row for _, _, row in selected] | |
| validate_rows(split, rows, expected=count) | |
| selection = { | |
| "input_count": len(source_rows), | |
| "eligible_count": len(eligible), | |
| "excluded_fewer_than_four": sum(len(row["choices"]) < 4 for row in converted), | |
| "capped_more_than_four": sum(len(row["choices"]) > 4 for row in converted), | |
| "input_choice_count_distribution": dict( | |
| sorted(Counter(str(len(row["choices"])) for row in converted).items()) | |
| ), | |
| "selected_source_row_indices": [index for index, _, _ in selected], | |
| "selected_choice_indices": [indices for _, indices, _ in selected], | |
| } | |
| if split == "tiny_arithmark_3_0": | |
| selection["excluded_quality_count"] = len(excluded_quality) | |
| selection["excluded_quality_source_row_indices"] = sorted(excluded_quality) | |
| return rows, selection | |
| def validate_rows(split, rows, expected=None): | |
| if split not in SOURCES: | |
| raise ValueError(f"Unknown base-evals split: {split}") | |
| if expected is not None and len(rows) != expected: | |
| raise ValueError(f"Unexpected count for {split}: {len(rows)} != {expected}") | |
| previous = -1 | |
| for row in rows: | |
| match = re.fullmatch(re.escape(split) + r":([0-9]{6})", str(row.get("id"))) | |
| if list(row) != COLUMNS or match is None or int(match[1]) <= previous: | |
| raise ValueError("Invalid columns, ID, or source order") | |
| previous = int(match[1]) | |
| context, choices, label = row["context"], row["choices"], row["label"] | |
| if not isinstance(context, str) or not context.strip(): | |
| raise ValueError("Invalid context") | |
| if context[-1].isspace(): | |
| raise ValueError("Invalid trailing context whitespace") | |
| if split == "tiny_pythonio" and ( | |
| "\r" in context or not re.search(r"\nInput: \S[^\n]*\nOutput:$", context) | |
| ): | |
| raise ValueError("PythonIO requires LF lines, inline Input: text, and final Output:") | |
| if not isinstance(choices, list) or len(choices) != 4: | |
| raise ValueError("Every split requires exactly four choices") | |
| for text in choices: | |
| if ( | |
| not isinstance(text, str) | |
| or len(text) < 2 | |
| or text[0] != " " | |
| or text[1].isspace() | |
| or not text.strip() | |
| ): | |
| raise ValueError("Choices must have exactly one leading ASCII space") | |
| if split == "tiny_pythonio" and text != text.rstrip(): | |
| raise ValueError("PythonIO choices must have no trailing whitespace") | |
| if len(set(choices)) != 4: | |
| raise ValueError("Duplicate choices") | |
| if type(label) is not int or not 0 <= label < 4: | |
| raise ValueError("Invalid label") | |
| def download_source(spec): | |
| from huggingface_hub import hf_hub_download | |
| path = Path( | |
| hf_hub_download( | |
| spec["repo"], | |
| spec["file"], | |
| repo_type="dataset", | |
| revision=spec["revision"], | |
| ) | |
| ) | |
| if digest(path) != spec["sha256"]: | |
| raise ValueError(f"Source checksum mismatch: {spec['repo']}/{spec['file']}") | |
| return path | |
| def read_source(path): | |
| if Path(path).suffix == ".jsonl": | |
| return [ | |
| json.loads(line) | |
| for line in Path(path).read_text(encoding="utf-8").splitlines() | |
| if line.strip() | |
| ] | |
| from pyarrow import parquet | |
| return parquet.read_table(path).to_pylist() | |
| def source_table(sources): | |
| rows = ["| split | source | source split | rows |", "| --- | --- | --- | ---: |"] | |
| for split, spec in sorted(sources.items()): | |
| rows.append( | |
| f"| `{split}` | [`{spec['repo']}@{spec['revision'][:8]}`]" | |
| f"(https://huggingface.co/datasets/{spec['repo']}/tree/{spec['revision']}) " | |
| f"| `{spec['split']}` | {spec['count']:,} |" | |
| ) | |
| rows.append(f"| **total** | | | **{sum(spec['count'] for spec in sources.values()):,}** |") | |
| return "\n".join(rows) | |
| def dataset_card(): | |
| files = "\n".join( | |
| f" - split: {split}\n path: data/{split}-00000-of-00001.parquet" for split in SOURCES | |
| ) | |
| return f"""--- | |
| language: | |
| - en | |
| license: other | |
| task_categories: | |
| - multiple-choice | |
| tags: | |
| - evaluation | |
| - base-models | |
| - zero-shot | |
| - log-likelihood | |
| configs: | |
| - config_name: default | |
| data_files: | |
| {files} | |
| --- | |
| # base-evals | |
| **0-shot, 4-choice** continuation evaluation for pretrained base models. | |
| ## Splits | |
| {source_table(SOURCES)} | |
| ## Format | |
| `id: string`, `context: string`, `choices: list[string]`, `label: int64`. | |
| Labels are zero-based. Input is **`context + choices[i]`**, with exactly one ASCII space | |
| before each choice and no trailing context whitespace. PythonIO uses LF line endings, | |
| `Input: {{input}}\\nOutput:` contexts, and choices without outer trailing whitespace; code | |
| indentation and output-value whitespace are retained. HellaSwag uses context cleanup; | |
| TruthfulQA uses `Q: {{question}}\\nA:`. | |
| ## Evaluation | |
| No few-shot examples, chat template, CoT, or added BOS/EOS. | |
| - **acc:** choose the largest sum of continuation-token log-probabilities. | |
| - **acc_norm:** choose the largest mean **log-probability** per continuation token. | |
| Exclude context/padding; include boundary whitespace. Reject ambiguous token boundaries | |
| and overlength inputs. Break ties by first index. Report each split separately. | |
| This custom protocol is not HellaSwag character normalization, TruthfulQA MC2, or IRT. | |
| ## Provenance | |
| Each split selects 500 questions with `random.Random(42)`; OpenBookQA retains its full test set. | |
| ArithMark 3.0 excludes `time_session` prompts without duration information before sampling. | |
| Rows with fewer than four choices are excluded; larger sets keep the answer and three sampled | |
| incorrect choices. | |
| Source row/choice order is preserved. Full rules, hashes and indices: `manifest.json`; | |
| original inputs/cards: `sources/`; offline rebuild: `build.py`. | |
| Evaluation only, including upstream train splits. Original source terms apply; PythonIO and | |
| OpenBookQA have no declared license. Pretraining contamination is unknown. | |
| """ | |
| def build(output, source_directory=None): | |
| from huggingface_hub import hf_hub_download | |
| from pyarrow import Table, int64, list_, parquet, schema, string | |
| output = Path(output).resolve() | |
| if output.exists(): | |
| raise FileExistsError(f"Output already exists; choose a new directory: {output}") | |
| output.parent.mkdir(parents=True, exist_ok=True) | |
| def get_source(spec, filename): | |
| if source_directory is None: | |
| return download_source(spec) | |
| path = Path(source_directory) / "sources" / filename | |
| if digest(path) != spec["sha256"]: | |
| raise ValueError(f"Source checksum mismatch: {path}") | |
| return path | |
| features = schema( | |
| [ | |
| ("id", string()), | |
| ("context", string()), | |
| ("choices", list_(string())), | |
| ("label", int64()), | |
| ] | |
| ) | |
| with tempfile.TemporaryDirectory(prefix=".base-evals-build-", dir=output.parent) as temporary: | |
| stage = Path(temporary) / "dataset" | |
| (stage / "data").mkdir(parents=True) | |
| (stage / "sources").mkdir() | |
| manifest = { | |
| "dataset": DATASET, | |
| "version": "2.5.0", | |
| "evaluation_only": True, | |
| "schema": { | |
| "id": "string", | |
| "context": "string", | |
| "choices": "list[string]", | |
| "label": "int64", | |
| }, | |
| "curation": CURATION, | |
| "protocol": PROTOCOL, | |
| "environment": { | |
| "python": platform.python_version(), | |
| **{ | |
| name: importlib.metadata.version(name) | |
| for name in ["huggingface-hub", "pyarrow"] | |
| }, | |
| }, | |
| "builder": {"file": "build.py", "sha256": digest(__file__)}, | |
| "splits": {}, | |
| "references": {}, | |
| } | |
| for split, spec in SOURCES.items(): | |
| filename = split + Path(spec["file"]).suffix | |
| source = get_source(spec, filename) | |
| source_rows = read_source(source) | |
| if len(source_rows) != spec["source_count"]: | |
| raise ValueError(f"Unexpected source count: {split}") | |
| rows, selection = curate(split, source_rows) | |
| saved_source = stage / "sources" / filename | |
| shutil.copyfile(source, saved_source) | |
| card_name = f"{split}.README.md" | |
| card = ( | |
| Path(source_directory) / "sources" / card_name | |
| if source_directory is not None | |
| else hf_hub_download( | |
| spec["repo"], | |
| "README.md", | |
| repo_type="dataset", | |
| revision=spec.get("card_revision", spec["revision"]), | |
| ) | |
| ) | |
| shutil.copyfile(card, stage / "sources" / card_name) | |
| target = stage / "data" / f"{split}-00000-of-00001.parquet" | |
| parquet.write_table( | |
| Table.from_pylist(rows, schema=features), | |
| target, | |
| compression="zstd", | |
| version="2.6", | |
| row_group_size=1000, | |
| ) | |
| restored = parquet.read_table(target) | |
| if restored.schema != features or restored.to_pylist() != rows: | |
| raise ValueError(f"Parquet round-trip mismatch: {split}") | |
| if split.startswith("tiny_arithmark_"): | |
| for row, index, indices in zip( | |
| rows, | |
| selection["selected_source_row_indices"], | |
| selection["selected_choice_indices"], | |
| strict=True, | |
| ): | |
| original = source_rows[index] | |
| if row["context"] != original["ctx"] or row["choices"] != [ | |
| original["endings"][i] for i in indices | |
| ]: | |
| raise ValueError("ArithMark text or whitespace changed") | |
| if split == "tiny_logicmark": | |
| for row, index, indices in zip( | |
| rows, | |
| selection["selected_source_row_indices"], | |
| selection["selected_choice_indices"], | |
| strict=True, | |
| ): | |
| original = source_rows[index] | |
| if row["context"] != original["context"] or row["choices"] != [ | |
| " " + original["options"][i] for i in indices | |
| ]: | |
| raise ValueError("LogicMark text or whitespace changed") | |
| if split == "tiny_pythonio": | |
| for row, index, indices in zip( | |
| rows, | |
| selection["selected_source_row_indices"], | |
| selection["selected_choice_indices"], | |
| strict=True, | |
| ): | |
| original = source_rows[index] | |
| if row["context"] != pythonio_context(original["question"]) or row[ | |
| "choices" | |
| ] != [pythonio_choice(original["choices"][i]) for i in indices]: | |
| raise ValueError("PythonIO text or whitespace changed") | |
| if split == "tiny_openbookqa": | |
| for row, index, indices in zip( | |
| rows, | |
| selection["selected_source_row_indices"], | |
| selection["selected_choice_indices"], | |
| strict=True, | |
| ): | |
| original = source_rows[index] | |
| if row["context"] != original["question_stem"] or row["choices"] != [ | |
| " " + original["choices"]["text"][i] for i in indices | |
| ]: | |
| raise ValueError("OpenBookQA text or whitespace changed") | |
| manifest["splits"][split] = { | |
| "count": len(rows), | |
| "source": spec, | |
| "selection": selection, | |
| "source_copy": str(saved_source.relative_to(stage)), | |
| "file": str(target.relative_to(stage)), | |
| "sha256": digest(target), | |
| "logical_sha256": logical_digest(rows), | |
| "label_counts": dict(sorted(Counter(str(row["label"]) for row in rows).items())), | |
| "choice_count_distribution": {"4": len(rows)}, | |
| } | |
| if split == "tiny_pythonio": | |
| selected = selection["selected_source_row_indices"] | |
| manifest["splits"][split]["normalization"] = { | |
| "input_header_inlined": len(rows), | |
| "contexts_with_cr_normalized": sum( | |
| "\r" in source_rows[index]["question"] for index in selected | |
| ), | |
| "choices_with_trailing_whitespace_removed": sum( | |
| source_rows[index]["choices"][choice] | |
| != source_rows[index]["choices"][choice].rstrip() | |
| for index, indices in zip( | |
| selected, selection["selected_choice_indices"], strict=True | |
| ) | |
| for choice in indices | |
| ), | |
| } | |
| for name, spec in REFERENCES.items(): | |
| filename = name + Path(spec["file"]).suffix | |
| path = get_source(spec, filename) | |
| target = stage / "sources" / filename | |
| shutil.copyfile(path, target) | |
| manifest["references"][name] = {**spec, "source_copy": str(target.relative_to(stage))} | |
| shutil.copyfile(__file__, stage / "build.py") | |
| (stage / "README.md").write_text(dataset_card(), encoding="utf-8") | |
| manifest["artifact_sha256"] = { | |
| str(path.relative_to(stage)): digest(path) | |
| for path in sorted(stage.rglob("*")) | |
| if path.is_file() | |
| } | |
| save_json(stage / "manifest.json", manifest) | |
| if output.exists(): | |
| raise FileExistsError(f"Output appeared during build: {output}") | |
| stage.rename(output) | |
| return manifest | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--output", required=True, help="New, unpublished dataset directory") | |
| parser.add_argument( | |
| "--source-directory", help="Existing release root with sources/ for offline rebuild" | |
| ) | |
| args = parser.parse_args() | |
| result = build(args.output, args.source_directory) | |
| print(json.dumps({name: split["count"] for name, split in result["splits"].items()}, indent=2)) | |