"""Dataset loaders for the reproduction pipeline. Uses the dataset classes from ``src/dataset/sequence_classification.py`` (released alongside the fine-tuning stage) so that train / validation / test splits match exactly what was used to fine-tune the encoders. Supported sources (from config ``data.source``): - ``hf_glue_cola`` -> ``CoLa()`` - ``hf_sst5`` -> ``SST5()`` - ``hf_toxigen`` -> ``ToxigenDataset()`` - ``hf_newsgroups`` -> ``NewsGroups()`` - ``hf_goemotions`` -> ``GoEmotions()`` - ``hf_yelp`` -> ``Yelp()`` - ``tsv`` -> legacy paper TSV (2-split only) For HF-based sources, ``load_splits`` returns a dict with keys ``train``, ``validation`` and ``test``, each a ``pd.DataFrame`` with columns ``sentence``, ``label``, ``idx``. For backward compatibility, when a caller asks for the legacy ``dev`` split it is silently mapped to ``test`` (the held-out evaluation set in this pipeline's protocol). """ from __future__ import annotations import importlib.util import sys from pathlib import Path from typing import Dict import pandas as pd # Import the dataset classes via an explicit file load, since both ``src`` # directories (this one, and the top-level one) collide on the package name. _REPO_ROOT = Path(__file__).resolve().parents[2] _DATASET_CLASSES_PATH = _REPO_ROOT / "training" / "src" / "dataset" / "sequence_classification.py" def _import_dataset_module(): spec = importlib.util.spec_from_file_location( "dataset_module", str(_DATASET_CLASSES_PATH)) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod COLA_COLUMNS = ["source", "label", "label_notes", "sentence"] # --------------------------------------------------------------------------- # Legacy TSV loader (En-CoLA paper data) # --------------------------------------------------------------------------- def load_cola_tsv(path: str | Path, text_col: str = "sentence", label_col: str = "label") -> pd.DataFrame: df = pd.read_csv(path, sep="\t", header=None, names=COLA_COLUMNS, na_filter=False) df = df[[text_col, label_col]].copy() df[label_col] = df[label_col].astype(int) df["idx"] = range(len(df)) return df # --------------------------------------------------------------------------- # Dataset-class-backed loaders # --------------------------------------------------------------------------- def _to_df(ds, text_col_candidates=("text", "sentence")) -> pd.DataFrame: """Convert a HF Dataset row-set to the (sentence, label, idx) frame the pipeline expects.""" cols = set(ds.column_names) text_col = next((c for c in text_col_candidates if c in cols), None) if text_col is None: raise ValueError(f"Dataset has no text column among {text_col_candidates}: {cols}") df = pd.DataFrame({"sentence": list(ds[text_col]), "label": list(ds["label"])}) df["idx"] = range(len(df)) return df def _load_class_splits(class_name: str) -> Dict[str, pd.DataFrame]: m = _import_dataset_module() cls = getattr(m, class_name) ds = cls().load() return { "train": _to_df(ds["train"]), "validation": _to_df(ds["validation"]), "test": _to_df(ds["test"]), } def load_cola_splits() -> Dict[str, pd.DataFrame]: """80% train + 20% validation of GLUE-CoLA train, plus GLUE-CoLA validation as test.""" return _load_class_splits("CoLa") def load_sst5_splits() -> Dict[str, pd.DataFrame]: """SetFit/sst5 train + validation + test (no 80/20 subsplit).""" return _load_class_splits("SST5") def load_toxigen_splits() -> Dict[str, pd.DataFrame]: """skg/toxigen-data with an 80/20 split of train, plus its original test.""" return _load_class_splits("ToxigenDataset") def load_newsgroups_splits() -> Dict[str, pd.DataFrame]: """sklearn 20-newsgroups with an 80/20 split of train, plus its original test.""" return _load_class_splits("NewsGroups") def load_goemotions_splits() -> Dict[str, pd.DataFrame]: """GoEmotions with an 80/10/10 split (max 5k samples per split).""" return _load_class_splits("GoEmotions") def load_yelp_splits() -> Dict[str, pd.DataFrame]: """Yelp 3-star sentiment (HF: $YELP_REPO).""" return _load_class_splits("Yelp") def load_amazon_splits() -> Dict[str, pd.DataFrame]: return _load_class_splits("Amazon") def load_sst2_splits() -> Dict[str, pd.DataFrame]: return _load_class_splits("SST2") def load_imdb_splits() -> Dict[str, pd.DataFrame]: return _load_class_splits("IMDB") # --------------------------------------------------------------------------- # Legacy single-split loaders (kept for direct callers — they call the # 3-split loaders under the hood and slice the requested view). # --------------------------------------------------------------------------- def _legacy(splits, split_name): """Map legacy ``train|dev|validation|test`` to the pipeline's 3-split layout. Old call sites used "dev" for the held-out evaluation set. We map it to "test" (which is what this protocol calls the held-out test split). """ if split_name == "dev": split_name = "test" return splits[split_name] def load_hf_glue_cola(split: str) -> pd.DataFrame: return _legacy(load_cola_splits(), split) def load_hf_sst5(split: str) -> pd.DataFrame: return _legacy(load_sst5_splits(), split) def load_hf_toxigen(split: str) -> pd.DataFrame: return _legacy(load_toxigen_splits(), split) def load_hf_newsgroups(split: str) -> pd.DataFrame: return _legacy(load_newsgroups_splits(), split) def load_hf_goemotions(split: str) -> pd.DataFrame: return _legacy(load_goemotions_splits(), split) def load_hf_yelp(split: str) -> pd.DataFrame: return _legacy(load_yelp_splits(), split) # --------------------------------------------------------------------------- # Top-level loader used by extract scripts # --------------------------------------------------------------------------- def load_splits(cfg: Dict) -> Dict[str, pd.DataFrame]: """Return ``{"train": ..., "validation": ..., "test": ...}`` for HF sources. For the legacy TSV (En-CoLA) source we still return ``{"train", "dev"}`` plus optional ``ood`` because no 3-split layout is defined there. """ data_cfg = cfg["data"] source = data_cfg.get("source", "tsv") if source == "tsv": splits = { "train": load_cola_tsv(data_cfg["train_tsv"], data_cfg["text_col"], data_cfg["label_col"]), "dev": load_cola_tsv(data_cfg["dev_tsv"], data_cfg["text_col"], data_cfg["label_col"]), } if data_cfg.get("ood_tsv"): splits["ood"] = load_cola_tsv(data_cfg["ood_tsv"], data_cfg["text_col"], data_cfg["label_col"]) return splits if source == "hf_glue_cola": return load_cola_splits() if source == "hf_sst5": return load_sst5_splits() if source == "hf_toxigen": return load_toxigen_splits() if source == "hf_newsgroups": return load_newsgroups_splits() if source == "hf_goemotions": return load_goemotions_splits() if source == "hf_yelp": return load_yelp_splits() if source == "hf_amazon": return load_amazon_splits() if source == "hf_sst2": return load_sst2_splits() if source == "hf_imdb": return load_imdb_splits() raise ValueError(f"unknown data source: {source}")