training.py 10 KB

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