blendable_dataset.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # coding=utf-8
  2. # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Blendable dataset."""
  16. import time
  17. import numpy as np
  18. import torch
  19. from megatron import print_rank_0
  20. from megatron import mpu
  21. class BlendableDataset(torch.utils.data.Dataset):
  22. def __init__(self, datasets, weights):
  23. self.datasets = datasets
  24. num_datasets = len(datasets)
  25. assert num_datasets == len(weights)
  26. self.size = 0
  27. for dataset in self.datasets:
  28. self.size += len(dataset)
  29. # Normalize weights.
  30. weights = np.array(weights, dtype=np.float64)
  31. sum_weights = np.sum(weights)
  32. assert sum_weights > 0.0
  33. weights /= sum_weights
  34. # Build indecies.
  35. start_time = time.time()
  36. assert num_datasets < 255
  37. self.dataset_index = np.zeros(self.size, dtype=np.uint8)
  38. self.dataset_sample_index = np.zeros(self.size, dtype=np.int64)
  39. from megatron.data import helpers
  40. helpers.build_blending_indices(self.dataset_index,
  41. self.dataset_sample_index,
  42. weights, num_datasets, self.size,
  43. torch.distributed.get_rank() == 0)
  44. print_rank_0('> elapsed time for building blendable dataset indices: '
  45. '{:.2f} (sec)'.format(time.time() - start_time))
  46. def __len__(self):
  47. return self.size
  48. def __getitem__(self, idx):
  49. dataset_idx = self.dataset_index[idx]
  50. sample_idx = self.dataset_sample_index[idx]
  51. return self.datasets[dataset_idx][sample_idx]