utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. import re
  2. import collections.abc
  3. import os
  4. import json
  5. from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU
  6. import hjson
  7. import sys
  8. import itertools
  9. import copy
  10. from ..utils import logger
  11. def search_error(filename):
  12. if not os.path.exists(filename):
  13. return "stderr.log does not exist"
  14. with open(filename) as f:
  15. for line in f:
  16. for s in ["Error", "error", "ERROR"]:
  17. idx = line.find(s)
  18. if idx != -1:
  19. return line[idx + len(s):].lstrip(": ")
  20. return None
  21. def was_interruptted(filename):
  22. if not os.path.exists(filename):
  23. return "stderr.log does not exist"
  24. with open(filename) as f:
  25. for line in f:
  26. s = "KeyboardInterrupt"
  27. idx = line.find(s)
  28. if idx != -1:
  29. return True
  30. return False
  31. def was_interruptted(filename):
  32. if not os.path.exists(filename):
  33. return "stderr.log does not exist"
  34. with open(filename) as f:
  35. for line in f:
  36. s = "KeyboardInterrupt"
  37. idx = line.find(s)
  38. if idx != -1:
  39. return True
  40. return False
  41. def find_replace_str(value, replace_dict):
  42. if not isinstance(value, str):
  43. return str(value)
  44. matches = re.findall("\$[A-Za-z0-9_]+", value)
  45. for var in matches:
  46. var_key = var.replace("$", "").lower()
  47. if var_key == "nvme_path":
  48. continue
  49. assert var_key in replace_dict, f"unknown var key: {var_key}, in {replace_dict}"
  50. if isinstance(replace_dict[var_key], str):
  51. value = value.replace(var, replace_dict[var_key])
  52. else:
  53. assert len(matches) == 1, "unable to replace multiple non-string matches"
  54. value = replace_dict[var_key]
  55. return value
  56. def find_replace(target, replace_dict):
  57. if isinstance(target, dict):
  58. for key, value in target.items():
  59. if isinstance(value, str):
  60. target[key] = find_replace_str(value, replace_dict)
  61. if isinstance(value, list):
  62. for i in range(len(value)):
  63. value[i] = find_replace_str(value[i], replace_dict)
  64. if isinstance(value, dict):
  65. find_replace(value, replace_dict)
  66. elif isinstance(target, list):
  67. for i in range(len(target)):
  68. target[i] = str(find_replace_str(target[i], replace_dict))
  69. def get_list(val):
  70. if not isinstance(val, list):
  71. return [val]
  72. else:
  73. return val
  74. def combine_dict(d, u):
  75. for k, v in u.items():
  76. if isinstance(v, collections.abc.Mapping):
  77. d[k] = combine_dict(d.get(k, {}), v)
  78. else:
  79. if k not in d:
  80. d[k] = v
  81. else:
  82. if not isinstance(d[k], list):
  83. d[k] = [d[k]]
  84. d[k].extend(i for i in get_list(v) if i not in d[k])
  85. return d
  86. def del_if_exists(t, d):
  87. if t in d:
  88. del d[t]
  89. return
  90. for k, v in d.items():
  91. if isinstance(v, collections.abc.Mapping):
  92. del_if_exists(t, v)
  93. def replace_dict(d, u, ignored_keys=[]):
  94. """Replaces values in dict d with values in dict u.
  95. Args:
  96. d (dict): the target dict to overwrite
  97. u (dict): the dict containing the values to overwrite the target dict
  98. Returns:
  99. dict d with values overwritten by the corresponding ones in dict u.
  100. """
  101. if u is not None:
  102. for k, v in u.items():
  103. if k not in ignored_keys:
  104. if v is None:
  105. del_if_exists(k, d)
  106. continue
  107. if isinstance(v, collections.abc.Mapping):
  108. d[k] = replace_dict(d.get(k, {}), v, ignored_keys)
  109. else:
  110. d[k] = v
  111. return d
  112. def get_val_by_key(d: dict, k):
  113. if k in d:
  114. return d[k]
  115. for v in d.values():
  116. if isinstance(v, dict):
  117. return get_val_by_key(v, k)
  118. return None
  119. def set_val_by_key(d: dict, k, vv):
  120. if k in d:
  121. d[k] = vv
  122. for v in d.values():
  123. if isinstance(v, dict):
  124. set_val_by_key(v, k, vv)
  125. def fetch_hostfile(hostfile_path):
  126. if not os.path.isfile(hostfile_path):
  127. logger.warning("Unable to find hostfile, will proceed with training "
  128. "with local resources only.")
  129. return None
  130. # e.g., worker-0 slots=16
  131. with open(hostfile_path, 'r') as fd:
  132. resource_pool = collections.OrderedDict()
  133. for line in fd.readlines():
  134. line = line.strip()
  135. if line == '':
  136. # skip empty lines
  137. continue
  138. try:
  139. hostname, slots = line.split()
  140. _, slot_count = slots.split("=")
  141. slot_count = int(slot_count)
  142. except ValueError as err:
  143. logger.error("Hostfile is not formatted correctly, unable to "
  144. "proceed with training.")
  145. raise err
  146. if hostname in resource_pool:
  147. logger.error("Hostfile contains duplicate hosts, unable to "
  148. "proceed with training.")
  149. raise ValueError("host {} is already defined".format(hostname))
  150. resource_pool[hostname] = slot_count
  151. return resource_pool
  152. def validate_ds_config(config: dict):
  153. def is_False(config: dict, key):
  154. if config is None:
  155. return False
  156. return bool(config.get(key))
  157. config_zero = config.get("zero_optimization", {})
  158. if not config_zero:
  159. return True
  160. stage = config_zero.get("stage")
  161. offload = False
  162. if stage == 1:
  163. return True
  164. elif stage == 2:
  165. if is_False(config_zero,
  166. "cpu_offload") and is_False(config_zero,
  167. "cpu_offload_params"):
  168. return False
  169. elif stage == 3:
  170. offload_devices = ["cpu", "nvme"]
  171. if config_zero.get("offload_optimizer", {}).get("device") in offload_devices:
  172. offload = True
  173. if config_zero.get("offload_param", {}).get("device") in offload_devices:
  174. offload = True
  175. else:
  176. return True
  177. # HF requires that "ZeRO Offload can only work with DeepSpeed optimizers"
  178. if offload and not config.get("optimizer"):
  179. return False
  180. return True
  181. def remove_dupe_dicts(l):
  182. """ Removes duplicate dictionaries from a list. Uses list comprehension and the json library to sort and stringify each dictionary and the set data type to ensure unique values. Works with nested data structures.
  183. Args:
  184. l (list): a list of (nested) data structures.
  185. Returns:
  186. A list of unique values.
  187. """
  188. list_of_strings = [json.dumps(d, sort_keys=True) for d in l]
  189. list_of_strings = set(list_of_strings)
  190. return [json.loads(s) for s in list_of_strings]
  191. def prune_config(config, ignored_keys=[]):
  192. """ Prunes the input configurations
  193. Args:
  194. configs (dict): A configuration dictionary.
  195. ignored_keys (list, optional): the keys of the sections to delete. Defaults to [].
  196. Returns:
  197. A configuration dictionary.
  198. """
  199. if ignored_keys:
  200. for k in ignored_keys:
  201. def find_del_key(d: dict, k: str):
  202. if k in d:
  203. del d[k]
  204. else:
  205. for dd in d.values():
  206. if isinstance(dd, dict):
  207. find_del_key(dd, k)
  208. find_del_key(config, k)
  209. def prune_configs(configs, ignored_keys=[]):
  210. """ Prunes the input list of configurations
  211. Args:
  212. configs (list): A list of configuration dictionaries.
  213. ignored_keys (list, optional): the keys of the sections to delete. Defaults to [].
  214. Returns:
  215. A list of valid and unique configuration dictionaries.
  216. """
  217. pruned_list = []
  218. for config in configs:
  219. prune_config(config, ignored_keys)
  220. pruned_list.append(config)
  221. return remove_dupe_dicts(pruned_list)
  222. def get_tuning_keys(tuning_space: dict):
  223. """Outputs the list of tunnable parameters in the tuning space dict.
  224. Args:
  225. tuning_space (dict): a configuration dictionary containing tunable parameters as lists of values.
  226. Returns:
  227. A list of strings
  228. """
  229. tuning_keys = []
  230. for key, val in tuning_space.items():
  231. if isinstance(val, dict):
  232. tuning_keys.extend(get_tuning_keys(val))
  233. if isinstance(val, list) and len(val) > 1:
  234. tuning_keys.append(key)
  235. return tuning_keys
  236. def get_all_configs(tuning_space: dict):
  237. """ Splits the tuning space dictionary to result in all combinations of values.
  238. Args:
  239. tuning_space (dict): the tuning space where tunable parameters are lists of values.
  240. """
  241. def gen_combinations(d: dict):
  242. keys, values = d.keys(), d.values()
  243. for v in values:
  244. if not isinstance(v, list):
  245. v = [v]
  246. values_choices = (gen_combinations(v) if isinstance(v,
  247. dict) else get_list(v)
  248. for v in values)
  249. for comb in itertools.product(*values_choices):
  250. yield dict(zip(keys, comb))
  251. all_configs = []
  252. for c in gen_combinations(tuning_space):
  253. all_configs.append(c)
  254. return all_configs
  255. def canonical_name(config: dict, tuning_keys=None, prefix="", omit_val=False):
  256. """ Generates a name from the acronyms of the tuning keys in the config dict. TRAIN_MICRO_BATCH_SIZE_PER_GPU is always included in the tuning keys.
  257. Args:
  258. config (dict): the config dict used to generate the name
  259. tuning_keys (list, optional): the tuning keys used to generate the name. Defaults to None.
  260. prefix (str, optional): a string added to the begining of the name. Defaults to None.
  261. """
  262. if TRAIN_MICRO_BATCH_SIZE_PER_GPU not in tuning_keys:
  263. tuning_keys.append(TRAIN_MICRO_BATCH_SIZE_PER_GPU)
  264. if GRADIENT_ACCUMULATION_STEPS not in tuning_keys:
  265. tuning_keys.append(GRADIENT_ACCUMULATION_STEPS)
  266. tuning_keys.sort()
  267. def get_offload_name(offload_config):
  268. cname = ""
  269. if offload_config is None:
  270. return "None_"
  271. for key, val in offload_config.items():
  272. key = "".join(map(lambda c: c[0], key.split('_')))
  273. if (isinstance(val, int) or isinstance(val, float)) and val > 9000:
  274. cname += key + '{:.1e}'.format(val) + "_"
  275. else:
  276. if isinstance(val, bool):
  277. val = "T" if val else "F"
  278. cname += f"{key}{val}_"
  279. return cname
  280. def get_name_by_keys(config: dict, tuning_keys=None, omit_val=False):
  281. cname = ""
  282. if not tuning_keys or config is None:
  283. return cname
  284. for key, val in config.items():
  285. # skip the arg_mappings section when naming the exp file
  286. if key == "arg_mappings":
  287. continue
  288. if key == "offload_param":
  289. cname += "op_"
  290. if not omit_val:
  291. cname += get_offload_name(val)
  292. continue
  293. if key == "offload_optimizer":
  294. cname += "oo_"
  295. if not omit_val:
  296. cname += get_offload_name(val)
  297. continue
  298. # recursively call the func to get name for the child dicts
  299. if isinstance(val, dict):
  300. n = get_name_by_keys(val, tuning_keys, omit_val=omit_val)
  301. if n != "":
  302. cname += n + "_"
  303. if tuning_keys and key not in tuning_keys:
  304. continue
  305. key_str = "".join(map(lambda c: c[0], key.split('_')))
  306. if not omit_val:
  307. if (isinstance(val, int) or isinstance(val, float)) and val > 9000:
  308. cname += key_str + '{:.1e}'.format(val) + "_"
  309. else:
  310. if isinstance(val, bool):
  311. val = "T" if val else "F"
  312. cname += f"{key_str}{val}_"
  313. else:
  314. cname += key_str + "_"
  315. return cname[:-1]
  316. name = get_name_by_keys(config, tuning_keys, omit_val=omit_val)
  317. return prefix + (name if name != "" else "exp")
  318. def get_first_config(config: dict):
  319. if not config:
  320. return None
  321. cfg = copy.deepcopy(config)
  322. for key, val in cfg.items():
  323. if isinstance(val, dict):
  324. cfg[key] = get_first_config(val)
  325. if isinstance(val, list) and len(val) > 0:
  326. cfg[key] = val[0]
  327. return cfg
  328. def write_experiments(exps: list, exps_dir: str):
  329. exp_paths = []
  330. for exp in exps:
  331. exp_name = exp['name']
  332. # write the expr config to a json file
  333. exp_path = os.path.join(exps_dir, f'{exp_name}.json')
  334. with open(exp_path, 'w') as fd:
  335. json.dump(exp, fd)
  336. exp_paths.append(exp_path)
  337. return exp_paths
  338. def memory_to_string(n, postfix="", units=None, precision=2):
  339. if units is None:
  340. if n // 10**12 > 0:
  341. return str(round(n / 1024**4, precision)) + " T" + postfix
  342. if n // 10**9 > 0:
  343. return str(round(n / 1024**3, precision)) + " G" + postfix
  344. elif n // 10**6 > 0:
  345. return str(round(n / 1024**2, precision)) + " M" + postfix
  346. elif n // 10**3 > 0:
  347. return str(round(n / 1014, precision)) + " K" + postfix
  348. else:
  349. return str(n) + " "
  350. else:
  351. if units == "T":
  352. return str(round(n / 1024**4, precision)) + " " + units
  353. if units == "G" + postfix:
  354. return str(round(n / 1024**3, precision)) + " " + units
  355. elif units == "M" + postfix:
  356. return str(round(n / 1024**2, precision)) + " " + units
  357. elif units == "K" + postfix:
  358. return str(round(n / 1024, precision)) + " " + units
  359. else:
  360. return str(n) + " "
  361. def number_to_string(n, postfix="", units=None, precision=2):
  362. if units is None:
  363. if n // 10**9 > 0:
  364. return str(round(n / 1000**3, precision)) + " B" + postfix
  365. if n // 10**6 > 0:
  366. return str(round(n / 1000**2, precision)) + " M" + postfix
  367. elif n // 10**3 > 0:
  368. return str(round(n / 1000**1, precision)) + " K" + postfix
  369. else:
  370. return str(n) + " "
  371. else:
  372. if units == "B" + postfix:
  373. return str(round(n / 1000**3, precision)) + " " + units
  374. elif units == "M" + postfix:
  375. return str(round(n / 1000**2, precision)) + " " + units
  376. elif units == "K" + postfix:
  377. return str(round(n / 1000**1, precision)) + " " + units
  378. else:
  379. return str(n) + " "