train_utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 fire
  7. import torch
  8. import transformers
  9. from datasets import load_dataset
  10. from tqdm import tqdm
  11. """
  12. Unused imports:
  13. import torch.nn as nn
  14. import bitsandbytes as bnb
  15. """
  16. from torch.nn import functional as F
  17. from peft import (
  18. LoraConfig,
  19. get_peft_model,
  20. get_peft_model_state_dict,
  21. prepare_model_for_int8_training,
  22. set_peft_model_state_dict,
  23. )
  24. from transformers import LlamaForCausalLM, LlamaTokenizer
  25. from torch.distributed.fsdp import StateDictType
  26. import torch.distributed as dist
  27. from pkg_resources import packaging
  28. from .memory_utils import MemoryTrace
  29. import model_checkpointing
  30. import torch.cuda.nccl as nccl
  31. from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler
  32. from pathlib import Path
  33. sys.path.append(str(Path(__file__).resolve().parent.parent))
  34. from policies import bfSixteen, fpSixteen,bfSixteen_mixed, get_llama_wrapper
  35. scaler = ShardedGradScaler()
  36. def set_tokenizer_params(tokenizer: LlamaTokenizer):
  37. tokenizer.pad_token_id = 0
  38. tokenizer.padding_side = "left"
  39. # Converting Bytes to Megabytes
  40. def byte2mb(x):
  41. return int(x / 2**20)
  42. def train(model, train_dataloader,eval_dataloader, tokenizer, optimizer, lr_scheduler, gradient_accumulation_steps, train_config, fsdp_config=None, local_rank=None, rank=None):
  43. """
  44. Trains the model on the given dataloader
  45. Args:
  46. model: The model to be trained
  47. train_dataloader: The dataloader containing the training data
  48. optimizer: The optimizer used for training
  49. lr_scheduler: The learning rate scheduler
  50. gradient_accumulation_steps: The number of steps to accumulate gradients before performing a backward/update operation
  51. num_epochs: The number of epochs to train for
  52. local_rank: The rank of the current node in a distributed setting
  53. train_config: The training configuration
  54. eval_dataloader: The dataloader containing the eval data
  55. tokenizer: tokenizer used in the eval for decoding the predicitons
  56. Returns: results dictionary containing average training and validation perplexity and loss
  57. """
  58. # Create a gradient scaler for fp16
  59. scaler = torch.cuda.amp.GradScaler() if train_config.use_fp16 else None
  60. train_prep = []
  61. train_loss = []
  62. val_prep = []
  63. val_loss =[]
  64. results = {}
  65. best_val_loss = float("inf")
  66. for epoch in range(train_config.num_epochs):
  67. with MemoryTrace() as memtrace: # track the memory usage
  68. model.train()
  69. total_loss = 0.0
  70. data_set_len = 0
  71. for step, batch in enumerate(tqdm(train_dataloader,colour="blue", desc=f"Training Epoch{epoch}")):
  72. for key in batch.keys():
  73. if train_config.enable_fsdp:
  74. batch[key] = batch[key].to(local_rank)
  75. else:
  76. batch[key] = batch[key].to('cuda')
  77. outputs = model(**batch)
  78. loss = outputs.loss
  79. loss = loss / gradient_accumulation_steps
  80. total_loss += loss.detach().float()
  81. first_key = next(iter(batch))
  82. data_set_len += len(batch[first_key])
  83. if train_config.use_fp16:
  84. # if fp16 is enabled, use gradient scaler to handle gradient update
  85. scaler.scale(loss).backward()
  86. if (step + 1) % gradient_accumulation_steps == 0 or step == len(train_dataloader) - 1:
  87. scaler.step(optimizer)
  88. scaler.update()
  89. optimizer.zero_grad()
  90. else:
  91. # regular backpropagation when fp16 is not used
  92. loss.backward()
  93. if (step + 1) % gradient_accumulation_steps == 0 or step == len(train_dataloader) - 1:
  94. optimizer.step()
  95. optimizer.zero_grad()
  96. print(f"\n step {step} is completed and loss is {loss.detach().float()}")
  97. # Reducing total_loss across all devices if there's more than one CUDA device
  98. if torch.cuda.device_count() > 1 and train_config.enable_fsdp:
  99. dist.all_reduce(total_loss, op=dist.ReduceOp.SUM)
  100. train_epoch_loss = total_loss / data_set_len
  101. train_perplexity = torch.exp(train_epoch_loss)
  102. train_prep.append(train_perplexity)
  103. train_loss.append(train_epoch_loss)
  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"Cuda Malloc retires : {memtrace.cuda_malloc_retires}")
  107. print(f"CPU Total Peak Memory consumed during the train (max): {memtrace.cpu_peaked + memtrace.cpu_begin} GB")
  108. # Update the learning rate as needed
  109. lr_scheduler.step()
  110. if train_config.run_validation:
  111. eval_ppl, eval_epoch_loss = evaluation(model, train_config, eval_dataloader, rank, tokenizer)
  112. if train_config.save_model and eval_epoch_loss < best_val_loss:
  113. if train_config.use_peft:
  114. print(f"we are in the saving the PEFT modules")
  115. model.save_pretrained(train_config.output_dir)
  116. print(f"PEFT modules are saved in {train_config.output_dir} directory")
  117. else:
  118. if not train_config.use_peft and fsdp_config.checkpoint_type == StateDictType.FULL_STATE_DICT:
  119. model_checkpointing.save_model_checkpoint(
  120. model, optimizer, rank, train_config, epoch=1
  121. )
  122. elif not train_config.use_peft and fsdp_config.checkpoint_type == StateDictType.SHARDED_STATE_DICT:
  123. print(" we are about to save the models *******")
  124. model_checkpointing.save_model_and_optimizer_sharded(model, rank, train_config)
  125. if train_config.save_optimizer:
  126. model_checkpointing.save_model_and_optimizer_sharded(model, rank, train_config, optim=optimizer)
  127. if not train_config.use_peft and train_config.save_optimizer:
  128. model_checkpointing.save_optimizer_checkpoint(
  129. model, optimizer, rank, train_config, epoch=1
  130. )
  131. if local_rank == 0 and eval_epoch_loss < best_val_loss:
  132. best_val_loss = eval_epoch_loss
  133. print(f"best eval loss on epoch {epoch} is {best_val_loss}")
  134. val_loss.append(best_val_loss)
  135. val_prep.append(eval_ppl)
  136. print(f"Epoch {epoch+1}: train_perplexity={train_perplexity:.4f}, train_epoch_loss={train_epoch_loss:.4f}")
  137. lr_scheduler.step()
  138. avg_train_prep = sum(train_prep)/len(train_prep)
  139. avg_train_loss = sum(train_loss)/len(train_loss)
  140. if train_config.run_validation:
  141. avg_eval_prep = sum(val_prep)/len(val_prep)
  142. avg_eval_loss = sum(val_loss)/len(val_loss)
  143. results['avg_train_prep'] = avg_train_prep
  144. results['avg_train_loss'] = avg_train_loss
  145. if train_config.run_validation:
  146. results['avg_eval_prep'] = avg_eval_prep
  147. results['avg_eval_loss'] = avg_eval_loss
  148. return results
  149. def evaluation(model,train_config, eval_dataloader, local_rank, tokenizer):
  150. """
  151. Evaluates the model on the given dataloader
  152. Args:
  153. model: The model to evaluate
  154. eval_dataloader: The dataloader containing the evaluation data
  155. local_rank: The rank of the current node in a distributed setting
  156. tokenizer: The tokenizer used to decode predictions
  157. Returns: eval_ppl, eval_epoch_loss
  158. """
  159. model.eval()
  160. eval_preds = []
  161. eval_loss = 0.0 # Initialize evaluation loss
  162. eval_dataset_len = 0
  163. with MemoryTrace() as memtrace:
  164. for step, batch in enumerate(tqdm(eval_dataloader,colour="green", desc="evaluating Epoch")):
  165. for key in batch.keys():
  166. if train_config.enable_fsdp:
  167. batch[key] = batch[key].to(local_rank)
  168. else:
  169. batch[key] = batch[key].to('cuda')
  170. # Ensure no gradients are computed for this scope to save memory
  171. with torch.no_grad():
  172. # Forward pass and compute loss
  173. outputs = model(**batch)
  174. loss = outputs.loss
  175. eval_loss += loss.detach().float()
  176. first_key = next(iter(batch))
  177. eval_dataset_len+= len(batch[first_key])
  178. # Decode predictions and add to evaluation predictions list
  179. preds = torch.argmax(outputs.logits, -1)
  180. eval_preds.extend(
  181. tokenizer.batch_decode(preds.detach().cpu().numpy(), skip_special_tokens=True)
  182. )
  183. # If there's more than one CUDA device, reduce evaluation loss across all devices
  184. if torch.cuda.device_count() > 1 and train_config.enable_fsdp:
  185. dist.all_reduce(eval_loss, op=dist.ReduceOp.SUM)
  186. # Compute average loss and perplexity
  187. eval_epoch_loss = eval_loss / eval_dataset_len
  188. eval_ppl = torch.exp(eval_epoch_loss)
  189. # Print evaluation metrics
  190. print(f" {eval_ppl=} {eval_epoch_loss=}")
  191. return eval_ppl, eval_epoch_loss
  192. def freeze_transformer_layers(model, num_layer):
  193. for i, layer in enumerate(model.model.layers):
  194. if i < num_layer:
  195. for param in layer.parameters():
  196. param.requires_grad = False
  197. def check_frozen_layers_peft_model(model):
  198. for i, layer in enumerate(model.base_model.model.model.layers):
  199. for name, param in layer.named_parameters():
  200. print(f"Layer {i}, parameter {name}: requires_grad = {param.requires_grad}")
  201. def setup():
  202. """Initialize the process group for distributed training"""
  203. dist.init_process_group("nccl")
  204. def setup_environ_flags(rank):
  205. """Set environment flags for debugging purposes"""
  206. os.environ["TORCH_SHOW_CPP_STACKTRACES"] = str(1)
  207. os.environ["NCCL_ASYNC_ERROR_HANDLING"] = str(1)
  208. os.environ["TORCH_DISTRIBUTED_DEBUG"] = "DETAIL"
  209. if rank == 0:
  210. print(f"--> Running with torch dist debug set to detail")
  211. def cleanup():
  212. """Clean up the process group after training"""
  213. dist.destroy_process_group()
  214. def clear_gpu_cache(rank=None):
  215. """Clear the GPU cache for all ranks"""
  216. if rank == 0:
  217. print(f"Clearing GPU cache for all ranks")
  218. torch.cuda.empty_cache()
  219. def get_parameter_dtypes(model):
  220. """Get the data types of model parameters"""
  221. parameter_dtypes = {}
  222. for name, parameter in model.named_parameters():
  223. parameter_dtypes[name] = parameter.dtype
  224. return parameter_dtypes
  225. def print_model_size(model, config, rank: int = 0) -> None:
  226. """
  227. Print model name, the number of trainable parameters and initialization time.
  228. Args:
  229. model: The PyTorch model.
  230. model_name (str): Name of the model.
  231. init_time_start (float): Initialization start time.
  232. init_time_end (float): Initialization end time.
  233. rank (int, optional): Current process's rank. Defaults to 0.
  234. """
  235. if rank == 0:
  236. print(f"--> Model {config.model_name}")
  237. total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
  238. print(f"\n--> {config.model_name} has {total_params / 1e6} Million params\n")
  239. def get_policies(cfg, rank):
  240. """Get the policies for mixed precision and fsdp wrapping"""
  241. verify_bfloat_support = (
  242. torch.version.cuda
  243. and torch.cuda.is_bf16_supported()
  244. and packaging.version.parse(torch.version.cuda).release >= (11, 0)
  245. and dist.is_nccl_available()
  246. and nccl.version() >= (2, 10)
  247. )
  248. mixed_precision_policy = None
  249. wrapping_policy = None
  250. # Mixed precision
  251. if cfg.mixed_precision:
  252. bf16_ready = verify_bfloat_support
  253. if bf16_ready and not cfg.use_fp16:
  254. mixed_precision_policy = bfSixteen_mixed
  255. if rank == 0:
  256. print(f"bFloat16 enabled for mixed precision - using bfSixteen policy")
  257. elif cfg.use_fp16:
  258. mixed_precision_policy = fpSixteen
  259. if rank == 0:
  260. print(f"FP16 enabled")
  261. else:
  262. print(f"bFloat16 support not present. Using FP32, and not mixed precision")
  263. wrapping_policy = get_llama_wrapper()
  264. return mixed_precision_policy, wrapping_policy