finetune.py 4.3 KB

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