finetune.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. def generate_prompt(data_point):
  62. # sorry about the formatting disaster gotta move fast
  63. if data_point["input"]:
  64. 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.
  65. ### Instruction:
  66. {data_point["instruction"]}
  67. ### Input:
  68. {data_point["input"]}
  69. ### Response:
  70. {data_point["output"]}"""
  71. else:
  72. return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
  73. ### Instruction:
  74. {data_point["instruction"]}
  75. ### Response:
  76. {data_point["output"]}"""
  77. def tokenize(prompt):
  78. # there's probably a way to do this with the tokenizer settings
  79. # but again, gotta move fast
  80. result = tokenizer(
  81. prompt,
  82. truncation=True,
  83. max_length=CUTOFF_LEN + 1,
  84. padding="max_length",
  85. )
  86. return {
  87. "input_ids": result["input_ids"][:-1],
  88. "attention_mask": result["attention_mask"][:-1],
  89. }
  90. def generate_and_tokenize_prompt(data_point):
  91. # This function masks out the labels for the input,
  92. # so that our loss is computed only on the response.
  93. user_prompt = (
  94. (
  95. 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.
  96. ### Instruction:
  97. {data_point["instruction"]}
  98. ### Input:
  99. {data_point["input"]}
  100. ### Response:
  101. """
  102. )
  103. if data_point["input"]
  104. else (
  105. f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
  106. ### Instruction:
  107. {data_point["instruction"]}
  108. ### Response:
  109. """
  110. )
  111. )
  112. len_user_prompt_tokens = (
  113. len(
  114. tokenizer(
  115. user_prompt,
  116. truncation=True,
  117. max_length=CUTOFF_LEN + 1,
  118. padding="max_length",
  119. )["input_ids"]
  120. )
  121. - 1
  122. ) # no eos token
  123. full_tokens = tokenizer(
  124. user_prompt + data_point["output"],
  125. truncation=True,
  126. max_length=CUTOFF_LEN + 1,
  127. padding="max_length",
  128. )["input_ids"][:-1]
  129. return {
  130. "input_ids": full_tokens,
  131. "labels": [-100] * len_user_prompt_tokens
  132. + full_tokens[len_user_prompt_tokens:],
  133. "attention_mask": [1] * (len(full_tokens)),
  134. }
  135. if VAL_SET_SIZE > 0:
  136. train_val = data["train"].train_test_split(
  137. test_size=VAL_SET_SIZE, shuffle=True, seed=42
  138. )
  139. train_data = train_val["train"].shuffle().map(generate_and_tokenize_prompt)
  140. val_data = train_val["test"].shuffle().map(generate_and_tokenize_prompt)
  141. else:
  142. train_data = data['train'].shuffle().map(generate_and_tokenize_prompt)
  143. val_data = None
  144. trainer = transformers.Trainer(
  145. model=model,
  146. train_dataset=train_data,
  147. eval_dataset=val_data,
  148. args=transformers.TrainingArguments(
  149. per_device_train_batch_size=MICRO_BATCH_SIZE,
  150. gradient_accumulation_steps=GRADIENT_ACCUMULATION_STEPS,
  151. warmup_steps=100,
  152. num_train_epochs=EPOCHS,
  153. learning_rate=LEARNING_RATE,
  154. fp16=True,
  155. logging_steps=20,
  156. evaluation_strategy="steps" if VAL_SET_SIZE > 0 else "no",
  157. save_strategy="steps",
  158. eval_steps=200 if VAL_SET_SIZE > 0 else None,
  159. save_steps=200,
  160. output_dir=OUTPUT_DIR,
  161. save_total_limit=3,
  162. load_best_model_at_end=True if VAL_SET_SIZE > 0 else False,
  163. ddp_find_unused_parameters=False if ddp else None,
  164. ),
  165. data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),
  166. )
  167. model.config.use_cache = False
  168. old_state_dict = model.state_dict
  169. model.state_dict = (
  170. lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict())
  171. ).__get__(model, type(model))
  172. if torch.__version__ >= "2" and sys.platform != 'win32':
  173. model = torch.compile(model)
  174. trainer.train()
  175. model.save_pretrained(OUTPUT_DIR)
  176. print("\n If there's a warning about missing keys above, please disregard :)")