training.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. def get_set():
  19. return ['None'] + sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path(path).glob('*.json'))), key=str.lower)
  20. return get_set
  21. def create_train_interface():
  22. with gr.Tab('Train LoRA', elem_id='lora-train-tab'):
  23. loraName = gr.Textbox(label="Name", info="The name of your new LoRA file")
  24. with gr.Row():
  25. # TODO: Implement multi-device support.
  26. microBatchSize = 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.')
  27. batchSize = 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.')
  28. with gr.Row():
  29. epochs = gr.Number(label='Epochs', value=1, 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.')
  30. learningRate = 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.')
  31. # TODO: What is the actual maximum rank? Likely distinct per model. This might be better to somehow be on a log scale.
  32. loraRank = 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.')
  33. loraAlpha = 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.')
  34. # TODO: Better explain what this does, in terms of real world effect especially.
  35. loraDropout = 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.')
  36. cutoffLen = 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.')
  37. with gr.Row():
  38. datasetFunction = get_json_dataset('training/datasets')
  39. dataset = gr.Dropdown(choices=datasetFunction(), value='None', label='Dataset', info='The dataset file to use for training.')
  40. ui.create_refresh_button(dataset, lambda : None, lambda : {'choices': datasetFunction()}, 'refresh-button')
  41. evalDataset = gr.Dropdown(choices=datasetFunction(), value='None', label='Evaluation Dataset', info='The dataset file used to evaluate the model after training.')
  42. ui.create_refresh_button(evalDataset, lambda : None, lambda : {'choices': datasetFunction()}, 'refresh-button')
  43. formatsFunction = get_json_dataset('training/formats')
  44. format = gr.Dropdown(choices=formatsFunction(), value='None', label='Data Format', info='The format file used to decide how to format the dataset input.')
  45. ui.create_refresh_button(format, lambda : None, lambda : {'choices': formatsFunction()}, 'refresh-button')
  46. with gr.Row():
  47. startButton = gr.Button("Start LoRA Training")
  48. stopButton = gr.Button("Interrupt")
  49. output = gr.Markdown(value="Ready")
  50. startEvent = startButton.click(do_train, [loraName, microBatchSize, batchSize, epochs, learningRate, loraRank, loraAlpha, loraDropout, cutoffLen, dataset, evalDataset, format], [output])
  51. stopButton.click(doInterrupt, [], [], cancels=[], queue=False)
  52. def doInterrupt():
  53. global WANT_INTERRUPT
  54. WANT_INTERRUPT = True
  55. class Callbacks(transformers.TrainerCallback):
  56. def on_step_begin(self, args: transformers.TrainingArguments, state: transformers.TrainerState, control: transformers.TrainerControl, **kwargs):
  57. global CURRENT_STEPS, MAX_STEPS
  58. CURRENT_STEPS = state.global_step * CURRENT_GRADIENT_ACCUM
  59. MAX_STEPS = state.max_steps * CURRENT_GRADIENT_ACCUM
  60. if WANT_INTERRUPT:
  61. control.should_epoch_stop = True
  62. control.should_training_stop = True
  63. def on_substep_end(self, args: transformers.TrainingArguments, state: transformers.TrainerState, control: transformers.TrainerControl, **kwargs):
  64. global CURRENT_STEPS
  65. CURRENT_STEPS += 1
  66. if WANT_INTERRUPT:
  67. control.should_epoch_stop = True
  68. control.should_training_stop = True
  69. def cleanPath(basePath: str, path: str):
  70. """"Strips unusual symbols and forcibly builds a path as relative to the intended directory."""
  71. # TODO: Probably could do with a security audit to guarantee there's no ways this can be bypassed to target an unwanted path.
  72. # Or swap it to a strict whitelist of [a-zA-Z_0-9]
  73. path = path.replace('\\', '/').replace('..', '_')
  74. if basePath is None:
  75. return path
  76. return f'{Path(basePath).absolute()}/{path}'
  77. def do_train(loraName: str, microBatchSize: int, batchSize: int, epochs: int, learningRate: float, loraRank: int, loraAlpha: int, loraDropout: float, cutoffLen: int, dataset: str, evalDataset: str, format: str):
  78. global WANT_INTERRUPT, CURRENT_STEPS, MAX_STEPS, CURRENT_GRADIENT_ACCUM
  79. WANT_INTERRUPT = False
  80. CURRENT_STEPS = 0
  81. MAX_STEPS = 0
  82. yield "Prepping..."
  83. # == Input validation / processing ==
  84. # TODO: --lora-dir PR once pulled will need to be applied here
  85. loraName = f"loras/{cleanPath(None, loraName)}"
  86. if dataset is None:
  87. return "**Missing dataset choice input, cannot continue.**"
  88. if format is None:
  89. return "**Missing format choice input, cannot continue.**"
  90. gradientAccumulationSteps = batchSize // microBatchSize
  91. CURRENT_GRADIENT_ACCUM = gradientAccumulationSteps
  92. actualLR = float(learningRate)
  93. shared.tokenizer.pad_token = 0
  94. shared.tokenizer.padding_side = "left"
  95. # == Prep the dataset, format, etc ==
  96. with open(cleanPath('training/formats', f'{format}.json'), 'r') as formatFile:
  97. formatData: dict[str, str] = json.load(formatFile)
  98. def tokenize(prompt):
  99. result = shared.tokenizer(prompt, truncation=True, max_length=cutoffLen + 1, padding="max_length")
  100. return {
  101. "input_ids": result["input_ids"][:-1],
  102. "attention_mask": result["attention_mask"][:-1],
  103. }
  104. def generate_prompt(data_point: dict[str, str]):
  105. for options, data in formatData.items():
  106. if set(options.split(',')) == set(x[0] for x in data_point.items() if len(x[1].strip()) > 0):
  107. for key, val in data_point.items():
  108. data = data.replace(f'%{key}%', val)
  109. return data
  110. raise RuntimeError(f'Data-point "{data_point}" has no keyset match within format "{list(formatData.keys())}"')
  111. def generate_and_tokenize_prompt(data_point):
  112. prompt = generate_prompt(data_point)
  113. return tokenize(prompt)
  114. print("Loading datasets...")
  115. data = load_dataset("json", data_files=cleanPath('training/datasets', f'{dataset}.json'))
  116. train_data = data['train'].shuffle().map(generate_and_tokenize_prompt)
  117. if evalDataset == 'None':
  118. evalData = None
  119. else:
  120. evalData = load_dataset("json", data_files=cleanPath('training/datasets', f'{evalDataset}.json'))
  121. evalData = evalData['train'].shuffle().map(generate_and_tokenize_prompt)
  122. # == Start prepping the model itself ==
  123. if not hasattr(shared.model, 'lm_head') or hasattr(shared.model.lm_head, 'weight'):
  124. print("Getting model ready...")
  125. prepare_model_for_int8_training(shared.model)
  126. print("Prepping for training...")
  127. config = LoraConfig(
  128. r=loraRank,
  129. lora_alpha=loraAlpha,
  130. # TODO: Should target_modules be configurable?
  131. target_modules=[ "q_proj", "v_proj" ],
  132. lora_dropout=loraDropout,
  133. bias="none",
  134. task_type="CAUSAL_LM"
  135. )
  136. loraModel = get_peft_model(shared.model, config)
  137. trainer = transformers.Trainer(
  138. model=loraModel,
  139. train_dataset=train_data,
  140. eval_dataset=evalData,
  141. args=transformers.TrainingArguments(
  142. per_device_train_batch_size=microBatchSize,
  143. gradient_accumulation_steps=gradientAccumulationSteps,
  144. # TODO: Should more of these be configurable? Probably.
  145. warmup_steps=100,
  146. num_train_epochs=epochs,
  147. learning_rate=actualLR,
  148. fp16=True,
  149. logging_steps=20,
  150. evaluation_strategy="steps" if evalData is not None else "no",
  151. save_strategy="steps",
  152. eval_steps=200 if evalData is not None else None,
  153. save_steps=200,
  154. output_dir=loraName,
  155. save_total_limit=3,
  156. load_best_model_at_end=True if evalData is not None else False,
  157. # TODO: Enable multi-device support
  158. ddp_find_unused_parameters=None
  159. ),
  160. data_collator=transformers.DataCollatorForLanguageModeling(shared.tokenizer, mlm=False),
  161. callbacks=list([Callbacks()])
  162. )
  163. loraModel.config.use_cache = False
  164. old_state_dict = loraModel.state_dict
  165. loraModel.state_dict = (
  166. lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict())
  167. ).__get__(loraModel, type(loraModel))
  168. if torch.__version__ >= "2" and sys.platform != "win32":
  169. loraModel = torch.compile(loraModel)
  170. # == Main run and monitor loop ==
  171. # TODO: save/load checkpoints to resume from?
  172. print("Starting training...")
  173. yield "Starting..."
  174. def threadedRun():
  175. trainer.train()
  176. thread = threading.Thread(target=threadedRun)
  177. thread.start()
  178. lastStep = 0
  179. startTime = time.perf_counter()
  180. while thread.is_alive():
  181. time.sleep(0.5)
  182. if WANT_INTERRUPT:
  183. yield "Interrupting, please wait... *(Run will stop after the current training step completes.)*"
  184. elif CURRENT_STEPS != lastStep:
  185. lastStep = CURRENT_STEPS
  186. timeElapsed = time.perf_counter() - startTime
  187. if timeElapsed <= 0:
  188. timerInfo = ""
  189. totalTimeEstimate = 999
  190. else:
  191. its = CURRENT_STEPS / timeElapsed
  192. if its > 1:
  193. timerInfo = f"`{its:.2f}` it/s"
  194. else:
  195. timerInfo = f"`{1.0/its:.2f}` s/it"
  196. totalTimeEstimate = (1.0/its) * (MAX_STEPS)
  197. yield f"Running... **{CURRENT_STEPS}** / **{MAX_STEPS}** ... {timerInfo}, `{timeElapsed:.0f}`/`{totalTimeEstimate:.0f}` seconds"
  198. print("Training complete, saving...")
  199. loraModel.save_pretrained(loraName)
  200. if WANT_INTERRUPT:
  201. print("Training interrupted.")
  202. yield f"Interrupted. Incomplete LoRA saved to `{loraName}`"
  203. else:
  204. print("Training complete!")
  205. yield f"Done! LoRA saved to `{loraName}`"