# SPDX-License-Identifier: Apache-2.0 """Length-aware batching and a bounded out-of-memory retry.""" from __future__ import annotations from collections import defaultdict from collections.abc import Callable, Iterable, Iterator from typing import TypeVar import torch from scripts.config import LIMITS T = TypeVar("T") R = TypeVar("R") def adaptive_batch_size(n_tokens: int, default: int = LIMITS.batch_size) -> int: """Keep long-window forwards from stacking, as in the RNAGym scorer.""" if n_tokens > 4000: return 1 if n_tokens > 2000: return min(2, default) if n_tokens > 1200: return min(4, default) return max(1, default) def batches(items: Iterable[T], key: Callable[[T], tuple[str, int]]) -> Iterator[list[T]]: """Group by checkpoint and exact token length to avoid padding masks.""" groups: dict[tuple[str, int], list[T]] = defaultdict(list) for item in items: groups[key(item)].append(item) for (_, length), group in groups.items(): step = adaptive_batch_size(length) for start in range(0, len(group), step): yield group[start : start + step] def with_oom_retry(fn: Callable[[list[T]], list[R]], items: list[T]) -> list[R]: """Retry smaller batches only on GPU memory errors; never hide other failures.""" try: return fn(items) except RuntimeError as exc: if not (isinstance(exc, torch.cuda.OutOfMemoryError) or "out of memory" in str(exc).lower()): raise if len(items) <= 1: raise # Leave the exception scope before clearing allocations held by the traceback. torch.cuda.empty_cache() middle = len(items) // 2 return with_oom_retry(fn, items[:middle]) + with_oom_retry(fn, items[middle:])