Skip to content
Edit this page

muscari.data

Dataset rows to (kind, text) pairs: columns and prompts, deduplication and the held-out split.

Columns

TextColumn dataclass

TextColumn(
    name: str, prompt: str = "", label: str | None = None
)

A dataset column, the prompt the encoder expects for its texts, and what kind of text it holds.

Statistics are reported per kind of text, for example separately for queries and documents. The prompt usually tells the kinds apart. An encoder that takes no prompt needs a label instead, and so do two kinds that share a prompt.

kind property

kind: str

The name the texts of this column are grouped under: the label, or else the prompt.

parse classmethod

parse(spec: str) -> TextColumn

Parse name, name=prompt, name:label or name:label=prompt.

Everything after the first = is the prompt, verbatim, so a trailing space such as the one in "query: " is kept. A column whose name contains : cannot be given this way; construct the TextColumn directly.

Raises:

  • ValueError –

    if the column name or a label announced by : is empty.

Source code in src/muscari/data/columns.py
@classmethod
def parse(cls, spec: str) -> TextColumn:
    """Parse ``name``, ``name=prompt``, ``name:label`` or ``name:label=prompt``.

    Everything after the first ``=`` is the prompt, verbatim, so a trailing space such as
    the one in ``"query: "`` is kept. A column whose name contains ``:`` cannot be given
    this way; construct the ``TextColumn`` directly.

    Raises:
        ValueError: if the column name or a label announced by ``:`` is empty.
    """
    head, separator, prompt = spec.partition("=")
    name, colon, label = head.partition(":")

    if not name:
        raise ValueError(f"Column spec {spec!r} has no column name.")
    if colon and not label:
        raise ValueError(f"Column spec {spec!r} has an empty label.")

    return cls(name=name, prompt=prompt if separator else "", label=label if colon else None)

prompt_of_kind

prompt_of_kind(
    columns: Iterable[TextColumn],
) -> dict[str, str]

Map each kind of text to the prompt its columns prepend.

Raises:

  • ValueError –

    if two columns of the same kind prepend different prompts.

Source code in src/muscari/data/columns.py
def prompt_of_kind(columns: Iterable[TextColumn]) -> dict[str, str]:
    """Map each kind of text to the prompt its columns prepend.

    Raises:
        ValueError: if two columns of the same kind prepend different prompts.
    """
    prompts: dict[str, str] = {}

    for column in columns:
        if prompts.setdefault(column.kind, column.prompt) != column.prompt:
            raise ValueError(f"Columns labelled {column.kind!r} use different prompts; give them different labels.")

    return prompts

Texts

iter_texts

iter_texts(
    rows: Iterable[Mapping[str, Any]],
    columns: Sequence[TextColumn],
    *,
    dedup: bool = True,
    min_chars: int = 1,
    holdout_pct: float = 0.0,
    split: str = "train",
) -> Iterator[tuple[str, str]]

Yield (kind, text) for every text in the requested columns.

The kind is the column's prompt, or its label if it has one. An activation source prepends a kind as the prompt unless it was told which prompt a label stands for.

Parameters:

  • rows (Iterable[Mapping[str, Any]]) –

    dataset rows. Missing columns and None cells are skipped.

  • columns (Sequence[TextColumn]) –

    which columns to read, with the prompt and optional label of each.

  • dedup (bool, default: True ) –

    drop exact repeats of (kind, text). Retrieval datasets repeat documents heavily (shared negatives), which would otherwise over-weight them. This keeps one 64-bit hash per distinct text in memory.

  • min_chars (int, default: 1 ) –

    skip texts shorter than this many characters.

  • holdout_pct (float, default: 0.0 ) –

    percentage of distinct texts reserved for evaluation.

  • split (str, default: 'train' ) –

    "train" yields the texts outside the held-out part, "holdout" the held-out ones, "all" ignores holdout_pct.

Raises:

  • ValueError –

    on an unknown split or an out-of-range holdout_pct.

