File size: 28,844 Bytes
57e1c5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68625b4
57e1c5c
68625b4
57e1c5c
 
 
68625b4
57e1c5c
68625b4
57e1c5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68625b4
 
 
 
 
 
57e1c5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68625b4
 
57e1c5c
 
 
 
 
 
 
 
 
 
 
68625b4
 
 
 
57e1c5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01ce0b4
 
57e1c5c
 
 
 
 
 
 
 
 
 
 
01ce0b4
57e1c5c
 
 
 
 
 
 
 
 
01ce0b4
57e1c5c
 
 
 
 
 
 
 
 
 
68625b4
57e1c5c
 
68625b4
 
 
57e1c5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68625b4
57e1c5c
 
 
 
 
 
 
 
 
 
68625b4
 
 
 
 
 
 
 
 
 
 
 
 
57e1c5c
 
 
 
 
 
 
 
 
 
 
 
 
 
68625b4
57e1c5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68625b4
57e1c5c
 
 
 
 
68625b4
 
 
 
 
 
 
 
 
57e1c5c
 
 
 
 
 
 
 
 
 
 
 
 
 
68625b4
 
 
 
57e1c5c
 
 
 
 
 
 
 
 
68625b4
 
 
 
57e1c5c
 
 
 
68625b4
 
 
 
57e1c5c
 
68625b4
57e1c5c
 
 
68625b4
 
 
 
57e1c5c
 
 
 
 
 
 
68625b4
 
 
 
57e1c5c
68625b4
 
57e1c5c
 
68625b4
 
 
57e1c5c
 
 
 
 
 
 
 
 
 
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
import gzip
import itertools
import json
import multiprocessing
import os
import pickle
import queue
import re
import urllib
import zipfile
from math import floor
from typing import Optional

import datasets
import numpy as np
from datasets import config
from datasets.arrow_dataset import Dataset
from datasets.arrow_reader import ArrowReader
from datasets.features.image import image_to_bytes
from datasets.fingerprint import Hasher
from PIL import Image, ImageFilter
from torchvision import transforms as T
from tqdm import tqdm

from classes import IMAGENET2012_CLASSES

logger = datasets.logging.get_logger(__name__)


_CITATION = """\
@misc{nauen2025foraug,
    title={ForAug: Recombining Foregrounds and Backgrounds to Improve Vision Transformer Training with Bias Mitigation},
    author={Tobias Christian Nauen and Brian Moser and Federico Raue and Stanislav Frolov and Andreas Dengel},
    year={2025},
    eprint={2503.09399},
    archivePrefix={arXiv},
    primaryClass={cs.CV},
}
"""

_DESCRIPTION = """\
ForNet is a dataset of foreground objects and backgrounds extracted (and infilled) from ImageNet. \
It's the output of the segmentation phase of the ForAug data augmentation. \
ForNet recombines these foregrounds and backgrounds on the fly to create new samples for training vision transformers.
"""

_GIT = "https://github.com/tobna/ForAug"
_HOMEPAGE = "Coming Soon"
_DATASET_URL = "https://huggingface.co/datasets/TNauen/ForNet/resolve/main/"
_CONST_URLS = (
    [_DATASET_URL + "settings.txt"]
    + [_DATASET_URL + f"fg_bg_ratios_{part}.json" for part in ["train", "val"]]
    + [_DATASET_URL + f"hf_{part}_indices.json" for part in ["train", "val"]]
)
_PATCH_URLS = [_DATASET_URL + f"train_{i}.zip" for i in range(20)] + [_DATASET_URL + "val.zip"]


