llama_finetuning.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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, Union
  6. import fire
  7. import torch
  8. import transformers
  9. from datasets import load_dataset
  10. import os.path as osp
  11. from tqdm import tqdm
  12. # Unused imports removed
  13. from utils import fsdp_auto_wrap_policy
  14. from transformers import (
  15. LlamaForCausalLM,
  16. LlamaTokenizer,
  17. AutoModelForCausalLM,
  18. AutoModelForSeq2SeqLM,
  19. AutoTokenizer,
  20. default_data_collator,
  21. BitsAndBytesConfig
  22. )
  23. import torch.distributed as dist
  24. from optimum.bettertransformer import BetterTransformer
  25. # Unused imports removed
  26. from utils.train_utils import (
  27. set_tokenizer_params,
  28. train,
  29. evaluation,
  30. freeze_transformer_layers,
  31. check_frozen_layers_peft_model,
  32. setup,
  33. setup_environ_flags,
  34. cleanup,
  35. clear_gpu_cache,
  36. get_parameter_dtypes,
  37. print_model_size,
  38. get_policies
  39. )
  40. from utils.dataset_utils import get_preprocessed_dataset
  41. from utils.config_utils import (
  42. update_config,
  43. generate_peft_config,
  44. generate_dataset_config,
  45. )
  46. from peft import get_peft_model, TaskType, prepare_model_for_int8_training
  47. import configs
  48. from torch.distributed.fsdp import (
  49. FullyShardedDataParallel as FSDP,
  50. MixedPrecision,
  51. )
  52. from torch.utils.data import DistributedSampler
  53. import policies
  54. from policies import AnyPrecisionAdamW
  55. from configs import fsdp_config, train_config
  56. import torch.optim as optim
  57. from torch.optim.lr_scheduler import StepLR
  58. from pkg_resources import packaging
  59. import torch
  60. import torch.cuda.nccl as nccl
  61. import torch.distributed as dist
  62. from transformers.models.llama.modeling_llama import LlamaDecoderLayer
  63. def main(**kwargs):
  64. # Update the configuration for the training and sharding process
  65. update_config((train_config, fsdp_config), **kwargs)
  66. # Set the seeds for reproducibility
  67. torch.cuda.manual_seed(train_config.seed)
  68. torch.manual_seed(train_config.seed)
  69. if train_config.enable_fsdp:
  70. setup()
  71. # torchrun specific
  72. local_rank = int(os.environ["LOCAL_RANK"])
  73. rank = int(os.environ["RANK"])
  74. world_size = int(os.environ["WORLD_SIZE"])
  75. if torch.distributed.is_initialized():
  76. torch.cuda.set_device(rank)
  77. setup_environ_flags(rank)
  78. # Calculate gradient accumulation steps
  79. gradient_accumulation_steps = train_config.batch_size_training // train_config.micro_batch_size
  80. # Load the pre-trained model and setup its configuration
  81. model = LlamaForCausalLM.from_pretrained(
  82. train_config.model_name,
  83. load_in_8bit=True if train_config.quantization else None,
  84. device_map="auto" if train_config.quantization else None,
  85. )
  86. if train_config.enable_fsdp and train_config.use_fast_kernels:
  87. """
  88. For FSDP and FSDP+PEFT, setting 'use_fast_kernels' will enable
  89. using of Flash Attention or Xformer memory-efficient kernels
  90. based on the hardware being used. This would speed up fine-tuning.
  91. """
  92. try:
  93. from optimum.bettertransformer import BetterTransformer
  94. except ImportError:
  95. print("Module 'optimum' not found. Please install 'optimum' it before proceeding.")
  96. model = BetterTransformer.transform(model)
  97. print_model_size(model, train_config, rank if train_config.enable_fsdp else 0)
  98. # Prepare the model for int8 training if quantization is enabled
  99. if train_config.quantization:
  100. model = prepare_model_for_int8_training(model)
  101. # Convert the model to bfloat16 if fsdp and pure_bf16 is enabled
  102. if train_config.enable_fsdp and fsdp_config.pure_bf16:
  103. model.to(torch.bfloat16)
  104. # Load the tokenizer and add special tokens
  105. tokenizer = LlamaTokenizer.from_pretrained(train_config.model_name)
  106. tokenizer.add_special_tokens(
  107. {
  108. "pad_token": "<PAD>",
  109. }
  110. )
  111. if train_config.use_peft:
  112. peft_config = generate_peft_config(train_config, kwargs)
  113. model = get_peft_model(model, peft_config)
  114. model.print_trainable_parameters()
  115. #setting up FSDP if enable_fsdp is enabled
  116. if train_config.enable_fsdp:
  117. if not train_config.use_peft and train_config.freeze_layers:
  118. freeze_transformer_layers(train_config.num_freeze_layers)
  119. mixed_precision_policy, wrapping_policy = get_policies(fsdp_config, rank)
  120. my_auto_wrapping_policy = fsdp_auto_wrap_policy(model, LlamaDecoderLayer)
  121. model = FSDP(
  122. model,
  123. auto_wrap_policy= my_auto_wrapping_policy if train_config.use_peft else wrapping_policy,
  124. mixed_precision=mixed_precision_policy if not fsdp_config.pure_bf16 else None,
  125. sharding_strategy=fsdp_config.sharding_strategy,
  126. device_id=torch.cuda.current_device(),
  127. limit_all_gathers=True,
  128. )
  129. if fsdp_config.fsdp_activation_checkpointing:
  130. policies.apply_fsdp_checkpointing(model)
  131. elif not train_config.quantization and not train_config.enable_fsdp:
  132. model.to("cuda")
  133. dataset_config = generate_dataset_config(train_config, kwargs)
  134. # Load and preprocess the dataset for training and validation
  135. dataset_train = get_preprocessed_dataset(
  136. tokenizer,
  137. dataset_config,
  138. split="train",
  139. )
  140. if not train_config.enable_fsdp or rank == 0:
  141. print(f"--> Training Set Length = {len(dataset_train)}")
  142. dataset_val = get_preprocessed_dataset(
  143. tokenizer,
  144. dataset_config,
  145. split="test",
  146. )
  147. if not train_config.enable_fsdp or rank == 0:
  148. print(f"--> Validation Set Length = {len(dataset_val)}")
  149. train_sampler = None
  150. val_sampler = None
  151. if train_config.enable_fsdp:
  152. train_sampler = DistributedSampler(
  153. dataset_train,
  154. rank=dist.get_rank(),
  155. num_replicas=dist.get_world_size(),
  156. shuffle=True,
  157. )
  158. if train_config.run_validation:
  159. val_sampler = DistributedSampler(
  160. dataset_val,
  161. rank=dist.get_rank(),
  162. num_replicas=dist.get_world_size(),
  163. )
  164. # Create DataLoaders for the training and validation dataset
  165. train_dataloader = torch.utils.data.DataLoader(
  166. dataset_train,
  167. batch_size=train_config.batch_size_training,
  168. num_workers=train_config.num_workers_dataloader,
  169. pin_memory=True,
  170. sampler=train_sampler if train_sampler else None,
  171. drop_last=True,
  172. collate_fn=default_data_collator,
  173. )
  174. if train_config.run_validation:
  175. eval_dataloader = torch.utils.data.DataLoader(
  176. dataset_val,
  177. batch_size=train_config.val_batch_size,
  178. num_workers=train_config.num_workers_dataloader,
  179. pin_memory=True,
  180. sampler=val_sampler if val_sampler else None,
  181. drop_last=True,
  182. collate_fn=default_data_collator,
  183. )
  184. # Initialize the optimizer and learning rate scheduler
  185. if fsdp_config.pure_bf16 and fsdp_config.optimizer == "anyprecision":
  186. optimizer = AnyPrecisionAdamW(
  187. model.parameters(),
  188. lr=train_config.lr,
  189. momentum_dtype=torch.bfloat16,
  190. variance_dtype=torch.bfloat16,
  191. use_kahan_summation=False,
  192. )
  193. else:
  194. optimizer = optim.AdamW(
  195. model.parameters(),
  196. lr=train_config.lr,
  197. weight_decay=0.0,
  198. )
  199. scheduler = StepLR(optimizer, step_size=1, gamma=train_config.gamma)
  200. # Start the training process
  201. results = train(
  202. model,
  203. train_dataloader,
  204. eval_dataloader,
  205. tokenizer,
  206. optimizer,
  207. scheduler,
  208. gradient_accumulation_steps,
  209. train_config,
  210. fsdp_config if train_config.enable_fsdp else None,
  211. local_rank if train_config.enable_fsdp else None,
  212. rank if train_config.enable_fsdp else None,
  213. )
  214. if not train_config.enable_fsdp or rank==0:
  215. [print(f'Key: {k}, Value: {v}') for k, v in results.items()]
  216. if __name__ == "__main__":
  217. fire.Fire(main)