finetune.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import os
  2. import sys
  3. import torch
  4. import torch.nn as nn
  5. import bitsandbytes as bnb
  6. from datasets import load_dataset
  7. import transformers
  8. assert (
  9. "LlamaTokenizer" in transformers._import_structure["models.llama"]
  10. ), "LLaMA is now in HuggingFace's main branch.\nPlease reinstall it: pip uninstall transformers && pip install git+https://github.com/huggingface/transformers.git"
  11. from transformers import LlamaForCausalLM, LlamaTokenizer
  12. from peft import (
  13. prepare_model_for_int8_training,
  14. LoraConfig,
  15. get_peft_model,
  16. get_peft_model_state_dict,
  17. )
  18. # optimized for RTX 4090. for larger GPUs, increase some of these?
  19. MICRO_BATCH_SIZE = 4 # this could actually be 5 but i like powers of 2
  20. BATCH_SIZE = 128
  21. GRADIENT_ACCUMULATION_STEPS = BATCH_SIZE // MICRO_BATCH_SIZE
  22. EPOCHS = 3 # we don't always need 3 tbh
  23. LEARNING_RATE = 3e-4 # the Karpathy constant
  24. CUTOFF_LEN = 256 # 256 accounts for about 96% of the data
  25. LORA_R = 8
  26. LORA_ALPHA = 16
  27. LORA_DROPOUT = 0.05
  28. VAL_SET_SIZE = 2000
  29. TARGET_MODULES = [
  30. "q_proj",
  31. "v_proj",
  32. ]
  33. DATA_PATH = "alpaca_data_cleaned.json"
  34. OUTPUT_DIR = "lora-alpaca"
  35. device_map = "auto"
  36. world_size = int(os.environ.get("WORLD_SIZE", 1))
  37. ddp = world_size != 1
  38. if ddp:
  39. device_map = {"": int(os.environ.get("LOCAL_RANK") or 0)}
  40. GRADIENT_ACCUMULATION_STEPS = GRADIENT_ACCUMULATION_STEPS // world_size
  41. model = LlamaForCausalLM.from_pretrained(
  42. "decapoda-research/llama-7b-hf",
  43. load_in_8bit=True,
  44. device_map=device_map,
  45. )
  46. tokenizer = LlamaTokenizer.from_pretrained(
  47. "decapoda-research/llama-7b-hf", add_eos_token=True
  48. )
  49. model = prepare_model_for_int8_training(model)
  50. config = LoraConfig(
  51. r=LORA_R,
  52. lora_alpha=LORA_ALPHA,
  53. target_modules=TARGET_MODULES,
  54. lora_dropout=LORA_DROPOUT,
  55. bias="none",
  56. task_type="CAUSAL_LM",
  57. )
  58. model = get_peft_model(model, config)
  59. tokenizer.pad_token_id = 0 # unk. we want this to be different from the eos token
  60. data = load_dataset("json", data_files=DATA_PATH)
  61. train_val = data["train"].train_test_split(
  62. test_size=VAL_SET_SIZE, shuffle=True, seed=42
  63. )
  64. train_data = train_val["train"]
  65. val_data = train_val["test"]
  66. def generate_prompt(data_point):
  67. # sorry about the formatting disaster gotta move fast
  68. if data_point["input"]:
  69. return f"""Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
  70. ### Instruction:
  71. {data_point["instruction"]}
  72. ### Input:
  73. {data_point["input"]}
  74. ### Response:
  75. {data_point["output"]}"""
  76. else:
  77. return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
  78. ### Instruction:
  79. {data_point["instruction"]}
  80. ### Response:
  81. {data_point["output"]}"""
  82. def tokenize(prompt):
  83. # there's probably a way to do this with the tokenizer settings
  84. # but again, gotta move fast
  85. result = tokenizer(
  86. prompt,
  87. truncation=True,
  88. max_length=CUTOFF_LEN + 1,
  89. padding="max_length",
  90. )
  91. return {
  92. "input_ids": result["input_ids"][:-1],
  93. "attention_mask": result["attention_mask"][:-1],
  94. }
  95. def generate_and_tokenize_prompt(data_point):
  96. # This function masks out the labels for the input,
  97. # so that our loss is computed only on the response.
  98. user_prompt = (
  99. (
  100. f"""Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
  101. ### Instruction:
  102. {data_point["instruction"]}
  103. ### Input:
  104. {data_point["input"]}
  105. ### Response:
  106. """
  107. )
  108. if data_point["input"]
  109. else (
  110. f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
  111. ### Instruction:
  112. {data_point["instruction"]}
  113. ### Response:
  114. """
  115. )
  116. )
  117. len_user_prompt_tokens = (
  118. len(
  119. tokenizer(
  120. user_prompt,
  121. truncation=True,
  122. max_length=CUTOFF_LEN + 1,
  123. padding="max_length",
  124. )["input_ids"]
  125. )
  126. - 1
  127. ) # no eos token
  128. full_tokens = tokenizer(
  129. user_prompt + data_point["output"],
  130. truncation=True,
  131. max_length=CUTOFF_LEN + 1,
  132. padding="max_length",
  133. )["input_ids"][:-1]
  134. return {
  135. "input_ids": full_tokens,
  136. "labels": [-100] * len_user_prompt_tokens
  137. + full_tokens[len_user_prompt_tokens:],
  138. "attention_mask": [1] * (len(full_tokens)),
  139. }
  140. train_data = train_data.shuffle().map(generate_and_tokenize_prompt)
  141. val_data = val_data.shuffle().map(generate_and_tokenize_prompt)
  142. trainer = transformers.Trainer(
  143. model=model,
  144. train_dataset=train_data,
  145. eval_dataset=val_data,
  146. args=transformers.TrainingArguments(
  147. per_device_train_batch_size=MICRO_BATCH_SIZE,
  148. gradient_accumulation_steps=GRADIENT_ACCUMULATION_STEPS,
  149. warmup_steps=100,
  150. num_train_epochs=EPOCHS,
  151. learning_rate=LEARNING_RATE,
  152. fp16=True,
  153. logging_steps=20,
  154. evaluation_strategy="steps",
  155. save_strategy="steps",
  156. eval_steps=200,
  157. save_steps=200,
  158. output_dir=OUTPUT_DIR,
  159. save_total_limit=3,
  160. load_best_model_at_end=True,
  161. ddp_find_unused_parameters=False if ddp else None,
  162. ),
  163. data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),
  164. )
  165. model.config.use_cache = False
  166. old_state_dict = model.state_dict
  167. model.state_dict = (
  168. lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict())
  169. ).__get__(model, type(model))
  170. if torch.__version__ >= "2" and sys.platform != 'win32':
  171. model = torch.compile(model)
  172. trainer.train()
  173. model.save_pretrained(OUTPUT_DIR)
  174. print("\n If there's a warning about missing keys above, please disregard :)")