Spaces:
Running on Zero

File size: 1,787 Bytes
0a96270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# 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:])