Datasets:
Download scripts/create_mcq_carbon.py from HuggingFaceBio/genomeqa: direct link, hf CLI and curl.
- Browser
- Download file 6.49 kB
-
https://huggingface.co/datasets/HuggingFaceBio/genomeqa/resolve/main/scripts/create_mcq_carbon.py
- Command line
-
hf download hf://datasets/HuggingFaceBio/genomeqa/scripts/create_mcq_carbon.py
-
curl -L -o create_mcq_carbon.py https://huggingface.co/datasets/HuggingFaceBio/genomeqa/resolve/main/scripts/create_mcq_carbon.py
6.49 kB
| """Create GenomeQA mcq_carbon by replacing species classification questions.""" | |
| import argparse | |
| import json | |
| import random | |
| from collections import defaultdict | |
| from pathlib import Path | |
| from datasets import Dataset, concatenate_datasets, load_dataset | |
| from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download | |
| DATASET_ID = "HuggingFaceBio/genomeqa" | |
| SEED = 42 | |
| PARQUET_PATH = "mcq_carbon/train-00000-of-00001.parquet" | |
| QUOTAS = {"basic_class": 300, "reverse_search": 100, "odd_one_out": 100} | |
| LABEL_KEYS = {"basic_class": "true", "reverse_search": "target", "odd_one_out": "minority"} | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--source-revision", required=True) | |
| parser.add_argument("--output-dataset", default=DATASET_ID) | |
| parser.add_argument("--output-dir", type=Path, default=Path.cwd()) | |
| parser.add_argument("--publish", action="store_true") | |
| args = parser.parse_args() | |
| mcq = load_dataset(DATASET_ID, "mcq", split="train", revision=args.source_revision) | |
| eukaryote = load_dataset(DATASET_ID, "eukaryote_cls", split="train", revision=args.source_revision) | |
| if mcq.features != eukaryote.features: | |
| raise ValueError("The source configurations must have matching features") | |
| strata = defaultdict(lambda: defaultdict(list)) | |
| for index, metadata_text in enumerate(eukaryote["metadata"]): | |
| metadata = json.loads(metadata_text) | |
| dimension = metadata["dim"] | |
| strata[dimension][metadata[LABEL_KEYS[dimension]]].append(index) | |
| rng = random.Random(SEED) | |
| selected = [] | |
| for dimension, quota in QUOTAS.items(): | |
| groups = strata[dimension] | |
| if sum(len(indices) for indices in groups.values()) != 2 * quota: | |
| raise ValueError(f"Expected {2 * quota} {dimension} source rows") | |
| take = {label: len(indices) // 2 for label, indices in groups.items()} | |
| odd_labels = sorted(label for label, indices in groups.items() if len(indices) % 2) | |
| rng.shuffle(odd_labels) | |
| for label in odd_labels[: quota - sum(take.values())]: | |
| take[label] += 1 | |
| for label in sorted(groups): | |
| selected.extend(rng.sample(groups[label], take[label])) | |
| rng.shuffle(selected) | |
| replacement = eukaryote.select(selected) | |
| species_positions = [index for index, subtask in enumerate(mcq["subtask"]) if subtask == "3_species_cls"] | |
| if len(species_positions) != 500 or species_positions != list(range(species_positions[0], species_positions[-1] + 1)): | |
| raise ValueError("Expected one contiguous 500-row 3_species_cls block") | |
| start = species_positions[0] | |
| combined = concatenate_datasets([mcq.select(range(start)), replacement, mcq.select(range(start + 500, len(mcq)))]) | |
| parquet_path = args.output_dir / PARQUET_PATH | |
| parquet_path.parent.mkdir(parents=True, exist_ok=True) | |
| combined.to_parquet(parquet_path) | |
| materialized = Dataset.from_parquet(str(parquet_path)) | |
| api = HfApi() | |
| head = api.repo_info(args.output_dataset, repo_type="dataset").sha | |
| card = Path(hf_hub_download(args.output_dataset, "README.md", repo_type="dataset", revision=head)).read_text() | |
| info = f"""- config_name: mcq_carbon | |
| features: | |
| - name: id | |
| dtype: int64 | |
| - name: subtask | |
| dtype: string | |
| - name: question | |
| dtype: string | |
| - name: options | |
| list: string | |
| - name: answer_index | |
| dtype: int64 | |
| - name: answer_text | |
| dtype: string | |
| - name: metadata | |
| dtype: string | |
| splits: | |
| - name: train | |
| num_bytes: {materialized.info.splits['train'].num_bytes} | |
| num_examples: {len(materialized)} | |
| download_size: {parquet_path.stat().st_size} | |
| dataset_size: {materialized.info.dataset_size} | |
| """ | |
| marker = "- config_name: eukaryote_cls\n features:" | |
| existing = "- config_name: mcq_carbon\n features:" | |
| if existing in card: | |
| start = card.index(existing) | |
| end = card.index(marker, start) | |
| card = card[:start] + info + card[end:] | |
| commit_message = "Correct mcq_carbon size metadata" | |
| else: | |
| card = card.replace(marker, info + marker, 1) | |
| commit_message = "Add stratified mcq_carbon configuration" | |
| config = """- config_name: mcq_carbon | |
| data_files: | |
| - split: train | |
| path: mcq_carbon/train-* | |
| """ | |
| card = card.replace("- config_name: eukaryote_cls\n data_files:", config + "- config_name: eukaryote_cls\n data_files:", 1) | |
| row = "| `mcq` | 2,600 | Full benchmark in four-option multiple-choice format. |\n" | |
| new_row = "| `mcq_carbon` | 2,600 | MCQ benchmark with the 500 `3_species_cls` rows replaced by 500 stratified `eukaryote_cls` rows. |\n" | |
| card = card.replace(row, row + new_row, 1) | |
| note = f"""The `mcq_carbon` configuration preserves the other `mcq` rows and inserts 500 `eukaryote_cls` questions at the | |
| original species-classification position. From source revision `{args.source_revision}`, seed {SEED} selects 300 | |
| `basic_class`, 100 `reverse_search`, and 100 `odd_one_out` rows, sampling approximately half of each taxon label | |
| within each question type. See [`scripts/create_mcq_carbon.py`](scripts/create_mcq_carbon.py). | |
| """ | |
| card = card.replace("The `eukaryote_cls` configuration uses the `mcq` feature schema", note + "The `eukaryote_cls` configuration uses the `mcq` feature schema", 1) | |
| if "### mcq_carbon" not in card: | |
| card += f""" | |
| ### mcq_carbon | |
| To rebuild and publish `mcq_carbon` from the pinned source revision, run: | |
| ```bash | |
| python scripts/create_mcq_carbon.py --source-revision {args.source_revision} --output-dataset {args.output_dataset} --publish | |
| ``` | |
| The script publishes the Parquet file, this card, and the builder script together. | |
| """ | |
| card_path = args.output_dir / "README.md" | |
| card_path.write_text(card) | |
| print(f"Prepared {len(combined)} rows ({len(replacement)} replacement rows) at {parquet_path}") | |
| if args.publish: | |
| commit = api.create_commit( | |
| repo_id=args.output_dataset, | |
| repo_type="dataset", | |
| parent_commit=head, | |
| commit_message=commit_message, | |
| operations=[ | |
| CommitOperationAdd(path_in_repo=PARQUET_PATH, path_or_fileobj=parquet_path), | |
| CommitOperationAdd(path_in_repo="README.md", path_or_fileobj=card_path), | |
| CommitOperationAdd(path_in_repo="scripts/create_mcq_carbon.py", path_or_fileobj=__file__), | |
| ], | |
| ) | |
| print(f"Published {commit.commit_url}") | |
| if __name__ == "__main__": | |
| main() | |