training.py 9.1 KB

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