File size: 7,455 Bytes
2eb3475 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | """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}")
|