train_utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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 os
  4. import time
  5. import yaml
  6. from contextlib import nullcontext
  7. from pathlib import Path
  8. from pkg_resources import packaging
  9. import torch
  10. import torch.cuda.nccl as nccl
  11. import torch.distributed as dist
  12. from torch.distributed.fsdp import StateDictType
  13. from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler
  14. from tqdm import tqdm
  15. from transformers import LlamaTokenizer
  16. from llama_recipes.model_checkpointing import save_model_checkpoint, save_model_and_optimizer_sharded, save_optimizer_checkpoint
  17. from llama_recipes.policies import fpSixteen,bfSixteen_mixed, get_llama_wrapper
  18. from llama_recipes.utils.memory_utils import MemoryTrace
  19. def set_tokenizer_params(tokenizer: LlamaTokenizer):
  20. tokenizer.pad_token_id = 0
  21. tokenizer.padding_side = "left"
  22. # Converting Bytes to Megabytes
  23. def byte2mb(x):
  24. return int(x / 2**20)
  25. def train(model, train_dataloader,eval_dataloader, tokenizer, optimizer, lr_scheduler, gradient_accumulation_steps, train_config, fsdp_config=None, local_rank=None, rank=None):
  26. """
  27. Trains the model on the given dataloader
  28. Args:
  29. model: The model to be trained
  30. train_dataloader: The dataloader containing the training data
  31. optimizer: The optimizer used for training
  32. lr_scheduler: The learning rate scheduler
  33. gradient_accumulation_steps: The number of steps to accumulate gradients before performing a backward/update operation
  34. num_epochs: The number of epochs to train for
  35. local_rank: The rank of the current node in a distributed setting
  36. train_config: The training configuration
  37. eval_dataloader: The dataloader containing the eval data
  38. tokenizer: tokenizer used in the eval for decoding the predicitons
  39. Returns: results dictionary containing average training and validation perplexity and loss
  40. """
  41. # Create a gradient scaler for fp16
  42. if train_config.use_fp16 and train_config.enable_fsdp:
  43. scaler = ShardedGradScaler()
  44. elif train_config.use_fp16 and not train_config.enable_fsdp:
  45. scaler = torch.cuda.amp.GradScaler()
  46. if train_config.enable_fsdp:
  47. world_size = int(os.environ["WORLD_SIZE"])
  48. autocast = torch.cuda.amp.autocast if train_config.use_fp16 else nullcontext
  49. train_prep = []
  50. train_loss = []
  51. val_prep = []
  52. val_loss =[]
  53. epoch_times = []
  54. checkpoint_times = []
  55. results = {}
  56. best_val_loss = float("inf")
  57. for epoch in range(train_config.num_epochs):
  58. epoch_start_time = time.perf_counter()
  59. with MemoryTrace() as memtrace: # track the memory usage
  60. model.train()
  61. total_loss = 0.0
  62. total_length = len(train_dataloader)//gradient_accumulation_steps
  63. pbar = tqdm(colour="blue", desc=f"Training Epoch: {epoch+1}", total=total_length, dynamic_ncols=True)
  64. for step, batch in enumerate(train_dataloader):
  65. for key in batch.keys():
  66. if train_config.enable_fsdp:
  67. batch[key] = batch[key].to(local_rank)
  68. else:
  69. batch[key] = batch[key].to('cuda:0')
  70. with autocast():
  71. loss = model(**batch).loss
  72. loss = loss / gradient_accumulation_steps
  73. total_loss += loss.detach().float()
  74. if train_config.use_fp16:
  75. # if fp16 is enabled, use gradient scaler to handle gradient update
  76. scaler.scale(loss).backward()
  77. if (step + 1) % gradient_accumulation_steps == 0 or step == len(train_dataloader) - 1:
  78. scaler.step(optimizer)
  79. scaler.update()
  80. optimizer.zero_grad()
  81. pbar.update(1)
  82. else:
  83. # regular backpropagation when fp16 is not used
  84. loss.backward()
  85. if (step + 1) % gradient_accumulation_steps == 0 or step == len(train_dataloader) - 1:
  86. optimizer.step()
  87. optimizer.zero_grad()
  88. pbar.update(1)
  89. pbar.set_description(f"Training Epoch: {epoch+1}/{train_config.num_epochs}, step {step}/{len(train_dataloader)} completed (loss: {loss.detach().float()})")
  90. pbar.close()
  91. epoch_end_time = time.perf_counter()-epoch_start_time
  92. epoch_times.append(epoch_end_time)
  93. # Reducing total_loss across all devices if there's more than one CUDA device
  94. if torch.cuda.device_count() > 1 and train_config.enable_fsdp:
  95. dist.all_reduce(total_loss, op=dist.ReduceOp.SUM)
  96. train_epoch_loss = total_loss / len(train_dataloader)
  97. if train_config.enable_fsdp:
  98. train_epoch_loss = train_epoch_loss/world_size
  99. train_perplexity = torch.exp(train_epoch_loss)
  100. train_prep.append(train_perplexity)
  101. train_loss.append(train_epoch_loss)
  102. if train_config.enable_fsdp:
  103. if rank==0:
  104. print(f"Max CUDA memory allocated was {memtrace.peak} GB")
  105. print(f"Max CUDA memory reserved was {memtrace.max_reserved} GB")
  106. print(f"Peak active CUDA memory was {memtrace.peak_active_gb} GB")
  107. print(f"Cuda Malloc retires : {memtrace.cuda_malloc_retires}")
  108. print(f"CPU Total Peak Memory consumed during the train (max): {memtrace.cpu_peaked + memtrace.cpu_begin} GB")
  109. else:
  110. print(f"Max CUDA memory allocated was {memtrace.peak} GB")
  111. print(f"Max CUDA memory reserved was {memtrace.max_reserved} GB")
  112. print(f"Peak active CUDA memory was {memtrace.peak_active_gb} GB")
  113. print(f"Cuda Malloc retires : {memtrace.cuda_malloc_retires}")
  114. print(f"CPU Total Peak Memory consumed during the train (max): {memtrace.cpu_peaked + memtrace.cpu_begin} GB")
  115. # Update the learning rate as needed
  116. lr_scheduler.step()
  117. if train_config.run_validation:
  118. eval_ppl, eval_epoch_loss = evaluation(model, train_config, eval_dataloader, local_rank, tokenizer)
  119. checkpoint_start_time = time.perf_counter()
  120. if train_config.save_model and eval_epoch_loss < best_val_loss:
  121. if train_config.enable_fsdp:
  122. dist.barrier()
  123. if train_config.use_peft:
  124. if train_config.enable_fsdp:
  125. if rank==0:
  126. print(f"we are about to save the PEFT modules")
  127. else:
  128. print(f"we are about to save the PEFT modules")
  129. model.save_pretrained(train_config.output_dir)
  130. if train_config.enable_fsdp:
  131. if rank==0:
  132. print(f"PEFT modules are saved in {train_config.output_dir} directory")
  133. else:
  134. print(f"PEFT modules are saved in {train_config.output_dir} directory")
  135. else:
  136. if not train_config.use_peft and fsdp_config.checkpoint_type == StateDictType.FULL_STATE_DICT:
  137. save_model_checkpoint(
  138. model, optimizer, rank, train_config, epoch=epoch
  139. )
  140. elif not train_config.use_peft and fsdp_config.checkpoint_type == StateDictType.SHARDED_STATE_DICT:
  141. print(" Saving the FSDP model checkpoints using SHARDED_STATE_DICT")
  142. print("=====================================================")
  143. save_model_and_optimizer_sharded(model, rank, train_config)
  144. if train_config.save_optimizer:
  145. save_model_and_optimizer_sharded(model, rank, train_config, optim=optimizer)
  146. print(" Saving the FSDP model checkpoints and optimizer using SHARDED_STATE_DICT")
  147. print("=====================================================")
  148. if not train_config.use_peft and train_config.save_optimizer:
  149. save_optimizer_checkpoint(
  150. model, optimizer, rank, train_config, epoch=epoch
  151. )
  152. print(" Saving the FSDP model checkpoints and optimizer using FULL_STATE_DICT")
  153. print("=====================================================")
  154. if train_config.enable_fsdp:
  155. dist.barrier()
  156. checkpoint_end_time = time.perf_counter() - checkpoint_start_time
  157. checkpoint_times.append(checkpoint_end_time)
  158. if eval_epoch_loss < best_val_loss:
  159. best_val_loss = eval_epoch_loss
  160. if train_config.enable_fsdp:
  161. if rank==0:
  162. print(f"best eval loss on epoch {epoch+1} is {best_val_loss}")
  163. else:
  164. print(f"best eval loss on epoch {epoch+1} is {best_val_loss}")
  165. val_loss.append(best_val_loss)
  166. val_prep.append(eval_ppl)
  167. if train_config.enable_fsdp:
  168. if rank==0:
  169. print(f"Epoch {epoch+1}: train_perplexity={train_perplexity:.4f}, train_epoch_loss={train_epoch_loss:.4f}, epoch time {epoch_end_time}s")
  170. else:
  171. print(f"Epoch {epoch+1}: train_perplexity={train_perplexity:.4f}, train_epoch_loss={train_epoch_loss:.4f}, epoch time {epoch_end_time}s")
  172. avg_epoch_time = sum(epoch_times)/ len(epoch_times)
  173. avg_checkpoint_time = sum(checkpoint_times)/ len(checkpoint_times) if len(checkpoint_times) > 0 else 0
  174. avg_train_prep = sum(train_prep)/len(train_prep)
  175. avg_train_loss = sum(train_loss)/len(train_loss)
  176. if train_config.run_validation:
  177. avg_eval_prep = sum(val_prep)/len(val_prep)
  178. avg_eval_loss = sum(val_loss)/len(val_loss)
  179. results['avg_train_prep'] = avg_train_prep
  180. results['avg_train_loss'] = avg_train_loss
  181. if train_config.run_validation:
  182. results['avg_eval_prep'] = avg_eval_prep
  183. results['avg_eval_loss'] = avg_eval_loss
  184. results["avg_epoch_time"] = avg_epoch_time
  185. results["avg_checkpoint_time"] = avg_checkpoint_time
  186. #saving the training params including fsdp setting for reference.
  187. if train_config.enable_fsdp and not train_config.use_peft:
  188. save_train_params(train_config, fsdp_config, rank)
  189. return results
  190. def evaluation(model,train_config, eval_dataloader, local_rank, tokenizer):
  191. """
  192. Evaluates the model on the given dataloader
  193. Args:
  194. model: The model to evaluate
  195. eval_dataloader: The dataloader containing the evaluation data
  196. local_rank: The rank of the current node in a distributed setting
  197. tokenizer: The tokenizer used to decode predictions
  198. Returns: eval_ppl, eval_epoch_loss
  199. """
  200. if train_config.enable_fsdp:
  201. world_size = int(os.environ["WORLD_SIZE"])
  202. model.eval()
  203. eval_preds = []
  204. eval_loss = 0.0 # Initialize evaluation loss
  205. with MemoryTrace() as memtrace:
  206. for step, batch in enumerate(tqdm(eval_dataloader,colour="green", desc="evaluating Epoch", dynamic_ncols=True)):
  207. for key in batch.keys():
  208. if train_config.enable_fsdp:
  209. batch[key] = batch[key].to(local_rank)
  210. else:
  211. batch[key] = batch[key].to('cuda:0')
  212. # Ensure no gradients are computed for this scope to save memory
  213. with torch.no_grad():
  214. # Forward pass and compute loss
  215. outputs = model(**batch)
  216. loss = outputs.loss
  217. eval_loss += loss.detach().float()
  218. # Decode predictions and add to evaluation predictions list
  219. preds = torch.argmax(outputs.logits, -1)
  220. eval_preds.extend(
  221. tokenizer.batch_decode(preds.detach().cpu().numpy(), skip_special_tokens=True)
  222. )
  223. # If there's more than one CUDA device, reduce evaluation loss across all devices
  224. if torch.cuda.device_count() > 1 and train_config.enable_fsdp:
  225. dist.all_reduce(eval_loss, op=dist.ReduceOp.SUM)
  226. # Compute average loss and perplexity
  227. eval_epoch_loss = eval_loss / len(eval_dataloader)
  228. if train_config.enable_fsdp:
  229. eval_epoch_loss = eval_epoch_loss/world_size
  230. eval_ppl = torch.exp(eval_epoch_loss)
  231. # Print evaluation metrics
  232. if train_config.enable_fsdp:
  233. if local_rank==0:
  234. print(f" {eval_ppl=} {eval_epoch_loss=}")
  235. else:
  236. print(f" {eval_ppl=} {eval_epoch_loss=}")
  237. return eval_ppl, eval_epoch_loss
  238. def freeze_transformer_layers(model, num_layer):
  239. for i, layer in enumerate(model.model.layers):
  240. if i < num_layer:
  241. for param in layer.parameters():
  242. param.requires_grad = False
  243. def check_frozen_layers_peft_model(model):
  244. for i, layer in enumerate(model.base_model.model.model.layers):
  245. for name, param in layer.named_parameters():
  246. print(f"Layer {i}, parameter {name}: requires_grad = {param.requires_grad}")
  247. def setup():
  248. """Initialize the process group for distributed training"""
  249. dist.init_process_group("nccl")
  250. def setup_environ_flags(rank):
  251. """Set environment flags for debugging purposes"""
  252. os.environ["TORCH_SHOW_CPP_STACKTRACES"] = str(1)
  253. os.environ["NCCL_ASYNC_ERROR_HANDLING"] = str(1)
  254. # os.environ["TORCH_DISTRIBUTED_DEBUG"] = "DETAIL"
  255. # This flag will help with CUDA memory fragmentations that can lead into OOM in some cases.
  256. # Note this is only availble in PyTorch Nighlies (as of July 30 2023)
  257. # os.environ['PYTORCH_CUDA_ALLOC_CONF']='expandable_segments:True'
  258. if rank == 0:
  259. print(f"--> Running with torch dist debug set to detail")
  260. def cleanup():
  261. """Clean up the process group after training"""
  262. dist.destroy_process_group()
  263. def clear_gpu_cache(rank=None):
  264. """Clear the GPU cache for all ranks"""
  265. if rank == 0:
  266. print(f"Clearing GPU cache for all ranks")
  267. torch.cuda.empty_cache()
  268. def get_parameter_dtypes(model):
  269. """Get the data types of model parameters"""
  270. parameter_dtypes = {}
  271. for name, parameter in model.named_parameters():
  272. parameter_dtypes[name] = parameter.dtype
  273. return parameter_dtypes
  274. def print_model_size(model, config, rank: int = 0) -> None:
  275. """
  276. Print model name, the number of trainable parameters and initialization time.
  277. Args:
  278. model: The PyTorch model.
  279. model_name (str): Name of the model.
  280. init_time_start (float): Initialization start time.
  281. init_time_end (float): Initialization end time.
  282. rank (int, optional): Current process's rank. Defaults to 0.
  283. """
  284. if rank == 0:
  285. print(f"--> Model {config.model_name}")
  286. total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
  287. print(f"\n--> {config.model_name} has {total_params / 1e6} Million params\n")
  288. def get_policies(cfg, rank):
  289. """Get the policies for mixed precision and fsdp wrapping"""
  290. verify_bfloat_support = (
  291. torch.version.cuda
  292. and torch.cuda.is_bf16_supported()
  293. and packaging.version.parse(torch.version.cuda).release >= (11, 0)
  294. and dist.is_nccl_available()
  295. and nccl.version() >= (2, 10)
  296. )
  297. mixed_precision_policy = None
  298. wrapping_policy = None
  299. # Mixed precision
  300. if cfg.mixed_precision:
  301. bf16_ready = verify_bfloat_support
  302. if bf16_ready and not cfg.use_fp16:
  303. mixed_precision_policy = bfSixteen_mixed
  304. if rank == 0:
  305. print(f"bFloat16 enabled for mixed precision - using bfSixteen policy")
  306. elif cfg.use_fp16:
  307. mixed_precision_policy = fpSixteen
  308. if rank == 0:
  309. print(f"FP16 enabled")
  310. else:
  311. print(f"bFloat16 support not present. Using FP32, and not mixed precision")
  312. wrapping_policy = get_llama_wrapper()
  313. return mixed_precision_policy, wrapping_policy
  314. def save_train_params(train_config, fsdp_config, rank):
  315. """
  316. This function saves the train_config and FSDP config into a train_params.yaml.
  317. This will be used by converter script in the inference folder to fetch the HF model name or path.
  318. It also would be hepful as a log for future references.
  319. """
  320. # Convert the train_config and fsdp_config objects to dictionaries,
  321. # converting all values to strings to ensure they can be serialized into a YAML file
  322. train_config_dict = {k: str(v) for k, v in vars(train_config).items() if not k.startswith('__')}
  323. fsdp_config_dict = {k: str(v) for k, v in vars(fsdp_config).items() if not k.startswith('__')}
  324. # Merge the two dictionaries into one
  325. train_params_dict = {**train_config_dict, **fsdp_config_dict}
  326. # Construct the folder name (follwoing FSDP checkpointing style) using properties of the train_config object
  327. folder_name = (
  328. train_config.dist_checkpoint_root_folder
  329. + "/"
  330. + train_config.dist_checkpoint_folder
  331. + "-"
  332. + train_config.model_name
  333. )
  334. save_dir = Path.cwd() / folder_name
  335. # If the directory does not exist, create it
  336. if not os.path.exists(save_dir):
  337. os.makedirs(save_dir)
  338. # Convert the dictionary to a YAML string
  339. config_yaml = yaml.dump(train_params_dict, indent=4)
  340. file_name = os.path.join(save_dir,'train_params.yaml')
  341. # Check if there's a directory with the same name as the file
  342. if os.path.isdir(file_name):
  343. print(f"Error: {file_name} is a directory, not a file.")
  344. else:
  345. # Write the YAML string to the file
  346. with open(file_name, 'w') as f:
  347. f.write(config_yaml)
  348. if rank==0:
  349. print(f"training params are saved in {file_name}")