|
| 1 | +"""Shared base for BEIR-layout graded-relevance ranking tasks. |
| 2 | +
|
| 3 | +Several tasks publish graded (0-4) relevance annotations on the Hugging Face |
| 4 | +Hub following the BEIR convention (``queries``, ``corpus``, ``qrels`` configs). |
| 5 | +They differ only in their task group and query input type (e.g. skill |
| 6 | +extraction from sentences vs skill normalization from surface terms), so the |
| 7 | +data-loading logic lives here and concrete tasks supply the task-specific |
| 8 | +properties. |
| 9 | +""" |
| 10 | + |
| 11 | +import pandas as pd |
| 12 | +from datasets import Dataset, load_dataset |
| 13 | + |
| 14 | +from workrb.tasks.abstract.base import DatasetSplit, LabelType, Language |
| 15 | +from workrb.tasks.abstract.ranking_base import RankingDataset, RankingTask |
| 16 | +from workrb.types import ModelInputType |
| 17 | + |
| 18 | + |
| 19 | +class GradedBEIRRankingTask(RankingTask): |
| 20 | + """Base class for BEIR-layout graded ranking tasks. |
| 21 | +
|
| 22 | + Reads the ``queries``, ``corpus`` and ``qrels`` configs published on the |
| 23 | + Hugging Face Hub via ``load_dataset``. The target_space is the corpus's |
| 24 | + ``title`` column (ESCO preferred labels, in corpus order); qrels are |
| 25 | + expected to contain only non-zero judgments (absent items are implicit |
| 26 | + grade 0). |
| 27 | +
|
| 28 | + Which splits a task exposes depends on what the underlying dataset |
| 29 | + publishes: some release both a validation and a test split, others only |
| 30 | + one. Because several tasks share this loader, the supported splits are |
| 31 | + declared per subclass via :attr:`split_to_hf_split` (which maps each |
| 32 | + supported :class:`DatasetSplit` to the HF split name its |
| 33 | + ``queries``/``qrels`` configs live under) rather than hardcoded with an |
| 34 | + inline guard as in the single-split tasks (e.g. ``MELORanking``). The |
| 35 | + default exposes only the validation split, the common case for in-progress |
| 36 | + benchmark datasets whose test split is withheld. |
| 37 | +
|
| 38 | + Concrete subclasses set ``hf_name`` via ``__init__`` and supply the |
| 39 | + task-specific ``task_group``, ``query_input_type``, ``name``, |
| 40 | + ``description`` and ``citation``. |
| 41 | + """ |
| 42 | + |
| 43 | + def __init__(self, hf_name: str, **kwargs): |
| 44 | + """Initialize the task. |
| 45 | +
|
| 46 | + Args: |
| 47 | + hf_name: Name of the Hugging Face dataset (BEIR layout). |
| 48 | + **kwargs: Additional arguments for the base class. |
| 49 | + """ |
| 50 | + self.hf_name = hf_name |
| 51 | + super().__init__(**kwargs) |
| 52 | + |
| 53 | + @property |
| 54 | + def split_to_hf_split(self) -> dict[DatasetSplit, str]: |
| 55 | + """Map each supported split to the HF split name backing it. |
| 56 | +
|
| 57 | + The corpus config is always loaded from the ``corpus`` split; this |
| 58 | + mapping only governs the ``queries`` and ``qrels`` configs. Override to |
| 59 | + expose more or fewer splits, e.g. ``{DatasetSplit.VAL: "validation", |
| 60 | + DatasetSplit.TEST: "test"}`` for a dataset that releases both. |
| 61 | + """ |
| 62 | + return {DatasetSplit.VAL: "validation"} |
| 63 | + |
| 64 | + @property |
| 65 | + def supported_query_languages(self) -> list[Language]: |
| 66 | + """Annotations are released in English only at this stage.""" |
| 67 | + return [Language.EN] |
| 68 | + |
| 69 | + @property |
| 70 | + def supported_target_languages(self) -> list[Language]: |
| 71 | + """The corpus titles are released in English only at this stage.""" |
| 72 | + return [Language.EN] |
| 73 | + |
| 74 | + @property |
| 75 | + def label_type(self) -> LabelType: |
| 76 | + """Label type is multi-label.""" |
| 77 | + return LabelType.MULTI_LABEL |
| 78 | + |
| 79 | + @property |
| 80 | + def target_input_type(self) -> ModelInputType: |
| 81 | + """Target input type for ESCO skills.""" |
| 82 | + return ModelInputType.SKILL_NAME |
| 83 | + |
| 84 | + @property |
| 85 | + def default_metrics(self) -> list[str]: |
| 86 | + """Default metrics include nDCG to leverage the graded labels. |
| 87 | +
|
| 88 | + ``ndcg`` without a cutoff scores the full ranking (k = |target_space|). |
| 89 | + """ |
| 90 | + return ["ndcg", "ndcg@5", "ndcg@10", "map", "rp@10", "mrr"] |
| 91 | + |
| 92 | + def load_dataset(self, dataset_id: str, split: DatasetSplit) -> RankingDataset: |
| 93 | + """Load BEIR-style graded annotations and convert to a RankingDataset.""" |
| 94 | + hf_split = self.split_to_hf_split.get(split) |
| 95 | + if hf_split is None: |
| 96 | + supported = ", ".join(sorted(s.value for s in self.split_to_hf_split)) |
| 97 | + raise ValueError( |
| 98 | + f"Split '{split.value}' not supported for {type(self).__name__}: " |
| 99 | + f"only [{supported}] {'is' if len(self.split_to_hf_split) == 1 else 'are'} " |
| 100 | + f"annotated for this dataset." |
| 101 | + ) |
| 102 | + |
| 103 | + queries_ds = load_dataset(self.hf_name, "queries", split=hf_split) |
| 104 | + corpus_ds = load_dataset(self.hf_name, "corpus", split="corpus") |
| 105 | + qrels_ds = load_dataset(self.hf_name, "qrels", split=hf_split) |
| 106 | + assert isinstance(queries_ds, Dataset) |
| 107 | + assert isinstance(corpus_ds, Dataset) |
| 108 | + assert isinstance(qrels_ds, Dataset) |
| 109 | + queries_df = queries_ds.to_pandas() |
| 110 | + corpus_df = corpus_ds.to_pandas() |
| 111 | + qrels_df = qrels_ds.to_pandas() |
| 112 | + assert isinstance(queries_df, pd.DataFrame) |
| 113 | + assert isinstance(corpus_df, pd.DataFrame) |
| 114 | + assert isinstance(qrels_df, pd.DataFrame) |
| 115 | + |
| 116 | + # target_space is the corpus titles in corpus order; URIs map by row index. |
| 117 | + target_space = corpus_df["title"].tolist() |
| 118 | + uri_to_idx = {uri: i for i, uri in enumerate(corpus_df["_id"])} |
| 119 | + |
| 120 | + qrels_df["target_idx"] = qrels_df["corpus-id"].map(uri_to_idx) |
| 121 | + # Every qrel should resolve; if any don't, surface the issue rather than silently dropping. |
| 122 | + unresolved = qrels_df["target_idx"].isna().sum() |
| 123 | + assert unresolved == 0, ( |
| 124 | + f"{unresolved} qrel rows reference corpus-ids not present in the corpus config" |
| 125 | + ) |
| 126 | + qrels_df["target_idx"] = qrels_df["target_idx"].astype(int) |
| 127 | + |
| 128 | + id_to_query = dict(zip(queries_df["_id"], queries_df["text"], strict=True)) |
| 129 | + qrels_df["sentence"] = qrels_df["query-id"].map(id_to_query) |
| 130 | + |
| 131 | + grouped = qrels_df.groupby("sentence") |
| 132 | + filtered_queries: list[str] = [] |
| 133 | + filtered_indices: list[list[int]] = [] |
| 134 | + filtered_relevance: list[list[float]] = [] |
| 135 | + for sentence, group in grouped: |
| 136 | + filtered_queries.append(str(sentence)) |
| 137 | + filtered_indices.append(group["target_idx"].tolist()) |
| 138 | + filtered_relevance.append([float(s) for s in group["score"].tolist()]) |
| 139 | + |
| 140 | + return RankingDataset( |
| 141 | + query_texts=filtered_queries, |
| 142 | + target_indices=filtered_indices, |
| 143 | + target_space=target_space, |
| 144 | + dataset_id=dataset_id, |
| 145 | + target_relevance=filtered_relevance, |
| 146 | + ) |
0 commit comments