File size: 19,691 Bytes
f121d74 |
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 |
import ast
import functools
import io
import json
import logging
import math
import os
import random
import sys
import tarfile
from dataclasses import dataclass
from multiprocessing import Value
import braceexpand
import torch
import torchvision
import webdataset as wds
from PIL import Image
from torch.utils.data import DataLoader, IterableDataset, get_worker_info
from torch.utils.data.distributed import DistributedSampler
from webdataset.filters import _shuffle
from webdataset.tariterators import (
base_plus_ext,
tar_file_expander,
url_opener,
valid_sample,
)
Image.MAX_IMAGE_PIXELS = 1000000000
MAX_NUM_TOKENS = 256
MAX_NUM_IMAGES = 5
TINY_IMAGE_SIZE_THRESHOLD = 1
N_CHANNELS = 3
INTERLEAVED_IMAGE_SIZE = 224
try:
import horovod.torch as hvd
except ImportError:
hvd = None
class SharedEpoch:
def __init__(self, epoch: int = 0):
self.shared_epoch = Value("i", epoch)
def set_value(self, epoch):
self.shared_epoch.value = epoch
def get_value(self):
return self.shared_epoch.value
@dataclass
class DataInfo:
dataloader: DataLoader
sampler: DistributedSampler = None
shared_epoch: SharedEpoch = None
def set_epoch(self, epoch):
if self.shared_epoch is not None:
self.shared_epoch.set_value(epoch)
if self.sampler is not None and isinstance(self.sampler, DistributedSampler):
self.sampler.set_epoch(epoch)
def get_dataset_size(shards):
shards_list = list(braceexpand.braceexpand(shards))
shards_list = shards
dir_path = os.path.dirname(shards[0])
sizes_filename = os.path.join(dir_path, "sizes.json")
len_filename = os.path.join(dir_path, "__len__")
if os.path.exists(sizes_filename):
sizes = json.load(open(sizes_filename, "r"))
total_size = sum(
[
int(sizes[os.path.basename(shard)])
if os.path.basename(shard) in sizes
else 0
for shard in shards_list
]
)
elif os.path.exists(len_filename):
# FIXME this used to be eval(open(...)) but that seemed rather unsafe
total_size = ast.literal_eval(open(len_filename, "r").read())
else:
total_size = None # num samples undefined
# some common dataset sizes (at time of authors last download)
# CC3M (train): 2905954
# CC12M: 10968539
# LAION-400M: 407332084
# LAION-2B (english): 2170337258
num_shards = len(shards_list)
return total_size, num_shards
def count_samples(dataloader):
os.environ["WDS_EPOCH"] = "0"
n_elements, n_batches = 0, 0
for images, texts in dataloader:
n_batches += 1
n_elements += len(images)
assert len(images) == len(texts)
return n_elements, n_batches
def filter_no_caption_or_no_image(sample):
return ("txt" in sample) and (
"png" in sample or "jpg" in sample or "jpeg" in sample
)
def log_and_continue(exn):
"""Call in an exception handler to ignore any exception, issue a warning, and continue."""
if "No images in sample" in str(exn) or "Only one image in sample" in str(
exn
): # Avoid spamming logs with these
return True
logging.warning(f"Handling webdataset error ({repr(exn)}). Ignoring.")
return True
def group_by_keys_nothrow(
data, keys=base_plus_ext, lcase=True, suffixes=None, handler=None
):
"""Return function over iterator that groups key, value pairs into samples.
:param keys: function that splits the key into key and extension (base_plus_ext)
:param lcase: convert suffixes to lower case (Default value = True)
"""
current_sample = None
for filesample in data:
assert isinstance(filesample, dict)
fname, value = filesample["fname"], filesample["data"]
prefix, suffix = keys(fname)
if prefix is None:
continue
if lcase:
suffix = suffix.lower()
# FIXME webdataset version throws if suffix in current_sample, but we have a potential for
# this happening in the current LAION400m dataset if a tar ends with same prefix as the next
# begins, rare, but can happen since prefix aren't unique across tar files in that dataset
if (
current_sample is None
or prefix != current_sample["__key__"]
or suffix in current_sample
):
if valid_sample(current_sample):
yield current_sample
current_sample = dict(__key__=prefix, __url__=filesample["__url__"])
if suffixes is None or suffix in suffixes:
current_sample[suffix] = value
if valid_sample(current_sample):
yield current_sample
def tarfile_to_samples_nothrow(src, handler=log_and_continue):
# NOTE this is a re-impl of the webdataset impl with group_by_keys that doesn't throw
streams = url_opener(src, handler=handler)
files = tar_file_expander(streams, handler=handler)
samples = group_by_keys_nothrow(files, handler=handler)
return samples
def pytorch_worker_seed(increment=0):
"""get dataloader worker seed from pytorch"""
worker_info = get_worker_info()
if worker_info is not None:
# favour using the seed already created for pytorch dataloader workers if it exists
seed = worker_info.seed
if increment:
# space out seed increments so they can't overlap across workers in different iterations
seed += increment * max(1, worker_info.num_workers)
return seed
# fallback to wds rank based seed
return wds.utils.pytorch_worker_seed()
_SHARD_SHUFFLE_SIZE = 2000
_SHARD_SHUFFLE_INITIAL = 500
_SAMPLE_SHUFFLE_SIZE = 5000
_SAMPLE_SHUFFLE_INITIAL = 1000
class detshuffle2(wds.PipelineStage):
def __init__(
self,
bufsize=1000,
initial=100,
seed=0,
epoch=-1,
):
self.bufsize = bufsize
self.initial = initial
self.seed = seed
self.epoch = epoch
def run(self, src):
if isinstance(self.epoch, SharedEpoch):
epoch = self.epoch.get_value()
else:
# NOTE: this is epoch tracking is problematic in a multiprocess (dataloader workers or train)
# situation as different workers may wrap at different times (or not at all).
self.epoch += 1
epoch = self.epoch
rng = random.Random()
if self.seed < 0:
# If seed is negative, we use the worker's seed, this will be different across all nodes/workers
seed = pytorch_worker_seed(epoch)
else:
# This seed to be deterministic AND the same across all nodes/workers in each epoch
seed = self.seed + epoch
rng.seed(seed)
return _shuffle(src, self.bufsize, self.initial, rng)
class ResampledShards2(IterableDataset):
"""An iterable dataset yielding a list of urls."""
def __init__(
self,
urls,
nshards=sys.maxsize,
worker_seed=None,
deterministic=False,
epoch=-1,
):
"""Sample shards from the shard list with replacement.
:param urls: a list of URLs as a Python list or brace notation string
"""
super().__init__()
urls = wds.shardlists.expand_urls(urls)
self.urls = urls
assert isinstance(self.urls[0], str)
self.nshards = nshards
self.rng = random.Random()
self.worker_seed = worker_seed
self.deterministic = deterministic
self.epoch = epoch
def __iter__(self):
"""Return an iterator over the shards."""
if isinstance(self.epoch, SharedEpoch):
epoch = self.epoch.get_value()
else:
# NOTE: this is epoch tracking is problematic in a multiprocess (dataloader workers or train)
# situation as different workers may wrap at different times (or not at all).
self.epoch += 1
epoch = self.epoch
if self.deterministic:
# reset seed w/ epoch if deterministic
if self.worker_seed is None:
# pytorch worker seed should be deterministic due to being init by arg.seed + rank + worker id
seed = pytorch_worker_seed(epoch)
else:
seed = self.worker_seed() + epoch
self.rng.seed(seed)
for _ in range(self.nshards):
yield dict(url=self.rng.choice(self.urls))
def preprocess_image(sample, image_processor):
image = [image_processor(s).unsqueeze(0) for s in sample]
image = torch.cat(image, dim=0)
# apply random horizontal flip and color jitter
image = torchvision.transforms.RandomHorizontalFlip(p=0.5)(image)
image = torchvision.transforms.ColorJitter(brightness=0.5, hue=0.3)(image)
return image
def preprocess_text(sample, tokenizer):
tokenizer.padding_side = "right"
sample = [
(f"<image>{s.strip()}<|endofchunk|>{tokenizer.eos_token}") for s in sample
]
text = tokenizer(
sample,
max_length=32,
padding="longest",
truncation="only_first",
return_tensors="pt",
)
return text["input_ids"], text["attention_mask"]
MIN_KB = 10
MAX_NUM_IMAGES = 5
def preprocess_interleaved(sample, tokenizer, clip_processor, sim_threshold):
info = json.loads(sample[0])
tar_file_obj = io.BytesIO(sample[1])
image_tar = tarfile.open(fileobj=tar_file_obj)
sentences = info["text_list"]
images, image_idxs = [], []
for image_path, sim in zip(info["image_info"], info["similarity_matrix"]):
# pick one image per sentence
if info["image_info"][image_path]["matched_text_index"] in image_idxs:
continue
rawbytes = image_tar.extractfile(
os.path.join(image_tar.getnames()[0], image_path)
).read()
# filter to images >= 10KB
if len(rawbytes) // 1000 <= MIN_KB:
continue
if sim[info["image_info"][image_path]["matched_text_index"]] < sim_threshold:
continue
image = Image.open(io.BytesIO(rawbytes)).convert("RGB")
images.append(image)
image_idxs.append(info["image_info"][image_path]["matched_text_index"])
if len(images) == 0:
raise ValueError("No images in sample")
# filter out images that are exact duplicates
images_tensors = preprocess_image(images, clip_processor)
keep_ixs = range(min(len(images_tensors), MAX_NUM_IMAGES))
images_tensors = images_tensors[keep_ixs]
image_idxs = [image_idxs[ix] for ix in keep_ixs]
# pad to 5 images
if len(images_tensors) < MAX_NUM_IMAGES:
zero_padding = torch.zeros(
(MAX_NUM_IMAGES - len(images_tensors), 3, 224, 224), dtype=torch.float
)
images_tensors = torch.cat((images_tensors, zero_padding), dim=0)
# add in <image> and <eoc> tokens
# eoc after sentence = "sentence loss"
for ix in image_idxs:
sentences[ix] = f"<|endofchunk|><image>{sentences[ix]}"
text = " ".join(sentences)
text = text.replace("<|endofchunk|>", "", 1) # but remove first eoc
# whitespace cleanup
text = (
text.replace(" <|endofchunk|>", "<|endofchunk|>")
.replace("<image> ", "<image>")
.replace(" <image>", "<image>")
)
text = f"{text}<|endofchunk|>{tokenizer.eos_token}"
tokenizer.padding_side = "right"
text_tensor = tokenizer(
text, max_length=256, truncation=True, padding="max_length", return_tensors="pt"
)
# reject sequences with too few images (after truncation)
num_images = torch.count_nonzero(
text_tensor["input_ids"]
== tokenizer.additional_special_tokens_ids[
tokenizer.additional_special_tokens.index("<image>")
]
)
if num_images == 0:
raise ValueError("No images in sample")
elif (
num_images == 1 and random.random() <= 0.5
): # 50% chance of keeping single image samples
raise ValueError("Only one image in sample")
return (
images_tensors,
(text_tensor["input_ids"], text_tensor["attention_mask"]),
)
def get_mmc4_dataset(args, image_processor, tokenizer, epoch=0, floor=False):
input_shards = args.mmc4_shards
assert input_shards is not None
resampled = getattr(args, "dataset_resampled", False)
num_samples, num_shards = get_dataset_size(input_shards)
num_samples = None
if not num_samples:
num_samples = args.train_num_samples_mmc4
if not num_samples:
raise RuntimeError(
"Currently, number of dataset samples must be specified for training dataset. "
"Please specify via `--train-num-samples` if no dataset length info present."
)
# create a shared epoch store to sync epoch to dataloader worker proc
shared_epoch = SharedEpoch(epoch=epoch)
if resampled:
pipeline = [
ResampledShards2(input_shards, deterministic=True, epoch=shared_epoch)
]
else:
pipeline = [wds.SimpleShardList(input_shards)]
preprocess_fn = functools.partial(
preprocess_interleaved,
clip_processor=image_processor,
tokenizer=tokenizer,
sim_threshold=args.mmc4_textsim_threshold,
)
# at this point we have an iterator over all the shards
if not resampled:
pipeline.extend(
[
detshuffle2(
bufsize=_SHARD_SHUFFLE_SIZE,
initial=_SHARD_SHUFFLE_INITIAL,
seed=args.seed,
epoch=shared_epoch,
),
wds.split_by_node,
wds.split_by_worker,
]
)
pipeline.extend(
[
# at this point, we have an iterator over the shards assigned to each worker at each node
# wds.tarfile_to_samples(handler=log_and_continue),
tarfile_to_samples_nothrow,
wds.shuffle(
bufsize=_SAMPLE_SHUFFLE_SIZE,
initial=_SAMPLE_SHUFFLE_INITIAL,
),
]
)
pipeline.extend(
[
wds.to_tuple("json", "tar", handler=log_and_continue),
wds.map(preprocess_fn, handler=log_and_continue),
wds.batched(args.batch_size_mmc4, partial=False),
]
)
dataset = wds.DataPipeline(*pipeline)
if not resampled:
assert (
num_shards >= args.workers * args.world_size
), "number of shards must be >= total workers"
# roll over and repeat a few samples to get same number of full batches on each node
round_fn = math.floor if floor else math.ceil
global_batch_size = args.batch_size_mmc4 * args.world_size
num_batches = round_fn(num_samples / global_batch_size)
num_workers = max(1, args.workers)
num_worker_batches = round_fn(num_batches / num_workers) # per dataloader worker
num_batches = num_worker_batches * num_workers
num_samples = num_batches * global_batch_size
# each worker is iterating over this
dataset = dataset.with_epoch(num_worker_batches)
dataloader = wds.WebLoader(
dataset,
batch_size=None,
shuffle=False,
num_workers=args.workers,
persistent_workers=True,
)
# add meta-data to dataloader instance for convenience
dataloader.num_batches = num_batches
dataloader.num_samples = num_samples
return DataInfo(dataloader=dataloader, shared_epoch=shared_epoch)
def get_laion_dataset(args, image_processor, tokenizer, epoch=0, floor=False):
input_shards = args.laion_shards
assert input_shards is not None
resampled = getattr(args, "dataset_resampled", False)
num_samples, num_shards = get_dataset_size(input_shards)
num_samples = None
if not num_samples:
num_samples = args.train_num_samples_laion
if not num_samples:
raise RuntimeError(
"Currently, number of dataset samples must be specified for training dataset. "
"Please specify via `--train-num-samples` if no dataset length info present."
)
# create a shared epoch store to sync epoch to dataloader worker proc
shared_epoch = SharedEpoch(epoch=epoch)
if resampled:
pipeline = [
ResampledShards2(input_shards, deterministic=True, epoch=shared_epoch)
]
else:
pipeline = [wds.SimpleShardList(input_shards)]
# create two preprocess functions that take in the passed in image_processor and tokenizer
preprocess_image_fn = functools.partial(
preprocess_image, image_processor=image_processor
)
preprocess_text_fn = functools.partial(preprocess_text, tokenizer=tokenizer)
# at this point we have an iterator over all the shards
if not resampled:
pipeline.extend(
[
detshuffle2(
bufsize=_SHARD_SHUFFLE_SIZE,
initial=_SHARD_SHUFFLE_INITIAL,
seed=args.seed,
epoch=shared_epoch,
),
wds.split_by_node,
wds.split_by_worker,
]
)
pipeline.extend(
[
# at this point, we have an iterator over the shards assigned to each worker at each node
# wds.tarfile_to_samples(handler=log_and_continue),
tarfile_to_samples_nothrow,
wds.shuffle(
bufsize=_SAMPLE_SHUFFLE_SIZE,
initial=_SAMPLE_SHUFFLE_INITIAL,
),
]
)
pipeline.extend(
[
wds.select(filter_no_caption_or_no_image),
wds.decode("pilrgb", handler=log_and_continue),
wds.to_tuple("jpg;png;jpeg", "txt", handler=log_and_continue),
wds.batched(args.batch_size_laion, partial=False),
wds.map_tuple(
preprocess_image_fn, preprocess_text_fn, handler=log_and_continue
),
]
)
dataset = wds.DataPipeline(*pipeline)
if not resampled:
assert (
num_shards >= args.workers * args.world_size
), "number of shards must be >= total workers"
# roll over and repeat a few samples to get same number of full batches on each node
round_fn = math.floor if floor else math.ceil
global_batch_size = args.batch_size_laion * args.world_size
num_batches = round_fn(num_samples / global_batch_size)
num_workers = max(1, args.workers)
num_worker_batches = round_fn(num_batches / num_workers) # per dataloader worker
num_batches = num_worker_batches * num_workers
num_samples = num_batches * global_batch_size
# each worker is iterating over this
dataset = dataset.with_epoch(num_worker_batches)
dataloader = wds.WebLoader(
dataset,
batch_size=None,
shuffle=False,
num_workers=args.workers,
persistent_workers=True,
)
# add meta-data to dataloader instance for convenience
dataloader.num_batches = num_batches
dataloader.num_samples = num_samples
return DataInfo(dataloader=dataloader, shared_epoch=shared_epoch)
def get_dataset_fn(dataset_type):
if dataset_type == "image_text":
return get_laion_dataset
elif dataset_type == "mmc4":
return get_mmc4_dataset
else:
raise ValueError(f"Unsupported dataset type: {dataset_type}")
def get_data(args, image_processor, tokenizer, dataset_type, epoch=0):
return get_dataset_fn(dataset_type)(
args, image_processor=image_processor, epoch=epoch, tokenizer=tokenizer
)
|