class RecombineDataset(Dataset):
    """Wrapper for ForNet dataset that recombines foregrounds and backgrounds on the fly."""

    def __init__(
        self,
        *args,
        background_combination,
        fg_scale_jitter,
        pruning_ratio,
        fg_size_mode,
        fg_bates_n,
        mask_smoothing_sigma,
        rel_jut_out,
        orig_img_prob,
        **kwargs,
    ):
        """Create the ForNet recombination dataset.

        Args:
            background_combination (str): Which backgrounds to combine with foregrounds. Options: "orig", "same", "all".
            fg_scale_jitter (tuple[float]): How much should the size of the foreground be changed (random ratio). Example: (0.1, 0.8).
            pruning_ratio (float): For pruning backgrounds, with (foreground size/background size) >= <pruning_ratio>. Backgrounds from images that contain very large foreground objects are mostly computer generated and therefore relatively unnatural. Full dataset: 1.1 .
            fg_size_mode (str): How to determine the size of the foreground, based on the foreground sizes of the foreground and background images. Options: "range", "min", "max", "mean".
            fg_bates_n (int): Bates parameter for the distribution of the object position in the foreground. Uniform Distribution: 1. The higher the value, the more likely the object is in the center. For fg_bates_n = 0, the object is always in the center.
            mask_smoothing_sigma (float): Sigma for the Gaussian blur of the mask edge.
            rel_jut_out (float): How much is the foreground allowed to stand/jut out of the background (and then cut off).
            orig_img_prob (float | str): Probability to use the original image, instead of the fg-bg recombinations. Options: 0.0-1.0, "linear", "revlinear", "cos".
        """
        super().__init__(*args, **kwargs)
        assert (isinstance(orig_img_prob, float) and 0.0 <= orig_img_prob <= 1.0) or orig_img_prob in [
            "linear",
            "revlinear",
            "cos",
        ], f"Invalid orig_img_prob {orig_img_prob}"
        assert background_combination in [
            "all",
            "same",
            "orig",
        ], f"Invalid background_combination {background_combination}"
        assert fg_size_mode in [
            "range",
            "min",
            "max",
            "mean",
        ], f"Invalid fg_size_mode {fg_size_mode}"
        self.background_combination = background_combination
        self.fg_scale_jitter = fg_scale_jitter
        self.pruning_ratio = pruning_ratio
        self.fg_size_mode = fg_size_mode
        self.fg_bates_n = fg_bates_n
        self.mask_smoothing_sigma = mask_smoothing_sigma
        self.rel_jut_out = rel_jut_out
        self.orig_img_prob = orig_img_prob
        self.epochs = 0
        self._epoch = 0
        self.cls_to_idx = {}

        bg_rat_indices = super()._getitem(0)["bg_rat_idx_file"]
        self.train = "train" in bg_rat_indices.split("/")[-1]

        with open(bg_rat_indices, "r") as f:
            bg_rat_indices = json.load(f)
        for in_cls in bg_rat_indices:
            if in_cls not in self.cls_to_idx:
                self.cls_to_idx[in_cls] = []
            for idx, rat in bg_rat_indices[in_cls]:
                if rat < self.pruning_ratio:
                    self.cls_to_idx[in_cls].append(idx)
        if self.background_combination == "all":
            self.cls_to_idx["all"] = list(itertools.chain(*self.cls_to_idx.values()))

    @property
    def total_epochs(self):
        return self.epochs

    @total_epochs.setter
    def total_epochs(self, value):
        self.epochs = value

    @property
    def epoch(self):
        return self._epoch

    @epoch.setter
    def epoch(self, value):
        assert 0 <= value < self.epochs, f"Epoch {value} is out of bounds for range [0, {self.epochs})"
        self._epoch = value

    def _getitem(self, key):
        fg_item = super()._getitem(key)
        out_dict = {"label": fg_item["label"]}
        in_cls = fg_item["path"].split("/")[0]

        if (
            (self.orig_img_prob == "linear" and np.random.rand() < self._epoch / self.epochs)
            or (self.orig_img_prob == "revlinear" and np.random.rand() < (self._epoch - self.epochs) / self.epochs)
            or (self.orig_img_prob == "cos" and np.random.rand() > np.cos(np.pi * self._epoch / (2 * self.epochs)))
            or (
                isinstance(self.orig_img_prob, float)
                and self.orig_img_prob > 0.0
                and np.random.rand() < self.orig_img_prob
            )
        ):
            # return original image
            out_dict["image"] = fg_item["in"]
            return out_dict

        if self.background_combination == "orig":
            bg_item = fg_item
        elif self.background_combination == "same":
            rand_idx = np.random.randint(len(self.cls_to_idx[in_cls]))
            rand_idx = self.cls_to_idx[in_cls][rand_idx]
            bg_item = super()._getitem(rand_idx)
        else:
            # all
            rand_idx = np.random.randint(len(self.cls_to_idx["all"]))
            rand_idx = self.cls_to_idx["all"][rand_idx]
            bg_item = super()._getitem(rand_idx)

        fg_img = fg_item["fg"].convert("RGBA")
        bg_img = bg_item["bg"].convert("RGB")
        bg_size = bg_img.size
        bg_area = bg_size[0] * bg_size[1]
        orig_fg_ratio = fg_item["fg/bg_area"]
        bg_fg_ratio = bg_item["fg/bg_area"]

        if self.fg_size_mode == "max":
            goal_fg_ratio_lower = goal_fg_ratio_upper = max(orig_fg_ratio, bg_fg_ratio)
        elif self.fg_size_mode == "min":
            goal_fg_ratio_lower = goal_fg_ratio_upper = min(orig_fg_ratio, bg_fg_ratio)
        elif self.fg_size_mode == "mean":
            goal_fg_ratio_lower = goal_fg_ratio_upper = (orig_fg_ratio + bg_fg_ratio) / 2
        else:
            # range
            goal_fg_ratio_lower = min(orig_fg_ratio, bg_fg_ratio)
            goal_fg_ratio_upper = max(orig_fg_ratio, bg_fg_ratio)

        fg_size_factor = T.ToTensor()(fg_img.split()[-1]).mean().item()

        fg_scale = (
            np.random.uniform(
                goal_fg_ratio_lower * (1 - self.fg_scale_jitter),
                goal_fg_ratio_upper * (1 + self.fg_scale_jitter),
            )
            / fg_size_factor
        )

        goal_shape_y = round(np.sqrt(bg_area * fg_scale * fg_img.size[1] / fg_img.size[0]))
        goal_shape_x = round(np.sqrt(bg_area * fg_scale * fg_img.size[0] / fg_img.size[1]))

        fg_img = fg_img.resize((goal_shape_x, goal_shape_y))

        if fg_img.size[0] > bg_size[0] or fg_img.size[1] > bg_size[1]:
            # random crop to fit
            goal_w, goal_h = (
                min(fg_img.size[0], bg_size[0]),
                min(fg_img.size[1], bg_size[1]),
            )
            fg_img = T.RandomCrop((goal_h, goal_w))(fg_img) if self.train else T.CenterCrop((goal_h, goal_w))(fg_img)

        # paste fg on bg
        z1, z2 = (
            (
                np.random.uniform(0, 1, abs(self.fg_bates_n)).mean(),  # bates distribution n=1 => uniform
                np.random.uniform(0, 1, abs(self.fg_bates_n)).mean(),
            )
            if self.fg_bates_n != 0
            else (0.5, 0.5)
        )
        if self.fg_bates_n < 0:
            z1 = z1 + 0.5 - floor(z1 + 0.5)
            z2 = z2 + 0.5 - floor(z2 + 0.5)

        x_min = -self.rel_jut_out * fg_img.size[0]
        x_max = bg_size[0] - fg_img.size[0] * (1 - self.rel_jut_out)
        y_min = -self.rel_jut_out * fg_img.size[1]
        y_max = bg_size[1] - fg_img.size[1] * (1 - self.rel_jut_out)

        if x_min > x_max:
            x_min = x_max = (x_min + x_max) / 2
        if y_min > y_max:
            y_min = y_max = (y_min + y_max) / 2

        offs_x = round(z1 * (x_max - x_min) + x_min)
        offs_y = round(z2 * (y_max - y_min) + y_min)

        paste_mask = fg_img.split()[-1]
        if self.mask_smoothing_sigma > 0.0:
            sigma = (np.random.rand() * 0.9 + 0.1) * self.mask_smoothing_sigma
            paste_mask = paste_mask.filter(ImageFilter.GaussianBlur(radius=sigma))
            paste_mask = paste_mask.point(lambda p: 2 * p - 255 if p > 128 else 0)

        bg_img.paste(fg_img.convert("RGB"), (offs_x, offs_y), paste_mask)
        bg_img = bg_img.convert("RGB")

        out_dict["image"] = bg_img

        return out_dict

    def __str__(self):
        return f"{self.__class__}(\n\t              features: ['image', 'label'],\n\t              num_rows: {len(self)},\n\tbackground_combination: {self.background_combination},\n\t         pruning_ratio: {self.pruning_ratio},\n\t          fg_size_mode: {self.fg_size_mode},\n\t  mask_smoothing_sigma: {self.mask_smoothing_sigma},\n\t         orig_img_prob: {self.orig_img_prob}\n)"


