training.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. # TODO: Add explanations of batch sizes and recommendations. Note that batch/microBatch determines gradient accumulation and explain what that means. Note the effects on VRAM usage from changing these values.
  16. microBatchSize = gr.Slider(label='Micro Batch Size', value=4, minimum=1, maximum=128, step=1, info='(TODO)')
  17. batchSize = gr.Slider(label='Batch Size', value=128, minimum=1, maximum=1024, step=4, info='(TODO)')
  18. epochs = gr.Slider(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.')
  19. 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.')
  20. # TODO: What is the actual maximum rank? Likely distinct per model. This might be better to somehow be on a log scale.
  21. 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.')
  22. 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.')
  23. # TODO: Better explain what this does.
  24. 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.')
  25. 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.')
  26. with gr.Row():
  27. datasetFunction = get_json_dataset('training/datasets')
  28. dataset = gr.Dropdown(choices=datasetFunction(), value='None', label='Dataset')
  29. ui.create_refresh_button(dataset, lambda : None, lambda : {'choices': datasetFunction()}, 'refresh-button')
  30. with gr.Row():
  31. evalDataset = gr.Dropdown(choices=datasetFunction(), value='None', label='Evaluation Dataset')
  32. ui.create_refresh_button(evalDataset, lambda : None, lambda : {'choices': datasetFunction()}, 'refresh-button')
  33. with gr.Row():
  34. formatsFunction = get_json_dataset('training/formats')
  35. format = gr.Dropdown(choices=formatsFunction(), value='None', label='Data Format')
  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. model = shared.model
  59. tokenizer = shared.tokenizer
  60. tokenizer.pad_token = 0
  61. tokenizer.padding_side = "left"
  62. # Prep the dataset, format, etc
  63. with open(cleanPath('training/formats', f'{format}.json'), 'r') as formatFile:
  64. formatData: dict[str, str] = json.load(formatFile)
  65. def tokenize(prompt):
  66. result = tokenizer(prompt, truncation=True, max_length=cutoffLen + 1, padding="max_length")
  67. return {
  68. "input_ids": result["input_ids"][:-1],
  69. "attention_mask": result["attention_mask"][:-1],
  70. }
  71. def generate_prompt(data_point: dict[str, str]):
  72. for options, data in formatData.items():
  73. if set(options.split(',')) == set(data_point.keys()):
  74. for key, val in data_point.items():
  75. data = data.replace(f'%{key}%', val)
  76. return data
  77. raise RuntimeError(f'Data-point "{data_point}" has no keyset match within format "{list(formatData.keys())}"')
  78. def generate_and_tokenize_prompt(data_point):
  79. prompt = generate_prompt(data_point)
  80. return tokenize(prompt)
  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. model = prepare_model_for_int8_training(model)
  90. config = LoraConfig(
  91. r=loraRank,
  92. lora_alpha=loraAlpha,
  93. # TODO: Should target_modules be configurable?
  94. target_modules=[ "q_proj", "v_proj" ],
  95. lora_dropout=loraDropout,
  96. bias="none",
  97. task_type="CAUSAL_LM"
  98. )
  99. model = get_peft_model(model, config)
  100. trainer = transformers.Trainer(
  101. model=model,
  102. train_dataset=train_data,
  103. eval_dataset=evalData,
  104. args=transformers.TrainingArguments(
  105. per_device_train_batch_size=microBatchSize,
  106. gradient_accumulation_steps=gradientAccumulationSteps,
  107. # TODO: Should more of these be configurable? Probably.
  108. warmup_steps=100,
  109. num_train_epochs=epochs,
  110. learning_rate=actualLR,
  111. fp16=True,
  112. logging_steps=20,
  113. evaluation_strategy="steps" if evalData is not None else "no",
  114. save_strategy="steps",
  115. eval_steps=200 if evalData is not None else None,
  116. save_steps=200,
  117. output_dir=loraName,
  118. save_total_limit=3,
  119. load_best_model_at_end=True if evalData is not None else False,
  120. # TODO: Enable multi-device support
  121. ddp_find_unused_parameters=None,
  122. ),
  123. data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),
  124. )
  125. model.config.use_cache = False
  126. old_state_dict = model.state_dict
  127. model.state_dict = (
  128. lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict())
  129. ).__get__(model, type(model))
  130. if torch.__version__ >= "2" and sys.platform != "win32":
  131. model = torch.compile(model)
  132. # Actually start and run and save at the end
  133. trainer.train()
  134. model.save_pretrained(loraName)
  135. return "Done!"