finetuning.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 dataclasses
  4. import os
  5. import random
  6. from collections import Counter
  7. from warnings import warn
  8. import fire
  9. import numpy as np
  10. import torch
  11. import torch.optim as optim
  12. from accelerate.utils import is_xpu_available
  13. from llama_recipes.configs import (
  14. fsdp_config as FSDP_CONFIG,
  15. quantization_config as QUANTIZATION_CONFIG,
  16. train_config as TRAIN_CONFIG,
  17. )
  18. from llama_recipes.data.concatenator import ConcatDataset
  19. from llama_recipes.policies import AnyPrecisionAdamW, apply_fsdp_checkpointing
  20. from llama_recipes.utils import fsdp_auto_wrap_policy
  21. from llama_recipes.utils.config_utils import (
  22. check_fsdp_config,
  23. generate_dataset_config,
  24. generate_peft_config,
  25. get_dataloader_kwargs,
  26. update_config,
  27. )
  28. from llama_recipes.utils.dataset_utils import (
  29. get_enote_dataset
  30. )
  31. from llama_recipes.utils.fsdp_utils import hsdp_device_mesh
  32. from llama_recipes.utils.train_utils import (
  33. clear_gpu_cache,
  34. freeze_transformer_layers,
  35. get_policies,
  36. print_model_size,
  37. setup,
  38. setup_environ_flags,
  39. train,
  40. )
  41. from peft import get_peft_model, PeftModel
  42. from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, ShardingStrategy
  43. from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload
  44. from torch.optim.lr_scheduler import StepLR
  45. from transformers import (
  46. AutoConfig,
  47. AutoProcessor,
  48. AutoTokenizer,
  49. BitsAndBytesConfig,
  50. LlamaForCausalLM,
  51. MllamaForConditionalGeneration,
  52. )
  53. from transformers.models.llama.modeling_llama import LlamaDecoderLayer
  54. from transformers.models.mllama.modeling_mllama import (
  55. MllamaCrossAttentionDecoderLayer,
  56. MllamaSelfAttentionDecoderLayer,
  57. MllamaVisionEncoderLayer,
  58. )
  59. from llama_recipes.inference.model_utils import load_peft_model
  60. def setup_wandb(train_config, fsdp_config, **kwargs):
  61. try:
  62. import wandb
  63. except ImportError:
  64. raise ImportError(
  65. "You are trying to use wandb which is not currently installed. "
  66. "Please install it using pip install wandb"
  67. )
  68. from llama_recipes.configs import wandb_config as WANDB_CONFIG
  69. wandb_config = WANDB_CONFIG()
  70. update_config(wandb_config, **kwargs)
  71. init_dict = dataclasses.asdict(wandb_config)
  72. run = wandb.init(**init_dict)
  73. run.config.update(train_config)
  74. run.config.update(fsdp_config, allow_val_change=True)
  75. return run
  76. def main(**kwargs):
  77. # Update the configuration for the training and sharding process
  78. train_config, fsdp_config = TRAIN_CONFIG(), FSDP_CONFIG()
  79. update_config((train_config, fsdp_config), **kwargs)
  80. # Set the seeds for reproducibility
  81. if is_xpu_available():
  82. torch.xpu.manual_seed(train_config.seed)
  83. torch.manual_seed(train_config.seed)
  84. random.seed(train_config.seed)
  85. np.random.seed(train_config.seed)
  86. if train_config.enable_fsdp:
  87. setup()
  88. # torchrun specific
  89. local_rank = int(os.environ["LOCAL_RANK"])
  90. rank = int(os.environ["RANK"])
  91. world_size = int(os.environ["WORLD_SIZE"])
  92. if torch.distributed.is_initialized():
  93. if is_xpu_available():
  94. torch.xpu.set_device(local_rank)
  95. elif torch.cuda.is_available():
  96. torch.cuda.set_device(local_rank)
  97. clear_gpu_cache(local_rank)
  98. setup_environ_flags(rank)
  99. wandb_run = None
  100. if train_config.use_wandb:
  101. if not train_config.enable_fsdp or rank == 0:
  102. wandb_run = setup_wandb(train_config, fsdp_config, **kwargs)
  103. # setting quantization configs
  104. bnb_config = None
  105. if train_config.quantization:
  106. if type(train_config.quantization) == type(True):
  107. warn(
  108. "Quantization (--quantization) is a boolean, please specify quantization as '4bit' or '8bit'. Defaulting to '8bit' but this might change in the future.",
  109. FutureWarning,
  110. )
  111. train_config.quantization = "8bit"
  112. if train_config.quantization == "8bit" and train_config.enable_fsdp:
  113. raise ValueError(
  114. "8bit quantization is not supported with FSDP, please use 4bit quantization"
  115. )
  116. quant_config = QUANTIZATION_CONFIG()
  117. update_config(quant_config, **kwargs)
  118. bnb_config = quant_config.create_bnb_config(train_config.quantization)
  119. # Load the pre-trained model and setup its configuration
  120. use_cache = False if train_config.enable_fsdp else None
  121. config = AutoConfig.from_pretrained(train_config.model_name)
  122. if config.model_type == "mllama":
  123. is_vision = True
  124. model = MllamaForConditionalGeneration.from_pretrained(
  125. train_config.model_name,
  126. quantization_config=bnb_config,
  127. attn_implementation="sdpa" if train_config.use_fast_kernels else None,
  128. device_map=(
  129. "auto"
  130. if train_config.quantization and not train_config.enable_fsdp
  131. else None
  132. ),
  133. torch_dtype=torch.float16 if train_config.use_fp16 else torch.bfloat16,
  134. )
  135. processor = AutoProcessor.from_pretrained(
  136. train_config.model_name
  137. if train_config.tokenizer_name is None
  138. else train_config.tokenizer_name
  139. )
  140. processor.tokenizer.padding_side = "right"
  141. model.supports_gradient_checkpointing = True
  142. model.language_model.supports_gradient_checkpointing = True
  143. elif config.model_type == "llama" or "qwen2":
  144. is_vision = False
  145. model = LlamaForCausalLM.from_pretrained(
  146. train_config.model_name,
  147. quantization_config=bnb_config,
  148. use_cache=use_cache,
  149. attn_implementation="sdpa" if train_config.use_fast_kernels else None,
  150. device_map=(
  151. "auto"
  152. if train_config.quantization and not train_config.enable_fsdp
  153. else None
  154. ),
  155. torch_dtype=torch.float16 if train_config.use_fp16 else torch.bfloat16,
  156. trust_remote_code=True,
  157. )
  158. if train_config.preload_peft_dir is not None:
  159. # merge peft into backbone, may not 100% aligned
  160. print("Load and merge peft...")
  161. model = load_peft_model(model, train_config.preload_peft_dir)
  162. model = model.merge_and_unload()
  163. else:
  164. raise ValueError(
  165. f"Model type {config.model_type} is not supported. Please use llama or mllama model."
  166. )
  167. # Load the tokenizer and add special tokens
  168. tokenizer = AutoTokenizer.from_pretrained(
  169. train_config.model_name
  170. if train_config.tokenizer_name is None
  171. else train_config.tokenizer_name,
  172. trust_remote_code=True,
  173. )
  174. if not tokenizer.pad_token_id:
  175. tokenizer.pad_token_id = tokenizer.eos_token_id
  176. tokenizer.padding_side = 'left'
  177. model.generation_config.pad_token_id = tokenizer.pad_token_id
  178. # If there is a mismatch between tokenizer vocab size and embedding matrix,
  179. # throw a warning and then expand the embedding matrix
  180. if len(tokenizer) > model.get_input_embeddings().weight.shape[0]:
  181. print(
  182. "WARNING: Resizing the embedding matrix to match the tokenizer vocab size."
  183. )
  184. model.resize_token_embeddings(len(tokenizer))
  185. print_model_size(model, train_config, rank if train_config.enable_fsdp else 0)
  186. # Convert the model to bfloat16 if fsdp and pure_bf16 is enabled
  187. if (
  188. train_config.enable_fsdp
  189. and fsdp_config.pure_bf16
  190. and not train_config.quantization
  191. ):
  192. model.to(torch.bfloat16)
  193. if train_config.use_peft:
  194. # Load the pre-trained peft model checkpoint and setup its configuration
  195. if train_config.from_peft_checkpoint:
  196. model = PeftModel.from_pretrained(
  197. model, train_config.from_peft_checkpoint, is_trainable=True
  198. )
  199. peft_config = model.peft_config
  200. # Generate the peft config and start fine-tuning from original model
  201. else:
  202. peft_config = generate_peft_config(train_config, kwargs)
  203. model = get_peft_model(model, peft_config)
  204. if wandb_run:
  205. wandb_run.config.update(peft_config)
  206. model.print_trainable_parameters()
  207. hsdp_device_mesh_plan = None
  208. if (
  209. fsdp_config.hsdp
  210. and fsdp_config.sharding_strategy == ShardingStrategy.HYBRID_SHARD
  211. ):
  212. hsdp_device_mesh_plan = hsdp_device_mesh(
  213. replica_group_size=fsdp_config.replica_group_size,
  214. sharding_group_size=fsdp_config.sharding_group_size,
  215. )
  216. print("HSDP device mesh is ready")
  217. # setting up FSDP if enable_fsdp is enabled
  218. if train_config.enable_fsdp:
  219. check_fsdp_config(fsdp_config)
  220. if not train_config.use_peft and train_config.freeze_layers:
  221. freeze_transformer_layers(model, train_config.num_freeze_layers)
  222. mixed_precision_policy, wrapping_policy = get_policies(fsdp_config, rank)
  223. # Create the FSDP wrapper for MllamaSelfAttentionDecoderLayer,MllamaSelfAttentionDecoderLayer,MllamaVisionEncoderLayer in vision models
  224. if is_vision:
  225. my_auto_wrapping_policy = fsdp_auto_wrap_policy(
  226. model,
  227. [
  228. MllamaSelfAttentionDecoderLayer,
  229. MllamaSelfAttentionDecoderLayer,
  230. MllamaVisionEncoderLayer,
  231. ],
  232. )
  233. else:
  234. # Create the FSDP wrapper for LlamaDecoderLayer in text models
  235. my_auto_wrapping_policy = fsdp_auto_wrap_policy(model, [LlamaDecoderLayer])
  236. device_id = 0
  237. if is_xpu_available():
  238. device_id = torch.xpu.current_device()
  239. elif torch.cuda.is_available():
  240. device_id = torch.cuda.current_device()
  241. model = FSDP(
  242. model,
  243. auto_wrap_policy=(
  244. my_auto_wrapping_policy if train_config.use_peft else wrapping_policy
  245. ),
  246. cpu_offload=(
  247. CPUOffload(offload_params=True)
  248. if fsdp_config.fsdp_cpu_offload
  249. else None
  250. ),
  251. mixed_precision=(
  252. mixed_precision_policy if not fsdp_config.pure_bf16 else None
  253. ),
  254. sharding_strategy=fsdp_config.sharding_strategy,
  255. device_mesh=hsdp_device_mesh_plan,
  256. device_id=device_id,
  257. limit_all_gathers=True,
  258. sync_module_states=train_config.low_cpu_fsdp,
  259. param_init_fn=(
  260. (
  261. lambda module: module.to_empty(
  262. device=torch.device("cuda"), recurse=False
  263. )
  264. )
  265. if train_config.low_cpu_fsdp and rank != 0
  266. else None
  267. ),
  268. )
  269. if fsdp_config.fsdp_activation_checkpointing:
  270. model.enable_input_require_grads()
  271. model.gradient_checkpointing_enable()
  272. apply_fsdp_checkpointing(model)
  273. elif not train_config.quantization and not train_config.enable_fsdp:
  274. if is_xpu_available():
  275. model.to("xpu:0")
  276. elif torch.cuda.is_available():
  277. model.to("cuda")
  278. # dataset_config = generate_dataset_config(train_config, kwargs)
  279. if is_vision:
  280. dataset_processer = processor
  281. else:
  282. dataset_processer = tokenizer
  283. # Load and preprocess the dataset for training and validation
  284. rule_names = train_config.rule_names
  285. dataset_train = get_enote_dataset(
  286. dataset_processer,
  287. train_config.dataset,
  288. mode="train",
  289. split="train",
  290. rule_names=rule_names,
  291. )
  292. if not train_config.enable_fsdp or rank == 0:
  293. print(f"--> Training Set Length = {len(dataset_train)}")
  294. if train_config.run_validation:
  295. dataset_val = get_enote_dataset(
  296. dataset_processer,
  297. train_config.dataset,
  298. mode="eval",
  299. split="valid",
  300. rule_names=rule_names,
  301. )
  302. if not train_config.enable_fsdp or rank == 0:
  303. print(f"--> Validation Set Length = {len(dataset_val)}")
  304. if train_config.batching_strategy == "packing":
  305. if is_vision:
  306. raise ValueError("Packing is not supported for vision datasets")
  307. else:
  308. dataset_train = ConcatDataset(
  309. dataset_train, chunk_size=train_config.context_length
  310. )
  311. train_dl_kwargs = get_dataloader_kwargs(
  312. train_config, dataset_train, dataset_processer, "train"
  313. )
  314. print("length of dataset_train", len(dataset_train))
  315. # custom_data_collator = get_custom_data_collator(dataset_processer, dataset_config)
  316. custom_data_collator = None
  317. if custom_data_collator:
  318. print("custom_data_collator is used")
  319. train_dl_kwargs["collate_fn"] = custom_data_collator
  320. # Create DataLoaders for the training and validation dataset
  321. train_dataloader = torch.utils.data.DataLoader(
  322. dataset_train,
  323. num_workers=train_config.num_workers_dataloader,
  324. pin_memory=True,
  325. **train_dl_kwargs,
  326. )
  327. print(f"--> Num of Training Set Batches loaded = {len(train_dataloader)}")
  328. eval_dataloader = None
  329. if train_config.run_validation:
  330. if train_config.batching_strategy == "packing":
  331. if is_vision:
  332. raise ValueError("Packing is not supported for vision datasets")
  333. else:
  334. dataset_val = ConcatDataset(
  335. dataset_val, chunk_size=train_config.context_length
  336. )
  337. val_dl_kwargs = get_dataloader_kwargs(
  338. train_config, dataset_val, dataset_processer, "val"
  339. )
  340. if custom_data_collator:
  341. val_dl_kwargs["collate_fn"] = custom_data_collator
  342. eval_dataloader = torch.utils.data.DataLoader(
  343. dataset_val,
  344. num_workers=train_config.num_workers_dataloader,
  345. pin_memory=True,
  346. **val_dl_kwargs,
  347. )
  348. print(f"--> Num of Validation Set Batches loaded = {len(eval_dataloader)}")
  349. if len(eval_dataloader) == 0:
  350. raise ValueError(
  351. f"The eval set size is too small for dataloader to load even one batch. Please increase the size of eval set. ({len(eval_dataloader)=})"
  352. )
  353. else:
  354. print(f"--> Num of Validation Set Batches loaded = {len(eval_dataloader)}")
  355. # Initialize the optimizer and learning rate scheduler
  356. if fsdp_config.pure_bf16 and fsdp_config.optimizer == "anyprecision":
  357. optimizer = AnyPrecisionAdamW(
  358. model.parameters(),
  359. lr=train_config.lr,
  360. momentum_dtype=torch.bfloat16,
  361. variance_dtype=torch.bfloat16,
  362. use_kahan_summation=False,
  363. weight_decay=train_config.weight_decay,
  364. )
  365. else:
  366. optimizer = optim.AdamW(
  367. model.parameters(),
  368. lr=train_config.lr,
  369. weight_decay=train_config.weight_decay,
  370. )
  371. scheduler = StepLR(optimizer, step_size=1, gamma=train_config.gamma)
  372. results = train(
  373. model,
  374. train_dataloader,
  375. eval_dataloader,
  376. tokenizer,
  377. optimizer,
  378. scheduler,
  379. train_config.gradient_accumulation_steps,
  380. train_config,
  381. fsdp_config if train_config.enable_fsdp else None,
  382. local_rank if train_config.enable_fsdp else None,
  383. rank if train_config.enable_fsdp else None,
  384. wandb_run,
  385. )
  386. if not train_config.enable_fsdp or rank == 0:
  387. [print(f"Key: {k}, Value: {v}") for k, v in results.items()]
  388. if train_config.use_wandb:
  389. for k, v in results.items():
  390. wandb_run.summary[k] = v
  391. if __name__ == "__main__":
  392. fire.Fire(main)