"""Create a 600-row, stratified subset of GenomeQA mcq_carbon.""" import argparse import json import random import re from collections import Counter, defaultdict from pathlib import Path from datasets import Dataset, load_dataset from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download DATASET_ID = "HuggingFaceBio/genomeqa" PARQUET_PATH = "mcq_carbon_600/train-00000-of-00001.parquet" QUOTAS = { "1_enhancer_vs_promoter": {"basic_class": 34, "selection": 33, "outlier": 33}, "2_splice_sites": {"fine_grained_class": 34, "generalized_selection": 33, "find_shuffled_outlier": 33}, "eukaryote_cls": {"basic_class": 60, "reverse_search": 20, "odd_one_out": 20}, "4_histone_marks": { "seq_to_label": 25, "label_to_seq": 25, "odd_one_out": 25, "chromatin_classify": 14, "chromatin_select_seq": 11, }, "5_tfbs": {"forward_classify": 34, "reverse_select": 33, "3d_structure_select": 33}, "6_motif": {"seq_to_motif": 50, "motif_to_seq": 50}, } MARK = re.compile(r"\b(?:H2AFZ|H3K\d+(?:me\d|ac)|H4K\d+me\d)\b") ENHANCER_OUTLIER_PATTERNS = ( r"Find the one containing a (enhancer|promoter)", r"specific sequence that contains a (enhancer|promoter)", r"sequence that includes a (enhancer|promoter)", r"one actually harbors a (enhancer|promoter)", r"sequence holds a (enhancer|promoter)", ) def label_for_row(row: dict, metadata: dict) -> tuple[str, ...]: subtask, dimension = row["subtask"], metadata["dim"] if subtask == "1_enhancer_vs_promoter": if dimension == "basic_class": return (row["answer_text"].lower(),) if dimension == "selection": labels = set(re.findall(r"\b(?:enhancer|promoter)\b", row["question"].lower())) if len(labels) != 1: raise ValueError(f"Cannot identify enhancer selection target: {row['id']}") return (labels.pop(),) for pattern in ENHANCER_OUTLIER_PATTERNS: match = re.search(pattern, row["question"], flags=re.IGNORECASE) if match: return (match.group(1).lower(),) raise ValueError(f"Cannot identify enhancer outlier target: {row['id']}") if subtask == "2_splice_sites": if dimension == "fine_grained_class": return (metadata["true_type"],) if dimension == "generalized_selection": return (metadata["target"],) return () if subtask == "eukaryote_cls": if dimension == "basic_class": return (metadata["true"],) if dimension == "reverse_search": return (metadata["target"],) return (metadata["minority"], metadata["majority"]) if subtask == "4_histone_marks": if dimension == "seq_to_label": return (row["answer_text"],) if dimension in {"label_to_seq", "odd_one_out"}: marks = MARK.findall(row["question"]) if not marks: raise ValueError(f"Cannot identify histone mark: {row['id']}") target = marks[1] if dimension == "odd_one_out" and "while one contains" in row["question"] else marks[0] return (target,) if dimension == "chromatin_classify": return (metadata["truth"].lower(),) return (metadata["target_state"].lower(),) if subtask == "5_tfbs": if dimension == "forward_classify": return (row["answer_text"],) if dimension == "reverse_select": return (metadata["target"],) return () def stratified_sample( indices: list[int], quota: int, labels: dict[int, tuple[str, ...]], rng: random.Random, depth: int = 0 ) -> list[int]: if quota == len(indices): return indices.copy() groups = defaultdict(list) for index in indices: label = labels[index][depth] if depth < len(labels[index]) else None groups[label].append(index) if list(groups) == [None]: return rng.sample(indices, quota) total = len(indices) take = {label: quota * len(group) // total for label, group in groups.items()} order = sorted(groups) rng.shuffle(order) order.sort(key=lambda label: quota * len(groups[label]) % total, reverse=True) for label in order[: quota - sum(take.values())]: take[label] += 1 selected = [] for label in sorted(groups): if take[label]: selected.extend(stratified_sample(groups[label], take[label], labels, rng, depth + 1)) return selected 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("--seed", type=int, default=42) parser.add_argument("--publish", action="store_true") args = parser.parse_args() source = load_dataset(DATASET_ID, "mcq_carbon", split="train", revision=args.source_revision) groups = defaultdict(list) labels = {} for index, row in enumerate(source): metadata = json.loads(row["metadata"]) groups[(row["subtask"], metadata["dim"])].append(index) labels[index] = label_for_row(row, metadata) + (str(row["answer_index"]),) expected = {(subtask, dimension) for subtask, quotas in QUOTAS.items() for dimension in quotas} if set(groups) != expected: raise ValueError(f"Unexpected source subtasks or dimensions: {set(groups) ^ expected}") rng = random.Random(args.seed) selected = [] for subtask, dimensions in QUOTAS.items(): for dimension, quota in dimensions.items(): candidates = groups[(subtask, dimension)] if len(candidates) < quota: raise ValueError(f"Only {len(candidates)} {subtask}/{dimension} rows for quota {quota}") selected.extend(stratified_sample(candidates, quota, labels, rng)) rng.shuffle(selected) subset = source.select(selected) if len(selected) != 600 or len(set(selected)) != 600 or Counter(subset["subtask"]) != dict.fromkeys(QUOTAS, 100): raise RuntimeError("The subset must contain 100 distinct rows per subtask") parquet_path = args.output_dir / PARQUET_PATH parquet_path.parent.mkdir(parents=True, exist_ok=True) subset.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_600 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_600\n features:" if existing in card: start = card.index(existing) end = card.index(marker, start) card = card[:start] + info + card[end:] else: if marker not in card: raise ValueError("Cannot find dataset_info insertion point in card") card = card.replace(marker, info + marker, 1) config = """- config_name: mcq_carbon_600 data_files: - split: train path: mcq_carbon_600/train-* """ card = card.replace( "- config_name: eukaryote_cls\n data_files:", config + "- config_name: eukaryote_cls\n data_files:", 1 ) row = ( "| `mcq_carbon` | 2,600 | MCQ benchmark with the 500 `3_species_cls` rows replaced by 500 stratified " "`eukaryote_cls` rows. |\n" ) new_row = "| `mcq_carbon_600` | 600 | Stratified 100-row sample from each `mcq_carbon` subtask. |\n" card = card.replace(row, row + new_row, 1) note = f"""The `mcq_carbon_600` configuration samples without replacement from `mcq_carbon` at revision `{args.source_revision}` using seed {args.seed}. It retains 100 rows per subtask and preserves the mix of question dimensions within each subtask. Within dimensions, it samples proportionally by target label where available; eukaryote odd-one-out questions are also stratified by majority taxon, and answer position is the final stratum. The 100 motif rows are all retained. See [`scripts/create_mcq_carbon_600.py`](scripts/create_mcq_carbon_600.py). """ card = card.replace( "The `eukaryote_cls` configuration uses", note + "The `eukaryote_cls` configuration uses", 1 ) if "### mcq_carbon_600" not in card: card += f""" ### mcq_carbon_600 To rebuild and publish `mcq_carbon_600` from the pinned source revision, run: ```bash python scripts/create_mcq_carbon_600.py --source-revision {args.source_revision} --output-dataset {args.output_dataset} --seed {args.seed} --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(subset)} rows at {parquet_path}") for subtask, dimensions in QUOTAS.items(): counts = Counter(json.loads(row["metadata"])["dim"] for row in subset if row["subtask"] == subtask) positions = Counter(row["answer_index"] for row in subset if row["subtask"] == subtask) print(subtask, dict(counts), "answer positions", dict(positions)) if args.publish: commit = api.create_commit( repo_id=args.output_dataset, repo_type="dataset", parent_commit=head, commit_message="Add stratified mcq_carbon_600 configuration", 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_600.py", path_or_fileobj=__file__), ], ) print(f"Published {commit.commit_url}") if __name__ == "__main__": main()