_CONFIG_HASH_IGNORE_KWARGS = [
    "background_combination",
    "fg_scale_jitter",
    "pruning_ratio",
    "fg_size_mode",
    "fg_bates_n",
    "mask_smoothing_sigma",
    "rel_jut_out",
    "orig_img_prob",
]


class ForNetConfig(datasets.BuilderConfig):
    """BuilderConfig for ForNet."""

    def __init__(
        self,
        background_combination,
        fg_scale_jitter,
        pruning_ratio,
        fg_size_mode,
        fg_bates_n,
        mask_smoothing_sigma,
        rel_jut_out,
        orig_img_prob,
        **kwargs,
    ):
        """BuilderConfig for ForNet.

        Args:
          **kwargs: keyword arguments forwarded to super.
        """
        super(ForNetConfig, self).__init__(**kwargs)
        self.background_combination = background_combination
        self.fg_scale_jitter = fg_scale_jitter
        self.pruning_ratio = pruning_ratio
        self.fg_size_mode = fg_size_mode
        self.fg_bates_n = fg_bates_n
        self.mask_smoothing_sigma = mask_smoothing_sigma
        self.rel_jut_out = rel_jut_out
        self.orig_img_prob = orig_img_prob

    def __str__(self):
        return f"ForNetConfig(name={self.name}, version={self.version}, data_dir={self.data_dir}, data_files={self.data_files}, description={self.description}, background_combination={self.background_combination}, fg_scale_jitter={self.fg_scale_jitter}, pruning_ratio={self.pruning_ratio}, fg_size_mode={self.fg_size_mode}, fg_bates_n={self.fg_bates_n}, mask_smoothing_sigma={self.mask_smoothing_sigma}, rel_jut_out={self.rel_jut_out}, orig_img_prob={self.orig_img_prob})"

    def create_config_id(
        self,
        config_kwargs: dict,
        custom_features=None,
    ) -> str:
        """The config id is used to build the cache directory.

        By default it is equal to the config name.
        However the name of a config is not sufficient to have a unique identifier for the dataset being generated
        since it doesn't take into account:
        - the config kwargs that can be used to overwrite attributes
        - the custom features used to write the dataset
        - the data_files for json/text/csv/pandas datasets.

        Therefore the config id is just the config name with an optional suffix based on these.
        """
        # Possibly add a suffix to the name to handle custom features/data_files/config_kwargs
        suffix: Optional[str] = None
        config_kwargs_to_add_to_suffix = config_kwargs.copy()
        # name and version are already used to build the cache directory
        config_kwargs_to_add_to_suffix.pop("name", None)
        config_kwargs_to_add_to_suffix.pop("version", None)

        # remove only recombination-relevant values
        for k in _CONFIG_HASH_IGNORE_KWARGS:
            config_kwargs_to_add_to_suffix.pop(k, None)

        # data dir handling (when specified it points to the manually downloaded data):
        # it was previously ignored before the introduction of config id because we didn't want
        # to change the config name. Now it's fine to take it into account for the config id.
        # config_kwargs_to_add_to_suffix.pop("data_dir", None)
        if "data_dir" in config_kwargs_to_add_to_suffix:
            if config_kwargs_to_add_to_suffix["data_dir"] is None:
                config_kwargs_to_add_to_suffix.pop("data_dir", None)
            else:
                # canonicalize the data dir to avoid two paths to the same location having different
                # hashes
                data_dir = config_kwargs_to_add_to_suffix["data_dir"]
                data_dir = os.path.normpath(data_dir)
                config_kwargs_to_add_to_suffix["data_dir"] = data_dir
        if config_kwargs_to_add_to_suffix:
            # we don't care about the order of the kwargs
            config_kwargs_to_add_to_suffix = {
                k: config_kwargs_to_add_to_suffix[k] for k in sorted(config_kwargs_to_add_to_suffix)
            }
            if all(isinstance(v, (str, bool, int, float)) for v in config_kwargs_to_add_to_suffix.values()):
                suffix = ",".join(
                    str(k) + "=" + urllib.parse.quote_plus(str(v)) for k, v in config_kwargs_to_add_to_suffix.items()
                )
                if len(suffix) > 32:  # hash if too long
                    suffix = Hasher.hash(config_kwargs_to_add_to_suffix)
            else:
                suffix = Hasher.hash(config_kwargs_to_add_to_suffix)

        if custom_features is not None:
            m = Hasher()
            if suffix:
                m.update(suffix)
            m.update(custom_features)
            suffix = m.hexdigest()

        if suffix:
            config_id = self.name + "-" + suffix
            if len(config_id) > config.MAX_DATASET_CONFIG_ID_READABLE_LENGTH:
                config_id = self.name + "-" + Hasher.hash(suffix)
            return config_id
        return self.name


