layerdepth-stratified / layerdepth_stratified /stratified_sampling.py
xiaohaox's picture
Upload layerdepth-stratified metadata, manifest, and preprocessing code
150d753 verified
Raw
History Blame Contribute Delete
2.65 kB
"""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]