File size: 2,649 Bytes
150d753
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""Stratified epoch ordering for LayeredDepth-Syn train splits."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Dict, List, Optional, Tuple

import numpy as np

DEFAULT_BATCH_MIX = {"1": 0.25, "2": 0.25, "3": 0.25, "4": 0.25}


def load_manifest(path: str | Path) -> Tuple[Dict[str, List[int]], Dict[str, float]]:
    payload = json.loads(Path(path).read_text(encoding="utf-8"))
    if "buckets" not in payload:
        raise ValueError('Manifest must contain a "buckets" object.')

    buckets = {str(k): [int(i) for i in v] for k, v in payload["buckets"].items()}
    batch_mix = payload.get("batch_mix", DEFAULT_BATCH_MIX)
    batch_mix = {str(k): float(v) for k, v in batch_mix.items()}
    return buckets, batch_mix


def build_round_robin_pattern(active_buckets: List[str], batch_mix: Optional[Dict[str, float]]) -> List[str]:
    weights = {}
    for bucket_id in active_buckets:
        if batch_mix and bucket_id in batch_mix:
            weights[bucket_id] = float(batch_mix[bucket_id])
        else:
            weights[bucket_id] = 1.0

    total = sum(weights.values())
    if total <= 0:
        raise ValueError("batch_mix must assign positive weight to at least one bucket.")

    pattern: List[str] = []
    for bucket_id in active_buckets:
        repeat = max(1, int(round(weights[bucket_id] / total * 20)))
        pattern.extend([bucket_id] * repeat)
    return pattern


def build_epoch_order(
    buckets: Dict[str, List[int]],
    batch_mix: Optional[Dict[str, float]],
    *,
    seed: int,
    epoch: int,
) -> List[int]:
    rng = np.random.RandomState(int(seed) + int(epoch))
    shuffled = {
        bucket_id: rng.permutation(indices).tolist()
        for bucket_id, indices in buckets.items()
        if indices
    }
    active = sorted(shuffled.keys())
    if not active:
        raise ValueError("No bucket indices in manifest.")

    pattern = build_round_robin_pattern(active, batch_mix)
    pointers = {bucket_id: 0 for bucket_id in active}
    total = sum(len(v) for v in shuffled.values())
    order: List[int] = []
    pattern_idx = 0
    while len(order) < total:
        bucket_id = pattern[pattern_idx % len(pattern)]
        pattern_idx += 1
        if pointers[bucket_id] >= len(shuffled[bucket_id]):
            continue
        order.append(shuffled[bucket_id][pointers[bucket_id]])
        pointers[bucket_id] += 1
    return order


def split_order_by_rank(order: List[int], rank: int, world_size: int) -> List[int]:
    if world_size <= 1:
        return order
    return [row_index for idx, row_index in enumerate(order) if idx % world_size == rank]