train_utils.py 19 KB

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