File size: 9,645 Bytes
29f4341
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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):
        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

        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 _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)
        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

            dataset_len = int(self.dataset_lens[dataset_id])
            g = torch.Generator()
            g.manual_seed(self.seed + self.epoch * total_batches + batch_idx)
            rand_indices = torch.randint(
                low=0,
                high=dataset_len,
                size=(self.batch_size,),
                generator=g,
            ).tolist()
            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