train_utils.py 15 KB

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