data_sampler.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. # Copyright (c) Microsoft Corporation.
  2. # SPDX-License-Identifier: Apache-2.0
  3. # DeepSpeed Team
  4. """
  5. coding=utf-8
  6. Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
  7. Licensed under the Apache License, Version 2.0 (the "License");
  8. you may not use this file except in compliance with the License.
  9. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing, software
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. Part of this code was adopted from https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/data/data_samplers.py
  17. """
  18. import torch
  19. import os
  20. import numpy as np
  21. import deepspeed.comm as dist
  22. from deepspeed.utils import logger
  23. from deepspeed.accelerator import get_accelerator
  24. from ..constants import *
  25. from ..curriculum_scheduler import CurriculumScheduler
  26. from .indexed_dataset import MMapIndexedDataset
  27. from .utils import create_mmap_dataset_builder, close_mmap_dataset_builder, find_fit_int_dtype
  28. class DeepSpeedDataSampler(object):
  29. def __init__(self,
  30. data_efficiency_config,
  31. one_epoch_total_samples,
  32. micro_batch_size,
  33. data_parallel_rank,
  34. data_parallel_size,
  35. data_parallel_group,
  36. gradient_accumulation_steps,
  37. global_rank,
  38. drop_last=True):
  39. # Keep a copy of input params for later use.
  40. self.data_efficiency_config = data_efficiency_config
  41. self.one_epoch_total_samples = one_epoch_total_samples
  42. self.index_dtype = find_fit_int_dtype(0, one_epoch_total_samples)
  43. self.total_samples = one_epoch_total_samples * self.data_efficiency_config[DATA_SAMPLING][
  44. DATA_SAMPLING_NUM_EPOCHS]
  45. self.micro_batch_size = micro_batch_size
  46. self.data_parallel_rank = data_parallel_rank
  47. self.data_parallel_group = data_parallel_group
  48. self.micro_batch_times_data_parallel_size = \
  49. self.micro_batch_size * data_parallel_size
  50. self.gradient_accumulation_steps = gradient_accumulation_steps
  51. self.global_batch_size = self.micro_batch_times_data_parallel_size * \
  52. self.gradient_accumulation_steps
  53. self.global_rank = global_rank
  54. self.drop_last = drop_last
  55. self.np_rng = np.random.default_rng(self.data_efficiency_config[DATA_EFFICIENCY_SEED])
  56. self.state = {}
  57. self.batch = []
  58. self.consumed_samples = 0
  59. if self.data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING][CURRICULUM_LEARNING_ENABLED]:
  60. self.curriculum_step = 0
  61. self.current_difficulties = {}
  62. self.data_cluster_paths = []
  63. self.data_cluster_current_position = []
  64. self.curriculum_schedulers = {}
  65. self.curriculum_index_to_sample = {}
  66. self.curriculum_index_to_metric = {}
  67. self.difficulty_type = {}
  68. self.clustering_type = {}
  69. self.data_1epoch_size = None
  70. if self.global_rank == 0:
  71. self.data_clusters = []
  72. self.data_cluster_sizes = []
  73. cluster_path = self.data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING][
  74. CURRICULUM_LEARNING_CLUSTER_PATH]
  75. if not os.path.exists(cluster_path):
  76. os.makedirs(cluster_path)
  77. for metric in self.data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING][CURRICULUM_LEARNING_METRICS]:
  78. self.curriculum_schedulers[metric] = CurriculumScheduler(
  79. data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING][CURRICULUM_LEARNING_METRICS][metric])
  80. self.difficulty_type[metric] = data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING][
  81. CURRICULUM_LEARNING_METRICS][metric][CURRICULUM_LEARNING_DIFFICULTY_TYPE]
  82. self.clustering_type[metric] = data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING][
  83. CURRICULUM_LEARNING_METRICS][metric][CURRICULUM_LEARNING_CLUSTERING_TYPE]
  84. if self.global_rank == 0:
  85. if self.clustering_type[metric] != CURRICULUM_LEARNING_SINGLE_CLUSTER:
  86. self.curriculum_index_to_sample[metric] = MMapIndexedDataset(
  87. data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING][CURRICULUM_LEARNING_METRICS]
  88. [metric][CURRICULUM_LEARNING_SAMPLE_PATH],
  89. skip_warmup=True)
  90. if self.difficulty_type[metric] == CURRICULUM_LEARNING_VALUE_BASED:
  91. self.curriculum_index_to_metric[metric] = MMapIndexedDataset(
  92. data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING][CURRICULUM_LEARNING_METRICS]
  93. [metric][CURRICULUM_LEARNING_METRIC_PATH],
  94. skip_warmup=True)
  95. # Sanity checks.
  96. assert self.total_samples > 0, \
  97. 'no sample to consume: {}'.format(self.total_samples)
  98. assert self.micro_batch_size > 0
  99. assert data_parallel_size > 0
  100. assert self.data_parallel_rank < data_parallel_size, \
  101. 'data_parallel_rank should be smaller than data size: {}, ' \
  102. '{}'.format(self.data_parallel_rank, data_parallel_size)
  103. def __len__(self):
  104. return self.total_samples
  105. def set_custom_curriculum_learning_schedule(self, schedule_func_dict):
  106. for metric in self.curriculum_schedulers:
  107. if metric in schedule_func_dict:
  108. self.curriculum_schedulers[metric].set_custom_get_difficulty(schedule_func_dict[metric])
  109. def get_start_end_idx(self):
  110. start_idx = self.data_parallel_rank * self.micro_batch_size
  111. end_idx = start_idx + self.micro_batch_size
  112. return start_idx, end_idx
  113. def get_sample_based_on_metric_value(self, metric, value_start, value_end):
  114. new_samples = None
  115. for row in range(len(self.curriculum_index_to_sample[metric])):
  116. if self.curriculum_index_to_metric[metric][row] <= value_end and self.curriculum_index_to_metric[metric][
  117. row] > value_start:
  118. row_samples = np.copy(self.curriculum_index_to_sample[metric][row])
  119. new_samples = row_samples if new_samples is None else np.concatenate(
  120. (new_samples, row_samples), axis=None)
  121. return new_samples
  122. def get_sample_based_on_metric_percentile(self, metric, percentile_start, percentile_end):
  123. new_samples = None
  124. if self.data_1epoch_size is None:
  125. self.data_1epoch_size = sum(len(x) for x in self.curriculum_index_to_sample[metric])
  126. max_percentile = self.data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING][CURRICULUM_LEARNING_METRICS][
  127. metric][CURRICULUM_LEARNING_MAX_DIFFICULTY]
  128. sample_per_percentile = self.data_1epoch_size // max_percentile
  129. start_count = sample_per_percentile * percentile_start
  130. end_count = sample_per_percentile * percentile_end
  131. if percentile_end == max_percentile:
  132. end_count = self.data_1epoch_size
  133. current_count = 0
  134. for row in range(len(self.curriculum_index_to_sample[metric])):
  135. row_size = len(self.curriculum_index_to_sample[metric][row])
  136. if current_count + row_size > start_count:
  137. row_start = max(0, start_count - current_count)
  138. if current_count + row_size <= end_count:
  139. row_end = row_size
  140. else:
  141. row_end = end_count - current_count
  142. row_samples = np.copy(self.curriculum_index_to_sample[metric][row][row_start:row_end])
  143. new_samples = row_samples if new_samples is None else np.concatenate(
  144. (new_samples, row_samples), axis=None)
  145. current_count += row_size
  146. if current_count >= end_count:
  147. break
  148. return new_samples
  149. def get_new_cluster(self, previous_difficulties):
  150. cluster_fname = CURRICULUM_LEARNING_CLUSTER_PREFIX
  151. for metric in self.curriculum_schedulers:
  152. cluster_fname = f"{cluster_fname}_{metric}{self.current_difficulties[metric]}"
  153. cluster_path = self.data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING][
  154. CURRICULUM_LEARNING_CLUSTER_PATH]
  155. cluster_path = f"{cluster_path}/{cluster_fname}"
  156. if self.global_rank == 0:
  157. new_cluster = None
  158. need_clustering = 0
  159. for metric in self.clustering_type:
  160. if self.clustering_type[metric] != CURRICULUM_LEARNING_SINGLE_CLUSTER:
  161. need_clustering += 1
  162. if need_clustering > 1:
  163. for metric in self.curriculum_schedulers:
  164. if self.clustering_type[metric] == CURRICULUM_LEARNING_SINGLE_CLUSTER:
  165. metric_cluster = np.arange(start=0,
  166. stop=self.one_epoch_total_samples,
  167. step=1,
  168. dtype=self.index_dtype)
  169. else:
  170. if self.difficulty_type[metric] == CURRICULUM_LEARNING_VALUE_BASED:
  171. metric_cluster = self.get_sample_based_on_metric_value(metric, float('-inf'),
  172. self.current_difficulties[metric])
  173. elif self.difficulty_type[metric] == CURRICULUM_LEARNING_PERCENTILE_BASED:
  174. metric_cluster = self.get_sample_based_on_metric_percentile(
  175. metric, 0, self.current_difficulties[metric])
  176. new_cluster = metric_cluster if new_cluster is None else \
  177. np.intersect1d(new_cluster, metric_cluster, assume_unique=True)
  178. for cluster in self.data_clusters:
  179. new_cluster = np.setdiff1d(new_cluster, cluster[0], assume_unique=True)
  180. else:
  181. if len(self.data_clusters) == 0:
  182. new_cluster = np.arange(start=0, stop=self.one_epoch_total_samples, step=1, dtype=self.index_dtype)
  183. for metric in self.curriculum_schedulers:
  184. if self.clustering_type[metric] != CURRICULUM_LEARNING_SINGLE_CLUSTER:
  185. if self.difficulty_type[metric] == CURRICULUM_LEARNING_VALUE_BASED:
  186. new_cluster = self.get_sample_based_on_metric_value(metric, previous_difficulties[metric],
  187. self.current_difficulties[metric])
  188. elif self.difficulty_type[metric] == CURRICULUM_LEARNING_PERCENTILE_BASED:
  189. new_cluster = self.get_sample_based_on_metric_percentile(
  190. metric, previous_difficulties[metric], self.current_difficulties[metric])
  191. if new_cluster is not None and len(new_cluster) > 0:
  192. logger.info(
  193. f"new data cluster (previous_difficulties {previous_difficulties}, current_difficulties {self.current_difficulties}) with size {len(new_cluster)} generated."
  194. )
  195. self.np_rng.shuffle(new_cluster)
  196. cluster_builder = create_mmap_dataset_builder(cluster_path, self.index_dtype)
  197. cluster_builder.add_item_numpy(new_cluster)
  198. close_mmap_dataset_builder(cluster_builder, cluster_path)
  199. self.data_clusters.append(MMapIndexedDataset(cluster_path, skip_warmup=True))
  200. self.data_cluster_sizes.append(len(self.data_clusters[-1][0]))
  201. else:
  202. logger.info(
  203. f"new data cluster (previous_difficulties {previous_difficulties}, current_difficulties {self.current_difficulties}) has no matched data thus skipped."
  204. )
  205. dist.barrier(group=self.data_parallel_group)
  206. if os.path.isfile(f"{cluster_path}.bin"):
  207. self.data_cluster_paths.append(cluster_fname)
  208. self.data_cluster_current_position.append(0)
  209. def sample_from_clusters(self):
  210. num_clusters = len(self.data_clusters)
  211. weight_sum = sum(self.data_cluster_sizes)
  212. weights = [x / weight_sum for x in self.data_cluster_sizes]
  213. samples = self.np_rng.choice(num_clusters, self.global_batch_size, replace=True, p=weights)
  214. samples = np.bincount(samples, minlength=num_clusters)
  215. return samples
  216. def reshuffle_clusters(self, cidx):
  217. cluster_fname = self.data_cluster_paths[cidx]
  218. cluster_path = self.data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING][
  219. CURRICULUM_LEARNING_CLUSTER_PATH]
  220. cluster_path = f"{cluster_path}/{cluster_fname}"
  221. cluster = np.copy(self.data_clusters[cidx][0])
  222. self.np_rng.shuffle(cluster)
  223. cluster_builder = create_mmap_dataset_builder(cluster_path, self.index_dtype)
  224. cluster_builder.add_item_numpy(cluster)
  225. close_mmap_dataset_builder(cluster_builder, cluster_path)
  226. self.data_clusters[cidx] = MMapIndexedDataset(cluster_path, skip_warmup=True)
  227. def get_sample_from_cluster(self, cidx, num_samples):
  228. start_idx = self.data_cluster_current_position[cidx]
  229. samples = list(np.copy(self.data_clusters[cidx][0][start_idx:(start_idx + num_samples)]))
  230. self.data_cluster_current_position[cidx] += num_samples
  231. if len(samples) < num_samples:
  232. num_samples_remained = num_samples - len(samples)
  233. logger.info(f"reshuffling cluster {cidx}.")
  234. self.reshuffle_clusters(cidx)
  235. samples += list(np.copy(self.data_clusters[cidx][0][:num_samples_remained]))
  236. self.data_cluster_current_position[cidx] = num_samples_remained
  237. return samples
  238. def get_next_global_batch(self):
  239. if self.data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING][CURRICULUM_LEARNING_ENABLED]:
  240. self.curriculum_step += 1
  241. new_cluster = False
  242. previous_difficulties = {}
  243. for metric in self.curriculum_schedulers:
  244. next_difficulty = self.curriculum_schedulers[metric].update_difficulty(self.curriculum_step)
  245. if metric not in self.current_difficulties or \
  246. next_difficulty != self.current_difficulties[metric]:
  247. new_cluster = True
  248. if metric in self.current_difficulties:
  249. previous_difficulties[metric] = self.current_difficulties[metric]
  250. else:
  251. if self.difficulty_type[metric] == CURRICULUM_LEARNING_VALUE_BASED:
  252. previous_difficulties[metric] = float('-inf')
  253. elif self.difficulty_type[metric] == CURRICULUM_LEARNING_PERCENTILE_BASED:
  254. previous_difficulties[metric] = 0
  255. self.current_difficulties[metric] = next_difficulty
  256. if new_cluster:
  257. self.get_new_cluster(previous_difficulties)
  258. if self.global_rank == 0:
  259. samples_per_cluster = self.sample_from_clusters()
  260. batch = []
  261. for cidx in range(len(samples_per_cluster)):
  262. batch += self.get_sample_from_cluster(cidx, samples_per_cluster[cidx])
  263. self.np_rng.shuffle(batch)
  264. batch = torch.tensor(batch, device=get_accelerator().current_device_name(), dtype=torch.long).view(-1)
  265. else:
  266. batch = torch.empty(self.global_batch_size,
  267. device=get_accelerator().current_device_name(),
  268. dtype=torch.long)
  269. dist.broadcast(batch, 0, group=self.data_parallel_group)
  270. self.batch = batch.tolist()
  271. def __iter__(self):
  272. while self.consumed_samples <= self.total_samples:
  273. if len(self.batch) == 0:
  274. self.get_next_global_batch()
  275. current_batch = self.batch[:self.micro_batch_times_data_parallel_size]
  276. self.batch = self.batch[self.micro_batch_times_data_parallel_size:]
  277. if len(current_batch) == self.micro_batch_times_data_parallel_size or \
  278. (len(current_batch) > 0 and not self.drop_last):
  279. start_idx, end_idx = self.get_start_end_idx()
  280. yield current_batch[start_idx:end_idx]
  281. self.consumed_samples += len(current_batch)
  282. current_batch = []
  283. def state_dict(self):
  284. return {
  285. CURRICULUM_LEARNING_BATCH: self.batch,
  286. CURRICULUM_LEARNING_CONSUMED_SAMPLES: self.consumed_samples,
  287. CURRICULUM_LEARNING_STEP: self.curriculum_step,
  288. CURRICULUM_LEARNING_CURRENT_DIFFICULTIES: self.current_difficulties,
  289. CURRICULUM_LEARNING_DATA_CLUSTER_PATHS: self.data_cluster_paths,
  290. CURRICULUM_LEARNING_DATA_CLUSTER_CURRENT_POSITION: self.data_cluster_current_position,
  291. CURRICULUM_LEARNING_NP_RNG_STATE: np.random.get_state()
  292. }
  293. def load_state_dict(self, state_dict):
  294. self.batch = state_dict[CURRICULUM_LEARNING_BATCH]
  295. self.consumed_samples = state_dict[CURRICULUM_LEARNING_CONSUMED_SAMPLES]
  296. self.curriculum_step = state_dict[CURRICULUM_LEARNING_STEP]
  297. self.current_difficulties = state_dict[CURRICULUM_LEARNING_CURRENT_DIFFICULTIES]
  298. self.data_cluster_paths = state_dict[CURRICULUM_LEARNING_DATA_CLUSTER_PATHS]
  299. self.data_cluster_current_position = state_dict[CURRICULUM_LEARNING_DATA_CLUSTER_CURRENT_POSITION]
  300. np.random.set_state(state_dict[CURRICULUM_LEARNING_NP_RNG_STATE])
  301. cluster_root_path = self.data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING][
  302. CURRICULUM_LEARNING_CLUSTER_PATH]
  303. # Backward compatibility: previously data_cluster_paths were stored as
  304. # absolute paths. Now we changed it to just the file name so that even
  305. # if user moved the cluster files, the checkpoint loading still works
  306. # as long as user set the correct new CURRICULUM_LEARNING_CLUSTER_PATH
  307. # in deepspeed json config.
  308. for idx in range(len(self.data_cluster_paths)):
  309. if '/' in self.data_cluster_paths[idx]:
  310. self.data_cluster_paths[idx] = self.data_cluster_paths[idx].split('/')[-1]
  311. if self.global_rank == 0:
  312. for cluster_fname in self.data_cluster_paths:
  313. cluster_path = f"{cluster_root_path}/{cluster_fname}"
  314. self.data_clusters.append(MMapIndexedDataset(cluster_path, skip_warmup=True))
  315. self.data_cluster_sizes.append(len(self.data_clusters[-1][0]))