training.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import json
  2. import sys
  3. import threading
  4. import time
  5. import traceback
  6. from pathlib import Path
  7. import gradio as gr
  8. import torch
  9. import transformers
  10. from datasets import Dataset, load_dataset
  11. from peft import (LoraConfig, get_peft_model, get_peft_model_state_dict,
  12. prepare_model_for_int8_training)
  13. from modules import shared, ui
  14. WANT_INTERRUPT = False
  15. CURRENT_STEPS = 0
  16. MAX_STEPS = 0
  17. CURRENT_GRADIENT_ACCUM = 1
  18. def get_dataset(path: str, ext: str):
  19. return ['None'] + sorted(set((k.stem for k in Path(path).glob(f'*.{ext}'))), key=str.lower)
  20. def create_train_interface():
  21. with gr.Tab('Train LoRA', elem_id='lora-train-tab'):
  22. lora_name = gr.Textbox(label="Name", info="The name of your new LoRA file")
  23. with gr.Row():
  24. # TODO: Implement multi-device support.
  25. 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.')
  26. batch_size = gr.Slider(label='Batch Size', value=128, minimum=0, 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.')
  27. with gr.Row():
  28. 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.')
  29. 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.')
  30. # TODO: What is the actual maximum rank? Likely distinct per model. This might be better to somehow be on a log scale.
  31. lora_rank = gr.Slider(label='LoRA Rank', value=32, minimum=0, 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.')
  32. lora_alpha = gr.Slider(label='LoRA Alpha', value=64, minimum=0, 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.')
  33. # TODO: Better explain what this does, in terms of real world effect especially.
  34. 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.')
  35. cutoff_len = gr.Slider(label='Cutoff Length', minimum=0, 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.')
  36. with gr.Tab(label="Formatted Dataset"):
  37. with gr.Row():
  38. dataset = gr.Dropdown(choices=get_dataset('training/datasets', 'json'), value='None', label='Dataset', info='The dataset file to use for training.')
  39. ui.create_refresh_button(dataset, lambda : None, lambda : {'choices': get_dataset('training/datasets', 'json')}, 'refresh-button')
  40. eval_dataset = gr.Dropdown(choices=get_dataset('training/datasets', 'json'), value='None', label='Evaluation Dataset', info='The dataset file used to evaluate the model after training.')
  41. ui.create_refresh_button(eval_dataset, lambda : None, lambda : {'choices': get_dataset('training/datasets', 'json')}, 'refresh-button')
  42. format = gr.Dropdown(choices=get_dataset('training/formats', 'json'), value='None', label='Data Format', info='The format file used to decide how to format the dataset input.')
  43. ui.create_refresh_button(format, lambda : None, lambda : {'choices': get_dataset('training/formats', 'json')}, 'refresh-button')
  44. with gr.Tab(label="Raw Text File"):
  45. with gr.Row():
  46. raw_text_file = gr.Dropdown(choices=get_dataset('training/datasets', 'txt'), value='None', label='Text File', info='The raw text file to use for training.')
  47. ui.create_refresh_button(raw_text_file, lambda : None, lambda : {'choices': get_dataset('training/datasets', 'txt')}, 'refresh-button')
  48. overlap_len = gr.Slider(label='Overlap Length', minimum=0,maximum=512, value=128, step=16, info='Overlap length - ie how many tokens from the prior chunk of text to include into the next chunk. (The chunks themselves will be of a size determined by Cutoff Length above). Setting overlap to exactly half the cutoff length may be ideal.')
  49. with gr.Row():
  50. start_button = gr.Button("Start LoRA Training")
  51. stop_button = gr.Button("Interrupt")
  52. output = gr.Markdown(value="Ready")
  53. 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, raw_text_file, overlap_len], [output])
  54. stop_button.click(do_interrupt, [], [], cancels=[], queue=False)
  55. def do_interrupt():
  56. global WANT_INTERRUPT
  57. WANT_INTERRUPT = True
  58. class Callbacks(transformers.TrainerCallback):
  59. def on_step_begin(self, args: transformers.TrainingArguments, state: transformers.TrainerState, control: transformers.TrainerControl, **kwargs):
  60. global CURRENT_STEPS, MAX_STEPS
  61. CURRENT_STEPS = state.global_step * CURRENT_GRADIENT_ACCUM
  62. MAX_STEPS = state.max_steps * CURRENT_GRADIENT_ACCUM
  63. if WANT_INTERRUPT:
  64. control.should_epoch_stop = True
  65. control.should_training_stop = True
  66. def on_substep_end(self, args: transformers.TrainingArguments, state: transformers.TrainerState, control: transformers.TrainerControl, **kwargs):
  67. global CURRENT_STEPS
  68. CURRENT_STEPS += 1
  69. if WANT_INTERRUPT:
  70. control.should_epoch_stop = True
  71. control.should_training_stop = True
  72. def clean_path(base_path: str, path: str):
  73. """"Strips unusual symbols and forcibly builds a path as relative to the intended directory."""
  74. # TODO: Probably could do with a security audit to guarantee there's no ways this can be bypassed to target an unwanted path.
  75. # Or swap it to a strict whitelist of [a-zA-Z_0-9]
  76. path = path.replace('\\', '/').replace('..', '_')
  77. if base_path is None:
  78. return path
  79. return f'{Path(base_path).absolute()}/{path}'
  80. def do_train(lora_name: str, micro_batch_size: int, batch_size: int, epochs: int, learning_rate: str, lora_rank: int,
  81. lora_alpha: int, lora_dropout: float, cutoff_len: int, dataset: str, eval_dataset: str, format: str, raw_text_file: str, overlap_len: int):
  82. global WANT_INTERRUPT, CURRENT_STEPS, MAX_STEPS, CURRENT_GRADIENT_ACCUM
  83. WANT_INTERRUPT = False
  84. CURRENT_STEPS = 0
  85. MAX_STEPS = 0
  86. # == Input validation / processing ==
  87. yield "Prepping..."
  88. lora_name = f"{shared.args.lora_dir}/{clean_path(None, lora_name)}"
  89. actual_lr = float(learning_rate)
  90. if cutoff_len <= 0 or micro_batch_size <= 0 or batch_size <= 0 or actual_lr <= 0 or lora_rank <= 0 or lora_alpha <= 0:
  91. yield "Cannot input zeroes."
  92. return
  93. gradient_accumulation_steps = batch_size // micro_batch_size
  94. CURRENT_GRADIENT_ACCUM = gradient_accumulation_steps
  95. shared.tokenizer.pad_token = 0
  96. shared.tokenizer.padding_side = "left"
  97. def tokenize(prompt):
  98. result = shared.tokenizer(prompt, truncation=True, max_length=cutoff_len + 1, padding="max_length")
  99. return {
  100. "input_ids": result["input_ids"][:-1],
  101. "attention_mask": result["attention_mask"][:-1],
  102. }
  103. # == Prep the dataset, format, etc ==
  104. if raw_text_file not in ['None', '']:
  105. print("Loading raw text file dataset...")
  106. with open(clean_path('training/datasets', f'{raw_text_file}.txt'), 'r') as file:
  107. raw_text = file.read()
  108. tokens = shared.tokenizer.encode(raw_text)
  109. del raw_text # Note: could be a gig for a large dataset, so delete redundant data as we go to be safe on RAM
  110. tokens = list(split_chunks(tokens, cutoff_len - overlap_len))
  111. for i in range(1, len(tokens)):
  112. tokens[i] = tokens[i - 1][-overlap_len:] + tokens[i]
  113. text_chunks = [shared.tokenizer.decode(x) for x in tokens]
  114. del tokens
  115. data = Dataset.from_list([tokenize(x) for x in text_chunks])
  116. train_data = data.shuffle()
  117. eval_data = None
  118. del text_chunks
  119. else:
  120. if dataset in ['None', '']:
  121. yield "**Missing dataset choice input, cannot continue.**"
  122. return
  123. if format in ['None', '']:
  124. yield "**Missing format choice input, cannot continue.**"
  125. return
  126. with open(clean_path('training/formats', f'{format}.json'), 'r') as formatFile:
  127. format_data: dict[str, str] = json.load(formatFile)
  128. def generate_prompt(data_point: dict[str, str]):
  129. for options, data in format_data.items():
  130. if set(options.split(',')) == set(x[0] for x in data_point.items() if len(x[1].strip()) > 0):
  131. for key, val in data_point.items():
  132. data = data.replace(f'%{key}%', val)
  133. return data
  134. raise RuntimeError(f'Data-point "{data_point}" has no keyset match within format "{list(format_data.keys())}"')
  135. def generate_and_tokenize_prompt(data_point):
  136. prompt = generate_prompt(data_point)
  137. return tokenize(prompt)
  138. print("Loading JSON datasets...")
  139. data = load_dataset("json", data_files=clean_path('training/datasets', f'{dataset}.json'))
  140. train_data = data['train'].shuffle().map(generate_and_tokenize_prompt)
  141. if eval_dataset == 'None':
  142. eval_data = None
  143. else:
  144. eval_data = load_dataset("json", data_files=clean_path('training/datasets', f'{eval_dataset}.json'))
  145. eval_data = eval_data['train'].shuffle().map(generate_and_tokenize_prompt)
  146. # == Start prepping the model itself ==
  147. if not hasattr(shared.model, 'lm_head') or hasattr(shared.model.lm_head, 'weight'):
  148. print("Getting model ready...")
  149. prepare_model_for_int8_training(shared.model)
  150. print("Prepping for training...")
  151. config = LoraConfig(
  152. r=lora_rank,
  153. lora_alpha=lora_alpha,
  154. # TODO: Should target_modules be configurable?
  155. target_modules=[ "q_proj", "v_proj" ],
  156. lora_dropout=lora_dropout,
  157. bias="none",
  158. task_type="CAUSAL_LM"
  159. )
  160. try:
  161. lora_model = get_peft_model(shared.model, config)
  162. except:
  163. yield traceback.format_exc()
  164. return
  165. trainer = transformers.Trainer(
  166. model=lora_model,
  167. train_dataset=train_data,
  168. eval_dataset=eval_data,
  169. args=transformers.TrainingArguments(
  170. per_device_train_batch_size=micro_batch_size,
  171. gradient_accumulation_steps=gradient_accumulation_steps,
  172. # TODO: Should more of these be configurable? Probably.
  173. warmup_steps=100,
  174. num_train_epochs=epochs,
  175. learning_rate=actual_lr,
  176. fp16=True,
  177. logging_steps=20,
  178. evaluation_strategy="steps" if eval_data is not None else "no",
  179. save_strategy="steps",
  180. eval_steps=200 if eval_data is not None else None,
  181. save_steps=200,
  182. output_dir=lora_name,
  183. save_total_limit=3,
  184. load_best_model_at_end=True if eval_data is not None else False,
  185. # TODO: Enable multi-device support
  186. ddp_find_unused_parameters=None
  187. ),
  188. data_collator=transformers.DataCollatorForLanguageModeling(shared.tokenizer, mlm=False),
  189. callbacks=list([Callbacks()])
  190. )
  191. lora_model.config.use_cache = False
  192. old_state_dict = lora_model.state_dict
  193. lora_model.state_dict = (
  194. lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict())
  195. ).__get__(lora_model, type(lora_model))
  196. if torch.__version__ >= "2" and sys.platform != "win32":
  197. lora_model = torch.compile(lora_model)
  198. # == Main run and monitor loop ==
  199. # TODO: save/load checkpoints to resume from?
  200. print("Starting training...")
  201. yield "Starting..."
  202. def threadedRun():
  203. trainer.train()
  204. thread = threading.Thread(target=threadedRun)
  205. thread.start()
  206. lastStep = 0
  207. startTime = time.perf_counter()
  208. while thread.is_alive():
  209. time.sleep(0.5)
  210. if WANT_INTERRUPT:
  211. yield "Interrupting, please wait... *(Run will stop after the current training step completes.)*"
  212. elif CURRENT_STEPS != lastStep:
  213. lastStep = CURRENT_STEPS
  214. timeElapsed = time.perf_counter() - startTime
  215. if timeElapsed <= 0:
  216. timerInfo = ""
  217. totalTimeEstimate = 999
  218. else:
  219. its = CURRENT_STEPS / timeElapsed
  220. if its > 1:
  221. timerInfo = f"`{its:.2f}` it/s"
  222. else:
  223. timerInfo = f"`{1.0/its:.2f}` s/it"
  224. totalTimeEstimate = (1.0/its) * (MAX_STEPS)
  225. yield f"Running... **{CURRENT_STEPS}** / **{MAX_STEPS}** ... {timerInfo}, `{timeElapsed:.0f}`/`{totalTimeEstimate:.0f}` seconds"
  226. print("Training complete, saving...")
  227. lora_model.save_pretrained(lora_name)
  228. if WANT_INTERRUPT:
  229. print("Training interrupted.")
  230. yield f"Interrupted. Incomplete LoRA saved to `{lora_name}`"
  231. else:
  232. print("Training complete!")
  233. yield f"Done! LoRA saved to `{lora_name}`"
  234. def split_chunks(arr, step):
  235. for i in range(0, len(arr), step):
  236. yield arr[i:i + step]