eMCR / src /mcr /data /base.py
Lux1997's picture
Duplicate from alibabagroup/eMCR
4a2f66d
Raw History Blame Contribute Delete
4.22 kB
"""Core data abstractions shared by every benchmark.
The whole framework is built around two ideas:
* :class:`Content` — one structure that represents a query OR a document for any
modality (plain text, image+text, or interleaved image-text). Loaders normalise
each benchmark's idiosyncratic schema into ``Content``; everything downstream
(encoders, retrievers, metrics) only ever sees ``Content``.
* :class:`RetrievalTask` — a single evaluatable unit (a domain/schema of a
benchmark). It yields normalised corpus/queries and BEIR-style qrels, plus an
optional per-query "difficulty" key for multi-condition stratified reporting.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
# A qrels mapping: {query_id: {doc_id: relevance}} — the BEIR convention.
QrelsType = Dict[str, Dict[str, int]]
@dataclass
class Segment:
"""One piece of content: a text span and/or an image.
``image`` is either a filesystem path (lazily opened by the encoder) or an
already-decoded ``PIL.Image.Image`` (used by MERIT, whose images live inside
parquet files and are decoded in memory).
"""
text: Optional[str] = None
image: Optional[Any] = None # str path | PIL.Image.Image | None
@property
def has_image(self) -> bool:
return self.image is not None and self.image != ""
@property
def has_text(self) -> bool:
return bool(self.text and self.text.strip())
@dataclass
class Content:
"""A query or a document, modality-agnostic.
The ``segments`` list preserves order, which is what makes interleaved
image-text queries (MERIT) representable in the same structure as a plain
string (a single text segment).
"""
segments: List[Segment] = field(default_factory=list)
meta: Dict[str, Any] = field(default_factory=dict)
# -- constructors -----------------------------------------------------
@classmethod
def from_text(cls, text: str, **meta: Any) -> "Content":
return cls(segments=[Segment(text=text)], meta=dict(meta))
@classmethod
def from_image_text(cls, image: Any, text: str, **meta: Any) -> "Content":
return cls(segments=[Segment(image=image), Segment(text=text)], meta=dict(meta))
# -- views ------------------------------------------------------------
def as_text(self, sep: str = "\n") -> str:
"""Flatten to plain text (drops images). Used by text-only encoders."""
return sep.join(s.text for s in self.segments if s.has_text).strip()
@property
def images(self) -> List[Any]:
return [s.image for s in self.segments if s.has_image]
@property
def is_multimodal(self) -> bool:
return any(s.has_image for s in self.segments)
class RetrievalTask(ABC):
"""One evaluatable unit (e.g. a single SSRB schema, or a MERIT split).
Concrete loaders subclass this and implement the three ``load_*`` methods.
A benchmark typically expands into many ``RetrievalTask`` instances (one per
domain/schema); see :mod:`mcr.data.registry`.
"""
#: short identifier, e.g. "ssrb/Academic/academic_collabo"
name: str = "task"
#: "text" | "image_text" | "interleaved"
modality: str = "text"
#: metric keys to highlight in the report so numbers line up with the paper
official_metrics: Tuple[str, ...] = ("ndcg@10", "recall@10")
@abstractmethod
def load_corpus(self) -> Iterator[Tuple[str, Content]]:
"""Yield ``(doc_id, Content)`` for every document in the corpus."""
@abstractmethod
def load_queries(self) -> Iterator[Tuple[str, Content]]:
"""Yield ``(query_id, Content)`` for every query."""
@abstractmethod
def load_qrels(self) -> QrelsType:
"""Return relevance judgements as ``{qid: {doc_id: rel}}``."""
def stratify_key(self, qid: str) -> Dict[str, Union[int, str]]:
"""Per-query difficulty descriptor for stratified reporting.
Default: no stratification. Multi-condition tasks override this to expose
e.g. ``{"n_cond": 3}`` or ``{"nf": 2, "ns": 1}``.
"""
return {}