test_length_based_batch_sampler.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
  3. import random
  4. import pytest
  5. import torch
  6. from llama_recipes.data.sampler import LengthBasedBatchSampler
  7. SAMPLES = 33
  8. @pytest.fixture
  9. def dataset():
  10. dataset = []
  11. def add_samples(ds, n, a, b):
  12. for _ in range(n):
  13. ds.append(random.randint(a,b) * [1,])
  14. add_samples(dataset, SAMPLES // 2, 1,9)
  15. add_samples(dataset, (SAMPLES // 2) + (SAMPLES % 2), 10,20)
  16. return random.sample(dataset, len(dataset))
  17. @pytest.mark.parametrize("batch_size, drop_last", [(2, False), (8, False), (2, True), (8, True)])
  18. def test_batch_sampler_array(dataset, batch_size, drop_last):
  19. sampler = LengthBasedBatchSampler(dataset, batch_size, drop_last)
  20. EXPECTED_LENGTH = SAMPLES // batch_size if drop_last else (SAMPLES // batch_size) + (SAMPLES % batch_size)
  21. assert len(sampler) == EXPECTED_LENGTH
  22. is_long = [len(d)>=10 for d in dataset]
  23. def check_batch(batch):
  24. return all(batch) or not any(batch)
  25. assert all(check_batch(is_long[i] for i in b) for b in sampler)
  26. @pytest.mark.parametrize("batch_size, drop_last", [(2, False), (8, False), (2, True), (8, True)])
  27. def test_batch_sampler_dict(dataset, batch_size, drop_last):
  28. dist_dataset = [{"input_ids": d, "attention_mask": d} for d in dataset]
  29. sampler = LengthBasedBatchSampler(dist_dataset, batch_size, drop_last)
  30. EXPECTED_LENGTH = SAMPLES // batch_size if drop_last else (SAMPLES // batch_size) + (SAMPLES % batch_size)
  31. assert len(sampler) == EXPECTED_LENGTH
  32. is_long = [len(d)>=10 for d in dataset]
  33. def check_batch(batch):
  34. return all(batch) or not any(batch)
  35. assert all(check_batch(is_long[i] for i in b) for b in sampler)