training.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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, minimum=1, maximum=1000, 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. # Input validation / processing
  50. # TODO: --lora-dir PR once pulled will need to be applied here
  51. loraName = f"loras/{cleanPath(None, loraName)}"
  52. if dataset is None:
  53. return "**Missing dataset choice input, cannot continue.**"
  54. if format is None:
  55. return "**Missing format choice input, cannot continue.**"
  56. gradientAccumulationSteps = batchSize // microBatchSize
  57. actualLR = float(learningRate)
  58. shared.tokenizer.pad_token = 0
  59. shared.tokenizer.padding_side = "left"
  60. # Prep the dataset, format, etc
  61. with open(cleanPath('training/formats', f'{format}.json'), 'r') as formatFile:
  62. formatData: dict[str, str] = json.load(formatFile)
  63. def tokenize(prompt):
  64. result = shared.tokenizer(prompt, truncation=True, max_length=cutoffLen + 1, padding="max_length")
  65. return {
  66. "input_ids": result["input_ids"][:-1],
  67. "attention_mask": result["attention_mask"][:-1],
  68. }
  69. def generate_prompt(data_point: dict[str, str]):
  70. for options, data in formatData.items():
  71. if set(options.split(',')) == set(x[0] for x in data_point.items() if len(x[1].strip()) > 0):
  72. for key, val in data_point.items():
  73. data = data.replace(f'%{key}%', val)
  74. return data
  75. raise RuntimeError(f'Data-point "{data_point}" has no keyset match within format "{list(formatData.keys())}"')
  76. def generate_and_tokenize_prompt(data_point):
  77. prompt = generate_prompt(data_point)
  78. return tokenize(prompt)
  79. data = load_dataset("json", data_files=cleanPath('training/datasets', f'{dataset}.json'))
  80. train_data = data['train'].shuffle().map(generate_and_tokenize_prompt)
  81. if evalDataset == 'None':
  82. evalData = None
  83. else:
  84. evalData = load_dataset("json", data_files=cleanPath('training/datasets', f'{evalDataset}.json'))
  85. evalData = evalData['train'].shuffle().map(generate_and_tokenize_prompt)
  86. # Start prepping the model itself
  87. if not hasattr(shared.model, 'lm_head') or hasattr(shared.model.lm_head, 'weight'):
  88. prepare_model_for_int8_training(shared.model)
  89. config = LoraConfig(
  90. r=loraRank,
  91. lora_alpha=loraAlpha,
  92. # TODO: Should target_modules be configurable?
  93. target_modules=[ "q_proj", "v_proj" ],
  94. lora_dropout=loraDropout,
  95. bias="none",
  96. task_type="CAUSAL_LM"
  97. )
  98. loraModel = get_peft_model(shared.model, config)
  99. trainer = transformers.Trainer(
  100. model=loraModel,
  101. train_dataset=train_data,
  102. eval_dataset=evalData,
  103. args=transformers.TrainingArguments(
  104. per_device_train_batch_size=microBatchSize,
  105. gradient_accumulation_steps=gradientAccumulationSteps,
  106. # TODO: Should more of these be configurable? Probably.
  107. warmup_steps=100,
  108. num_train_epochs=epochs,
  109. learning_rate=actualLR,
  110. fp16=True,
  111. logging_steps=20,
  112. evaluation_strategy="steps" if evalData is not None else "no",
  113. save_strategy="steps",
  114. eval_steps=200 if evalData is not None else None,
  115. save_steps=200,
  116. output_dir=loraName,
  117. save_total_limit=3,
  118. load_best_model_at_end=True if evalData is not None else False,
  119. # TODO: Enable multi-device support
  120. ddp_find_unused_parameters=None,
  121. ),
  122. data_collator=transformers.DataCollatorForLanguageModeling(shared.tokenizer, mlm=False),
  123. )
  124. loraModel.config.use_cache = False
  125. old_state_dict = loraModel.state_dict
  126. loraModel.state_dict = (
  127. lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict())
  128. ).__get__(loraModel, type(loraModel))
  129. if torch.__version__ >= "2" and sys.platform != "win32":
  130. loraModel = torch.compile(loraModel)
  131. # Actually start and run and save at the end
  132. trainer.train()
  133. loraModel.save_pretrained(loraName)
  134. return "Done!"