training.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import json
  2. import sys
  3. import threading
  4. import time
  5. from pathlib import Path
  6. import gradio as gr
  7. import torch
  8. import transformers
  9. from datasets import load_dataset
  10. from peft import (LoraConfig, get_peft_model, get_peft_model_state_dict,
  11. prepare_model_for_int8_training)
  12. from modules import shared, ui
  13. WANT_INTERRUPT = False
  14. CURRENT_STEPS = 0
  15. MAX_STEPS = 0
  16. CURRENT_GRADIENT_ACCUM = 1
  17. def get_json_dataset(path: str):
  18. return ['None'] + sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path(path).glob('*.json'))), key=str.lower)
  19. def create_train_interface():
  20. with gr.Tab('Train LoRA', elem_id='lora-train-tab'):
  21. lora_name = gr.Textbox(label="Name", info="The name of your new LoRA file")
  22. with gr.Row():
  23. # TODO: Implement multi-device support.
  24. micro_batch_size = gr.Slider(label='Micro Batch Size', value=4, minimum=1, maximum=128, step=1, info='Per-device batch size (NOTE: multiple devices not yet implemented). Increasing this will increase VRAM usage.')
  25. batch_size = gr.Slider(label='Batch Size', value=128, minimum=1, maximum=1024, step=4, info='Global batch size. The two batch sizes together determine gradient accumulation (gradientAccum = batch / microBatch). Higher gradient accum values lead to better quality training.')
  26. with gr.Row():
  27. epochs = gr.Number(label='Epochs', value=3, info='Number of times every entry in the dataset should be fed into training. So 1 means feed each item in once, 5 means feed it in five times, etc.')
  28. learning_rate = gr.Textbox(label='Learning Rate', value='3e-4', info='Learning rate, in scientific notation. 3e-4 is a good starting base point. 1e-2 is extremely high, 1e-6 is extremely low.')
  29. # TODO: What is the actual maximum rank? Likely distinct per model. This might be better to somehow be on a log scale.
  30. lora_rank = gr.Slider(label='LoRA Rank', value=8, minimum=1, maximum=1024, step=4, info='LoRA Rank, or dimension count. Higher values produce a larger file with better control over the model\'s content. Smaller values produce a smaller file with less overall control. Small values like 4 or 8 are great for stylistic guidance, high values like 128 or 256 are good for teaching content upgrades. Higher ranks also require higher VRAM.')
  31. lora_alpha = gr.Slider(label='LoRA Alpha', value=16, minimum=1, maximum=2048, step=4, info='LoRA Alpha. This divided by the rank becomes the scaling of the LoRA. Higher means stronger. A good standard value is twice your Rank.')
  32. # TODO: Better explain what this does, in terms of real world effect especially.
  33. lora_dropout = gr.Slider(label='LoRA Dropout', minimum=0.0, maximum=1.0, step=0.025, value=0.05, info='Percentage probability for dropout of LoRA layers.')
  34. cutoff_len = gr.Slider(label='Cutoff Length', minimum=1,maximum=2048, value=256, step=32, info='Cutoff length for text input. Essentially, how long of a line of text to feed in at a time. Higher values require drastically more VRAM.')
  35. with gr.Row():
  36. dataset = gr.Dropdown(choices=get_json_dataset('training/datasets'), value='None', label='Dataset', info='The dataset file to use for training.')
  37. ui.create_refresh_button(dataset, lambda : None, lambda : {'choices': get_json_dataset('training/datasets')}, 'refresh-button')
  38. eval_dataset = gr.Dropdown(choices=get_json_dataset('training/datasets'), value='None', label='Evaluation Dataset', info='The dataset file used to evaluate the model after training.')
  39. ui.create_refresh_button(eval_dataset, lambda : None, lambda : {'choices': get_json_dataset('training/datasets')}, 'refresh-button')
  40. format = gr.Dropdown(choices=get_json_dataset('training/formats'), value='None', label='Data Format', info='The format file used to decide how to format the dataset input.')
  41. ui.create_refresh_button(format, lambda : None, lambda : {'choices': get_json_dataset('training/formats')}, 'refresh-button')
  42. with gr.Row():
  43. start_button = gr.Button("Start LoRA Training")
  44. stop_button = gr.Button("Interrupt")
  45. output = gr.Markdown(value="Ready")
  46. start_button.click(do_train, [lora_name, micro_batch_size, batch_size, epochs, learning_rate, lora_rank, lora_alpha, lora_dropout, cutoff_len, dataset, eval_dataset, format], [output])
  47. stop_button.click(do_interrupt, [], [], cancels=[], queue=False)
  48. def do_interrupt():
  49. global WANT_INTERRUPT
  50. WANT_INTERRUPT = True
  51. class Callbacks(transformers.TrainerCallback):
  52. def on_step_begin(self, args: transformers.TrainingArguments, state: transformers.TrainerState, control: transformers.TrainerControl, **kwargs):
  53. global CURRENT_STEPS, MAX_STEPS
  54. CURRENT_STEPS = state.global_step * CURRENT_GRADIENT_ACCUM
  55. MAX_STEPS = state.max_steps * CURRENT_GRADIENT_ACCUM
  56. if WANT_INTERRUPT:
  57. control.should_epoch_stop = True
  58. control.should_training_stop = True
  59. def on_substep_end(self, args: transformers.TrainingArguments, state: transformers.TrainerState, control: transformers.TrainerControl, **kwargs):
  60. global CURRENT_STEPS
  61. CURRENT_STEPS += 1
  62. if WANT_INTERRUPT:
  63. control.should_epoch_stop = True
  64. control.should_training_stop = True
  65. def clean_path(base_path: str, path: str):
  66. """"Strips unusual symbols and forcibly builds a path as relative to the intended directory."""
  67. # TODO: Probably could do with a security audit to guarantee there's no ways this can be bypassed to target an unwanted path.
  68. # Or swap it to a strict whitelist of [a-zA-Z_0-9]
  69. path = path.replace('\\', '/').replace('..', '_')
  70. if base_path is None:
  71. return path
  72. return f'{Path(base_path).absolute()}/{path}'
  73. def do_train(lora_name: str, micro_batch_size: int, batch_size: int, epochs: int, learning_rate: float, lora_rank: int, lora_alpha: int, lora_dropout: float, cutoff_len: int, dataset: str, eval_dataset: str, format: str):
  74. global WANT_INTERRUPT, CURRENT_STEPS, MAX_STEPS, CURRENT_GRADIENT_ACCUM
  75. WANT_INTERRUPT = False
  76. CURRENT_STEPS = 0
  77. MAX_STEPS = 0
  78. # == Input validation / processing ==
  79. yield "Prepping..."
  80. # TODO: --lora-dir PR once pulled will need to be applied here
  81. lora_name = f"loras/{clean_path(None, lora_name)}"
  82. if dataset is None:
  83. return "**Missing dataset choice input, cannot continue.**"
  84. if format is None:
  85. return "**Missing format choice input, cannot continue.**"
  86. gradient_accumulation_steps = batch_size // micro_batch_size
  87. CURRENT_GRADIENT_ACCUM = gradient_accumulation_steps
  88. actual_lr = float(learning_rate)
  89. shared.tokenizer.pad_token = 0
  90. shared.tokenizer.padding_side = "left"
  91. # == Prep the dataset, format, etc ==
  92. with open(clean_path('training/formats', f'{format}.json'), 'r') as formatFile:
  93. format_data: dict[str, str] = json.load(formatFile)
  94. def tokenize(prompt):
  95. result = shared.tokenizer(prompt, truncation=True, max_length=cutoff_len + 1, padding="max_length")
  96. return {
  97. "input_ids": result["input_ids"][:-1],
  98. "attention_mask": result["attention_mask"][:-1],
  99. }
  100. def generate_prompt(data_point: dict[str, str]):
  101. for options, data in format_data.items():
  102. if set(options.split(',')) == set(x[0] for x in data_point.items() if len(x[1].strip()) > 0):
  103. for key, val in data_point.items():
  104. data = data.replace(f'%{key}%', val)
  105. return data
  106. raise RuntimeError(f'Data-point "{data_point}" has no keyset match within format "{list(format_data.keys())}"')
  107. def generate_and_tokenize_prompt(data_point):
  108. prompt = generate_prompt(data_point)
  109. return tokenize(prompt)
  110. print("Loading datasets...")
  111. data = load_dataset("json", data_files=clean_path('training/datasets', f'{dataset}.json'))
  112. train_data = data['train'].shuffle().map(generate_and_tokenize_prompt)
  113. if eval_dataset == 'None':
  114. eval_data = None
  115. else:
  116. eval_data = load_dataset("json", data_files=clean_path('training/datasets', f'{eval_dataset}.json'))
  117. eval_data = eval_data['train'].shuffle().map(generate_and_tokenize_prompt)
  118. # == Start prepping the model itself ==
  119. if not hasattr(shared.model, 'lm_head') or hasattr(shared.model.lm_head, 'weight'):
  120. print("Getting model ready...")
  121. prepare_model_for_int8_training(shared.model)
  122. print("Prepping for training...")
  123. config = LoraConfig(
  124. r=lora_rank,
  125. lora_alpha=lora_alpha,
  126. # TODO: Should target_modules be configurable?
  127. target_modules=[ "q_proj", "v_proj" ],
  128. lora_dropout=lora_dropout,
  129. bias="none",
  130. task_type="CAUSAL_LM"
  131. )
  132. lora_model = get_peft_model(shared.model, config)
  133. trainer = transformers.Trainer(
  134. model=lora_model,
  135. train_dataset=train_data,
  136. eval_dataset=eval_data,
  137. args=transformers.TrainingArguments(
  138. per_device_train_batch_size=micro_batch_size,
  139. gradient_accumulation_steps=gradient_accumulation_steps,
  140. # TODO: Should more of these be configurable? Probably.
  141. warmup_steps=100,
  142. num_train_epochs=epochs,
  143. learning_rate=actual_lr,
  144. fp16=True,
  145. logging_steps=20,
  146. evaluation_strategy="steps" if eval_data is not None else "no",
  147. save_strategy="steps",
  148. eval_steps=200 if eval_data is not None else None,
  149. save_steps=200,
  150. output_dir=lora_name,
  151. save_total_limit=3,
  152. load_best_model_at_end=True if eval_data is not None else False,
  153. # TODO: Enable multi-device support
  154. ddp_find_unused_parameters=None
  155. ),
  156. data_collator=transformers.DataCollatorForLanguageModeling(shared.tokenizer, mlm=False),
  157. callbacks=list([Callbacks()])
  158. )
  159. lora_model.config.use_cache = False
  160. old_state_dict = lora_model.state_dict
  161. lora_model.state_dict = (
  162. lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict())
  163. ).__get__(lora_model, type(lora_model))
  164. if torch.__version__ >= "2" and sys.platform != "win32":
  165. lora_model = torch.compile(lora_model)
  166. # == Main run and monitor loop ==
  167. # TODO: save/load checkpoints to resume from?
  168. print("Starting training...")
  169. yield "Starting..."
  170. def threadedRun():
  171. trainer.train()
  172. thread = threading.Thread(target=threadedRun)
  173. thread.start()
  174. lastStep = 0
  175. startTime = time.perf_counter()
  176. while thread.is_alive():
  177. time.sleep(0.5)
  178. if WANT_INTERRUPT:
  179. yield "Interrupting, please wait... *(Run will stop after the current training step completes.)*"
  180. elif CURRENT_STEPS != lastStep:
  181. lastStep = CURRENT_STEPS
  182. timeElapsed = time.perf_counter() - startTime
  183. if timeElapsed <= 0:
  184. timerInfo = ""
  185. totalTimeEstimate = 999
  186. else:
  187. its = CURRENT_STEPS / timeElapsed
  188. if its > 1:
  189. timerInfo = f"`{its:.2f}` it/s"
  190. else:
  191. timerInfo = f"`{1.0/its:.2f}` s/it"
  192. totalTimeEstimate = (1.0/its) * (MAX_STEPS)
  193. yield f"Running... **{CURRENT_STEPS}** / **{MAX_STEPS}** ... {timerInfo}, `{timeElapsed:.0f}`/`{totalTimeEstimate:.0f}` seconds"
  194. print("Training complete, saving...")
  195. lora_model.save_pretrained(lora_name)
  196. if WANT_INTERRUPT:
  197. print("Training interrupted.")
  198. yield f"Interrupted. Incomplete LoRA saved to `{lora_name}`"
  199. else:
  200. print("Training complete!")
  201. yield f"Done! LoRA saved to `{lora_name}`"