elasticity.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. """
  2. Copyright 2020 The Microsoft DeepSpeed Team
  3. """
  4. import os
  5. import re
  6. import json
  7. import numpy as np
  8. from packaging import version as pkg_version
  9. from .config import ElasticityConfig, ElasticityConfigError, ElasticityError, \
  10. ElasticityIncompatibleWorldSize
  11. from .constants import ELASTICITY, ENABLED, ENABLED_DEFAULT, LATEST_ELASTICITY_VERSION, \
  12. MINIMUM_DEEPSPEED_VERSION, IGNORE_NON_ELASTIC_BATCH_INFO, \
  13. IGNORE_NON_ELASTIC_BATCH_INFO_DEFAULT, DEEPSPEED_ELASTICITY_CONFIG
  14. from ..git_version_info import version as __version__
  15. from ..utils import logger
  16. # Thirty eight smallest highly composite numbers. The list should
  17. # be enough to support up to 720K batch size.
  18. HCN_LIST = [
  19. 1,
  20. 2,
  21. 4,
  22. 6,
  23. 12,
  24. 24,
  25. 36,
  26. 48,
  27. 60,
  28. 120,
  29. 180,
  30. 240,
  31. 360,
  32. 720,
  33. 840,
  34. 1260,
  35. 1680,
  36. 2520,
  37. 5040,
  38. 7560,
  39. 10080,
  40. 15120,
  41. 20160,
  42. 25200,
  43. 27720,
  44. 45360,
  45. 50400,
  46. 55440,
  47. 83160,
  48. 110880,
  49. 166320,
  50. 221760,
  51. 277200,
  52. 332640,
  53. 498960,
  54. 554400,
  55. 665280,
  56. 720720
  57. ]
  58. def get_candidate_batch_sizes(base_list, max_acceptable_batch_size):
  59. candidate_batch_size = []
  60. #brute force is fine here. We are working with very small lists
  61. for base in base_list:
  62. batch_size = base
  63. for hcn in HCN_LIST:
  64. new_batch_size = base * hcn
  65. if new_batch_size > max_acceptable_batch_size:
  66. break
  67. batch_size = new_batch_size
  68. candidate_batch_size.append(batch_size)
  69. return list(set(candidate_batch_size))
  70. def get_valid_gpus(batch_size, micro_batches, min_valid_gpus, max_valid_gpus):
  71. valid_gpus = []
  72. for micro_batch in micro_batches:
  73. if batch_size % micro_batch == 0:
  74. max_gpus = batch_size // micro_batch
  75. if max_gpus >= min_valid_gpus and max_gpus <= max_valid_gpus:
  76. valid_gpus.append(max_gpus)
  77. for i in range(1, max_gpus // 2 + 1):
  78. if max_gpus % i == 0:
  79. if i >= min_valid_gpus and i <= max_valid_gpus:
  80. valid_gpus.append(i)
  81. valid_gpus = set(valid_gpus)
  82. valid_gpus = sorted(list(valid_gpus))
  83. return valid_gpus
  84. def get_best_candidates(candidate_batch_sizes,
  85. micro_batches,
  86. min_gpus,
  87. max_gpus,
  88. prefer_larger):
  89. max_valid_gpus = 0
  90. valid_gpus = None
  91. final_batch_size = int(min(micro_batches))
  92. for batch_size in candidate_batch_sizes:
  93. current_valid_gpus = get_valid_gpus(batch_size,
  94. micro_batches,
  95. min_gpus,
  96. max_gpus)
  97. if (len(current_valid_gpus) > max_valid_gpus
  98. or (len(current_valid_gpus) == max_valid_gpus and
  99. ((prefer_larger and batch_size > final_batch_size) or
  100. (not prefer_larger and batch_size < final_batch_size)))):
  101. max_valid_gpus = len(current_valid_gpus)
  102. valid_gpus = current_valid_gpus
  103. final_batch_size = batch_size
  104. return final_batch_size, valid_gpus
  105. def _get_compatible_gpus_v01(micro_batches,
  106. max_acceptable_batch_size,
  107. min_gpus=None,
  108. max_gpus=None,
  109. prefer_larger=True):
  110. '''We use two heuristics to compute the batch size
  111. 1. We use the Lowest Common Multiple of the micro-batches
  112. as the base batch size and scale it by a HCN such that the result is
  113. the largest batch size less than the max_acceptable batch size
  114. 2. We use each of the micro batches as a base and scale it
  115. by a HCN such that the result is the largest batch size less than the
  116. max_acceptable batch size.
  117. We then use brute force to count the number of compatible GPU count for
  118. each of the aforementioned cases, and return the batch size with the most number of
  119. compatible GPU counts in the min-max GPU range if provided, other wise
  120. we return the batch size with the most number of total compatible GPU counts.
  121. Returns:
  122. final_batch_size
  123. valid_gpus
  124. '''
  125. if min_gpus is None:
  126. min_gpus = int(1)
  127. if max_gpus is None:
  128. max_gpus = int(max_acceptable_batch_size / min(micro_batches))
  129. assert all(mb <= max_acceptable_batch_size for mb in micro_batches ), \
  130. f"All micro batches must be less than \
  131. or equal to max_acceptable_batch_size: {max_acceptable_batch_size}"
  132. lcm = np.lcm.reduce(micro_batches)
  133. base_list = []
  134. base_list.extend(micro_batches)
  135. base_list.append(lcm)
  136. candidate_batch_sizes = get_candidate_batch_sizes(base_list,
  137. max_acceptable_batch_size)
  138. final_batch_size, valid_gpus = get_best_candidates(
  139. candidate_batch_sizes,
  140. micro_batches,
  141. min_gpus,
  142. max_gpus,
  143. prefer_larger)
  144. return final_batch_size, valid_gpus
  145. def _compatible_ds_version_check(target_deepspeed_version: str):
  146. min_version = pkg_version.parse(MINIMUM_DEEPSPEED_VERSION)
  147. target_version = pkg_version.parse(target_deepspeed_version)
  148. err_str = f"Target deepspeed version of {target_deepspeed_version} is not compatible " \
  149. f"with minimum version {MINIMUM_DEEPSPEED_VERSION} supporting elasticity."
  150. if target_version < min_version:
  151. raise ElasticityError(err_str)
  152. return True
  153. def elasticity_enabled(ds_config: dict):
  154. if ELASTICITY not in ds_config:
  155. return False
  156. return ds_config[ELASTICITY].get(ENABLED, ENABLED_DEFAULT)
  157. def ensure_immutable_elastic_config(runtime_elastic_config_dict: dict):
  158. """
  159. Ensure the resource scheduler saw the same elastic config we are using at runtime
  160. """
  161. if DEEPSPEED_ELASTICITY_CONFIG in os.environ:
  162. scheduler_elastic_config_dict = json.loads(
  163. os.environ[DEEPSPEED_ELASTICITY_CONFIG])
  164. scheduler_elastic_config = ElasticityConfig(scheduler_elastic_config_dict)
  165. runtime_elastic_config = ElasticityConfig(runtime_elastic_config_dict)
  166. err_str = "Elastic config '{}={}' seen by resource scheduler does not match config passed to runtime {}={}"
  167. if runtime_elastic_config.max_acceptable_batch_size != scheduler_elastic_config.max_acceptable_batch_size:
  168. raise ElasticityConfigError(
  169. err_str.format('max_acceptable_batch_size',
  170. scheduler_elastic_config.max_acceptable_batch_size,
  171. 'max_acceptable_batch_size',
  172. runtime_elastic_config.max_acceptable_batch_size))
  173. if runtime_elastic_config.micro_batches != scheduler_elastic_config.micro_batches:
  174. raise ElasticityConfigError(
  175. err_str.format('micro_batches',
  176. scheduler_elastic_config.micro_batches,
  177. 'micro_batches',
  178. runtime_elastic_config.micro_batches))
  179. if runtime_elastic_config.version != scheduler_elastic_config.version:
  180. raise ElasticityConfigError(
  181. err_str.format('version',
  182. scheduler_elastic_config.version,
  183. 'version',
  184. runtime_elastic_config.version))
  185. else:
  186. logger.warning("Unable to find DEEPSPEED_ELASTICITY_CONFIG environment variable, cannot " \
  187. "guarantee resource scheduler will scale this job using compatible GPU counts.")
  188. def compute_elastic_config(ds_config: dict, target_deepspeed_version: str, world_size=0):
  189. """Core deepspeed elasticity API. Given an elastic config (similar to the example below)
  190. DeepSpeed will compute a total train batch size corresponding valid GPU count list that
  191. provides a high level of elasticity. Elasticity in this case means we are safe to scale
  192. the training job up/down across the GPU count list *without* any negative impacts on
  193. training convergence. This is achievable primarily due to DeepSpeed's gradient accumulation
  194. feature which allows us to decompose a global training batch size into:
  195. micro-batch-size * gradient-accumulation-steps * world-size.
  196. "elasticity": {
  197. "enabled": true,
  198. "max_train_batch_size": 2000,
  199. "micro_batch_sizes": [2,4,6],
  200. "min_gpus": 1,
  201. "max_gpus" : 10000
  202. "min_time": 20
  203. "version": 0.1
  204. }
  205. Intended to be called both by scheduling infrastructure and deepspeed runtime.
  206. For the same `ds_config` we should return deterministic results.
  207. Args:
  208. ds_config (dict): DeepSpeed config dictionary/json
  209. target_deepspeed_version (str): When called from scheduling
  210. infrastructure we want to ensure that the target deepspeed version is
  211. compatible with the elasticity version used in the backend.
  212. world_size (int, optional): Intended/current world size, will do some sanity
  213. checks to ensure world size is actually valid with the config.
  214. Raises:
  215. ElasticityConfigError: Missing required elasticity config or elasticity disabled
  216. ElasticityError: If target deepspeed version is not compatible with current version
  217. Returns:
  218. final_batch_size (int): total batch size used for training
  219. valid_gpus (list(int)): list of valid GPU counts with this config
  220. micro_batch_size (int, optional): if world_size is provided will return
  221. specific micro batch size
  222. """
  223. if not isinstance(ds_config, dict):
  224. raise ValueError("Expected ds_config to be a dictionary but received " \
  225. f"a {type(ds_config)}, containing: {ds_config}")
  226. if ELASTICITY not in ds_config:
  227. raise ElasticityConfigError(f"'{ELASTICITY}' is missing from config json," \
  228. " please add it if running an elastic training job.")
  229. elastic_config_dict = ds_config[ELASTICITY]
  230. if not elastic_config_dict.get(ENABLED, ENABLED_DEFAULT):
  231. raise ElasticityConfigError("Elasticity is disabled, please enable it " \
  232. "('enabled':true) if running an elastic training job.")
  233. elastic_config = ElasticityConfig(elastic_config_dict)
  234. if float(elastic_config.version) > LATEST_ELASTICITY_VERSION:
  235. raise ElasticityConfigError("Attempting to run elasticity version " \
  236. f"{elastic_config.version} but runtime only supports up " \
  237. f"to {LATEST_ELASTICITY_VERSION}")
  238. # Ensure target deepspeed version works with intended elasticity version
  239. if not _compatible_ds_version_check(target_deepspeed_version):
  240. raise ElasticityError("Unable to run elasticity on target deepspeed version of" \
  241. f" {target_deepspeed_version}, currently {__version__}")
  242. if float(elastic_config.version) == 0.1:
  243. final_batch_size, valid_gpus = _get_compatible_gpus_v01(
  244. micro_batches=elastic_config.micro_batches,
  245. max_acceptable_batch_size=elastic_config.max_acceptable_batch_size,
  246. min_gpus=elastic_config.min_gpus,
  247. max_gpus=elastic_config.max_gpus,
  248. prefer_larger=elastic_config.prefer_larger_batch_size)
  249. # ensure batch size is int dtype
  250. final_batch_size = int(final_batch_size)
  251. else:
  252. raise NotImplementedError(
  253. f"Unable to find elastic logic for version: {elastic_config.version}")
  254. if world_size > 0:
  255. if world_size not in valid_gpus:
  256. raise ElasticityIncompatibleWorldSize(f"World size ({world_size}) is not valid " \
  257. f"with the current list of valid GPU counts: {valid_gpus}")
  258. # Pick largest valid micro batch size
  259. micro_batch_size = None
  260. for mbsz in sorted(list(set(elastic_config.micro_batches)), reverse=True):
  261. if final_batch_size // world_size % mbsz == 0:
  262. micro_batch_size = mbsz
  263. break
  264. assert micro_batch_size is not None, "Unable to find divisible micro batch size" \
  265. f" world_size={world_size}, final_batch_size={final_batch_size}, and " \
  266. f" micro_batches={elastic_config.micro_batches}."
  267. return final_batch_size, valid_gpus, micro_batch_size
  268. return final_batch_size, valid_gpus