class ForNet(datasets.GeneratorBasedBuilder):
    """ForNet dataset."""

    def __init__(self, *args, **kwargs):
        """Initialize the ForNet Builder."""
        super().__init__(*args, **kwargs)
        self.cls_to_idx_locs = {}

    BUILDER_CONFIGS = [
        ForNetConfig(
            name="fornet",
            version=datasets.Version("1.0.0", ""),
            description="ForNet dataset",
            background_combination="all",
            fg_scale_jitter=0.3,
            pruning_ratio=0.8,
            fg_size_mode="range",
            fg_bates_n=1,
            mask_smoothing_sigma=4.0,
            rel_jut_out=0.0,
            orig_img_prob=0.0,
        )
    ]

    DEFAULT_WRITER_BATCH_SIZE = 1000

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "path": datasets.Value("string"),
                    "bg": datasets.features.Image(),
                    "fg": datasets.features.Image(),
                    "in": datasets.features.Image(),
                    "label": datasets.features.ClassLabel(names=list(IMAGENET2012_CLASSES.values())),
                    "fg/bg_area": datasets.Value("float"),
                    "bg_rat_idx_file": datasets.Value("string"),
                }
            ),
            supervised_keys=("image", "label"),
            homepage=_HOMEPAGE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager: datasets.DownloadManager):
        urls_to_download = _CONST_URLS + _PATCH_URLS
        dl_paths = dl_manager.download(urls_to_download)

        train_re = re.compile(r".*/train_(\d+)\.zip$")
        val_re = re.compile(r".*/val\.zip$")

        train_patches = [f for f in dl_paths if train_re.match(f)]
        val_patches = [f for f in dl_paths if val_re.match(f)]

        hf_train_indices = [f for f in dl_paths if f.endswith("hf_train_indices.json")][0]
        hf_val_indices = [f for f in dl_paths if f.endswith("hf_val_indices.json")][0]

        cls_to_idx_locs = {
            "train": hf_train_indices.replace("hf_train_indices", "train_cls_to_idx"),
            "val": hf_val_indices.replace("hf_val_indices", "val_cls_to_idx"),
        }

        fg_bg_ratios = [
            [f for f in dl_paths if f.endswith(f"fg_bg_ratios_{part}.json")][0] for part in ["train", "val"]
        ]

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "patch_files": train_patches,
                    "split": "train",
                    "hf_indices": hf_train_indices,
                    "cls_to_idx_loc": cls_to_idx_locs["train"],
                    "fg_bg_ratios": fg_bg_ratios[0],
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "patch_files": val_patches,
                    "split": "val",
                    "hf_indices": hf_val_indices,
                    "cls_to_idx_loc": cls_to_idx_locs["val"],
                    "fg_bg_ratios": fg_bg_ratios[1],
                },
            ),
        ]

    def _generate_examples(self, patch_files, split, hf_indices, cls_to_idx_loc, fg_bg_ratios):
        logger.info(f"Generating examples from {len(patch_files)} patch files")
        logger.info("Opening files")
        class_to_zipfile = {}
        for f in patch_files:
            with zipfile.ZipFile(f, "r") as zf:
                for name in zf.namelist():
                    if name.endswith(".pkl") or name.endswith(".pkl.gz"):
                        class_to_zipfile[name.split("/")[-2]] = f
                        file_ending = "pkl" if name.endswith(".pkl") else "pkl.gz"
                        name_start = "/".join(name.split("/")[:-2])
        if len(name_start) > 0:
            name_start += "/"
        logger.info(f"Loading extra information: {hf_indices}, {fg_bg_ratios}")
        with open(hf_indices, "r") as f:
            path_to_in_idx = json.load(f)
        idx_to_path = {v: k for k, v in path_to_in_idx.items()}
        # print("idx_to_path", list(idx_to_path.items())[:5])
        with open(fg_bg_ratios, "r") as f:
            fg_bg_ratios = json.load(f)
        fg_bg_ratios = {"/".join(k.split("/")[-2:]).split(".")[0]: v for k, v in fg_bg_ratios.items()}
        # print("fg_bg_ratios", list(fg_bg_ratios.items())[:5])

        logger.info("Starting extraction with ImageNet")
        foraug_idx = 0

        manager = multiprocessing.Manager()
        num_workers = multiprocessing.cpu_count()
        if os.environ.get("MAX_WORKERS", None):
            num_workers = int(os.environ["MAX_WORKERS"])
        in_queue = manager.Queue(maxsize=4 * num_workers)
        ret_queue = manager.Queue(maxsize=4 * num_workers)
        comm_dict = manager.dict()
        comm_dict["running"] = True
        running = True
        comm_dict["n_errors"] = 0

        if num_workers > 8:
            num_workers -= 2  # leave some cores for the main process and imagenet iterator

        in_proc = multiprocessing.Process(target=_in_iterator, args=(in_queue, split))
        in_proc.start()
        zip_procs = [
            multiprocessing.Process(
                target=_zip_loader,
                args=(
                    in_queue,
                    ret_queue,
                    comm_dict,
                    patch_files,
                    class_to_zipfile,
                    name_start,
                    file_ending,
                    idx_to_path,
                    fg_bg_ratios,
                ),
            )
            for _ in range(num_workers)
        ]
        for proc in zip_procs:
            proc.start()

        last_errors = 0
        cls_to_idx = {}
        while running:
            if not ret_queue.empty():
                data = ret_queue.get()
                in_cls = data["path"].split("/")[0]
                if in_cls not in cls_to_idx:
                    cls_to_idx[in_cls] = []
                cls_to_idx[in_cls].append((foraug_idx, data["fg/bg_area"]))
                if foraug_idx == 0:
                    data["bg_rat_idx_file"] = cls_to_idx_loc
                yield foraug_idx, data
                foraug_idx += 1
            else:
                if in_queue.empty() and not in_proc.is_alive():
                    comm_dict["running"] = False
                    running = False
                    tqdm.write("Finished imagenet iteration; waiting for zip loaders to finish")

            if foraug_idx % 10_000 == 0:
                errors = comm_dict["n_errors"]
                if errors > last_errors:
                    last_errors = errors
                    tqdm.write(
                        f"@step {foraug_idx}: errors {errors}; error rate {errors / foraug_idx:.2%} (expected {6_610 / 1_274_227:.2%})"
                    )

        in_proc.join()
        for proc in zip_procs:
            proc.join()

        # tqdm.write("Finished all processes")
        while not ret_queue.empty():
            data = ret_queue.get()
            in_cls = data["path"].split("/")[0]
            if in_cls not in cls_to_idx:
                cls_to_idx[in_cls] = []
            cls_to_idx[in_cls].append(foraug_idx)
            yield foraug_idx, data
            foraug_idx += 1
        tqdm.write("Done")
        with open(cls_to_idx_loc, "w") as f:
            json.dump(cls_to_idx, f)

    def _as_streaming_dataset_single(self, *args, **kwargs):
        raise NotImplementedError("ForNet does not support streaming datasets")

    def _as_dataset(self, split=datasets.Split.TRAIN, in_memory=False):
        """Constructs a `Dataset`.

        This is the internal implementation to overwrite called when user calls
        `as_dataset`. It should read the pre-processed datasets files and generate
        the `Dataset` object.

        Args:
            split (`datasets.Split`):
                which subset of the data to read.
            in_memory (`bool`, defaults to `False`):
                Whether to copy the data in-memory.

        Returns:
            `Dataset`
        """
        cache_dir = self._fs._strip_protocol(self._output_dir)
        dataset_name = self.dataset_name
        if self._check_legacy_cache():
            dataset_name = self.name
        dataset_kwargs = ArrowReader(cache_dir, self.info).read(
            name=dataset_name,
            instructions=split,
            split_infos=self.info.splits.values(),
            in_memory=in_memory,
        )

        fingerprint = self._get_dataset_fingerprint(split)
        # print("config", self.config)
        # print("rel data dir", self._relative_data_dir())
        # print("split", str(split))
        # print("fingerprint", fingerprint)

        splitname = str(split)
        if splitname == "validation":
            splitname = "val"

        return RecombineDataset(
            fingerprint=fingerprint,
            background_combination=self.config.background_combination,
            fg_scale_jitter=self.config.fg_scale_jitter,
            pruning_ratio=self.config.pruning_ratio,
            fg_size_mode=self.config.fg_size_mode,
            fg_bates_n=self.config.fg_bates_n,
            mask_smoothing_sigma=self.config.mask_smoothing_sigma,
            rel_jut_out=self.config.rel_jut_out,
            orig_img_prob=self.config.orig_img_prob,
            **dataset_kwargs,
        )

    def _create_builder_config(self, config_name=None, custom_features=None, **config_kwargs):
        config_hash_kwargs = {k: v for k, v in config_kwargs.items() if k not in _CONFIG_HASH_IGNORE_KWARGS}
        builder_config, config_id = super()._create_builder_config(config_name, custom_features, **config_hash_kwargs)
        for k in _CONFIG_HASH_IGNORE_KWARGS:
            if k in config_kwargs:
                setattr(builder_config, k, config_kwargs[k])
        return builder_config, config_id


