2023-07-12 10:19:12 -04:00
import os
os . environ [ " WANDB_MODE " ] = " offline "
2023-07-12 10:53:31 -04:00
# os.environ["WANDB_DISABLED"] = "true"
2023-07-12 10:19:12 -04:00
2023-03-27 20:24:39 -04:00
import json
2023-04-16 01:35:13 -04:00
import math
2023-05-24 11:43:22 -04:00
import random
2023-07-11 21:49:06 -04:00
import shutil
2023-03-27 20:24:39 -04:00
import sys
import threading
import time
2023-03-29 10:55:34 -04:00
import traceback
2023-07-11 21:49:06 -04:00
from datetime import datetime
2023-03-25 15:08:26 -04:00
from pathlib import Path
2023-03-27 20:24:39 -04:00
2023-03-25 15:08:26 -04:00
import gradio as gr
2023-03-27 20:24:39 -04:00
import torch
2023-03-25 15:08:26 -04:00
import transformers
2023-03-28 01:15:32 -04:00
from datasets import Dataset , load_dataset
2023-06-25 00:44:36 -04:00
from peft import (
LoraConfig ,
get_peft_model ,
2023-08-22 16:14:59 -04:00
prepare_model_for_kbit_training ,
2023-06-25 00:44:36 -04:00
set_peft_model_state_dict
)
2023-08-18 15:58:38 -04:00
from peft . utils . other import \
TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING as model_to_lora_modules
2023-10-26 22:39:51 -04:00
from transformers import is_torch_xpu_available
2023-08-18 15:58:38 -04:00
from transformers . models . auto . modeling_auto import (
MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
)
2023-03-27 20:24:39 -04:00
2023-05-05 22:14:56 -04:00
from modules import shared , ui , utils
2023-06-25 00:44:36 -04:00
from modules . evaluate import (
calculate_perplexity ,
generate_markdown_table ,
save_past_evaluations
)
2023-05-21 21:42:34 -04:00
from modules . logging_colors import logger
2023-08-18 15:58:38 -04:00
from modules . models import reload_model
2023-07-12 10:44:30 -04:00
from modules . utils import natural_keys
2023-03-25 15:08:26 -04:00
2023-08-18 15:58:38 -04:00
MODEL_CLASSES = { v [ 1 ] : v [ 0 ] for v in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES . items ( ) }
2023-10-22 14:57:19 -04:00
PARAMETERS = [ " lora_name " , " always_override " , " q_proj_en " , " v_proj_en " , " k_proj_en " , " o_proj_en " , " gate_proj_en " , " down_proj_en " , " up_proj_en " , " save_steps " , " micro_batch_size " , " batch_size " , " epochs " , " learning_rate " , " lr_scheduler_type " , " lora_rank " , " lora_alpha " , " lora_dropout " , " cutoff_len " , " dataset " , " eval_dataset " , " format " , " eval_steps " , " raw_text_file " , " overlap_len " , " newline_favor_len " , " higher_rank_limit " , " warmup_steps " , " optimizer " , " hard_cut_string " , " train_only_after " , " stop_at_loss " , " add_eos_token " , " min_chars " , " report_to " ]
2023-08-18 15:58:38 -04:00
WANT_INTERRUPT = False
2023-04-16 01:46:27 -04:00
2023-06-19 23:47:36 -04:00
train_log = { }
2023-06-25 14:34:46 -04:00
train_template = { }
2023-03-27 13:25:08 -04:00
2023-04-16 01:35:13 -04:00
2023-08-06 20:49:27 -04:00
def create_ui ( ) :
2023-09-26 08:44:04 -04:00
mu = shared . args . multi_user
2023-08-06 20:49:27 -04:00
with gr . Tab ( " Training " , elem_id = " training-tab " ) :
with gr . Tab ( ' Train LoRA ' , elem_id = ' lora-train-tab ' ) :
2023-08-18 15:58:38 -04:00
tmp = gr . State ( ' ' )
2023-03-28 01:15:32 -04:00
with gr . Row ( ) :
2023-08-18 15:58:38 -04:00
with gr . Column ( ) :
2023-10-23 13:09:57 -04:00
gr . Markdown ( " [Tutorial](https://github.com/oobabooga/text-generation-webui/wiki/05- %E 2 %80% 90-Training-Tab) " )
2023-04-16 01:46:27 -04:00
2023-08-18 15:58:38 -04:00
with gr . Row ( ) :
2023-09-26 08:44:04 -04:00
copy_from = gr . Dropdown ( label = ' Copy parameters from ' , value = ' None ' , choices = utils . get_available_loras ( ) , elem_classes = [ ' slim-dropdown ' ] , interactive = not mu )
ui . create_refresh_button ( copy_from , lambda : None , lambda : { ' choices ' : utils . get_available_loras ( ) } , ' refresh-button ' , interactive = not mu )
2023-04-06 01:04:11 -04:00
2023-08-18 15:58:38 -04:00
with gr . Row ( ) :
with gr . Column ( scale = 5 ) :
lora_name = gr . Textbox ( label = ' Name ' , info = ' The name of your new LoRA file ' )
with gr . Column ( ) :
2023-08-22 23:18:16 -04:00
always_override = gr . Checkbox ( label = ' Override Existing Files ' , value = False , info = ' If the name is the same, checking will replace the existing file, and unchecking will load and continue from it (the rank must be the same). ' , elem_classes = [ ' no-background ' ] )
2023-04-16 01:46:27 -04:00
2023-10-22 14:57:19 -04:00
with gr . Accordion ( label = ' Target Modules ' , open = False ) :
gr . Markdown ( " Selects which modules to target in training. Targeting more modules is closer to a full fine-tune at the cost of increased VRAM requirements and adapter size. \n NOTE: Only works for model_id= ' llama ' , other types will retain default training behavior and not use these settings. " )
with gr . Row ( ) :
with gr . Column ( ) :
q_proj_en = gr . Checkbox ( label = ' Enable q_proj ' , value = True )
with gr . Column ( ) :
v_proj_en = gr . Checkbox ( label = ' Enable v_proj ' , value = True )
with gr . Column ( ) :
k_proj_en = gr . Checkbox ( label = ' Enable k_proj ' , value = False )
with gr . Column ( ) :
o_proj_en = gr . Checkbox ( label = ' Enable o_proj ' , value = False )
with gr . Column ( ) :
gate_proj_en = gr . Checkbox ( label = ' Enable gate_proj ' , value = False )
with gr . Column ( ) :
down_proj_en = gr . Checkbox ( label = ' Enable down_proj ' , value = False )
with gr . Column ( ) :
up_proj_en = gr . Checkbox ( label = ' Enable up_proj ' , value = False )
2023-08-18 15:58:38 -04:00
with gr . Row ( ) :
with gr . Column ( ) :
lora_rank = gr . Slider ( label = ' LoRA Rank ' , value = 32 , minimum = 0 , maximum = 1024 , step = 4 , info = ' Also called dimension count. Higher values = larger file, more content control. Smaller values = smaller file, less control. Use 4 or 8 for style, 128 or 256 to teach, 1024+ for fine-detail on big data. More VRAM is needed for higher ranks. ' )
lora_alpha = gr . Slider ( label = ' LoRA Alpha ' , value = 64 , minimum = 0 , maximum = 2048 , step = 4 , info = ' This divided by the rank becomes the scaling of the LoRA. Higher means stronger. A good standard value is twice your Rank. ' )
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. ' )
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. ' )
2023-10-22 14:57:19 -04:00
cutoff_len = gr . Slider ( label = ' Cutoff Length ' , minimum = 0 , maximum = 4096 , 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. ' )
2023-04-20 23:20:33 -04:00
2023-08-18 15:58:38 -04:00
with gr . Column ( ) :
save_steps = gr . Number ( label = ' Save every n steps ' , value = 0 , info = ' If above 0, a checkpoint of the LoRA will be saved every time this many steps pass. ' )
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. ' )
learning_rate = gr . Textbox ( label = ' Learning Rate ' , value = ' 3e-4 ' , info = ' In scientific notation. 3e-4 is a good starting base point. 1e-2 is extremely high, 1e-6 is extremely low. ' )
2023-10-10 21:20:49 -04:00
with gr . Row ( ) :
lr_scheduler_type = gr . Dropdown ( label = ' LR Scheduler ' , value = ' linear ' , choices = [ ' linear ' , ' constant ' , ' constant_with_warmup ' , ' cosine ' , ' cosine_with_restarts ' , ' polynomial ' , ' inverse_sqrt ' ] , info = ' Learning rate scheduler - defines how the learning rate changes over time. " Constant " means never change, " linear " means to go in a straight line from the learning rate down to 0, cosine follows a curve, etc. ' , elem_classes = [ ' slim-dropdown ' ] )
2023-07-12 14:29:43 -04:00
2023-08-18 15:58:38 -04:00
with gr . Accordion ( label = ' Advanced Options ' , open = False ) :
with gr . Row ( ) :
with gr . Column ( ) :
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. This can help reduce overfitting. Most users should leave at default. ' )
stop_at_loss = gr . Slider ( label = ' Stop at loss ' , minimum = 0.0 , maximum = 3.0 , step = 0.1 , value = 0.00 , info = ' The process will automatically stop once the desired loss value is reached. (reasonable numbers are 1.5-1.8) ' )
2023-10-10 21:20:49 -04:00
with gr . Row ( ) :
optimizer = gr . Dropdown ( label = ' Optimizer ' , value = ' adamw_torch ' , choices = [ ' adamw_hf ' , ' adamw_torch ' , ' adamw_torch_fused ' , ' adamw_torch_xla ' , ' adamw_apex_fused ' , ' adafactor ' , ' adamw_bnb_8bit ' , ' adamw_anyprecision ' , ' sgd ' , ' adagrad ' ] , info = ' Different optimizer implementation options, for advanced users. Effects of different options are not well documented yet. ' , elem_classes = [ ' slim-dropdown ' ] )
2023-08-18 15:58:38 -04:00
with gr . Column ( ) :
warmup_steps = gr . Number ( label = ' Warmup Steps ' , value = 100 , info = ' For this many steps at the start, the learning rate will be lower than normal. This helps the trainer prepare the model and precompute statistics to improve the quality of training after the start. ' )
train_only_after = gr . Textbox ( label = ' Train Only After ' , value = ' ' , info = ' Only consider text *after* this string in any given chunk for training. For Alpaca datasets, use " ### Response: " to only train the response and ignore the input. ' )
add_eos_token = gr . Checkbox ( label = ' Add EOS token ' , value = False , info = " Adds EOS token for each dataset item. In case of raw text, the EOS will be added at the Hard Cut " )
higher_rank_limit = gr . Checkbox ( label = ' Enable higher ranks ' , value = False , info = ' If checked, changes Rank/Alpha slider above to go much higher. This will not work without a datacenter-class GPU. ' )
report_to = gr . Radio ( label = " Save detailed logs with " , value = " None " , choices = [ " None " , " wandb " , " tensorboard " ] , interactive = True )
with gr . Column ( ) :
with gr . Tab ( label = ' Formatted Dataset ' ) :
with gr . Row ( ) :
2023-09-26 08:44:04 -04:00
format = gr . Dropdown ( choices = utils . get_datasets ( ' training/formats ' , ' json ' ) , value = ' None ' , label = ' Data Format ' , info = ' The format file used to decide how to format the dataset input. ' , elem_classes = [ ' slim-dropdown ' ] , interactive = not mu )
ui . create_refresh_button ( format , lambda : None , lambda : { ' choices ' : utils . get_datasets ( ' training/formats ' , ' json ' ) } , ' refresh-button ' , interactive = not mu )
2023-08-18 15:58:38 -04:00
with gr . Row ( ) :
2023-09-26 08:44:04 -04:00
dataset = gr . Dropdown ( choices = utils . get_datasets ( ' training/datasets ' , ' json ' ) , value = ' None ' , label = ' Dataset ' , info = ' The dataset file to use for training. ' , elem_classes = [ ' slim-dropdown ' ] , interactive = not mu )
ui . create_refresh_button ( dataset , lambda : None , lambda : { ' choices ' : utils . get_datasets ( ' training/datasets ' , ' json ' ) } , ' refresh-button ' , interactive = not mu )
2023-08-18 15:58:38 -04:00
with gr . Row ( ) :
2023-09-26 08:44:04 -04:00
eval_dataset = gr . Dropdown ( choices = utils . get_datasets ( ' training/datasets ' , ' json ' ) , value = ' None ' , label = ' Evaluation Dataset ' , info = ' The (optional) dataset file used to evaluate the model after training. ' , elem_classes = [ ' slim-dropdown ' ] , interactive = not mu )
ui . create_refresh_button ( eval_dataset , lambda : None , lambda : { ' choices ' : utils . get_datasets ( ' training/datasets ' , ' json ' ) } , ' refresh-button ' , interactive = not mu )
2023-08-18 15:58:38 -04:00
eval_steps = gr . Number ( label = ' Evaluate every n steps ' , value = 100 , info = ' If an evaluation dataset is given, test it every time this many steps pass. ' )
with gr . Tab ( label = " Raw text file " ) :
with gr . Row ( ) :
2023-09-26 08:44:04 -04:00
raw_text_file = gr . Dropdown ( choices = utils . get_datasets ( ' training/datasets ' , ' txt ' ) , value = ' None ' , label = ' Text file ' , info = ' The raw text file to use for training. ' , elem_classes = [ ' slim-dropdown ' ] , interactive = not mu )
ui . create_refresh_button ( raw_text_file , lambda : None , lambda : { ' choices ' : utils . get_datasets ( ' training/datasets ' , ' txt ' ) } , ' refresh-button ' , interactive = not mu )
2023-08-18 15:58:38 -04:00
with gr . Row ( ) :
with gr . Column ( ) :
overlap_len = gr . Slider ( label = ' Overlap Length ' , minimum = 0 , maximum = 512 , value = 128 , step = 16 , info = ' 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). Setting overlap to exactly half the cutoff length may be ideal. ' )
newline_favor_len = gr . Slider ( label = ' Prefer Newline Cut Length ' , minimum = 0 , maximum = 512 , value = 128 , step = 16 , info = ' Length (in characters, not tokens) of the maximum distance to shift an overlap cut by to ensure chunks cut at newlines. If too low, cuts may occur in the middle of lines. ' )
with gr . Column ( ) :
hard_cut_string = gr . Textbox ( label = ' Hard Cut String ' , value = ' \\ n \\ n \\ n ' , info = ' String that indicates a hard cut between text parts. Helps prevent unwanted overlap. ' )
min_chars = gr . Number ( label = ' Ignore small blocks ' , value = 0 , info = ' Ignore Hard Cut blocks that have less or equal characters than this number ' )
with gr . Row ( ) :
2023-09-26 08:44:04 -04:00
start_button = gr . Button ( " Start LoRA Training " , variant = ' primary ' , interactive = not mu )
stop_button = gr . Button ( " Interrupt " , interactive = not mu )
2023-08-18 15:58:38 -04:00
output = gr . Markdown ( value = " Ready " )
2023-08-06 20:49:27 -04:00
with gr . Tab ( ' Perplexity evaluation ' , elem_id = ' evaluate-tab ' ) :
with gr . Row ( ) :
with gr . Column ( ) :
2023-09-26 08:44:04 -04:00
models = gr . Dropdown ( utils . get_available_models ( ) , label = ' Models ' , multiselect = True , interactive = not mu )
evaluate_text_file = gr . Dropdown ( choices = [ ' wikitext ' , ' ptb ' , ' ptb_new ' ] + utils . get_datasets ( ' training/datasets ' , ' txt ' ) [ 1 : ] , value = ' wikitext ' , label = ' Input dataset ' , info = ' The raw text file on which the model will be evaluated. The first options are automatically downloaded: wikitext, ptb, and ptb_new. The next options are your local text files under training/datasets. ' , interactive = not mu )
2023-08-06 20:49:27 -04:00
with gr . Row ( ) :
2023-08-18 15:58:38 -04:00
with gr . Column ( ) :
2023-09-29 16:06:26 -04:00
stride_length = gr . Slider ( label = ' Stride ' , minimum = 0 , maximum = 32768 , value = 512 , step = 256 , info = ' Used to make the evaluation faster at the cost of accuracy. 1 = slowest but most accurate. 512 is a common value. ' )
2023-08-18 15:58:38 -04:00
with gr . Column ( ) :
2023-12-04 18:48:34 -05:00
max_length = gr . Slider ( label = ' max_length ' , minimum = 0 , maximum = shared . settings [ ' truncation_length_max ' ] , value = 0 , step = 256 , info = ' The context for each evaluation. If set to 0, the maximum context length for the model will be used. ' )
2023-08-06 20:49:27 -04:00
with gr . Row ( ) :
2023-09-26 08:44:04 -04:00
start_current_evaluation = gr . Button ( " Evaluate loaded model " , interactive = not mu )
start_evaluation = gr . Button ( " Evaluate selected models " , interactive = not mu )
stop_evaluation = gr . Button ( " Interrupt " , interactive = not mu )
2023-08-06 20:49:27 -04:00
with gr . Column ( ) :
evaluation_log = gr . Markdown ( value = ' ' )
2023-10-27 09:49:14 -04:00
evaluation_table = gr . Dataframe ( value = generate_markdown_table ( ) , interactive = True )
2023-08-06 20:49:27 -04:00
with gr . Row ( ) :
2023-09-26 08:44:04 -04:00
save_comments = gr . Button ( ' Save comments ' , elem_classes = " small-button " , interactive = not mu )
refresh_table = gr . Button ( ' Refresh the table ' , elem_classes = " small-button " , interactive = not mu )
2023-08-06 20:49:27 -04:00
# Training events
2023-10-22 14:57:19 -04:00
all_params = [ lora_name , always_override , q_proj_en , v_proj_en , k_proj_en , o_proj_en , gate_proj_en , down_proj_en , up_proj_en , save_steps , micro_batch_size , batch_size , epochs , learning_rate , lr_scheduler_type , lora_rank , lora_alpha , lora_dropout , cutoff_len , dataset , eval_dataset , format , eval_steps , raw_text_file , overlap_len , newline_favor_len , higher_rank_limit , warmup_steps , optimizer , hard_cut_string , train_only_after , stop_at_loss , add_eos_token , min_chars , report_to ]
2023-07-12 10:53:31 -04:00
2023-04-20 23:20:33 -04:00
copy_from . change ( do_copy_params , [ copy_from ] + all_params , all_params )
start_button . click ( do_train , all_params , output )
stop_button . click ( do_interrupt , None , None , queue = False )
higher_rank_limit . change ( change_rank_limit , [ higher_rank_limit ] , [ lora_rank , lora_alpha ] )
# Evaluation events. For some reason, the interrupt event
# doesn't work with the .then() syntax, so I write them one
# by one in this ugly but functional way.
ev = start_evaluation . click ( calculate_perplexity , [ models , evaluate_text_file , stride_length , max_length ] , evaluation_log , show_progress = False )
2024-02-21 23:27:25 -05:00
ev . then ( generate_markdown_table , None , evaluation_table , show_progress = False )
2023-04-20 23:20:33 -04:00
2024-02-21 23:27:25 -05:00
ev_cur = start_current_evaluation . click (
lambda : [ ' current model ' ] , None , tmp ) . then (
calculate_perplexity , [ tmp , evaluate_text_file , stride_length , max_length ] , evaluation_log , show_progress = False )
ev_cur . then ( generate_markdown_table , None , evaluation_table , show_progress = False )
2023-04-20 23:20:33 -04:00
stop_evaluation . click ( None , None , None , cancels = [ ev , ev_cur ] , queue = False )
2023-05-25 14:06:22 -04:00
refresh_table . click ( generate_markdown_table , None , evaluation_table , show_progress = True )
2023-04-20 23:20:33 -04:00
save_comments . click (
save_past_evaluations , evaluation_table , None ) . then (
lambda : " Comments saved. " , None , evaluation_log , show_progress = False )
2023-04-16 01:35:13 -04:00
2023-04-06 23:15:45 -04:00
2023-03-27 21:19:06 -04:00
def do_interrupt ( ) :
2023-03-27 13:43:01 -04:00
global WANT_INTERRUPT
WANT_INTERRUPT = True
2023-03-25 15:08:26 -04:00
2023-04-06 23:15:45 -04:00
2023-04-19 18:39:03 -04:00
def do_copy_params ( lora_name : str , * args ) :
f_name = f " { shared . args . lora_dir } / { clean_path ( None , lora_name ) } /training_parameters.json "
if Path ( f_name ) . is_file ( ) :
with open ( f_name , ' r ' , encoding = ' utf-8 ' ) as format_file :
params : dict [ str , str ] = json . load ( format_file )
else :
params = { }
result = list ( )
for i in range ( 0 , len ( PARAMETERS ) ) :
key = PARAMETERS [ i ]
if key in params :
result . append ( params [ key ] )
else :
result . append ( args [ i ] )
2023-04-20 23:20:33 -04:00
2023-04-19 18:39:03 -04:00
return result
def change_rank_limit ( use_higher_ranks : bool ) :
mult = 2 if use_higher_ranks else 1
return { " maximum " : 1024 * mult , " __type__ " : " update " } , { " maximum " : 2048 * mult , " __type__ " : " update " }
2023-03-27 21:19:06 -04:00
def clean_path ( base_path : str , path : str ) :
2023-05-19 11:58:54 -04:00
""" Strips unusual symbols and forcibly builds a path as relative to the intended directory. """
2023-03-25 15:08:26 -04:00
path = path . replace ( ' \\ ' , ' / ' ) . replace ( ' .. ' , ' _ ' )
2023-03-27 21:17:42 -04:00
if base_path is None :
2023-03-25 15:08:26 -04:00
return path
2023-04-16 01:46:27 -04:00
2023-03-27 21:17:42 -04:00
return f ' { Path ( base_path ) . absolute ( ) } / { path } '
2023-03-25 15:08:26 -04:00
2023-04-06 23:15:45 -04:00
2023-06-27 17:24:04 -04:00
def backup_adapter ( input_folder ) :
# Get the creation date of the file adapter_model.bin
try :
adapter_file = Path ( f " { input_folder } /adapter_model.bin " )
if adapter_file . is_file ( ) :
2023-12-19 23:54:32 -05:00
logger . info ( " Backing up existing LoRA adapter " )
2023-06-27 17:24:04 -04:00
creation_date = datetime . fromtimestamp ( adapter_file . stat ( ) . st_ctime )
creation_date_str = creation_date . strftime ( " Backup- % Y- % m- %d " )
# Create the new subfolder
2023-07-11 21:49:06 -04:00
subfolder_path = Path ( f " { input_folder } / { creation_date_str } " )
2023-06-27 17:24:04 -04:00
subfolder_path . mkdir ( parents = True , exist_ok = True )
# Check if the file already exists in the subfolder
backup_adapter_file = Path ( f " { input_folder } / { creation_date_str } /adapter_model.bin " )
if backup_adapter_file . is_file ( ) :
print ( " - Backup already exists. Skipping backup process. " )
return
# Copy existing files to the new subfolder
existing_files = Path ( input_folder ) . iterdir ( )
for file in existing_files :
if file . is_file ( ) :
shutil . copy2 ( file , subfolder_path )
except Exception as e :
print ( " An error occurred in backup_adapter: " , str ( e ) )
2023-07-11 21:49:06 -04:00
2023-07-03 16:38:36 -04:00
def calc_trainable_parameters ( model ) :
trainable_params = 0
all_param = 0
for _ , param in model . named_parameters ( ) :
num_params = param . numel ( )
# if using DS Zero 3 and the weights are initialized empty
if num_params == 0 and hasattr ( param , " ds_numel " ) :
num_params = param . ds_numel
all_param + = num_params
if param . requires_grad :
trainable_params + = num_params
2023-07-11 21:49:06 -04:00
return trainable_params , all_param
2023-07-03 16:38:36 -04:00
2023-06-27 17:24:04 -04:00
2023-10-22 14:57:19 -04:00
def do_train ( lora_name : str , always_override : bool , q_proj_en : bool , v_proj_en : bool , k_proj_en : bool , o_proj_en : bool , gate_proj_en : bool , down_proj_en : bool , up_proj_en : bool , save_steps : int , micro_batch_size : int , batch_size : int , epochs : int , learning_rate : str , lr_scheduler_type : str , lora_rank : int , lora_alpha : int , lora_dropout : float , cutoff_len : int , dataset : str , eval_dataset : str , format : str , eval_steps : int , raw_text_file : str , overlap_len : int , newline_favor_len : int , higher_rank_limit : bool , warmup_steps : int , optimizer : str , hard_cut_string : str , train_only_after : str , stop_at_loss : float , add_eos_token : bool , min_chars : int , report_to : str ) :
2023-04-19 18:39:03 -04:00
if shared . args . monkey_patch :
2023-09-11 00:22:20 -04:00
from alpaca_lora_4bit . monkeypatch . peft_tuners_lora_monkey_patch import (
replace_peft_model_with_int4_lora_model
2023-06-25 00:44:36 -04:00
)
2023-09-11 00:22:20 -04:00
replace_peft_model_with_int4_lora_model ( )
2023-04-19 18:39:03 -04:00
2023-04-16 01:35:13 -04:00
global WANT_INTERRUPT
2023-03-27 13:43:01 -04:00
WANT_INTERRUPT = False
2023-03-27 21:17:42 -04:00
2023-03-27 13:25:08 -04:00
# == Input validation / processing ==
2023-08-18 15:58:38 -04:00
yield " Preparing the input... "
2023-04-19 18:39:03 -04:00
lora_file_path = clean_path ( None , lora_name )
if lora_file_path . strip ( ) == ' ' :
yield " Missing or invalid LoRA file name input. "
return
2023-08-18 15:58:38 -04:00
lora_file_path = f " { Path ( shared . args . lora_dir ) } / { lora_file_path } "
2023-03-28 01:15:32 -04:00
actual_lr = float ( learning_rate )
2023-04-06 01:04:11 -04:00
model_type = type ( shared . model ) . __name__
2023-04-16 02:08:37 -04:00
2023-04-16 01:35:13 -04:00
if model_type in MODEL_CLASSES :
model_id = MODEL_CLASSES [ model_type ]
else :
2023-04-17 20:40:46 -04:00
model_id = " llama "
2023-04-06 01:04:11 -04:00
if model_type == " PeftModelForCausalLM " :
2023-07-03 16:41:18 -04:00
if len ( shared . lora_names ) > 0 :
2023-04-23 11:54:41 -04:00
yield " You are trying to train a LoRA while you already have another LoRA loaded. This will work, but may have unexpected effects. *(Will continue anyway in 5 seconds, press `Interrupt` to stop.)* "
2023-05-21 21:42:34 -04:00
logger . warning ( " Training LoRA over top of another LoRA. May have unexpected effects. " )
2023-04-23 11:54:41 -04:00
else :
yield " Model ID not matched due to LoRA loading. Consider reloading base model. *(Will continue anyway in 5 seconds, press `Interrupt` to stop.)* "
2023-05-21 21:42:34 -04:00
logger . warning ( " Model ID not matched due to LoRA loading. Consider reloading base model. " )
2023-04-06 01:04:11 -04:00
else :
2023-04-23 11:54:41 -04:00
yield " LoRA training has only currently been validated for LLaMA, OPT, GPT-J, and GPT-NeoX models. Unexpected errors may follow. *(Will continue anyway in 5 seconds, press `Interrupt` to stop.)* "
2023-05-21 21:42:34 -04:00
logger . warning ( f " LoRA training has only currently been validated for LLaMA, OPT, GPT-J, and GPT-NeoX models. (Found model type: { model_type } ) " )
2023-05-03 20:43:17 -04:00
2023-04-06 01:04:11 -04:00
time . sleep ( 5 )
2023-08-22 16:16:44 -04:00
if shared . args . loader == ' GPTQ-for-LLaMa ' and not shared . args . monkey_patch :
yield " LoRA training with GPTQ-for-LLaMa requires loading with `--monkey-patch` "
2023-04-06 01:04:11 -04:00
return
2023-03-28 01:15:32 -04:00
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 :
2023-04-02 23:54:56 -04:00
yield " Cannot input zeroes. "
2023-03-28 01:15:32 -04:00
return
2023-03-27 21:17:42 -04:00
gradient_accumulation_steps = batch_size / / micro_batch_size
2023-05-02 22:16:08 -04:00
shared . tokenizer . pad_token_id = 0
2023-03-25 15:57:36 -04:00
shared . tokenizer . padding_side = " left "
2023-03-27 21:17:42 -04:00
2023-10-22 14:57:19 -04:00
# Populate target_modules list with chosen X_proj modules. Llama-based models only atm, non-llama will revert to default behavior.
def list_target_modules ( model_id ) :
2024-01-03 18:42:20 -05:00
if model_id != " llama " and model_id != " mistral " :
2023-10-22 14:57:19 -04:00
return model_to_lora_modules [ model_id ]
available_modules = {
" gate " : gate_proj_en ,
" down " : down_proj_en ,
" up " : up_proj_en ,
" q " : q_proj_en ,
" v " : v_proj_en ,
" k " : k_proj_en ,
" o " : o_proj_en ,
}
target_mods = [ f " { name } _proj " for name , enabled in available_modules . items ( ) if enabled ]
return target_mods
2023-05-24 11:43:22 -04:00
def encode ( text , add_bos_token ) :
result = shared . tokenizer . encode ( text , truncation = True , max_length = cutoff_len )
2023-07-12 14:29:43 -04:00
# Check if the first two tokens are BOS
if len ( result ) > = 2 and result [ : 2 ] == [ shared . tokenizer . bos_token_id , shared . tokenizer . bos_token_id ] :
result = result [ 1 : ]
2023-05-24 11:43:22 -04:00
if not add_bos_token and result [ 0 ] == shared . tokenizer . bos_token_id :
result = result [ 1 : ]
return result
2023-07-12 14:29:43 -04:00
def tokenize ( prompt , append_eos_token = False ) :
2023-05-24 11:43:22 -04:00
if train_only_after == ' ' or train_only_after not in prompt :
input_ids = encode ( prompt , True )
2023-07-12 14:29:43 -04:00
if append_eos_token and input_ids [ - 1 ] != shared . tokenizer . eos_token_id and len ( input_ids ) < cutoff_len :
input_ids . append ( shared . tokenizer . eos_token_id )
2023-05-24 11:43:22 -04:00
input_ids = [ shared . tokenizer . pad_token_id ] * ( cutoff_len - len ( input_ids ) ) + input_ids
labels = [ 1 ] * len ( input_ids )
else :
ind = prompt . index ( train_only_after ) + len ( train_only_after )
2023-05-24 12:54:36 -04:00
before_tokens = encode ( prompt [ : ind ] , True )
2023-05-24 11:43:22 -04:00
after_tokens = encode ( prompt [ ind : ] , False )
2023-07-12 14:29:43 -04:00
if append_eos_token and after_tokens [ - 1 ] != shared . tokenizer . eos_token_id :
after_tokens . append ( shared . tokenizer . eos_token_id )
2023-05-24 11:43:22 -04:00
full_length = len ( after_tokens ) + len ( before_tokens )
if full_length > cutoff_len :
after_tokens = after_tokens [ : cutoff_len - len ( before_tokens ) ]
else :
before_tokens = [ shared . tokenizer . pad_token_id ] * ( cutoff_len - full_length ) + before_tokens
input_ids = before_tokens + after_tokens
labels = [ - 100 ] * len ( before_tokens ) + [ 1 ] * len ( after_tokens )
input_ids = torch . tensor ( input_ids )
2023-03-25 15:08:26 -04:00
return {
2023-05-24 11:43:22 -04:00
" input_ids " : input_ids ,
" labels " : labels ,
" attention_mask " : input_ids . ne ( shared . tokenizer . pad_token_id ) ,
2023-03-25 15:08:26 -04:00
}
2023-03-27 21:17:42 -04:00
2023-06-25 14:34:46 -04:00
train_template . clear ( )
2023-03-28 01:15:32 -04:00
# == Prep the dataset, format, etc ==
2023-03-29 10:48:17 -04:00
if raw_text_file not in [ ' None ' , ' ' ] :
2023-06-25 14:34:46 -04:00
train_template [ " template_type " ] = " raw_text "
2023-12-19 23:54:32 -05:00
logger . info ( " Loading raw text file dataset " )
2023-07-12 10:44:30 -04:00
fullpath = clean_path ( ' training/datasets ' , f ' { raw_text_file } ' )
fullpath = Path ( fullpath )
if fullpath . is_dir ( ) :
logger . info ( ' Training path directory {} ' . format ( raw_text_file ) )
raw_text = " "
file_paths = sorted ( fullpath . glob ( ' *.txt ' ) , key = lambda path : natural_keys ( path . name ) )
for file_path in file_paths :
if file_path . is_file ( ) :
with file_path . open ( ' r ' , encoding = ' utf-8 ' ) as file :
2023-07-12 12:52:20 -04:00
raw_text + = file . read ( ) . replace ( ' \r ' , ' ' )
2023-07-12 10:44:30 -04:00
logger . info ( f " Loaded training file: { file_path . name } " )
else :
with open ( clean_path ( ' training/datasets ' , f ' { raw_text_file } .txt ' ) , ' r ' , encoding = ' utf-8 ' ) as file :
2023-07-12 12:52:20 -04:00
raw_text = file . read ( ) . replace ( ' \r ' , ' ' )
2023-04-16 01:46:27 -04:00
2023-05-19 11:58:54 -04:00
cut_string = hard_cut_string . replace ( ' \\ n ' , ' \n ' )
2023-07-12 14:29:43 -04:00
eos_added = 0
2023-05-19 11:58:54 -04:00
out_tokens = [ ]
for text_part in raw_text . split ( cut_string ) :
2023-07-12 14:29:43 -04:00
if len ( text_part . strip ( ) ) < = min_chars :
2023-05-19 11:58:54 -04:00
continue
tokens = shared . tokenizer . encode ( text_part )
2023-07-12 14:29:43 -04:00
if add_eos_token :
tokens . append ( shared . tokenizer . eos_token_id )
eos_added + = 1
2023-05-19 11:58:54 -04:00
step = cutoff_len - overlap_len
if step < = 0 :
yield f " Error: overlap_len ( { overlap_len } ) cannot be greater than or equal to cutoff_len ( { cutoff_len } ) "
return
2023-04-16 01:46:27 -04:00
2023-07-12 11:05:37 -04:00
out_tokens . extend ( split_chunks ( tokens , cutoff_len , step ) )
2023-05-19 11:58:54 -04:00
2023-07-12 14:29:43 -04:00
if eos_added > 0 :
print ( f " EOS added to { eos_added } text blocks " )
2023-05-19 11:58:54 -04:00
del raw_text # Note: could be a gig for a large dataset, so delete redundant data as we go to be safe on RAM
text_chunks = [ shared . tokenizer . decode ( x ) for x in out_tokens ]
del out_tokens
2023-04-06 01:04:11 -04:00
if newline_favor_len > 0 :
text_chunks = [ cut_chunk_for_newline ( x , newline_favor_len ) for x in text_chunks ]
train_data = Dataset . from_list ( [ tokenize ( x ) for x in text_chunks ] )
2023-03-28 01:15:32 -04:00
del text_chunks
2023-04-06 01:04:11 -04:00
eval_data = None
2023-03-28 01:15:32 -04:00
else :
2023-03-29 10:48:17 -04:00
if dataset in [ ' None ' , ' ' ] :
2023-08-18 15:58:38 -04:00
yield " Missing dataset choice input, cannot continue. "
2023-03-28 01:15:32 -04:00
return
2023-03-29 10:48:17 -04:00
if format in [ ' None ' , ' ' ] :
2023-08-18 15:58:38 -04:00
yield " Missing format choice input, cannot continue. "
2023-03-28 01:15:32 -04:00
return
2023-03-27 21:17:42 -04:00
2023-06-25 14:34:46 -04:00
train_template [ " template_type " ] = " dataset "
with open ( clean_path ( ' training/formats ' , f ' { format } .json ' ) , ' r ' , encoding = ' utf-8-sig ' ) as formatFile :
2023-03-29 10:48:17 -04:00
format_data : dict [ str , str ] = json . load ( formatFile )
2023-06-25 14:34:46 -04:00
# == store training prompt ==
for _ , value in format_data . items ( ) :
prompt_key = f " template_ { len ( train_template ) } "
train_template [ prompt_key ] = value
2023-03-28 01:15:32 -04:00
def generate_prompt ( data_point : dict [ str , str ] ) :
for options , data in format_data . items ( ) :
2023-07-25 18:00:25 -04:00
if set ( options . split ( ' , ' ) ) == set ( x [ 0 ] for x in data_point . items ( ) if ( type ( x [ 1 ] ) is str and len ( x [ 1 ] . strip ( ) ) > 0 ) ) :
2023-03-28 01:15:32 -04:00
for key , val in data_point . items ( ) :
2023-07-25 18:00:25 -04:00
if type ( val ) is str :
2023-04-12 10:38:01 -04:00
data = data . replace ( f ' % { key } % ' , val )
return data
2023-03-28 01:15:32 -04:00
raise RuntimeError ( f ' Data-point " { data_point } " has no keyset match within format " { list ( format_data . keys ( ) ) } " ' )
2023-03-27 21:17:42 -04:00
2023-03-28 01:15:32 -04:00
def generate_and_tokenize_prompt ( data_point ) :
prompt = generate_prompt ( data_point )
2023-07-12 14:29:43 -04:00
return tokenize ( prompt , add_eos_token )
2023-03-28 01:15:32 -04:00
2023-12-19 23:54:32 -05:00
logger . info ( " Loading JSON datasets " )
2023-03-28 01:15:32 -04:00
data = load_dataset ( " json " , data_files = clean_path ( ' training/datasets ' , f ' { dataset } .json ' ) )
2023-05-24 11:43:22 -04:00
train_data = data [ ' train ' ] . map ( generate_and_tokenize_prompt , new_fingerprint = ' %030x ' % random . randrange ( 16 * * 30 ) )
2023-03-28 01:15:32 -04:00
if eval_dataset == ' None ' :
eval_data = None
else :
eval_data = load_dataset ( " json " , data_files = clean_path ( ' training/datasets ' , f ' { eval_dataset } .json ' ) )
2023-05-24 11:43:22 -04:00
eval_data = eval_data [ ' train ' ] . map ( generate_and_tokenize_prompt , new_fingerprint = ' %030x ' % random . randrange ( 16 * * 30 ) )
2023-04-06 23:15:45 -04:00
2023-07-12 14:29:43 -04:00
# == We MUST reload model if it went through any previous training, even failed one ==
if shared . model_dirty_from_training :
selected_model = shared . model_name
if selected_model :
print ( " \033 [1;31;1m(Model has been modified by previous training, it needs to be reloaded...) \033 [0;37;0m " )
try :
yield f " Reloading { selected_model } ... "
2023-08-18 15:58:38 -04:00
reload_model ( )
2023-07-12 14:29:43 -04:00
if shared . model is not None :
print ( " Model reloaded OK, continue with training. " )
else :
return f " Failed to load { selected_model } . "
except :
exc = traceback . format_exc ( )
logger . error ( ' Failed to reload the model. ' )
print ( exc )
2023-08-03 09:57:21 -04:00
return exc . replace ( ' \n ' , ' \n \n ' )
2023-07-12 14:29:43 -04:00
2023-03-27 13:25:08 -04:00
# == Start prepping the model itself ==
2023-03-25 15:57:36 -04:00
if not hasattr ( shared . model , ' lm_head ' ) or hasattr ( shared . model . lm_head , ' weight ' ) :
2023-12-19 23:54:32 -05:00
logger . info ( " Getting model ready " )
2024-01-03 18:42:20 -05:00
if ' quantization_config ' in shared . model . config . to_dict ( ) :
prepare_model_for_kbit_training ( shared . model )
2023-04-06 23:15:45 -04:00
2023-07-12 14:29:43 -04:00
# base model is now frozen and should not be reused for any other LoRA training than this one
shared . model_dirty_from_training = True
2023-12-19 23:54:32 -05:00
logger . info ( " Preparing for training " )
2023-03-25 15:08:26 -04:00
config = LoraConfig (
2023-03-27 21:17:42 -04:00
r = lora_rank ,
lora_alpha = lora_alpha ,
2023-10-22 14:57:19 -04:00
target_modules = list_target_modules ( model_id ) ,
2023-03-27 21:17:42 -04:00
lora_dropout = lora_dropout ,
2023-03-25 15:08:26 -04:00
bias = " none " ,
task_type = " CAUSAL_LM "
)
2023-03-29 10:55:34 -04:00
2023-06-27 17:24:04 -04:00
# == Backup the existing adapter ==
if not always_override :
backup_adapter ( lora_file_path )
2023-07-03 16:38:36 -04:00
# == get model trainable params
model_trainable_params , model_all_params = calc_trainable_parameters ( shared . model )
2023-03-29 10:55:34 -04:00
try :
2023-12-19 23:54:32 -05:00
logger . info ( " Creating LoRA model " )
2023-04-19 18:39:03 -04:00
lora_model = get_peft_model ( shared . model , config )
2023-04-16 01:35:13 -04:00
if not always_override and Path ( f " { lora_file_path } /adapter_model.bin " ) . is_file ( ) :
2023-12-19 23:54:32 -05:00
logger . info ( " Loading existing LoRA data " )
2023-11-02 13:07:08 -04:00
state_dict_peft = torch . load ( f " { lora_file_path } /adapter_model.bin " , weights_only = True )
2023-04-19 18:39:03 -04:00
set_peft_model_state_dict ( lora_model , state_dict_peft )
2023-03-29 10:55:34 -04:00
except :
2023-08-03 09:57:21 -04:00
yield traceback . format_exc ( ) . replace ( ' \n ' , ' \n \n ' )
2023-03-29 10:55:34 -04:00
return
2023-04-19 18:39:03 -04:00
if shared . args . monkey_patch :
2023-09-11 00:22:20 -04:00
from alpaca_lora_4bit . autograd_4bit import Autograd4bitQuantLinear
from alpaca_lora_4bit . models import Linear4bitLt
for _ , m in lora_model . named_modules ( ) :
if isinstance ( m , Autograd4bitQuantLinear ) or isinstance ( m , Linear4bitLt ) :
2023-04-19 18:39:03 -04:00
if m . is_v1_model :
m . zeros = m . zeros . half ( )
m . scales = m . scales . half ( )
2023-04-16 01:35:13 -04:00
class Tracked ( ) :
def __init__ ( self ) :
self . current_steps = 0
self . max_steps = 0
2023-04-19 18:39:03 -04:00
self . did_save = False
2023-04-16 01:35:13 -04:00
tracked = Tracked ( )
2023-04-19 18:39:03 -04:00
actual_save_steps = math . ceil ( save_steps / gradient_accumulation_steps )
2023-04-16 01:35:13 -04:00
class Callbacks ( transformers . TrainerCallback ) :
def on_step_begin ( self , args : transformers . TrainingArguments , state : transformers . TrainerState , control : transformers . TrainerControl , * * kwargs ) :
2023-04-19 18:39:03 -04:00
tracked . current_steps = state . global_step * gradient_accumulation_steps
tracked . max_steps = state . max_steps * gradient_accumulation_steps
2023-04-16 01:35:13 -04:00
if WANT_INTERRUPT :
control . should_epoch_stop = True
control . should_training_stop = True
2023-04-19 18:39:03 -04:00
elif state . global_step > 0 and actual_save_steps > 0 and state . global_step % actual_save_steps == 0 :
lora_model . save_pretrained ( f " { lora_file_path } /checkpoint- { tracked . current_steps } / " )
2023-06-25 14:34:46 -04:00
# Save log
2023-06-19 23:47:36 -04:00
with open ( f " { lora_file_path } /checkpoint- { tracked . current_steps } /training_log.json " , ' w ' , encoding = ' utf-8 ' ) as file :
2023-06-25 14:34:46 -04:00
json . dump ( train_log , file , indent = 2 )
# == Save training prompt ==
with open ( f " { lora_file_path } /checkpoint- { tracked . current_steps } /training_prompt.json " , ' w ' , encoding = ' utf-8 ' ) as file :
json . dump ( train_template , file , indent = 2 )
2023-04-16 01:35:13 -04:00
def on_substep_end ( self , args : transformers . TrainingArguments , state : transformers . TrainerState , control : transformers . TrainerControl , * * kwargs ) :
tracked . current_steps + = 1
if WANT_INTERRUPT :
control . should_epoch_stop = True
control . should_training_stop = True
2023-06-25 14:34:46 -04:00
2023-06-19 23:47:36 -04:00
def on_log ( self , args : transformers . TrainingArguments , state : transformers . TrainerState , control : transformers . TrainerControl , logs , * * kwargs ) :
train_log . update ( logs )
2023-06-25 14:34:46 -04:00
train_log . update ( { " current_steps " : tracked . current_steps } )
if WANT_INTERRUPT :
print ( " \033 [1;31;1mInterrupted by user \033 [0;37;0m " )
print ( f " \033 [1;30;40mStep: { tracked . current_steps } \033 [0;37;0m " , end = ' ' )
if ' loss ' in logs :
loss = float ( logs [ ' loss ' ] )
if loss < = stop_at_loss :
control . should_epoch_stop = True
control . should_training_stop = True
print ( f " \033 [1;31;1mStop Loss { stop_at_loss } reached. \033 [0;37;0m " )
2023-04-16 01:35:13 -04:00
2024-01-17 15:11:49 -05:00
# Fix training for mixed precision models
for param in shared . model . parameters ( ) :
if param . requires_grad :
param . data = param . data . float ( )
2023-03-25 15:08:26 -04:00
trainer = transformers . Trainer (
2023-03-27 21:17:42 -04:00
model = lora_model ,
2023-03-25 15:08:26 -04:00
train_dataset = train_data ,
2023-03-27 21:17:42 -04:00
eval_dataset = eval_data ,
2023-03-25 15:08:26 -04:00
args = transformers . TrainingArguments (
2023-07-12 10:53:31 -04:00
report_to = report_to if report_to != " None " else None ,
2023-03-27 21:17:42 -04:00
per_device_train_batch_size = micro_batch_size ,
gradient_accumulation_steps = gradient_accumulation_steps ,
2023-04-19 18:39:03 -04:00
warmup_steps = math . ceil ( warmup_steps / gradient_accumulation_steps ) ,
2023-03-25 15:08:26 -04:00
num_train_epochs = epochs ,
2023-03-27 21:17:42 -04:00
learning_rate = actual_lr ,
2024-01-03 18:42:20 -05:00
fp16 = False if shared . args . cpu or shared . args . bf16 else True ,
bf16 = shared . args . bf16 ,
2023-04-19 18:39:03 -04:00
optim = optimizer ,
2023-06-25 14:34:46 -04:00
logging_steps = 2 if stop_at_loss > 0 else 5 ,
2023-03-27 21:17:42 -04:00
evaluation_strategy = " steps " if eval_data is not None else " no " ,
2023-04-16 01:35:13 -04:00
eval_steps = math . ceil ( eval_steps / gradient_accumulation_steps ) if eval_data is not None else None ,
2023-05-16 12:40:19 -04:00
save_strategy = " steps " if eval_data is not None else " no " ,
2023-04-16 01:35:13 -04:00
output_dir = lora_file_path ,
2023-04-19 18:39:03 -04:00
lr_scheduler_type = lr_scheduler_type ,
2023-05-16 12:40:19 -04:00
load_best_model_at_end = eval_data is not None ,
2023-03-25 15:08:26 -04:00
# TODO: Enable multi-device support
2023-04-10 16:29:00 -04:00
ddp_find_unused_parameters = None ,
2023-07-12 10:53:31 -04:00
no_cuda = shared . args . cpu ,
2024-01-03 18:42:20 -05:00
use_ipex = True if is_torch_xpu_available ( ) and not shared . args . cpu else False
2023-03-25 15:08:26 -04:00
) ,
2023-03-25 15:57:36 -04:00
data_collator = transformers . DataCollatorForLanguageModeling ( shared . tokenizer , mlm = False ) ,
2023-03-27 13:25:08 -04:00
callbacks = list ( [ Callbacks ( ) ] )
2023-03-25 15:08:26 -04:00
)
2023-03-27 21:17:42 -04:00
lora_model . config . use_cache = False
2023-03-25 15:08:26 -04:00
if torch . __version__ > = " 2 " and sys . platform != " win32 " :
2023-03-27 21:17:42 -04:00
lora_model = torch . compile ( lora_model )
2023-03-27 20:24:39 -04:00
2023-04-16 01:35:13 -04:00
# == Save parameters for reuse ==
with open ( f " { lora_file_path } /training_parameters.json " , ' w ' , encoding = ' utf-8 ' ) as file :
vars = locals ( )
2023-06-19 23:47:36 -04:00
json . dump ( { x : vars [ x ] for x in PARAMETERS } , file , indent = 2 )
2023-04-16 01:35:13 -04:00
2023-06-25 14:34:46 -04:00
# == Save training prompt ==
with open ( f " { lora_file_path } /training_prompt.json " , ' w ' , encoding = ' utf-8 ' ) as file :
json . dump ( train_template , file , indent = 2 )
2023-03-27 13:25:08 -04:00
# == Main run and monitor loop ==
2023-12-19 23:54:32 -05:00
logger . info ( " Starting training " )
2023-03-27 13:25:08 -04:00
yield " Starting... "
2023-06-25 14:34:46 -04:00
2023-07-03 16:38:36 -04:00
lora_trainable_param , lora_all_param = calc_trainable_parameters ( lora_model )
2023-10-22 14:57:19 -04:00
projections_string = " , " . join ( [ projection . replace ( " _proj " , " " ) for projection in list_target_modules ( model_id ) ] )
2023-07-12 14:29:43 -04:00
print ( f " Training ' { model_id } ' model using ( { projections_string } ) projections " )
2023-07-11 21:49:06 -04:00
if lora_all_param > 0 :
print ( f " Trainable params: { lora_trainable_param : ,d } ( { 100 * lora_trainable_param / lora_all_param : .4f } %), All params: { lora_all_param : ,d } (Model: { model_all_params : ,d } ) " )
2023-07-03 16:38:36 -04:00
2023-06-25 14:34:46 -04:00
train_log . update ( { " base_model_name " : shared . model_name } )
train_log . update ( { " base_model_class " : shared . model . __class__ . __name__ } )
train_log . update ( { " base_loaded_in_4bit " : getattr ( lora_model , " is_loaded_in_4bit " , False ) } )
train_log . update ( { " base_loaded_in_8bit " : getattr ( lora_model , " is_loaded_in_8bit " , False ) } )
2023-07-12 14:29:43 -04:00
train_log . update ( { " projections " : projections_string } )
2023-06-25 14:34:46 -04:00
if stop_at_loss > 0 :
print ( f " Monitoring loss \033 [1;31;1m(Auto-Stop at: { stop_at_loss } ) \033 [0;37;0m " )
2023-04-06 01:04:11 -04:00
if WANT_INTERRUPT :
yield " Interrupted before start. "
return
2023-07-12 10:44:30 -04:00
2023-07-12 10:26:45 -04:00
def log_train_dataset ( trainer ) :
decoded_entries = [ ]
# Try to decode the entries and write the log file
try :
# Iterate over the first 10 elements in the dataset (or fewer if there are less than 10)
for i in range ( min ( 10 , len ( trainer . train_dataset ) ) ) :
decoded_text = shared . tokenizer . decode ( trainer . train_dataset [ i ] [ ' input_ids ' ] )
decoded_entries . append ( { " value " : decoded_text } )
# Write the log file
Path ( ' logs ' ) . mkdir ( exist_ok = True )
with open ( Path ( ' logs/train_dataset_sample.json ' ) , ' w ' ) as json_file :
json . dump ( decoded_entries , json_file , indent = 4 )
logger . info ( " Log file ' train_dataset_sample.json ' created in the ' logs ' directory. " )
except Exception as e :
logger . error ( f " Failed to create log file due to error: { e } " )
2023-03-27 20:24:39 -04:00
2023-04-06 01:04:11 -04:00
def threaded_run ( ) :
2023-07-12 10:26:45 -04:00
log_train_dataset ( trainer )
2023-03-27 13:25:08 -04:00
trainer . train ( )
2023-04-19 18:39:03 -04:00
# Note: save in the thread in case the gradio thread breaks (eg browser closed)
lora_model . save_pretrained ( lora_file_path )
2023-05-21 21:42:34 -04:00
logger . info ( " LoRA training run is completed and saved. " )
2023-06-19 23:47:36 -04:00
# Save log
with open ( f " { lora_file_path } /training_log.json " , ' w ' , encoding = ' utf-8 ' ) as file :
json . dump ( train_log , file , indent = 2 )
2023-03-27 20:24:39 -04:00
2023-04-06 01:04:11 -04:00
thread = threading . Thread ( target = threaded_run )
2023-03-27 13:25:08 -04:00
thread . start ( )
2023-04-06 01:04:11 -04:00
last_step = 0
start_time = time . perf_counter ( )
2023-03-27 20:24:39 -04:00
2023-03-27 13:25:08 -04:00
while thread . is_alive ( ) :
time . sleep ( 0.5 )
2023-03-27 13:43:01 -04:00
if WANT_INTERRUPT :
yield " Interrupting, please wait... *(Run will stop after the current training step completes.)* "
2023-04-06 01:04:11 -04:00
2023-04-16 01:35:13 -04:00
elif tracked . current_steps != last_step :
last_step = tracked . current_steps
2023-04-06 01:04:11 -04:00
time_elapsed = time . perf_counter ( ) - start_time
if time_elapsed < = 0 :
timer_info = " "
total_time_estimate = 999
2023-03-27 13:25:08 -04:00
else :
2023-04-16 01:35:13 -04:00
its = tracked . current_steps / time_elapsed
2023-03-27 13:25:08 -04:00
if its > 1 :
2023-04-06 01:04:11 -04:00
timer_info = f " ` { its : .2f } ` it/s "
2023-03-27 13:25:08 -04:00
else :
2023-04-06 01:04:11 -04:00
timer_info = f " ` { 1.0 / its : .2f } ` s/it "
2023-04-16 01:46:27 -04:00
2023-04-16 01:35:13 -04:00
total_time_estimate = ( 1.0 / its ) * ( tracked . max_steps )
2023-04-16 01:46:27 -04:00
2023-04-16 01:35:13 -04:00
yield f " Running... ** { tracked . current_steps } ** / ** { tracked . max_steps } ** ... { timer_info } , { format_time ( time_elapsed ) } / { format_time ( total_time_estimate ) } ... { format_time ( total_time_estimate - time_elapsed ) } remaining "
2023-03-27 20:24:39 -04:00
2023-04-19 18:39:03 -04:00
# Saving in the train thread might fail if an error occurs, so save here if so.
if not tracked . did_save :
2023-12-19 23:54:32 -05:00
logger . info ( " Training complete, saving " )
2023-04-19 18:39:03 -04:00
lora_model . save_pretrained ( lora_file_path )
2023-03-27 20:24:39 -04:00
2023-03-27 13:43:01 -04:00
if WANT_INTERRUPT :
2023-05-21 21:42:34 -04:00
logger . info ( " Training interrupted. " )
2023-08-18 15:58:38 -04:00
yield f " Interrupted. Incomplete LoRA saved to ` { lora_file_path } `. "
2023-03-27 13:43:01 -04:00
else :
2023-05-21 21:42:34 -04:00
logger . info ( " Training complete! " )
2023-08-18 15:58:38 -04:00
yield f " Done! LoRA saved to ` { lora_file_path } `. \n \n Before testing your new LoRA, make sure to first reload the model, as it is currently dirty from training. "
2023-03-28 01:15:32 -04:00
2023-04-06 23:15:45 -04:00
2023-07-12 11:05:37 -04:00
def split_chunks ( arr , size , step ) :
2023-03-28 01:15:32 -04:00
for i in range ( 0 , len ( arr ) , step ) :
2023-07-12 11:05:37 -04:00
yield arr [ i : i + size ]
2023-04-06 01:04:11 -04:00
2023-04-06 23:15:45 -04:00
2023-04-06 01:04:11 -04:00
def cut_chunk_for_newline ( chunk : str , max_length : int ) :
if ' \n ' not in chunk :
return chunk
2023-04-16 01:46:27 -04:00
2023-04-06 01:04:11 -04:00
first_newline = chunk . index ( ' \n ' )
if first_newline < max_length :
chunk = chunk [ first_newline + 1 : ]
2023-04-16 01:46:27 -04:00
2023-04-06 01:04:11 -04:00
if ' \n ' not in chunk :
return chunk
2023-04-16 01:46:27 -04:00
2023-04-06 01:04:11 -04:00
last_newline = chunk . rindex ( ' \n ' )
if len ( chunk ) - last_newline < max_length :
chunk = chunk [ : last_newline ]
2023-04-16 01:46:27 -04:00
2023-04-06 01:04:11 -04:00
return chunk
2023-04-06 23:15:45 -04:00
2023-04-06 01:04:11 -04:00
def format_time ( seconds : float ) :
if seconds < 120 :
return f " ` { seconds : .0f } ` seconds "
2023-04-16 01:46:27 -04:00
2023-04-06 01:04:11 -04:00
minutes = seconds / 60
if minutes < 120 :
return f " ` { minutes : .0f } ` minutes "
2023-04-16 01:46:27 -04:00
2023-04-06 01:04:11 -04:00
hours = minutes / 60
return f " ` { hours : .0f } ` hours "