Sampler
BucketBatchSampler
Bases: Sampler[List[int]]
A batch sampler to create batches with sizes of elements from each pre-defined bucket ranges.
Elements of the dataset are first grouped into each bucket based on the bucket ranges and the sizes of elements. Then, a base batch sampler is used for each bucket to create mini-batches.
The bucket ranges are specified by bucket_boundaries
, which will be first sorted internally and used to create
len(bucket_boundaries) - 1
left-closed right-open intervals.
e.g. if bucket_boundaries tensor is [10, 5, 0, 16], it will be sorted as [0, 5, 10, 16] and 3 buckets will be created
with ranges: [0, 5), [5, 10), [10, 16).
The base batch sampler will be created by passing the element indices in each bucket as the data source, and
base_batch_sampler_shared_kwargs
and base_batch_sampler_individual_kwargs
to the constructor of the base batch sampler class specified as base_batch_sampler_class
.
e.g. base_batch_sampler_shared_kwargs = {'drop_last': True}
and base_batch_sampler_individual_kwargs = {'batch_size': [8,10,12]}
will be used to create 3 batch samplers with drop_last=True and batch_size=8, 10 and 12, and initialized like
base_batch_sampler_class(bucket_element_indices[0], batch_size=8, drop_last=True)
.
In the __iter__
method, if shuffle
is True
, the element indices in each bucket will be shuffled, and a bucket
is randomly selected each time to create a mini-batch. If shuffle
is False
, there is no shuffle on element indices,
and the bucket is selected in ascending order of its interval boundaries.
This class is used to create homogeneous batches of data for training or evaluation, and reduce the padding necessary to align the shape of elements.
Modified from https://github.com/rssrwn/semla-flow/blob/main/semlaflow/data/util.py
Examples:
>>> import torch
>>> from bionemo.size_aware_batching.sampler import BucketBatchSampler
>>> # Define the sizes for a dataset
>>> sizes = torch.arange(25)
>>> # Define bucket ranges
>>> bucket_boundaries = torch.tensor([0, 6, 15, 25])
>>> # Create a bucket batch sampler with torch.utils.data.BatchSampler as base batch sampler
>>> # As there are 3 buckets, there will be 3 base batch samplers with batch sizes 2, 3, and 5.
>>> batch_sampler = BucketBatchSampler(
sizes=sizes,
bucket_boundaries=bucket_boundaries,
base_batch_sampler_class=torch.utils.data.BatchSampler,
base_batch_sampler_shared_kwargs={'drop_last': False},
base_batch_sampler_individual_kwargs={'batch_size': [2,3,5]},
shuffle=False,
)
>>> # Iterate over batches of indices that lies in the same bucket and with different batch sizes.
>>> print(list(batch_sampler))
[[0, 1], [2, 3], [4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]
>>> # randomize the dataset and buckets
>>> batch_sampler = BucketBatchSampler(
sizes=sizes,
bucket_boundaries=bucket_boundaries,
base_batch_sampler_class=torch.utils.data.BatchSampler,
base_batch_sampler_shared_kwargs={'drop_last': False},
base_batch_sampler_individual_kwargs={'batch_size': [2,3,5]},
shuffle=True,
generator=torch.Generator().manual_seed(0),
)
>>> print(list(batch_sampler))
[[24, 17, 16, 22, 19], [2, 5], [12, 10, 11], [3, 0], [15, 18, 20, 21, 23], [7, 13, 6], [14, 9, 8], [1, 4]]
>>> print(list(batch_sampler))
[[14, 9, 13], [23, 16, 20, 21, 15], [5, 0], [8, 10, 11], [17, 24, 22, 18, 19], [12, 6, 7], [4, 2], [3, 1]]
>>> # Combine with SizeAwareBatchSampler to control the cost of each batch
>>> from bionemo.size_aware_batching.sampler import SizeAwareBatchSampler
>>> item_costs = sizes.tolist()
>>> def cost_of_element(index):
return item_costs[index]
>>> batch_sampler = BucketBatchSampler(
sizes=sizes,
bucket_boundaries=bucket_boundaries,
base_batch_sampler_class=SizeAwareBatchSampler,
base_batch_sampler_shared_kwargs={"sizeof": cost_of_element, "max_total_size": 40},
base_batch_sampler_individual_kwargs={},
shuffle=True,
generator=torch.Generator().manual_seed(0),
)
>>> print(list(iter(batch_sampler)))
[[24], [2, 5, 3, 0, 1, 4], [12, 10, 11, 7], [13, 6, 14], [17, 16], [22], [19, 15], [9, 8], [18, 20], [21], [23]]
Source code in bionemo/size_aware_batching/sampler.py
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 |
|
__init__(sizes, bucket_boundaries, base_batch_sampler_class, base_batch_sampler_shared_kwargs=None, base_batch_sampler_individual_kwargs=None, shuffle=True, generator=None)
Initializes the BucketBatchSampler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sizes
|
Tensor
|
A 1D tensor of real numbers representing the size of each element in the dataset. |
required |
bucket_boundaries
|
Tensor
|
A 1D tensor of real numbers representing the boundaries of the bucket ranges.
It will be first sorted and used to create |
required |
base_batch_sampler_class
|
Type[S]
|
Base batch sampler class type, which will be used for each bucket, and initialized with the bucket element indices,
|
required |
base_batch_sampler_shared_kwargs
|
Optional[Dict[str, Any]]
|
Shared keyword argument dictionary used to initialize all base batch samplers for all buckets.
Sufficient and valid arguments should be provided for |
None
|
base_batch_sampler_individual_kwargs
|
Optional[Dict[str, Iterable]]
|
Keyword argument dictionary used to initialize
each bucket batch sampler with the corresponding key value pairs.
Length of each value in this dict must be equal to len(bucket_boundaries) - 1 (the number of buckets).
Sufficient and valid arguments should be provided for |
None
|
shuffle
|
Optional[bool]
|
A boolean indicating whether to shuffle the dataset and buckets. Defaults to True. |
True
|
generator
|
Optional[Generator]
|
Generator used in sampling. Defaults to None. |
None
|
Raises:
Type | Description |
---|---|
ValueError
|
If |
ValueError
|
If |
ValueError
|
If |
ValueError
|
If the length of values in the dict of |
RuntimeError
|
If there is no elements with sizes inside the ranges specified by |
Source code in bionemo/size_aware_batching/sampler.py
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 |
|
__iter__()
Iterate over batches of indices.
This function yields batches of indices of elements with sizes from each bucket range.
Yields:
Type | Description |
---|---|
List[int]
|
List[int]: A batch of indices of elements with sizes from each bucket range. |
Source code in bionemo/size_aware_batching/sampler.py
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 |
|
__len__()
Get the number of batches.
Can only be called if the base_batch_sampler_class
has len() implemented
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of batches |
Source code in bionemo/size_aware_batching/sampler.py
544 545 546 547 548 549 550 551 552 553 |
|
SizeAwareBatchSampler
Bases: Sampler[List[int]]
Varriying-size batching data sampler class that ensures batch size doesn't exceed maximum.
A sampler that batches elements of varying sizes while ensuring that the total size of each batch does not exceed a specified maximum.
This is useful when dealing with datasets where each element has a
different size, such as graphs or sequences of varying lengths.
The sampler uses a provided sizeof
function to determine the size
of each element in the dataset and ensures that the total size of
each batch does not exceed the specified max_total_size
.
Examples:
>>> import torch
>>> from bionemo.size_aware_batching.sampler import SizeAwareBatchSampler
>>> # Define a sample dataset with torch.tensor
>>> dataset = [torch.tensor([1, 2]), torch.tensor([3, 4]), torch.tensor([5, 6]),
... torch.tensor([7, 8]), torch.tensor([9, 10])]
>>> # Define a function that returns the size of each element in the dataset.
>>> def sizeof(index):
... return dataset[index].numel()
>>> # Create a SizeAwareBatchSampler with a maximum total batch size of 10.
>>> batch_sampler = SizeAwareBatchSampler(
... sampler=torch.utils.data.SequentialSampler(dataset),
... sizeof=sizeof,
... max_total_size=4
... )
>>> # Iterate over batches of indices that do not exceed the maximum total size.
>>> print(list(batch_sampler))
[[0, 1], [2, 3], [4]]
Source code in bionemo/size_aware_batching/sampler.py
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 |
|
__init__(sampler, sizeof, max_total_size, info_logger=None, warn_logger=None)
Initializes the SizeAwareBatchSampler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sampler
|
Union[Sampler[List[int]], Iterable[int]]
|
The underlying sampler. |
required |
sizeof
|
Callable[[int], Real]
|
A function that returns the size at each index. E.g., this can used to
determine how much memory an element consumes. Its return type must be
comparable with |
required |
max_total_size
|
Real
|
The maximum total size of a mini-batch. The semantics of "size"
is defined by the |
required |
info_logger
|
Optional[Callable[[str], None]]
|
A function to log info. Defaults to None. |
None
|
warn_logger
|
Optional[Callable[[str], None]]
|
A function to log warnings. Defaults None. |
None
|
Raises:
Type | Description |
---|---|
TypeError
|
If sampler is not an instance of Sampler or Iterable, or if sizeof is not a callable, dictionary, or sequence container. |
ValueError
|
If max_total_size is not a positive number. |
Source code in bionemo/size_aware_batching/sampler.py
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 |
|
__iter__()
Iterate over batches of indices.
This function yields batches of indices that do not exceed the maximum total size.
Yields:
Type | Description |
---|---|
List[int]
|
A batch of indices that do not exceed the maximum total size. |
Source code in bionemo/size_aware_batching/sampler.py
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
|
size_aware_batching(dataset, sizeof, max_total_size, collate_fn=None, info_logger=None, warn_logger=None)
Creates a batching iterator where each batch size varries (within a max limit) according to memory consumption.
A generator that batches elements from an iterable while ensuring that the total size of each batch does not exceed a specified maximum. Here the size can be a measurement of memory consumption of the elements in the batch. This can be useful for both indexible data or non-indexible but iterable data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset
|
Iterable[Data]
|
The input iterable. |
required |
sizeof
|
Callable[[Data], Real]
|
A function or mapping that returns the "size" of each element in |
required |
max_total_size
|
Real
|
The maximum total "size" of each batch. The semantics of "size"
is defined by the |
required |
collate_fn
|
Optional[Callable[[Iterable[Data]], BatchCollated]]
|
An optional function to collate batches. Defaults to None, in which case each batch is a list of elements from the input dataset |
None
|
info_logger
|
Optional[Callable[[str], None]]
|
A function to log info. Defaults to None. |
None
|
warn_logger
|
Optional[Callable[[str], None]]
|
A function to log warnings. Defaults to None. |
None
|
Yields:
Type | Description |
---|---|
Union[List[Data], BatchCollated]
|
A generator that yields batches from |
Assumptions
1. Linear complexity. This function consumes the given Iterable of data (dataset
) once,
by going over the data item one by one to build a batch and yield it as soon as the
addition of the next data item to the batch would exceed max_total_size
or if the
batch is the last one (end of iteration)
2. Additive size measurement. For the general usage case of building mini-batches with
a threshold of the batch's memory consumption, it assumes that the size of the batch is
the sum of all elements in the batch (additive property).
3. Comparable type of max_total_size
and sizeof
's return. sizeof
's return values
must be compared with max_total_size
to threshold the size of batches
Caveat 1: The generated batch sizes may have large variance - how to workaround: filter the output of this generator using a batch size threshold 2: The number of batches may vary a lot across different epochs. - how to workaround: increase the number of steps that compose an epoch, e.g., in the Lightning training/validation loop, which effectively increases the input dataset size per epoch
Example:
>>> import torch
>>> from torch.utils.data import default_collate
>>> from bionemo.size_aware_batching.sampler import size_aware_batching
>>> # Define a sample dataset with torch.tensor
>>> dataset = [torch.tensor([1, 2]), torch.tensor([3, 4]), torch.tensor([5, 6]),
... torch.tensor([7, 8]), torch.tensor([9, 10])]
>>> # Define a sizeof function that returns the size of each tensor
>>> def sizeof(x):
... return x.numel()
>>> # Create a generator with max_total_size=4 and default_collate_fn
>>> gen = size_aware_batching(dataset, sizeof, 4, collate_fn=default_collate)
>>> batches = list(gen)
>>> print(batches)
[tensor([[1, 2], [3, 4]]), tensor([[5, 6], [7, 8]]), tensor([[9, 10]])]
Source code in bionemo/size_aware_batching/sampler.py
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 |
|