Nelly43 commited on
Commit
1eecba3
·
1 Parent(s): 099c327

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +2 -862
app.py CHANGED
@@ -226,7 +226,7 @@ def next_ques(ques,ans):
226
  ques_temp,ans_temp=random_ques_ans2()
227
  return gr.Label(value=ques_temp)
228
 
229
- with gr.Blocks(title="LLM QA Chatbot Builder",theme=gr.themes.Soft()) as demo:
230
  gr.Markdown("""
231
  # LLM QA Chatbot Builder
232
  """)
@@ -905,864 +905,4 @@ with gr.Blocks(title="LLM QA Chatbot Builder",theme=gr.themes.Soft()) as demo:
905
  btn_model=gr.Button("Deploy")
906
  btn_model.click(deploy_func,model_name)
907
 
908
- demo.launch(share=True, debug=True)
909
- save_ques_ans=[]
910
- save_ques_ans_test=[]
911
- cur_time=current_time()
912
-
913
- def random_ques_ans(model_ans):
914
- df_temp=pd.read_excel(os.path.join("model_ans",str(model_ans)))
915
- global cnt
916
- id=int((df_temp.loc[cnt])['id'])
917
- ques_temp=(df_temp.loc[cnt])['question']
918
- ans_temp=(df_temp.loc[cnt])['answer']
919
- cnt+=1
920
- if cnt>=len(df_temp):
921
- cnt=0
922
- return ques_temp,ans_temp,id,0
923
- return ques_temp,ans_temp,id,1
924
- def save_all(model_ans):
925
- temp=pd.DataFrame(data)
926
- temp.to_excel(f"score_report\\{model_ans+cur_time}.xlsx",index=False)
927
- gr.Info("Sucessfully save all the answer!!!")
928
-
929
- def score_save(ques,ans,score,model_ans,token_key):
930
- data.append({
931
- "question":ques,
932
- 'answer':ans,
933
- 'rating':score
934
- })
935
- # if len(data)%5==0:
936
- temp=pd.DataFrame(data)
937
- temp.to_excel(f"score_report\\{model_ans+cur_time}.xlsx",index=False)
938
- gr.Info("Sucessfully saved in local folder!!!")
939
- ques_temp,ans_temp,id,flag=random_ques_ans(model_ans)
940
- gr.Info("Your opinion is submitted successfully!!!")
941
- return gr.Label(value=id,label="ID"),gr.Label(value=ques_temp, label="Question"), gr.Label(value=ans_temp, label="Answer")
942
-
943
- def new_ques(model_ans):
944
- ques_temp,ans_temp,id2,flag=random_ques_ans(model_ans)
945
- return {
946
- id:gr.Label(value=id2,label="ID"),
947
- ques:gr.Label(value=ques_temp,label="Question"),
948
- ans:gr.Label(value=ans_temp,label="Answer")
949
- }
950
-
951
- def save_the_ques(ques,ans,file_type = 'xlsx'):
952
- """
953
- Saves a question and answer pair to a specified file (xlsx or csv).
954
-
955
- Args:
956
- ques (str): The question.
957
- ans (str): The answer.
958
- file_type (str, optional): The file type to save to ("xlsx" or "csv").
959
- Defaults to "xlsx".
960
-
961
- Returns:
962
- str: A success label.
963
- """
964
-
965
- new_data = {"question": [ques], "answer": [ans]}
966
- df_new = pd.DataFrame(new_data)
967
-
968
- filepath = f"data/finetune_data.{file_type}"
969
-
970
- if Path(filepath).is_file():
971
- df_existing = pd.read_excel(filepath) if file_type == "xlsx" else pd.read_csv(filepath)
972
- df_combined = pd.concat([df_existing, df_new], ignore_index=True)
973
- else:
974
- df_combined = df_new
975
-
976
- if file_type == "xlsx":
977
- df_combined.to_excel(filepath, index=False)
978
- elif file_type == "csv":
979
- df_combined.to_csv(filepath, index=False)
980
-
981
- return gr.Label(value="Successfully saved in local folder.", visible=True)
982
-
983
- def save_the_ques_test(ques, ans, file_type = 'xlsx'):
984
- """
985
- Saves a question and answer pair to a specified file (xlsx or csv).
986
-
987
- Args:
988
- ques (str): The question.
989
- ans (str): The answer.
990
- file_type (str, optional): The file type to save to ("xlsx" or "csv").
991
- Defaults to "xlsx".
992
-
993
- Returns:
994
- str: A success label.
995
- """
996
-
997
- new_data = {"question": [ques], "answer": [ans]}
998
- df_new = pd.DataFrame(new_data)
999
-
1000
- filepath = f"data/testing_data.{file_type}"
1001
-
1002
- if Path(filepath).is_file():
1003
- df_existing = pd.read_excel(filepath) if file_type == "xlsx" else pd.read_csv(filepath)
1004
- df_combined = pd.concat([df_existing, df_new], ignore_index=True)
1005
- else:
1006
- df_combined = df_new
1007
-
1008
- if file_type == "xlsx":
1009
- df_combined.to_excel(filepath, index=False)
1010
- elif file_type == "csv":
1011
- df_combined.to_csv(filepath, index=False)
1012
-
1013
- return gr.Label(value="Successfully saved in local folder.", visible=True)
1014
-
1015
- import pandas as pd
1016
- from pathlib import Path
1017
-
1018
- def save_emb_data(loss_function, first_input, second_input, third_input, file_type="xlsx"):
1019
- """
1020
- Saves embedding data based on the specified loss function to either an Excel
1021
- file (xlsx) or a CSV file (csv).
1022
-
1023
- Args:
1024
- loss_function (str): The name of the loss function.
1025
- first_input: The first input data.
1026
- second_input: The second input data.
1027
- third_input: The third input data.
1028
- file_type (str, optional): The file type to save to ("xlsx" or "csv").
1029
- Defaults to "xlsx".
1030
-
1031
- Returns:
1032
- str: A success message indicating whether data was appended or a new file
1033
- was created.
1034
- """
1035
-
1036
- if loss_function == "MultipleNegativesRankingLoss":
1037
- data = pd.DataFrame({
1038
- "anchor": [first_input],
1039
- "positive": [second_input],
1040
- "negative": [third_input]
1041
- })
1042
- elif loss_function == "OnlineContrastiveLoss":
1043
- data = pd.DataFrame({
1044
- "sentence1": [first_input],
1045
- "sentence2": [second_input],
1046
- "label": [third_input]
1047
- })
1048
- elif loss_function == "CoSENTLoss":
1049
- data = pd.DataFrame({
1050
- "sentence1": [first_input],
1051
- "sentence2": [second_input],
1052
- "score": [third_input]
1053
- })
1054
- elif loss_function == "GISTEmbedLoss":
1055
- data = pd.DataFrame({
1056
- "anchor": [first_input],
1057
- "positive": [second_input],
1058
- "negative": [third_input]
1059
- })
1060
- elif loss_function == "TripletLoss":
1061
- data = pd.DataFrame({
1062
- "anchor": [first_input],
1063
- "positive": [second_input],
1064
- "negative": [third_input]
1065
- })
1066
-
1067
- filepath = f"data/emb_data.{file_type}"
1068
-
1069
- try:
1070
- if file_type == "xlsx":
1071
- existing_data = pd.read_excel(filepath)
1072
- elif file_type == "csv":
1073
- existing_data = pd.read_csv(filepath)
1074
-
1075
- if list(data.columns) == list(existing_data.columns):
1076
- combined_data = pd.concat([existing_data, data], ignore_index=True)
1077
- if file_type == "xlsx":
1078
- combined_data.to_excel(filepath, index=False)
1079
- elif file_type == "csv":
1080
- combined_data.to_csv(filepath, index=False)
1081
- return "Data appended to existing file!"
1082
- else:
1083
- if file_type == "xlsx":
1084
- data.to_excel(filepath, index=False)
1085
- elif file_type == "csv":
1086
- data.to_csv(filepath, index=False)
1087
- return "Data saved to a new file (overwritten)!"
1088
-
1089
- except FileNotFoundError:
1090
- if file_type == "xlsx":
1091
- data.to_excel(filepath, index=False)
1092
- elif file_type == "csv":
1093
- data.to_csv(filepath, index=False)
1094
- return "Data saved to a new file!"
1095
-
1096
- def parse_data_func(link_temp,progress=gr.Progress()):
1097
- progress(0, desc="Starting...")
1098
- parse_data(link_temp,progress)
1099
- gr.Info("Finished parsing!! Save as a docx file.")
1100
-
1101
- def next_ques(ques,ans):
1102
- ques_temp,ans_temp=random_ques_ans2()
1103
- return gr.Label(value=ques_temp)
1104
-
1105
- with gr.Blocks(title="LLM QA Chatbot Builder",theme=gr.themes.Soft()) as demo:
1106
- gr.Markdown("""
1107
- # LLM QA Chatbot Builder
1108
- """)
1109
- with gr.Tab("Data Collection"):
1110
- gr.Markdown(""" # Instructions:
1111
- In this page you can prepare data for LLM fine-tuning, testing and embedding model finetuning your model. The data can be provided through Excel file or CSV file or directly via web interface. Additionally, data can be parsed from the target website (Data parsing for RAG) to further enhance the model performance.
1112
-
1113
- ## 1. If you want to provide data in Excel file or CSV file for model fine-tuning and testing.
1114
- - Create an Excel or CSV file in the data folder and name it `finetune_data.xlsx` or `finetune_data.csv` for finetuning the model.
1115
- - Create an Excel or CSV file in the data folder and name it `testing_data.xlsx` or `testing_data.csv` for generating answers using the fine-tuned model.
1116
- - `finetune_data.xlsx` or `finetune_data.csv` has two columns: `question` and `answer`. `testing_data.xlsx` or `testing_data.csv` has three columns: `question`, `ground_truth` ,`context`.
1117
- """)
1118
- gr.Markdown("""
1119
- ## `finetune_data.xlsx` | `finetune_data.csv`
1120
- """)
1121
- gr.HTML(value=display_table(), label="finetune_data.xlsx or finetune_data.csv")
1122
- gr.Markdown("""
1123
- ## `testing_data.xlsx` | `testing_data.csv`
1124
- """)
1125
- gr.HTML(value=display_table("data/demo_test_data.xlsx"), label="testing_data.xlsx or testing_data.csv")
1126
- gr.Markdown("""
1127
- ## 2. You can use the below interface to create the dataset for training and testing models.
1128
- """)
1129
-
1130
- #Training data generation
1131
- with gr.Tab("Training Data Generation"):
1132
- with gr.Tab("Existing Questions"):
1133
- gr.Markdown("""
1134
- Existing questions are provided by the administrator and placed in the data folder named `existing_dataset.xlsx`. This file has only one column: `question`.
1135
- After clicking the `Save the Answer` button. Those questions and answers are saved in the `data` folder as a `finetune_data.xlsx` file.
1136
- """)
1137
- ques_temp,ans_temp=random_ques_ans2()
1138
- with gr.Row():
1139
- ques=gr.Label(value=ques_temp,label="Question")
1140
- with gr.Row():
1141
- ans=gr.TextArea(label="Answer")
1142
- with gr.Row():
1143
- with gr.Row():
1144
- type_options = gr.Dropdown(choices=["Save xlsx", "Save csv"], value="Save xlsx", label="Preferred file type")
1145
- save_training = gr.Button(value="Save")
1146
- question = gr.Button("Generate New Question")
1147
- with gr.Row():
1148
- lab=gr.Label(visible=False)
1149
- question.click(next_ques,None,ques)
1150
- save_training.click(save_the_ques,[ques,ans,type_options],lab)
1151
-
1152
- with gr.Tab("Custom Questions"):
1153
- gr.Markdown("""
1154
- After clicking the `save the answer` button. Those questions and answers are saved in the `data` folder as a `finetune_data.xlsx` file.
1155
- """)
1156
- with gr.Row():
1157
- ques=gr.Textbox(label="Question")
1158
- with gr.Row():
1159
- ans=gr.TextArea(label="Answer")
1160
- with gr.Row():
1161
- with gr.Row():
1162
- type_options = gr.Dropdown(choices=["Save xlsx", "Save csv"], value="Save xlsx", label="Preferred file type")
1163
- save_training = gr.Button(value="Save")
1164
- with gr.Row():
1165
- lab=gr.Label(visible=False,value="You answer is submitted!!! Thank you for your contribution.",label="Submitted")
1166
- save_training.click(save_the_ques,[ques,ans,type_options],lab)
1167
-
1168
- ### Testing data generation
1169
- with gr.Tab("Testing Data Generation"):
1170
- gr.Markdown("""
1171
- You can create test data for generating answers using the fine-tune model, which will be used for testing the model's performance.
1172
- After clicking the `Save the Answer` button. Those questions and answers are saved in the `data` folder as a `testing_data.xlsx` file.
1173
- """)
1174
- with gr.Row():
1175
- ques=gr.Textbox(label="Question")
1176
- with gr.Row():
1177
- ans=gr.TextArea(label="Ground Truth")
1178
- with gr.Row():
1179
- ans=gr.TextArea(label="Contexts")
1180
- with gr.Row():
1181
- with gr.Row():
1182
- type_options = gr.Dropdown(choices=["Save xlsx", "Save csv"], value="Save xlsx", label="Preferred file type")
1183
- save_test = gr.Button(value="Save")
1184
- with gr.Row():
1185
- lab=gr.Label(visible=False,value="You answer is submitted!!! Thank you for your contribution.",label="Submitted")
1186
- save_test.click(save_the_ques_test,[ques,ans,type_options],None)
1187
-
1188
- ## Embedding data generation
1189
- def update_fields(loss_function):
1190
- if loss_function == "MultipleNegativesRankingLoss":
1191
- first_input = gr.Textbox(label="Anchor", visible=True, placeholder="The sentence to be embedded.")
1192
- second_input = gr.Textbox(label="Positive", visible=True, placeholder="A sentence semantically similar to the anchor.")
1193
- third_input = gr.Textbox(label="Negative", visible=True, placeholder="A sentence semantically dissimilar to the anchor.")
1194
- markdown = gr.Markdown(
1195
- """
1196
- **MultipleNegativesRankingLoss:**
1197
- Expects data with columns: `anchor`, `positive`, `negative`.
1198
- - `anchor`: The sentence to be embedded.
1199
- - `positive`: A sentence semantically similar to the anchor.
1200
- - `negative`: A sentence semantically dissimilar to the anchor.""",
1201
- visible=True
1202
- )
1203
- elif loss_function == "OnlineContrastiveLoss":
1204
- first_input = gr.Textbox(label="Sentence 1", visible=True, placeholder="The first sentence.")
1205
- second_input = gr.Textbox(label="Sentence 2", visible=True, placeholder="The second sentence.")
1206
- third_input = gr.Textbox(label="Label", visible=True, placeholder="1 if the sentences are similar, 0 if dissimilar.")
1207
- markdown = gr.Markdown(
1208
- """
1209
- **OnlineContrastiveLoss:**
1210
- Expects data with columns: `sentence1`, `sentence2`, `label`.
1211
- - `sentence1`, `sentence2`: Pairs of sentences.
1212
- - `label`: 1 if the sentences are similar, 0 if dissimilar.""",
1213
- visible=True
1214
- )
1215
- elif loss_function == "CoSENTLoss":
1216
- first_input = gr.Textbox(label="Sentence 1", visible=True, placeholder="The first sentence.")
1217
- second_input = gr.Textbox(label="Sentence 2", visible=True, placeholder="The second sentence.")
1218
- third_input = gr.Textbox(label="Score", visible=True, placeholder="A float value (e.g., 0-1) representing their similarity.")
1219
- markdown = gr.Markdown(
1220
- """
1221
- **CoSENTLoss:**
1222
- Expects data with columns: `sentence1`, `sentence2`, `score`.
1223
- - `sentence1`, `sentence2`: Pairs of sentences.
1224
- - `score`: A float value (e.g., 0-1) representing their similarity.""",
1225
- visible=True
1226
- )
1227
- elif loss_function == "GISTEmbedLoss":
1228
- first_input = gr.Textbox(label="Anchor", visible=True, placeholder="The sentence to be embedded.")
1229
- second_input = gr.Textbox(label="Positive", visible=True, placeholder="A sentence semantically similar to the anchor.")
1230
- third_input = gr.Textbox(label="Negative", visible=True, placeholder="A sentence semantically dissimilar to the anchor. Can be empty.")
1231
- markdown = gr.Markdown(
1232
- """
1233
- **GISTEmbedLoss:**
1234
- Expects data with either:
1235
- - Columns: `anchor`, `positive`, `negative` (like TripletLoss).
1236
- - Columns: `anchor`, `positive` (for pairs of similar sentences).""",
1237
- visible=True
1238
- )
1239
- elif loss_function == "TripletLoss":
1240
- first_input = gr.Textbox(label="Anchor", visible=True, placeholder="The sentence to be embedded.")
1241
- second_input = gr.Textbox(label="Positive", visible=True, placeholder="A sentence semantically similar to the anchor.")
1242
- third_input = gr.Textbox(label="Negative", visible=True, placeholder="A sentence semantically dissimilar to the anchor.")
1243
- markdown = gr.Markdown(
1244
- """
1245
- **TripletLoss:**
1246
- Expects data with columns: `anchor`, `positive`, `negative`.
1247
- - `anchor`: The sentence to be embedded.
1248
- - `positive`: A sentence semantically similar to the anchor.
1249
- - `negative`: A sentence semantically dissimilar to the anchor.""",
1250
- visible=True
1251
- )
1252
- else:
1253
- first_input = gr.Textbox(visible=False)
1254
- second_input = gr.Textbox(visible=False)
1255
- third_input = gr.Textbox(visible=False)
1256
- markdown = gr.Markdown(visible=False)
1257
-
1258
- return first_input, second_input, third_input, markdown
1259
-
1260
- with gr.Tab("Embedding Data Generation"):
1261
- gr.Markdown("**Choose a loss function to format your embedding data.**")
1262
- with gr.Row():
1263
- loss_function = gr.Dropdown(
1264
- choices=[
1265
- "MultipleNegativesRankingLoss",
1266
- "OnlineContrastiveLoss",
1267
- "CoSENTLoss",
1268
- "GISTEmbedLoss",
1269
- "TripletLoss",
1270
- ],
1271
- label="Select the loss function",
1272
- )
1273
- with gr.Row():
1274
- gr.Markdown("""Format `data/emb_data.xlsx` or `data/emb_data.csv` to the expected data format, according to the selected loss function.
1275
- If the file exists and has matching columns, new data will be appended.
1276
- Otherwise, the file will be overwritten.""")
1277
- with gr.Row():
1278
- loss_info_markdown = gr.Markdown(visible=False)
1279
- with gr.Row():
1280
- first_input = gr.Textbox(label="Anchor", value="",visible=False)
1281
- second_input = gr.Textbox(label="Positive", value="",visible=False)
1282
- third_input = gr.Textbox(label="Negative", value="",visible=False)
1283
- loss_function.change(update_fields, loss_function, [first_input, second_input, third_input,loss_info_markdown])
1284
- with gr.Row():
1285
- with gr.Row():
1286
- type_options = gr.Dropdown(choices=["Save xlsx", "Save csv"], value="Save xlsx", label="Preferred file type")
1287
- save_emb = gr.Button(value="Save")
1288
- save_emb.click(save_emb_data,[loss_function,first_input,second_input,third_input,type_options])
1289
-
1290
- with gr.Row():
1291
- gr.Markdown("""
1292
- ## 3. Data parsing for RAG
1293
- """)
1294
- with gr.Row():
1295
- link_temp=gr.Textbox(label="Enter Link to Parse Data for RAG",info="To provide the link for parsing the data from the website, this link can help create RAG data for the model.")
1296
- parse_data_btn=gr.Button("Parse Data")
1297
- from utils import parse_data
1298
- parse_data_btn.click(parse_data_func,link_temp,link_temp)
1299
-
1300
- #***************************************************
1301
- with gr.Tab("Fine-tuning"):
1302
- with gr.Tab("Fine-tune LLM"):
1303
- with gr.Row():
1304
- def login_hug(token):
1305
- from huggingface_hub import login
1306
- login(token=token)
1307
- login_hug(os.getenv('HF_TOKEN'))
1308
- gr.Markdown("""
1309
- # Instructions:
1310
- - Required VRAM for training: 24GB, for inference: 16GB.(Mistral, Zepyhr and Lllama)\n
1311
- - Required VRAM for training: 5GB, for inference: 4GB.(Phi,Flan-T5)
1312
- - For fine-tuning a custom model select `custom model` option in `Select the model for fine-tuning` dropdown section. The custom model can be configured by editing the code section.\n
1313
- - After fine-tuning the model, it will be saved in the `models` folder.
1314
- """)
1315
-
1316
- def edit_model_parameter(model_name_temp,edit_code,code_temp,lr,epoch,batch_size,gradient_accumulation,quantization,lora_r,lora_alpha,lora_dropout, progress=gr.Progress()):
1317
- progress(0, desc="Fine-tune started!! please wait ...")
1318
- # write code to files if code was edited
1319
- if edit_code and len(code_temp)!=0:
1320
- if model_name_temp=="Mistral":
1321
- open(r"fine_tune_file/mistral_finetune.py","w").write(code_temp)
1322
- elif model_name_temp=="Zephyr":
1323
- open(r"fine_tune_file/zepyhr_finetune.py","w").write(code_temp)
1324
- elif model_name_temp=="Llama":
1325
- open(r"fine_tune_file/llama_finetune.py","w").write(code_temp)
1326
- elif model_name_temp=="Phi":
1327
- open(r"fine_tune_file/phi_finetune.py","w").write(code_temp)
1328
- elif model_name_temp=="Custom model":
1329
- open(r"fine_tune_file/finetune_file.py","w").write(code_temp)
1330
- # importing just before finetuning, to ensure the latest code is used
1331
- # from fine_tune_file.mistral_finetune import mistral_trainer
1332
- # from fine_tune_file.zepyhr_finetune import zephyr_trainer
1333
- # from fine_tune_file.llama_finetune import llama_trainer
1334
- # from fine_tune_file.phi_finetune import phi_trainer
1335
- from fine_tune_file.finetune_file import custom_model_trainer
1336
- # from fine_tune_file.flant5_finetune import flant5_trainer
1337
- from fine_tune_file.modular_finetune import get_trainer
1338
- # create instance of the finetuning classes and then call the finetune function
1339
-
1340
- if model_name_temp=="Custom model":
1341
- gr.Info("Fine-tune started!!!")
1342
- trainer=custom_model_trainer()
1343
- trainer.custom_model_finetune()
1344
- gr.Info("Fine-tune Ended!!!")
1345
- else:
1346
- trainer=get_trainer(model_name_temp)
1347
- gr.Info("Fine-tune started!!!")
1348
- if model_name_temp=="Mistral":
1349
- trainer.mistral_finetune(lr,epoch,batch_size,gradient_accumulation,quantization,lora_r,lora_alpha,lora_dropout)
1350
- elif model_name_temp=="Zephyr":
1351
- trainer.zepyhr_finetune(lr,epoch,batch_size,gradient_accumulation,quantization,lora_r,lora_alpha,lora_dropout)
1352
- elif model_name_temp=="Llama":
1353
- trainer.llama_finetune(lr,epoch,batch_size,gradient_accumulation,quantization,lora_r,lora_alpha,lora_dropout)
1354
- elif model_name_temp=="Phi":
1355
- trainer.phi_finetune(lr,epoch,batch_size,gradient_accumulation,quantization,lora_r,lora_alpha,lora_dropout)
1356
- elif model_name_temp=="Flant5":
1357
- trainer.flant5_finetune(lr,epoch,batch_size,gradient_accumulation,quantization,lora_r,lora_alpha,lora_dropout)
1358
- gr.Info("Fine-tune Ended!!!")
1359
-
1360
- def code_show(model_name):
1361
- if model_name=="Mistral":
1362
- f=open(r"fine_tune_file/mistral_finetune.py").read()
1363
- return gr.Code(visible=True,value=f,interactive=True,language="python")
1364
- elif model_name=="Zephyr":
1365
- f=open(r"fine_tune_file/zepyhr_finetune.py").read()
1366
- return gr.Code(visible=True,value=f,interactive=True,language="python")
1367
- elif model_name=="Llama":
1368
- f=open(r"fine_tune_file/llama_finetune.py").read()
1369
- return gr.Code(visible=True,value=f,interactive=True,language="python")
1370
- elif model_name=="Phi":
1371
- f=open(r"fine_tune_file/phi_finetune.py").read()
1372
- return gr.Code(visible=True,value=f,interactive=True,language="python")
1373
- elif model_name=="Flant5":
1374
- f=open(r"fine_tune_file/flant5_finetune.py").read()
1375
- return gr.Code(visible=True,value=f,interactive=True,language="python")
1376
-
1377
- def custom_model(model_name): # It shows custom model code in the UI.
1378
- if model_name=="Custom model":
1379
- f=open(r"fine_tune_file/finetune_file.py").read()
1380
- return [gr.Code(visible=True,value=f,interactive=True,language="python"),gr.Button(visible=False)]
1381
- else:
1382
- return [gr.Code(visible=False),gr.Button("Advance Code Editing",visible=True)]
1383
- def change_code_fun(code_,model_name):
1384
- if model_name=="Mistral":
1385
- open(r"fine_tune_file/mistral_finetune.py","w").write(code_)
1386
- gr.Info("Successfully saved code!!!")
1387
- elif model_name=="Zephyr":
1388
- open(r"fine_tune_file/zepyhr_finetune.py","w").write(code_)
1389
- gr.Info("Successfully saved code!!!")
1390
- elif model_name=="Llama":
1391
- open(r"fine_tune_file/llama_finetune.py","w").write(code_)
1392
- gr.Info("Successfully saved code!!!")
1393
- elif model_name=="Phi":
1394
- open(r"fine_tune_file/phi_finetune.py","w").write(code_)
1395
- gr.Info("Successfully saved code!!!")
1396
- elif model_name=="Flant5":
1397
- open(r"fine_tune_file/flant5_finetune.py","w").write(code_)
1398
- gr.Info("Successfully saved code!!!")
1399
-
1400
- def finetune_emb(model_name, loss_name, epochs = 1, batch_size = 8):
1401
- gr.Info("Embedding model fine-tune is started!!!")
1402
- from embedding_tuner import EmbeddingFinetuner
1403
- finetuner = EmbeddingFinetuner(
1404
- model_name=model_name,
1405
- loss_function=loss_name,
1406
- epochs=epochs,
1407
- batch_size=batch_size,
1408
- )
1409
- success = finetuner.train()
1410
- if success:
1411
- gr.Info("Embedding model fine-tune finished!!!")
1412
-
1413
- with gr.Row():
1414
- code_temp=gr.Code(visible=False)
1415
- with gr.Row():
1416
- model_name=gr.Dropdown(choices=["Mistral","Zephyr","Llama","Phi","Flant5","Custom model"],label="Select the LLM for fine-tuning")
1417
- with gr.Accordion("Parameter Setup"):
1418
- with gr.Row():
1419
- lr=gr.Number(label="learning_rate",value=5e-6,interactive=True,info="The step size at which the model parameters are updated during training. It controls the magnitude of the updates to the model's weights.")
1420
- epoch=gr.Number(label="epochs",value=2,interactive=True,info="One complete pass through the entire training dataset during the training process. It's a measure of how many times the algorithm has seen the entire dataset.")
1421
- batch_size=gr.Number(label="batch_size",value=4,interactive=True,info="The number of training examples used in one iteration of training. It affects the speed and stability of the training process.")
1422
- gradient_accumulation = gr.Number(info="Gradient accumulation involves updating model weights after accumulating gradients over multiple batches, instead of after each individual batch.",label="gradient_accumulation",value=4,interactive=True)
1423
- with gr.Row():
1424
- quantization = gr.Dropdown(info="Quantization is a technique used to reduce the precision of numerical values, typically from 32-bit floating-point numbers to lower bit representations.",label="quantization",choices=[4,8],value=8,interactive=True)
1425
- lora_r = gr.Number(info="LoRA_r is a hyperparameter associated with the rank of the low-rank approximation used in LoRA.",label="lora_r",value=16,interactive=True)
1426
- lora_alpha = gr.Number(info="LoRA_alpha is a hyperparameter used in LoRA for controlling the strength of the adaptation.",label="lora_alpha",value=32,interactive=True)
1427
- lora_dropout = gr.Number(info="LoRA_dropout is a hyperparameter used in LoRA to control the dropout rate during fine-tuning.",label="lora_dropout",value=.05,interactive=True)
1428
- with gr.Row():
1429
- edit_code=gr.Button("Advance Code Editing")
1430
- with gr.Row():
1431
- code_temp=gr.Code(visible=False)
1432
- with gr.Row():
1433
- parameter_alter=gr.Button("Fine-tune")
1434
- with gr.Row():
1435
- fin_com=gr.Label(visible=False)
1436
- edit_code.click(code_show,model_name,code_temp)
1437
- # On click finetune button
1438
- parameter_alter.click(edit_model_parameter,[model_name,edit_code,code_temp,lr,epoch,batch_size,gradient_accumulation,quantization,lora_r,lora_alpha,lora_dropout],model_name)
1439
- model_name.change(custom_model,model_name,[code_temp,edit_code])
1440
- with gr.Tab("Embedding model"):
1441
- with gr.Row():
1442
- embedding_model = gr.Dropdown(
1443
- choices=[
1444
- "BAAI/bge-base-en-v1.5",
1445
- "dunzhang/stella_en_1.5B_v5",
1446
- "dunzhang/stella_en_400M_v5",
1447
- "nvidia/NV-Embed-v2",
1448
- "Alibaba-NLP/gte-Qwen2-1.5B-instruct",
1449
- ],
1450
- label="Select the embedding model for fine-tuning",
1451
- )
1452
- loss_function = gr.Dropdown(
1453
- choices=[
1454
- "MultipleNegativesRankingLoss",
1455
- "OnlineContrastiveLoss",
1456
- "CoSENTLoss",
1457
- "GISTEmbedLoss",
1458
- "TripletLoss",
1459
- ],
1460
- label="Select the loss function",
1461
- )
1462
-
1463
- epoch=gr.Number(label="epochs",value=1,interactive=True,info="One complete pass through the entire training dataset during the training process.")
1464
- batch_size=gr.Number(label="batch_size",value=8,interactive=True,info="The number of training examples used in one iteration of training.")
1465
- with gr.Row():
1466
- btn_emb = gr.Button("Fine-tune the embedding model")
1467
-
1468
-
1469
- # with gr.Row():
1470
- # with gr.Accordion(label="Expected data format according to loss function"):
1471
- # loss_info = gr.Markdown(
1472
- # """
1473
- # # Expected data format according to loss function:
1474
- # ### Format `data/emb_data.xlsx` | `data/emb_data.xlsx` accordingly.
1475
-
1476
- # **MultipleNegativesRankingLoss:**
1477
- # Expects data with columns: `anchor`, `positive`, `negative`.
1478
- # - `anchor`: The sentence to be embedded.
1479
- # - `positive`: A sentence semantically similar to the anchor.
1480
- # - `negative`: A sentence semantically dissimilar to the anchor.
1481
-
1482
- # **OnlineContrastiveLoss:**
1483
- # Expects data with columns: `sentence1`, `sentence2`, `label`.
1484
- # - `sentence1`, `sentence2`: Pairs of sentences.
1485
- # - `label`: 1 if the sentences are similar, 0 if dissimilar.
1486
-
1487
- # **CoSENTLoss:**
1488
- # Expects data with columns: `sentence1`, `sentence2`, `score`.
1489
- # - `sentence1`, `sentence2`: Pairs of sentences.
1490
- # - `score`: A float value (e.g., 0-1) representing their similarity.
1491
-
1492
- # **GISTEmbedLoss:**
1493
- # Expects data with either:
1494
- # - Columns: `anchor`, `positive`, `negative` (like TripletLoss).
1495
- # - Columns: `anchor`, `positive` (for pairs of similar sentences).
1496
-
1497
- # **TripletLoss:**
1498
- # Expects data with columns: `anchor`, `positive`, `negative`.
1499
- # - `anchor`: The sentence to be embedded.
1500
- # - `positive`: A sentence semantically similar to the anchor.
1501
- # - `negative`: A sentence semantically dissimilar to the anchor.
1502
- # """
1503
- # )
1504
-
1505
-
1506
-
1507
- btn_emb.click(finetune_emb,[embedding_model, loss_function, epoch, batch_size], None)
1508
- #***************************************************
1509
- with gr.Tab("Testing Data Generation and RAG Customization"):
1510
- from utils import save_params_to_file
1511
- def ans_gen_fun(model_name,embedding_name,
1512
- splitter_type_dropdown,chunk_size_slider,
1513
- chunk_overlap_slider,separator_textbox,max_tokens_slider,save_as_fav,progress=gr.Progress()):
1514
- if not os.path.exists(os.path.join("data","testing_dataset.xlsx")):
1515
- gr.Warning("You need to create testing dataset first from Data collection.")
1516
- return
1517
- if save_as_fav:
1518
- save_params_to_file(model_name,embedding_name,
1519
- splitter_type_dropdown,chunk_size_slider,
1520
- chunk_overlap_slider,separator_textbox,max_tokens_slider)
1521
- if not os.path.exists(model_name):
1522
- gr.Error("Model not found in local folder!!")
1523
- import time
1524
- from model_ret import calculate_rag_metrics
1525
- progress(0, desc="Starting...")
1526
- idx=1
1527
- model_ques_ans_gen=[]
1528
- df_temp=pd.read_excel(r"data/testing_dataset.xlsx")
1529
- infer_model = model_chain(model_name,None,
1530
- True,embedding_name,splitter_type_dropdown,chunk_size_slider,
1531
- chunk_overlap_slider,separator_textbox,max_tokens_slider)
1532
- rag_chain=infer_model.rag_chain_ret()
1533
- for x in progress.tqdm(df_temp.values):
1534
- model_ques_ans_gen.append({
1535
- "id":idx,
1536
- "question":x[0]
1537
- ,'answer':rag_chain.ans_ret(x,rag_chain)
1538
- , "contexts":x[2]
1539
- , "ground_truths":x[1]
1540
- })
1541
- idx+=1
1542
- temp=calculate_rag_metrics(model_ques_ans_gen,model_name)
1543
- temp['Average Rating'] = temp.mean(axis=1)
1544
- pd.DataFrame(temp).to_excel(os.path.join("model_ans",f"_{model_name+cur_time}.xlsx"),index=False)
1545
- rag_metrics = ['answer_correctness', 'answer_similarity', 'answer_relevancy', 'faithfulness', 'context_recall', 'context_precision']
1546
- new_df = pd.DataFrame({'Rag Metric': rag_metrics, 'Average Rating': temp.mean()})
1547
-
1548
- return gr.BarPlot(
1549
- new_df,
1550
- x="Rag Metric",
1551
- y="Average Rating",
1552
- x_title="Rag Metric",
1553
- y_title="Average Rating",
1554
- title="RAG performance",
1555
- tooltip=["Rag Metric", "Average Rating"],
1556
- y_lim=[1, 200],
1557
- width=150,
1558
- # height=1000,
1559
- visible=True
1560
- )
1561
- gr.Info("Generating answer from model is finished!!! Now, it is ready for human evaluation. Model answer is saved in \"model_ans\" folder. ")
1562
-
1563
- gr.Markdown(""" # Instructions:\n
1564
- In this page you can generate answer from fine-tuned models for human evaluation. The questions must be created using `Testing data generation` section of `Data collection` tab.
1565
- """)
1566
- with gr.Row():
1567
- embedding_name=gr.Dropdown(choices=["BAAI/bge-base-en-v1.5","dunzhang/stella_en_1.5B_v5","dunzhang/stella_en_400M_v5",
1568
- "nvidia/NV-Embed-v2","Alibaba-NLP/gte-Qwen2-1.5B-instruct"],
1569
- label="Select the Embedding Model")
1570
- splitter_type_dropdown = gr.Dropdown(choices=["character", "recursive", "token"],
1571
- value="character", label="Splitter Type",interactive=True)
1572
-
1573
- chunk_size_slider = gr.Slider(minimum=100, maximum=2000, value=500, step=50, label="Chunk Size")
1574
- chunk_overlap_slider = gr.Slider(minimum=0, maximum=500, value=30, step=10, label="Chunk Overlap",interactive=True)
1575
- separator_textbox = gr.Textbox(value="\n", label="Separator (e.g., newline '\\n')",interactive=True)
1576
- max_tokens_slider = gr.Slider(minimum=100, maximum=5000, value=1000, step=100, label="Max Tokens",interactive=True)
1577
- with gr.Row():
1578
- save_as_fav=gr.Checkbox(label="Save this settings as favorite")
1579
- model_name=gr.Dropdown(choices=os.listdir("models"),label="Select the Model")
1580
- with gr.Row():
1581
- ans_gen=gr.Button("Generate Answer for Testing Dataset")
1582
- with gr.Row():
1583
- plot = gr.BarPlot(visible=False)
1584
- ans_gen.click(ans_gen_fun,[model_name,embedding_name,
1585
- splitter_type_dropdown,chunk_size_slider,
1586
- chunk_overlap_slider,separator_textbox,max_tokens_slider,save_as_fav],plot)
1587
- #***************************************************Human evaluation
1588
- import secrets
1589
-
1590
- def generate_token():
1591
- while True:
1592
- token=secrets.token_hex(6)
1593
- f=[x[:-5] for x in os.listdir("save_ques_ans")]
1594
- if token not in f:
1595
- data = {
1596
- 'id': [],
1597
- 'question': [],
1598
- 'answer': []
1599
- }
1600
- df = pd.DataFrame(data)
1601
- df.to_excel("save_ques_ans//"+str(token)+".xlsx", index=False)
1602
- return gr.Label(label="Please keep the token for tracking question answer data",value=token,visible=True)
1603
-
1604
- def bar_plot_fn():
1605
- temp=score_report_bar()
1606
- return gr.BarPlot(
1607
- temp,
1608
- x="Model Name",
1609
- y="Average Rating",
1610
- x_title="Model name",
1611
- y_title="Average Rating",
1612
- title="Model performance",
1613
- tooltip=["Model Name", "Average Rating"],
1614
- y_lim=[1, 200],
1615
- width=150,
1616
- # height=1000,
1617
- visible=True
1618
- )
1619
- with gr.Tab("Human Evaluation"):
1620
- def answer_updated(model_ans):
1621
- df_ques_ans=pd.read_excel(os.path.join("model_ans",str(model_ans)))
1622
- num=0
1623
- print(df_ques_ans['id'][num],"**"*10)
1624
- return [gr.Markdown(value=f"""# Model_name: {model_ans}
1625
- # Number of questions: {len(df_ques_ans)}""",visible=True),
1626
- gr.Label(value=str(df_ques_ans['id'][num])),
1627
- gr.Label(value=str(df_ques_ans['question'][num])),
1628
- gr.Label(value=str(df_ques_ans['answer'][num])),
1629
- gr.Dropdown(visible=False),
1630
- gr.Button(visible=False)
1631
- ]
1632
-
1633
- with gr.Row():
1634
- new_user=gr.Button("New User")
1635
- with gr.Row():
1636
- new_user_token=gr.Label(visible=False)
1637
- with gr.Row():
1638
- token_key=gr.Textbox(label="Enter your Token")
1639
- model_ans=gr.Dropdown(choices=os.listdir("model_ans"),label="Select the Model Answer for Human Evaluation")
1640
- btn_1=gr.Button("Submit")
1641
- gr.Markdown(""" # Instructions:
1642
- In this section, humans evaluate the answers of the model given specific questions. Each answer is rated between 1 and 5 by anonymous students.
1643
- Those values are saved in the `scrore_report` folder.
1644
- """)
1645
- lab_temp=gr.Markdown(visible=False)
1646
-
1647
- with gr.Row():
1648
- id=gr.Label(value="",label="ID")
1649
- with gr.Row():
1650
- ques=gr.Label(value="",label="Question")
1651
- with gr.Row():
1652
- ans=gr.Label(value="",label="Answer")
1653
- with gr.Row():
1654
- score = gr.Radio(choices=[1,2,3,4,5],label="Rating")
1655
- with gr.Row():
1656
- human_ans_btn=gr.Button("Show Answer From Other Evaluators")
1657
- with gr.Row():
1658
- human_ans_lab=gr.Label(label="Human Answer",visible=False)
1659
- with gr.Row():
1660
- btn = gr.Button("Save")
1661
- question = gr.Button("Skip")
1662
- # with gr.Row():
1663
- # save_all_btn=gr.Button("Save all the data in dataframe")
1664
- # with gr.Row():
1665
- # move=gr.Number(label="Move to the question")
1666
- # move_btn=gr.Button("move")
1667
- with gr.Row():
1668
- btn_plot=gr.Button("Plot Generation")
1669
- with gr.Row():
1670
- plot = gr.BarPlot(visible=False)
1671
- btn_plot.click(bar_plot_fn, None, outputs=plot)
1672
- btn_1.click(answer_updated,model_ans,[lab_temp,id,ques,ans,model_ans,btn_1])
1673
- btn.click(score_save, inputs=[ques,ans,score,model_ans,token_key], outputs=[id,ques,ans])
1674
- question.click(new_ques,model_ans,[id,ques,ans])
1675
- # save_all_btn.click(save_all,model_ans,None)
1676
- # move_btn.click(move_to,[move,model_ans],[id,ques,ans])
1677
- def human_ans_func(id, ques):
1678
- temp=all_contri_ans(id,ques)
1679
- return [gr.Button("Show Answer from Other Evaluators"),gr.Label(value="\n".join(temp),visible=True)]
1680
- human_ans_btn.click(human_ans_func,[id, ques],[human_ans_btn,human_ans_lab])
1681
- new_user.click(generate_token,None,new_user_token)
1682
-
1683
- #***************************************************
1684
- infer_ragchain=None
1685
- with gr.Tab("Inference"):
1686
- def echo(message, history,model_name_local,model_name_online,
1687
- inf_checkbox,embedding_name,splitter_type_dropdown,chunk_size_slider,
1688
- chunk_overlap_slider,separator_textbox,max_tokens_slider):
1689
- global infer_ragchain
1690
- if infer_ragchain is None:
1691
- gr.Info("Please wait!!! model is loading!!")
1692
- if inf_checkbox:
1693
- gr.Info("Model is loading from Huggingface!!")
1694
- infer_ragchain = model_chain(model_name_local,model_name_online,
1695
- inf_checkbox,embedding_name,splitter_type_dropdown,chunk_size_slider,
1696
- chunk_overlap_slider,separator_textbox,max_tokens_slider)
1697
- rag_chain=infer_ragchain.rag_chain_ret()
1698
- return infer_ragchain.ans_ret(message,rag_chain)
1699
- from utils import load_params_from_file
1700
- saved_params = load_params_from_file()
1701
- # If saved parameters exist, use them; otherwise, set default values
1702
- default_model_name = saved_params['model_name'] if saved_params else "Llama"
1703
- default_embedding_name = saved_params['embedding_name'] if saved_params else "BAAI/bge-base-en-v1.5"
1704
- default_splitter_type = saved_params['splitter_type_dropdown'] if saved_params else "character"
1705
- default_chunk_size = saved_params['chunk_size_slider'] if saved_params else 500
1706
- default_chunk_overlap = saved_params['chunk_overlap_slider'] if saved_params else 30
1707
- default_separator = saved_params['separator_textbox'] if saved_params else "\n"
1708
- default_max_tokens = saved_params['max_tokens_slider'] if saved_params else 1000
1709
- with gr.Row():
1710
- def login_hug(token):
1711
- from huggingface_hub import login
1712
- login(token=token)
1713
- login_hug(os.getenv('HF_TOKEN'))
1714
- with gr.Row():
1715
- embedding_name=gr.Dropdown(choices=["BAAI/bge-base-en-v1.5","dunzhang/stella_en_1.5B_v5","dunzhang/stella_en_400M_v5",
1716
- "nvidia/NV-Embed-v2","Alibaba-NLP/gte-Qwen2-1.5B-instruct"],value=default_embedding_name,
1717
- label="Select the Embedding Model")
1718
- splitter_type_dropdown = gr.Dropdown(choices=["character", "recursive", "token"],
1719
- value=default_splitter_type, label="Splitter Type",interactive=True)
1720
-
1721
- chunk_size_slider = gr.Slider(minimum=100, maximum=2000, value=default_chunk_size, step=50, label="Chunk Size")
1722
- chunk_overlap_slider = gr.Slider(minimum=0, maximum=500, value=default_chunk_overlap, step=10, label="Chunk Overlap",interactive=True)
1723
- separator_textbox = gr.Textbox(value=default_separator, label="Separator (e.g., newline '\\n')",interactive=True)
1724
- max_tokens_slider = gr.Slider(minimum=100, maximum=5000, value=default_max_tokens, step=100, label="Max Tokens",interactive=True)
1725
-
1726
- inf_checkbox=gr.Checkbox(label="Do you want to use without fine-tuned model from Hugging face?")
1727
- model_name_local=gr.Dropdown(choices=os.listdir("models"),visible=True,label="Select the fine-tuned LLM",value=default_model_name)
1728
- model_name_online=gr.Dropdown(visible=False)
1729
- def model_online_local_show(inf_checkbox):
1730
- if inf_checkbox:
1731
- return [gr.Dropdown(visible=False),
1732
- gr.Dropdown(choices=["Zephyr","Llama","Mistral", "Phi", "Flant5"],
1733
- label="Select the LLM from Huggingface",visible=True)]
1734
- else:
1735
- return [gr.Dropdown(choices=os.listdir("models"),label="Select the fine-tuned LLM",visible=True),
1736
- gr.Dropdown(visible=False)]
1737
-
1738
- inf_checkbox.change(model_online_local_show,[inf_checkbox],[model_name_local,model_name_online])
1739
- gr.ChatInterface(fn=echo,
1740
- additional_inputs=[model_name_local,model_name_online,inf_checkbox,embedding_name,
1741
- splitter_type_dropdown,chunk_size_slider,
1742
- chunk_overlap_slider,separator_textbox,max_tokens_slider],
1743
- title="Chatbot")
1744
- #----------------------------------------------
1745
- with gr.Tab("Deployment"):
1746
- gr.Markdown("""`deploy` folder has all the code for the deployment of the model.
1747
- For installing dependencies use the following command: `pip install -r requirements.txt`.
1748
- """)
1749
- def deploy_func(model_name):
1750
- import shutil
1751
- import os
1752
- src_folder = 'src'
1753
- deploy_folder = 'deploy'
1754
- files_to_copy = ['model_ret.py', 'create_retriever.py', 'inference.py']
1755
- for file_name in files_to_copy:
1756
- src_file_path = os.path.join(src_folder, file_name)
1757
- dest_file_path = os.path.join(deploy_folder, file_name)
1758
- param_list=load_params_from_file()
1759
- param_list["model_name"]=model_name
1760
- save_params_to_file(param_list)
1761
- # f.write(f"{model_name}")
1762
-
1763
-
1764
- model_name=gr.Dropdown(choices=os.listdir("models"),label="Select the Model")
1765
- btn_model=gr.Button("Deploy")
1766
- btn_model.click(deploy_func,model_name)
1767
-
1768
- demo.launch(share=False)
 
226
  ques_temp,ans_temp=random_ques_ans2()
227
  return gr.Label(value=ques_temp)
228
 
229
+ with gr.Blocks(title="LLM QA Chatbot Builder") as demo:
230
  gr.Markdown("""
231
  # LLM QA Chatbot Builder
232
  """)
 
905
  btn_model=gr.Button("Deploy")
906
  btn_model.click(deploy_func,model_name)
907
 
908
+ demo.launch(share=False, debug=True)