File size: 4,983 Bytes
5f4e9ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Batch sampler that never mixes image and text-only rows in one micro-batch."""

from __future__ import annotations

import random
from collections.abc import Iterator, Sequence

from torch.utils.data import BatchSampler, Sampler


class HasImageBatchSampler(BatchSampler):
    def __init__(
        self,
        has_image: Sequence[bool],
        batch_size: int,
        *,
        shuffle: bool = True,
        seed: int = 42,
        drop_last: bool = False,
        epoch: int = 0,
        num_replicas: int = 1,
        rank: int = 0,
    ) -> None:
        if batch_size < 1:
            raise ValueError("batch_size must be >= 1")
        self.has_image = list(has_image)
        self.batch_size = batch_size
        self.shuffle = shuffle
        self.seed = seed
        self.drop_last = drop_last
        self.epoch = epoch
        self.num_replicas = max(1, int(num_replicas))
        self.rank = int(rank)
        if not (0 <= self.rank < self.num_replicas):
            raise ValueError(f"rank {rank} out of range for {self.num_replicas} replicas")
        self.image_indices = [i for i, flag in enumerate(self.has_image) if flag]
        self.text_indices = [i for i, flag in enumerate(self.has_image) if not flag]
        dummy = _IndexSampler(len(self.has_image))
        super().__init__(dummy, batch_size, drop_last)

    def _shard(self, indices: list[int]) -> list[int]:
        if self.num_replicas == 1:
            return list(indices)
        return list(indices[self.rank :: self.num_replicas])

    def set_epoch(self, epoch: int) -> None:
        self.epoch = epoch

    def _batches_for(self, indices: list[int], rng: random.Random) -> list[list[int]]:
        order = list(indices)
        if self.shuffle:
            rng.shuffle(order)
        batches = [order[i : i + self.batch_size] for i in range(0, len(order), self.batch_size)]
        if self.drop_last and batches and len(batches[-1]) < self.batch_size:
            batches = batches[:-1]
        return [b for b in batches if b]

    def __iter__(self) -> Iterator[list[int]]:
        rng = random.Random(self.seed + self.epoch)
        image = self._shard(self.image_indices)
        text = self._shard(self.text_indices)
        batches = self._batches_for(image, rng) + self._batches_for(text, rng)
        if self.shuffle:
            rng.shuffle(batches)
        yield from batches

    def __len__(self) -> int:
        def count(n: int) -> int:
            if n == 0:
                return 0
            if self.drop_last:
                return n // self.batch_size
            return (n + self.batch_size - 1) // self.batch_size

        return count(len(self._shard(self.image_indices))) + count(len(self._shard(self.text_indices)))


class _IndexSampler(Sampler[int]):
    def __init__(self, length: int) -> None:
        self._length = length

    def __iter__(self) -> Iterator[int]:
        return iter(range(self._length))

    def __len__(self) -> int:
        return self._length


class HasImageRepeatSampler(Sampler[int]):
    """RepeatSampler that never mixes image and text unique prompts in one generation chunk."""

    def __init__(
        self,
        has_image: Sequence[bool],
        *,
        mini_repeat_count: int,
        batch_size: int,
        repeat_count: int = 1,
        shuffle: bool = True,
        seed: int | None = 42,
    ) -> None:
        if mini_repeat_count < 1 or batch_size < 1 or repeat_count < 1:
            raise ValueError("mini_repeat_count, batch_size, and repeat_count must be >= 1")
        self.has_image = [bool(v) for v in has_image]
        self.mini_repeat_count = int(mini_repeat_count)
        self.batch_size = int(batch_size)
        self.repeat_count = int(repeat_count)
        self.shuffle = bool(shuffle)
        self.seed = seed
        self.image_indices = [i for i, flag in enumerate(self.has_image) if flag]
        self.text_indices = [i for i, flag in enumerate(self.has_image) if not flag]

    def __iter__(self) -> Iterator[int]:
        rng = random.Random(self.seed)
        chunks: list[list[int]] = []
        for pool in (self.image_indices, self.text_indices):
            order = list(pool)
            if self.shuffle:
                rng.shuffle(order)
            for i in range(0, len(order), self.batch_size):
                chunk = order[i : i + self.batch_size]
                if len(chunk) == self.batch_size:
                    chunks.append(chunk)
        if self.shuffle:
            rng.shuffle(chunks)
        for chunk in chunks:
            for _ in range(self.repeat_count):
                for index in chunk:
                    for _ in range(self.mini_repeat_count):
                        yield index

    def __len__(self) -> int:
        def full(n: int) -> int:
            return (n // self.batch_size) * self.batch_size

        unique = full(len(self.image_indices)) + full(len(self.text_indices))
        return unique * self.mini_repeat_count * self.repeat_count