import torch from torch.utils.data import Sampler from accelerate import Accelerator import math import os import random from dataclasses import dataclass from psi.utils import initialize_overwatch overwatch = initialize_overwatch(__name__) def _normalize_positive_weights(mixture_ratios): weights = torch.tensor(mixture_ratios, dtype=torch.double) if weights.numel() == 0: raise ValueError("Sampler received empty mixture ratios") if torch.any(weights < 0): raise ValueError(f"Sampler received negative mixture ratios: {mixture_ratios}") weight_sum = weights.sum() if weight_sum.item() <= 0: raise ValueError("Sampler received no positive mixture ratios") weights /= weight_sum return weights class BatchMixtureSampler(Sampler): """ Multi-node safe dataset mixture sampler. Example: datasets = [ds1, ds2], ratio = [4, 1] """ def __init__(self, dataset_lens, mixture_ratios, num_samples_per_epoch, batch_size, seed=42): self.dataset_lens = dataset_lens self.weights = _normalize_positive_weights(mixture_ratios) self.num_samples = num_samples_per_epoch self.batch_size = batch_size self.seed = seed # Distributed settings self.rank = int(os.environ.get("RANK", 0)) self.world_size = int(os.environ.get("WORLD_SIZE", 1)) # each rank gets this many samples self.num_samples_rank = math.ceil(self.num_samples / self.world_size) self.epoch = 0 self.batch_counts = self._build_batch_counts() def _build_batch_counts(self): positive_ids = [i for i, weight in enumerate(self.weights.tolist()) if weight > 0] if not positive_ids: raise ValueError("BatchMixtureSampler received no positive mixture ratios") counts = torch.zeros(len(self.dataset_lens), dtype=torch.long) if self.batch_size >= len(positive_ids): counts[positive_ids] = 1 remaining = self.batch_size - len(positive_ids) if remaining > 0: positive_weights = self.weights[positive_ids] positive_weights = positive_weights / positive_weights.sum() raw_extra = positive_weights * remaining extra_counts = torch.floor(raw_extra).long() counts[positive_ids] += extra_counts extra_left = remaining - int(extra_counts.sum().item()) if extra_left > 0: frac = raw_extra - extra_counts.double() for frac_index in torch.argsort(frac, descending=True)[:extra_left].tolist(): counts[positive_ids[frac_index]] += 1 else: for dataset_id in torch.argsort(self.weights, descending=True)[:self.batch_size].tolist(): counts[dataset_id] += 1 return counts.tolist() def set_epoch(self, epoch): self.epoch = epoch def __iter__(self): num_batches_rank = len(self) total_batches = num_batches_rank * self.world_size for batch_idx in range(total_batches): if batch_idx % self.world_size != self.rank: continue g = torch.Generator() g.manual_seed(self.seed + self.epoch * total_batches + batch_idx) batch = [] for dataset_id, count in enumerate(self.batch_counts): if count <= 0: continue dataset_len = int(self.dataset_lens[dataset_id]) rand_indices = torch.randint( low=0, high=dataset_len, size=(count,), generator=g, ).tolist() batch.extend((dataset_id, sample_id) for sample_id in rand_indices) shuffle_order = torch.randperm(len(batch), generator=g).tolist() yield [batch[i] for i in shuffle_order] def __len__(self): return math.ceil(self.num_samples_rank / self.batch_size) class TaskMixtureSampler(Sampler): """ Multi-node safe dataset mixture sampler that assigns exactly one dataset to each global batch, then samples a full homogeneous batch from that dataset. """ def __init__(self, dataset_lens, mixture_ratios, num_samples_per_epoch, batch_size, seed=42, datasets=None): self.dataset_lens = dataset_lens self.datasets = datasets self.weights = _normalize_positive_weights(mixture_ratios) self.num_samples = num_samples_per_epoch self.batch_size = batch_size self.seed = seed self.sync_across_ranks = os.environ.get("PSI_TASK_MIXTURE_SYNC_RANKS", "0").strip().lower() in { "1", "true", "yes", "on", } self.shard_aware = os.environ.get("PSI_TASK_MIXTURE_SHARD_AWARE", "0").strip().lower() in { "1", "true", "yes", "on", } self.rank = int(os.environ.get("RANK", 0)) self.world_size = int(os.environ.get("WORLD_SIZE", 1)) self.num_samples_rank = math.ceil(self.num_samples / self.world_size) self.epoch = 0 def set_epoch(self, epoch): self.epoch = epoch def _sample_dataset_indices(self, dataset_id: int, generator: torch.Generator) -> list[int]: dataset_len = int(self.dataset_lens[dataset_id]) if self.shard_aware and self.datasets is not None: dataset = self.datasets[dataset_id] sampler = getattr(dataset, "sample_shard_aware_indices", None) if callable(sampler): indices = sampler(self.batch_size, generator) if indices is not None: if len(indices) != self.batch_size: raise RuntimeError( f"Shard-aware sampler for dataset {dataset_id} returned {len(indices)} " f"indices, expected {self.batch_size}" ) return [int(i) for i in indices] return torch.randint( low=0, high=dataset_len, size=(self.batch_size,), generator=generator, ).tolist() def _build_batch_schedule(self, total_batches): positive_ids = [i for i, weight in enumerate(self.weights.tolist()) if weight > 0] if not positive_ids: raise ValueError("TaskMixtureSampler received no positive mixture ratios") positive_weights = self.weights[positive_ids] positive_weights = positive_weights / positive_weights.sum() raw_counts = positive_weights * total_batches batch_counts = torch.floor(raw_counts).long() batches_left = total_batches - int(batch_counts.sum().item()) if batches_left > 0: frac = raw_counts - batch_counts.double() for frac_index in torch.argsort(frac, descending=True)[:batches_left].tolist(): batch_counts[frac_index] += 1 schedule = [] for local_idx, dataset_id in enumerate(positive_ids): schedule.extend([dataset_id] * int(batch_counts[local_idx].item())) if len(schedule) != total_batches: raise RuntimeError( f"TaskMixtureSampler built invalid schedule: expected {total_batches} batches, got {len(schedule)}" ) g = torch.Generator() g.manual_seed(self.seed + self.epoch) shuffle_order = torch.randperm(len(schedule), generator=g).tolist() return [schedule[i] for i in shuffle_order] def __iter__(self): num_batches_rank = len(self) if self.sync_across_ranks: batch_schedule = self._build_batch_schedule(num_batches_rank) for local_batch_idx, dataset_id in enumerate(batch_schedule): g = torch.Generator() g.manual_seed( self.seed + self.epoch * num_batches_rank * self.world_size + local_batch_idx * self.world_size + self.rank ) rand_indices = self._sample_dataset_indices(dataset_id, g) yield [(dataset_id, sample_id) for sample_id in rand_indices] return total_batches = num_batches_rank * self.world_size batch_schedule = self._build_batch_schedule(total_batches) for batch_idx, dataset_id in enumerate(batch_schedule): if batch_idx % self.world_size != self.rank: continue g = torch.Generator() g.manual_seed(self.seed + self.epoch * total_batches + batch_idx) rand_indices = self._sample_dataset_indices(dataset_id, g) yield [(dataset_id, sample_id) for sample_id in rand_indices] def __len__(self): return math.ceil(self.num_samples_rank / self.batch_size) @dataclass class DatasetSpec: # dataset: torch.utils.data.Dataset dataset_length: int prob: float # mixture ratio image_size: tuple[int, int] # e.g. 224, 448 tokens_per_image: int # (image_size / patch)^2 class TokenMixtureSampler(Sampler): """ Multi-node safe dataset mixture sampler that samples from datasets with different image resolutoion while keeping the total number of tokens per batch (approximately) fixed. """ def __init__( self, specs: list[DatasetSpec], tokens_per_batch: int, # per rank num_batches_per_rank: int, seed: int = 0, ): self.specs = specs self.tokens_per_batch = tokens_per_batch self.num_batches_per_rank = num_batches_per_rank self.seed = seed self.probs = [s.prob for s in specs] self.epoch = 0 # Distributed settings self.rank = int(os.environ.get("RANK", 0)) self.world_size = int(os.environ.get("WORLD_SIZE", 1)) def set_epoch(self, epoch): self.epoch = epoch # overwatch.info(f"TokenMixtureSampler set to epoch {epoch}") def __iter__(self): # assert self.epoch is not None, "TokenMixtureSampler epoch not set. Please call set_epoch(epoch) before iterating." # For each global batch index, synchronize dataset_id selection across all ranks for batch_idx in range(self.num_batches_per_rank * self.world_size): if batch_idx % self.world_size != self.rank: continue # Use a deterministic RNG for this global! batch to pick dataset_id and indices batch_seed = self.seed + self.epoch + batch_idx # // self.world_size local_rng = random.Random(batch_seed) dataset_id = local_rng.choices(range(len(self.specs)), weights=self.probs, k=1)[0] # print(f"[TokenMixtureSampler] rank={self.rank} seed={batch_seed} dataset_id={dataset_id}") spec = self.specs[dataset_id] batch_size = max(1, self.tokens_per_batch // spec.tokens_per_image) local_batch_rng = random.Random(self.seed + self.epoch + batch_idx) indices = [ (dataset_id, local_batch_rng.randrange(spec.dataset_length)) for _ in range(batch_size) ] # overwatch.info(f"rank {overwatch.rank()}: {self.epoch} batch {batch_idx} dataset_id {dataset_id} batch_size {batch_size}") yield indices def __len__(self): return self.num_batches_per_rank