finetune.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. BASE_MODEL = None
  36. assert (
  37. BASE_MODEL
  38. ), "Please specify a BASE_MODEL in the script, e.g. 'decapoda-research/llama-7b-hf'"
  39. device_map = "auto"
  40. world_size = int(os.environ.get("WORLD_SIZE", 1))
  41. ddp = world_size != 1
  42. if ddp:
  43. device_map = {"": int(os.environ.get("LOCAL_RANK") or 0)}
  44. GRADIENT_ACCUMULATION_STEPS = GRADIENT_ACCUMULATION_STEPS // world_size
  45. model = LlamaForCausalLM.from_pretrained(
  46. BASE_MODEL,
  47. load_in_8bit=True,
  48. device_map=device_map,
  49. )
  50. tokenizer = LlamaTokenizer.from_pretrained(BASE_MODEL, add_eos_token=True)
  51. model = prepare_model_for_int8_training(model)
  52. config = LoraConfig(
  53. r=LORA_R,
  54. lora_alpha=LORA_ALPHA,
  55. target_modules=TARGET_MODULES,
  56. lora_dropout=LORA_DROPOUT,
  57. bias="none",
  58. task_type="CAUSAL_LM",
  59. )
  60. model = get_peft_model(model, config)
  61. tokenizer.pad_token_id = 0 # unk. we want this to be different from the eos token
  62. data = load_dataset("json", data_files=DATA_PATH)
  63. def generate_prompt(data_point):
  64. # sorry about the formatting disaster gotta move fast
  65. if data_point["input"]:
  66. 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.
  67. ### Instruction:
  68. {data_point["instruction"]}
  69. ### Input:
  70. {data_point["input"]}
  71. ### Response:
  72. {data_point["output"]}"""
  73. else:
  74. return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
  75. ### Instruction:
  76. {data_point["instruction"]}
  77. ### Response:
  78. {data_point["output"]}"""
  79. def tokenize(prompt):
  80. # there's probably a way to do this with the tokenizer settings
  81. # but again, gotta move fast
  82. result = tokenizer(
  83. prompt,
  84. truncation=True,
  85. max_length=CUTOFF_LEN + 1,
  86. padding="max_length",
  87. )
  88. return {
  89. "input_ids": result["input_ids"][:-1],
  90. "attention_mask": result["attention_mask"][:-1],
  91. }
  92. def generate_and_tokenize_prompt(data_point):
  93. prompt = generate_prompt(data_point)
  94. return tokenize(prompt)
  95. if VAL_SET_SIZE > 0:
  96. train_val = data["train"].train_test_split(
  97. test_size=VAL_SET_SIZE, shuffle=True, seed=42
  98. )
  99. train_data = train_val["train"].shuffle().map(generate_and_tokenize_prompt)
  100. val_data = train_val["test"].shuffle().map(generate_and_tokenize_prompt)
  101. else:
  102. train_data = data["train"].shuffle().map(generate_and_tokenize_prompt)
  103. val_data = None
  104. trainer = transformers.Trainer(
  105. model=model,
  106. train_dataset=train_data,
  107. eval_dataset=val_data,
  108. args=transformers.TrainingArguments(
  109. per_device_train_batch_size=MICRO_BATCH_SIZE,
  110. gradient_accumulation_steps=GRADIENT_ACCUMULATION_STEPS,
  111. warmup_steps=100,
  112. num_train_epochs=EPOCHS,
  113. learning_rate=LEARNING_RATE,
  114. fp16=True,
  115. logging_steps=20,
  116. evaluation_strategy="steps" if VAL_SET_SIZE > 0 else "no",
  117. save_strategy="steps",
  118. eval_steps=200 if VAL_SET_SIZE > 0 else None,
  119. save_steps=200,
  120. output_dir=OUTPUT_DIR,
  121. save_total_limit=3,
  122. load_best_model_at_end=True if VAL_SET_SIZE > 0 else False,
  123. ddp_find_unused_parameters=False if ddp else None,
  124. ),
  125. data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),
  126. )
  127. model.config.use_cache = False
  128. old_state_dict = model.state_dict
  129. model.state_dict = (
  130. lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict())
  131. ).__get__(model, type(model))
  132. if torch.__version__ >= "2" and sys.platform != "win32":
  133. model = torch.compile(model)
  134. trainer.train()
  135. model.save_pretrained(OUTPUT_DIR)
  136. print("\n If there's a warning about missing keys above, please disregard :)")