Source code in src/muscari/data/texts.py
def iter_texts(
    rows: Iterable[Mapping[str, Any]],
    columns: Sequence[TextColumn],
    *,
    dedup: bool = True,
    min_chars: int = 1,
    holdout_pct: float = 0.0,
    split: str = "train",
) -> Iterator[tuple[str, str]]:
    """Yield ``(kind, text)`` for every text in the requested columns.

    The kind is the column's prompt, or its label if it has one. An activation source prepends
    a kind as the prompt unless it was told which prompt a label stands for.

    Args:
        rows: dataset rows. Missing columns and ``None`` cells are skipped.
        columns: which columns to read, with the prompt and optional label of each.
        dedup: drop exact repeats of ``(kind, text)``. Retrieval datasets repeat documents
            heavily (shared negatives), which would otherwise over-weight them. This keeps one
            64-bit hash per distinct text in memory.
        min_chars: skip texts shorter than this many characters.
        holdout_pct: percentage of distinct texts reserved for evaluation.
        split: ``"train"`` yields the texts outside the held-out part, ``"holdout"`` the
            held-out ones, ``"all"`` ignores ``holdout_pct``.

    Raises:
        ValueError: on an unknown ``split`` or an out-of-range ``holdout_pct``.
    """
    if split not in SPLITS:
        raise ValueError(f"split must be one of {SPLITS}, got {split!r}.")
    _check_holdout_pct(holdout_pct)

    want_holdout = split == "holdout"
    seen: set[int] = set()

    for row in rows:
        for column in columns:
            cell = row.get(column.name)
            if cell is None:
                continue

            for text in _cell_texts(cell, min_chars):
                if split != "all" and is_holdout(text, holdout_pct) != want_holdout:
                    continue

                if dedup:
                    key = _hash64(column.kind + "\x00" + text)
                    if key in seen:
                        continue
                    seen.add(key)

                yield column.kind, text

is_holdout

is_holdout(text: str, holdout_pct: float) -> bool

Deterministically assign a text to the held-out split by its content hash.

The same text always lands on the same side, whatever row or column it appears in, so a document that recurs as a negative in many rows cannot leak from training into evaluation. holdout_pct is a percentage with a resolution of 0.01.

Source code in src/muscari/data/texts.py
def is_holdout(text: str, holdout_pct: float) -> bool:
    """Deterministically assign a text to the held-out split by its content hash.

    The same text always lands on the same side, whatever row or column it appears in, so a
    document that recurs as a negative in many rows cannot leak from training into evaluation.
    ``holdout_pct`` is a percentage with a resolution of 0.01.
    """
    _check_holdout_pct(holdout_pct)
    return (_hash64(text) % 10_000) < round(holdout_pct * 100)

repeat_texts

repeat_texts(
    make_iter: Callable[[], Iterable[tuple[str, str]]],
    max_epochs: int | None = None,
) -> Iterator[tuple[str, str]]

Re-run make_iter() each time it is exhausted, forever or for max_epochs passes.

Deduplication inside make_iter restarts on every pass, so each pass is one epoch over the distinct texts.

Raises:

  • ValueError –

    if a pass yields nothing, which would otherwise loop forever.

Source code in src/muscari/data/texts.py
def repeat_texts(
    make_iter: Callable[[], Iterable[tuple[str, str]]],
    max_epochs: int | None = None,
) -> Iterator[tuple[str, str]]:
    """Re-run ``make_iter()`` each time it is exhausted, forever or for ``max_epochs`` passes.

    Deduplication inside ``make_iter`` restarts on every pass, so each pass is one epoch over
    the distinct texts.

    Raises:
        ValueError: if a pass yields nothing, which would otherwise loop forever.
    """
    epoch = 0

    while max_epochs is None or epoch < max_epochs:
        empty = True
        for item in make_iter():
            empty = False
            yield item

        if empty:
            raise ValueError("The text source yielded nothing; check the dataset and column names.")
        epoch += 1

Rows

load_rows

load_rows(
    *,
    dataset: str | None,
    subsets: Sequence[str] | None,
    data_files: Sequence[str] | None,
    split: str,
    column_names: Sequence[str],
    seed: int,
) -> Iterable[dict[str, Any]]

Load rows, keep the wanted columns and shuffle the row order.

Local data_files take precedence over dataset. Several subsets are concatenated before shuffling so that training does not walk through them one after another.

Raises:

  • ValueError –

    on an unsupported file extension, mixed file types, or when none of the requested columns exists.

Source code in src/muscari/data/rows.py
def load_rows(
    *,
    dataset: str | None,
    subsets: Sequence[str] | None,
    data_files: Sequence[str] | None,
    split: str,
    column_names: Sequence[str],
    seed: int,
) -> Iterable[dict[str, Any]]:
    """Load rows, keep the wanted columns and shuffle the row order.

    Local ``data_files`` take precedence over ``dataset``. Several subsets are concatenated
    before shuffling so that training does not walk through them one after another.

    Raises:
        ValueError: on an unsupported file extension, mixed file types, or when none of the
            requested columns exists.
    """
    from datasets import concatenate_datasets

    parts = _load_parts(dataset, subsets, data_files, split)
    wanted = [part.select_columns([name for name in column_names if name in part.column_names]) for part in parts]

    if not any(part.column_names for part in wanted):
        raise ValueError(f"None of the columns {list(column_names)} exists in the data.")

    rows: Iterable[dict[str, Any]] = concatenate_datasets(wanted).shuffle(seed=seed)
    return rows

public_name

public_name(name: str) -> str

Record a local path by its last component so that outputs carry no directory layout.

Source code in src/muscari/data/rows.py
def public_name(name: str) -> str:
    """Record a local path by its last component so that outputs carry no directory layout."""
    return Path(name).name if Path(name).exists() else name