def _in_iterator(in_queue, split):
    if split == "val":
        split = "validation"
    imagenet = datasets.load_dataset("ILSVRC/imagenet-1k", split=split)
    for idx, ex in enumerate(imagenet):
        in_queue.put((idx, ex["image"]))


def _zip_loader(
    in_queue,
    ret_queue,
    comm_dict,
    patch_files,
    class_to_zipfile,
    name_start,
    file_ending,
    idx_to_path,
    fg_bg_ratios,
):
    while comm_dict["running"]:
        if not in_queue.empty():
            try:
                in_idx, in_img = in_queue.get(block=False)
            except queue.Empty:
                continue
            patch_name = idx_to_path[in_idx]
            in_class, in_file_name = patch_name.split("/")

            try:
                with zipfile.ZipFile(class_to_zipfile[in_class], "r") as zf, (
                    zf.open(f"{name_start}{patch_name}.{file_ending}", "r")
                    if file_ending == "pkl"
                    else gzip.GzipFile(
                        fileobj=zf.open(f"{name_start}{patch_name}.{file_ending}", "r"),
                        mode="r",
                    )
                ) as pklf:
                    patch_data = pickle.load(pklf)
            except KeyError:
                comm_dict["n_errors"] += 1
                continue

            in_img = in_img.convert("RGB")

            if "bg_diff" in patch_data:
                if in_img.size != (
                    patch_data["bg_diff"].shape[1],
                    patch_data["bg_diff"].shape[0],
                ):
                    in_img = in_img.resize((patch_data["bg_diff"].shape[1], patch_data["bg_diff"].shape[0]))
            else:
                max_size = max(in_img.size)
                if max_size > 512:
                    goal_size = (
                        round(in_img.size[0] * 512 / max_size),
                        round(in_img.size[1] * 512 / max_size),
                    )
                    in_img = in_img.resize(goal_size)

            in_arr = np.array(in_img)

            if "bg_diff" in patch_data:
                bg_diff = patch_data["bg_diff"]
                bg_img = in_arr.astype(np.int64) + bg_diff
                bg_img = bg_img.clip(0, 255).astype(np.uint8)
                bg_img = Image.fromarray(bg_img)
                bg_img = image_to_bytes(bg_img)
            else:
                bg_img = None

            if "fg_mask" in patch_data:
                x_offs, y_offs = patch_data["fg_off"]
                fg_mask = patch_data["fg_mask"]

                fg_crop = in_arr[
                    y_offs : y_offs + fg_mask.shape[0],
                    x_offs : x_offs + fg_mask.shape[1],
                ]
                fg_img = np.concatenate([fg_crop, fg_mask * 255], axis=-1).clip(0, 255).astype(np.uint8)
                fg_img = Image.fromarray(fg_img)
                fg_img = image_to_bytes(fg_img)
            else:
                fg_img = None

            in_img = image_to_bytes(in_img)

            ret_queue.put(
                {
                    "path": patch_name,
                    "bg": bg_img,
                    "fg": fg_img,
                    "label": IMAGENET2012_CLASSES[in_class],
                    "in": in_img,
                    "fg/bg_area": fg_bg_ratios[patch_name],
                }
            )