og2_small / scripts /og2dataloader.py
AutomatedScientist's picture
Add files using upload-large-folder tool
6f32cc3 verified
Raw History Blame Contribute Delete
6.73 kB
"""PyTorch data loading for the subset: next-base prediction samples with an optional loss mask for non-ACGT targets.
from og2dataloader import RandomCrops, EvalTiles, make_loader
train = RandomCrops(root, "train", ctx=4096, seed=0, rc_prob=0.5, mask_non_acgt=True)
loader = make_loader(train, batch_size=16, num_workers=4) # infinite stream of batches
for batch in loader:
batch["input_ids"] # [B, ctx] int64, A=0 C=1 G=2 T=3 N/other=4 (case dropped)
batch["labels"] # [B, ctx] int64, the next base; -100 where the target is not A/C/G/T (if mask_non_acgt)
batch["loss_mask"] # [B, ctx] bool, True where the loss counts
batch["lowercase"] # [B, ctx] bool, the target is soft-masked (repeat); for weighting or per-class metrics
heldout = EvalTiles(root, "heldout", ctx=4096) # every window tiled once, deterministic order
loss = F.cross_entropy(logits.flatten(0, 1), batch["labels"].flatten(), ignore_index=-100)
A sample is ctx + 1 consecutive bases of one window (windows never cross record, contig or tag boundaries):
input = bases[:-1], labels = bases[1:]. With mask_non_acgt=False every target counts and N is a fifth class.
Inputs keep N (id 4) either way, so a model sees gaps. RandomCrops draws windows with probability proportional to
their number of possible crops (so every base is equally likely to be trained on), reproducibly per (seed, worker).
EvalTiles cuts every window into consecutive non-overlapping ctx + 1 tiles (the remainder shorter, right-padded
with labels -100); windows shorter than 2 bases are skipped.
Filters: subset="metagenomes", taxon=r"P__CHORDATA" (regex on the window's taxonomy tag), as in og2load.Windows.
"""
from __future__ import annotations
import numpy as np
from og2load import Windows
try:
import torch
from torch.utils.data import DataLoader, Dataset, IterableDataset, get_worker_info
except ImportError as e: # pragma: no cover - torch is optional for the rest of the scripts
raise ImportError("og2dataloader needs PyTorch: pip install torch") from e
IGNORE = -100
COMP = np.array([3, 2, 1, 0, 4], dtype=np.int64) # A<->T, C<->G, N->N
def to_sample(codes: np.ndarray, mask_non_acgt: bool, rc: bool = False, pad_to: int | None = None) -> dict:
"""uint8 codes of ctx + 1 bases -> one sample (tensors)."""
base = (codes & 7).astype(np.int64)
lower = (codes & 0x80) != 0
if rc:
base, lower = COMP[base[::-1]], lower[::-1]
x, y, low = base[:-1], base[1:].copy(), lower[1:].copy()
mask = y < 4 if mask_non_acgt else np.ones_like(y, dtype=bool)
y[~mask] = IGNORE
if pad_to is not None and len(x) < pad_to:
n = pad_to - len(x)
x = np.concatenate([x, np.full(n, 4, dtype=np.int64)])
y = np.concatenate([y, np.full(n, IGNORE, dtype=np.int64)])
mask = np.concatenate([mask, np.zeros(n, dtype=bool)])
low = np.concatenate([low, np.zeros(n, dtype=bool)])
return {"input_ids": torch.from_numpy(np.ascontiguousarray(x)), "labels": torch.from_numpy(np.ascontiguousarray(y)),
"loss_mask": torch.from_numpy(np.ascontiguousarray(mask)),
"lowercase": torch.from_numpy(np.ascontiguousarray(low))}
class RandomCrops(IterableDataset):
"""Infinite stream of random ctx + 1 crops, length-weighted over windows; reproducible per (seed, worker)."""
def __init__(self, root, split: str = "train", ctx: int = 4096, seed: int = 0, rc_prob: float = 0.0,
mask_non_acgt: bool = True, subset: str | None = None, taxon: str | None = None) -> None:
self.windows = Windows(root, split, subset, taxon)
self.ctx, self.seed, self.rc_prob, self.mask = ctx, seed, rc_prob, mask_non_acgt
usable = np.maximum(self.windows.lengths - ctx, 0) # crops of ctx + 1 bases per window
if usable.sum() == 0:
raise ValueError(f"no window in {split} has {ctx + 1} bases")
self.p = usable / usable.sum()
self.usable = usable
def __iter__(self):
info = get_worker_info()
rng = np.random.default_rng([self.seed, info.id if info else 0])
while True:
i = int(rng.choice(len(self.p), p=self.p))
arr, m = self.windows.items[i]
s = m["offset"] + int(rng.integers(0, self.usable[i]))
codes = np.asarray(arr[s: s + self.ctx + 1])
yield to_sample(codes, self.mask, rc=bool(rng.random() < self.rc_prob))
class EvalTiles(Dataset):
"""Every window cut into consecutive ctx + 1 tiles (deterministic); for bits/base on heldout or valid."""
def __init__(self, root, split: str = "heldout", ctx: int = 4096, mask_non_acgt: bool = True,
subset: str | None = None, taxon: str | None = None) -> None:
self.windows = Windows(root, split, subset, taxon)
self.ctx, self.mask = ctx, mask_non_acgt
self.tiles: list[tuple[int, int, int]] = [] # (window index, start, length incl. the extra base)
for i, (_, m) in enumerate(self.windows.items):
for s in range(0, m["len"] - 1, ctx):
n = min(ctx + 1, m["len"] - s)
if n >= 2:
self.tiles.append((i, s, n))
def __len__(self) -> int:
return len(self.tiles)
def __getitem__(self, k: int) -> dict:
i, s, n = self.tiles[k]
arr, m = self.windows.items[i]
codes = np.asarray(arr[m["offset"] + s: m["offset"] + s + n])
out = to_sample(codes, self.mask, pad_to=self.ctx)
out["subset"] = m["subset"]
return out
def collate(samples: list[dict]) -> dict:
out = {k: torch.stack([s[k] for s in samples]) for k in ("input_ids", "labels", "loss_mask", "lowercase")}
if "subset" in samples[0]:
out["subset"] = [s["subset"] for s in samples]
return out
def make_loader(ds, batch_size: int, num_workers: int = 0) -> DataLoader:
return DataLoader(ds, batch_size=batch_size, num_workers=num_workers, collate_fn=collate,
persistent_workers=num_workers > 0)
if __name__ == "__main__":
import argparse
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--root", default=".")
ap.add_argument("--split", default="train")
ap.add_argument("--ctx", type=int, default=4096)
ap.add_argument("--batch", type=int, default=4)
a = ap.parse_args()
b = next(iter(make_loader(RandomCrops(a.root, a.split, a.ctx, rc_prob=0.5), a.batch)))
print({k: (tuple(v.shape), v.dtype) for k, v in b.items()})
print(f"masked targets: {(~b['loss_mask']).float().mean():.5f}, soft-masked targets: {b['lowercase'].float().mean():.3f}")