-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.py
3280 lines (2959 loc) · 210 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pandas as pd
import math
import numpy as np
import gc
import os,requests
from src.utils.common import login_huggingface
import subprocess,threading
from src.finetune.huggingface_inference import HuggingfaceInference
from src.finetune.llama_cpp_inference import LlamaCppInference
from src.rag.qa_with_rag import QAWithRAG
import time
import gradio as gr
import os
from src.utils.common import read_yaml,get_first_row_from_dataset,\
get_runs_model_names_from_dir,get_hg_model_names_from_dir,get_hg_model_names_and_gguf_from_dir,validate_model_path,get_runs_models
from src.utils.chat_prompts import get_model_type,get_chat_history_prompt,get_model_prompt_template
from transformers.training_args import OptimizerNames
from huggingface_hub import hf_hub_download
from src.utils import download_model
from pathlib import Path
import traceback
import numpy as np
import glob
import shutil
import torch
from src.finetune.qlora_trainer import QloraTrainer
from src.finetune.qlora_trainer import TRAINING_STATUS
from src.utils.download_huggingface_repo import download_model_wrapper,download_dataset_wrapper
import socket
# os.environ['HTTP_PROXY'] = 'http://127.0.0.1:8889'
# os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:8889'
LOCAL_HOST_IP = "0.0.0.0"
TENSORBOARD_URL = "http://" + LOCAL_HOST_IP + ":6006/"
INIT_DATASET_NAME = "test_python_code_instructions_5000_rows"
RAG_DATA_LIST_DROPDOWN = ""
TEXT_SPLITTER_DROPDOWN = ""
CHUNK_SIZE_SLIDER = 0
CHUNK_OVERLAP_SLIDER = -1
SEPARATORS_TEXTBOX = ""
EMBEDDING_MODEL_SOURCE_RADIO = ""
HUB_EMBEDDING_MODEL_NAMES_DROPDOWN = ""
LOCAL_EMBEDDING_MODEL_NAMES_DROPDOWN = ""
CHAT_MODEL_SOURCE_RADIO = ""
HUB_CHAT_MODEL_NAMES_DROPDOWN = ""
LOCAL_CHAT_MODEL_NAMES_DROPDOWN = ""
SEARCH_TOP_K_SLIDER = ""
SEARCH_SCORE_THRESHOLD_SLIDER = ""
training_ret_val = -1
error_msg = ""
current_running_model_name = ""
infer_model = None
stop_generation_status = False
chatbot_history=[]
chatbot_height = 500
rag_chatbot_history=[]
rag_stop_generation_status = False
qa_with_rag = QAWithRAG()
train_param_config = {}
train_param_config["dataset"]={}
train_param_config["model"]={}
train_param_config["training"]={}
model_zoo_config = {}
transformer_optimizer_list = []
model_context_window = 0
init_train_file_path = None
init_val_file_path = None
INIT_PREFIX1 = ""
INIT_PREFIX2 = ""
INIT_PREFIX3 = ""
INIT_PREFIX4 = ""
INIT_COL1_TEXT = ""
INIT_COL2_TEXT = ""
INIT_COL3_TEXT = ""
INIT_COL4_TEXT = ""
col_names = []
DATASET_FIRST_ROW = None
local_model_list = ""
local_model_root_dir = ""
base_model_names = []
training_base_model_names = []
embedding_model_names = []
base_model_context_window = []
local_dataset_list = []
local_dataset_root_dir = ""
def get_local_embedding_model_list():
local_model_root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rag", "embedding_models")
local_model_root_files = os.listdir(local_model_root_dir)
local_model_list = []
for model_dir in local_model_root_files:
if os.path.isdir(os.path.join(local_model_root_dir, model_dir)):
local_model_list.append(model_dir)
return local_model_list,local_model_root_dir
def get_local_model_list():
local_model_root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
local_model_root_files = os.listdir(local_model_root_dir)
local_model_list = []
for model_dir in local_model_root_files:
if os.path.isdir(os.path.join(local_model_root_dir, model_dir)):
local_model_list.append(model_dir)
return local_model_list,local_model_root_dir
def get_local_dataset_list():
local_dataset_list = []
local_dataset_root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "datasets")
matched_dataset_file_path_list = glob.glob(os.path.join(local_dataset_root_dir,"**","dataset_infos.json"),recursive=False)
for matched_file_path in matched_dataset_file_path_list:
matched_pos1 = matched_file_path.rfind("datasets")
matched_pos2 = matched_file_path.rfind("dataset_infos.json")
local_dataset_list.append(matched_file_path[matched_pos1 + 9:matched_pos2-1])
matched_dataset_file_path_list = glob.glob(os.path.join(local_dataset_root_dir,"**","dataset_dict.json"),recursive=False)
for matched_file_path in matched_dataset_file_path_list:
matched_pos1 = matched_file_path.rfind("datasets")
matched_pos2 = matched_file_path.rfind("dataset_dict.json")
local_dataset_list.append(matched_file_path[matched_pos1 + 9:matched_pos2-1])
return local_dataset_list,local_dataset_root_dir
def start_tensorboard_server():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((LOCAL_HOST_IP, 6006))
s.close()
except Exception as e:
tensorboard_cmd = f"tensorboard --logdir {os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs')} --reload_multifile True"
tensorboard_proc = subprocess.Popen(tensorboard_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
shell=True, close_fds=True) # bufsize=0, close_fds=True
def init():
global config_dict,transformer_optimizer_list,model_context_window,init_train_file_path,init_val_file_path
global INIT_PREFIX1,INIT_COL1_TEXT,INIT_PREFIX2,INIT_COL2_TEXT,INIT_PREFIX3,INIT_COL3_TEXT,INIT_PREFIX4,INIT_COL4_TEXT,col_names,DATASET_FIRST_ROW
global local_model_list,local_model_root_dir
global base_model_names,base_model_context_window,embedding_model_names,training_base_model_names
global local_dataset_list, local_dataset_root_dir
start_tensorboard_server()
model_zoo_config = read_yaml(os.path.join(os.path.dirname(os.path.abspath(__file__)),"config","model_zoo.yaml"))
transformer_optimizer_list = list(vars(OptimizerNames)["_value2member_map_"].keys())
#get dynamic context window from selected model
model_context_window = [2048,1024,512]
init_train_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "datasets", INIT_DATASET_NAME)
DATASET_FIRST_ROW,split_list = get_first_row_from_dataset(init_train_file_path)
col_names = list(DATASET_FIRST_ROW)
col_names.insert(0,"")
INIT_PREFIX1 = "<s>[INST] "
INIT_PREFIX2 = "here are the inputs "
INIT_PREFIX3 = " [/INST]"
INIT_PREFIX4 = "</s>"
INIT_COL1_TEXT = str(DATASET_FIRST_ROW[col_names[1]])
INIT_COL2_TEXT = str(DATASET_FIRST_ROW[col_names[2]])
INIT_COL3_TEXT = str(DATASET_FIRST_ROW[col_names[3]])
INIT_COL4_TEXT = ""
local_model_list,local_model_root_dir = get_local_model_list()
base_model_names = [model_name for model_name in model_zoo_config["model_list"]]
training_base_model_names = [model_name for model_name in base_model_names if not model_name.endswith(".gguf")]
# base_model_context_window = [model_name[1] for model_name in model_zoo_config["model_list"]]
embedding_model_names = [model_name for model_name in model_zoo_config["embedding_model_list"]]
local_dataset_list, local_dataset_root_dir = get_local_dataset_list()
with gr.Blocks(title="FINETUNE",css="#vertical_center_align_markdown { position:absolute; top:30%;background-color:white;} .white_background {background-color: #ffffff} .none_border {border: none;border-collapse:collapse;}") as demo:
init()
local_model_root_dir_textbox = gr.Textbox(label="", value=local_model_root_dir, visible=False)
local_dataset_root_dir_textbox = gr.Textbox(label="",value=local_dataset_root_dir, visible=False)
local_embedding_model_root_dir_textbox = gr.Textbox(label="", value=os.path.join(os.path.dirname(os.path.abspath(__file__)), "rag", "embedding_models"), visible=False)
local_chat_model_root_dir_textbox = gr.Textbox(label="", value=local_model_root_dir, visible=False)
local_home_chat_model_root_dir_textbox = gr.Textbox(label="", value=local_model_root_dir, visible=False)
session_state = gr.State(value={})
# html = gr.HTML("<p align='center';>llm-web-ui</p>",elem_id="header")
with gr.Tab("Home"):
with gr.Row():
# with gr.Column(scale=4, min_width=1):
with gr.Group():
gr.Markdown("## ChatBot", elem_classes="white_background")
with gr.Group():
gr.Markdown("### Chat Model", elem_classes="white_background")
local_home_chat_model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
runs_model_root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "runs")
local_home_chat_model_names = get_hg_model_names_and_gguf_from_dir(local_home_chat_model_dir,
runs_model_root_dir)
home_chat_model_source_radio_choices = ["Download From Huggingface Hub",
f"From Local Dir(hg format:{local_home_chat_model_dir})"]
home_chat_model_source_radio = gr.Radio(home_chat_model_source_radio_choices,
label="Chat Model source", show_label=False,
value=home_chat_model_source_radio_choices[0],
interactive=True)
with gr.Row():
hub_home_chat_model_names_dropdown = gr.Dropdown(base_model_names,
label=f"Chat Model", show_label=False,
allow_custom_value=True,
value=base_model_names[
0] if base_model_names else None,
interactive=True, scale=4, min_width=1)
local_home_chat_model_names_dropdown = gr.Dropdown(local_home_chat_model_names,
label=f"Chat Model", show_label=False,
value=local_home_chat_model_names[
0] if local_home_chat_model_names else None,
interactive=True, scale=4, min_width=1,
visible=False)
download_hub_home_chat_model_names_btn = gr.Button("Download", scale=1)
stop_download_hub_home_chat_model_names_btn = gr.Button("Stop", scale=1, visible=False)
refresh_local_home_chat_model_names_btn = gr.Button("Refresh", scale=1, visible=False)
load_home_chat_model_btn = gr.Button("Load Model", scale=1, visible=True)
using_4bit_quantization_checkbox = gr.Checkbox(True, label="Using 4-bit quantization",
interactive=True, visible=True,
info="Less memory but slower", scale=1
)
if validate_model_path(base_model_names[0])[0]:
download_hub_home_chat_model_status_markdown = gr.Markdown(
'<span style="color:green"> This model has already been downloaded to local,click load model to run.</span>')
else:
download_hub_home_chat_model_status_markdown = gr.Markdown(
'<span style="color:red"> This model has not been downloaded.</span>')
# home_chat_model_running_status_markdown = gr.Markdown(
# '<span style="color:red"> This model has not been downloaded.</span>')
with gr.Row():
chatbot = gr.Chatbot(value=[],bubble_full_width=False,rtl=False,layout="panel",height=chatbot_height,
avatar_images=((os.path.join(os.path.abspath(''),"pics", "user1.png")), (os.path.join(os.path.abspath(''),"pics", "bot4.png"))),
)
with gr.Row():
input_txtbox = gr.Textbox(
show_label=False,autofocus=True,
placeholder="Enter text and press enter",scale=3
)
generate_btn = gr.Button("Generate", scale=1)
stop_btn = gr.Button("Stop", scale=1)
# clear_btn = gr.Button("Clear",scale=1)
with gr.Tab("Fine-Tuning"):
with gr.Tabs() as tensorboard_tab:
with gr.TabItem("Training", id=0):
with gr.Row():
with gr.Column(scale=1, min_width=1):
with gr.Group():
gr.Markdown("## 1.Training", elem_classes="white_background")
with gr.Group():
gr.Markdown("### 1).Model", elem_classes="white_background")
with gr.Group():
# gr.Markdown("<br> Base Model")
base_model_source_radio_choices = ["Download From Huggingface Hub",
f"From Local Dir(hg format:{local_model_root_dir})"]
base_model_source_radio = gr.Radio(base_model_source_radio_choices,
label="Base Model",
value=base_model_source_radio_choices[0],
interactive=True)
with gr.Row(elem_classes="white_background"):
base_model_name_dropdown = gr.Dropdown(training_base_model_names,
label="Model Name", value=training_base_model_names[0] if training_base_model_names else None,
interactive=True, visible=True, scale=5,
allow_custom_value=True)
download_local_model_btn = gr.Button("Download", scale=1, visible=True)
stop_download_local_model_btn = gr.Button("Stop", scale=1, visible=False)
# model_download_status = gr.Markdown("<div id='vertical_center_align_markdown'><p style='text-align: center;'>Not downloaded</p></div>", elem_classes="white_background",scale=1,full_width=True,visible=False)
if validate_model_path(training_base_model_names[0])[0]:
download_model_status_markdown = gr.Markdown('<span style="color:green"> This model has already been downloaded to local.</span>')
else:
download_model_status_markdown = gr.Markdown('<span style="color:red"> This model has not been downloaded.</span>')
with gr.Row():
# local_home_chat_model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
# runs_model_root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "runs")
# local_model_list = get_hg_model_names_and_gguf_from_dir(local_home_chat_model_dir,runs_model_root_dir)
local_model_list = get_hg_model_names_from_dir(os.path.dirname(os.path.abspath(__file__)), "models")
local_model_dropdown = gr.Dropdown(local_model_list, label="Local Model",
info="",
value=local_model_list[0] if len(local_model_list) > 0 else None,
interactive=True,
elem_classes="white_background", scale=5,
visible=False)
refresh_local_model_list_btn = gr.Button("Refresh", scale=1, visible=False)
fine_tuning_type_dropdown = gr.Dropdown(["QLoRA", "LoRA"],
label="Fine-Tuning Type", info="",
value="QLoRA", interactive=True)
with gr.Group():
with gr.Row(elem_classes="white_background"):
# gr.Markdown("### LoRA Config", elem_classes="white_background")
lora_r_list = [str(ri) for ri in range(8, 65, 8)]
lora_r_slider = gr.Slider(8, 64, value=8, step=8, label="lora_r",
interactive=True)
# lora_r_dropdown = gr.Dropdown(lora_r_list,label="lora_r", value=lora_r_list[0],interactive=True,allow_custom_value=True)
lora_alpha_slider = gr.Slider(8, 96, value=32, step=8, label="lora_alpha",
interactive=True)
# lora_alpha_list = [str(ri) for ri in range(8, 97, 8)]
# lora_alpha_dropdown = gr.Dropdown(lora_alpha_list,label="lora_alpha", value=lora_alpha_list[3],interactive=True,allow_custom_value=True)
with gr.Row(elem_classes="white_background"):
lora_dropout_slider = gr.Slider(0, 1, value=0.05, step=0.01,
label="lora_dropout", interactive=True)
lora_bias_dropdown = gr.Dropdown(["none", "all", "lora_only"],
label="lora_bias", info="", value="none",
interactive=True)
with gr.Group():
gr.Markdown("### 2).Dataset",elem_classes="white_background")
dataset_source_radio_choices = ["Download From Huggingface Hub",
f"From Local HG Dataset In {local_dataset_root_dir})"]
dataset_source_radio = gr.Radio(dataset_source_radio_choices, label="Dataset Source",
value=dataset_source_radio_choices[1], interactive=True)
with gr.Row(equal_height=True):
hg_dataset_path_textbox = gr.Textbox(label="Dataset Name:",elem_classes="none_border",visible=False, interactive=True, scale=4,
value="iamtarun/python_code_instructions_18k_alpaca")
download_local_dataset_btn = gr.Button("Download", scale=1, visible=False)
stop_download_local_dataset_btn = gr.Button("Stop", scale=1, visible=False)
download_dataset_status_markdown = gr.Markdown('')
with gr.Row():
hg_train_dataset_dropdown = gr.Dropdown(["train"], label="Train set", info="", interactive=False,visible=False,
elem_classes="white_background", scale=1,value="train")
hg_val_dataset_dropdown = gr.Dropdown([], label="Val set", info="", interactive=False,visible=False,
elem_classes="white_background", scale=1)
with gr.Row():
local_dataset_list.pop(
local_dataset_list.index(INIT_DATASET_NAME))
local_dataset_list.insert(0, INIT_DATASET_NAME)
local_train_path_dataset_dropdown = gr.Dropdown(local_dataset_list, label="Train Dataset", info="",
value=local_dataset_list[0] if len(local_dataset_list)>0 else None, interactive=True,
elem_classes="white_background", scale=5, visible=True)
refresh_local_train_path_dataset_list_btn = gr.Button("Refresh", scale=1, visible=True)
with gr.Row():
local_train_dataset_dropdown = gr.Dropdown(["train"], label="Train set", info="", interactive=True,
elem_classes="white_background", scale=1,value="train",visible=True)
local_val_dataset_dropdown = gr.Dropdown([], label="Val set", info="", interactive=True,
elem_classes="white_background", scale=1,visible=True)
with gr.Group(elem_classes="white_background"):
# gr.Markdown("<h4><br> Prompt Template: (Prefix1 + ColumnName1 + Prefix2 + ColumnName2)</h4>",elem_classes="white_background")
gr.Markdown("<br> **Prompt Template: (Prefix1+ColumnName1+Prefix2+ColumnName2+Prefix3+ColumnName3+Prefix4+ColumnName4)**",elem_classes="white_background")
gr.Markdown(
"<span> **Note**: Llama2/Mistral Chat Template:<s\>[INST] instruction+input [/INST] output</s\> </span>",elem_classes="white_background")
# using_llama2_chat_template_checkbox = gr.Checkbox(True, label="Using Llama2/Mistral chat template",interactive=True,visible=False)
with gr.Row(elem_classes="white_background"):
# prompt_template
prefix1_textbox = gr.Textbox(label="Prefix1:",value=INIT_PREFIX1,lines=2,interactive=True,elem_classes="white_background")
datatset_col1_dropdown = gr.Dropdown(col_names, label="ColumnName1:", info="",value=col_names[1],interactive=True,elem_classes="white_background")
prefix2_textbox = gr.Textbox(label="Prefix2:",value=INIT_PREFIX2,lines=2,interactive=True,elem_classes="white_background")
datatset_col2_dropdown = gr.Dropdown(col_names, label="ColumnName2:", info="",value=col_names[2],interactive=True,elem_classes="white_background")
with gr.Row(elem_classes="white_background"):
prefix3_textbox = gr.Textbox(label="Prefix3:",value=INIT_PREFIX3,lines=2,interactive=True,elem_classes="white_background")
datatset_col3_dropdown = gr.Dropdown(col_names, label="ColumnName3:", info="",value=col_names[3],interactive=True,elem_classes="white_background")
prefix4_textbox = gr.Textbox(label="Prefix4:",value=INIT_PREFIX4,lines=2,interactive=True,elem_classes="white_background")
datatset_col4_dropdown = gr.Dropdown(col_names, label="ColumnName4:", info="",value=col_names[0],interactive=True,elem_classes="white_background")
# print("")
prompt_sample = INIT_PREFIX1 + INIT_COL1_TEXT + INIT_PREFIX2 + INIT_COL2_TEXT + INIT_PREFIX3 + INIT_COL3_TEXT + INIT_PREFIX4 + INIT_COL4_TEXT
prompt_sample_textbox = gr.Textbox(label="Prompt Sample:",interactive=False,value=prompt_sample,lines=4)
max_length_dropdown = gr.Dropdown(["Model Max Length"]+model_context_window, label="Max Length",value="Model Max Length", interactive=True,allow_custom_value=True)
with gr.Group():
gr.Markdown("### 3).Training Arguments",elem_classes="white_background")
with gr.Row(elem_classes="white_background"):
epochs_slider = gr.Slider(1, 100, value=10, step=1, label="Epochs", interactive=True)
# epochs_dropdown = gr.Dropdown([1]+[bi for bi in range(10,101,10)], label="Epochs",value=1, interactive=True,allow_custom_value=True)
batch_size_list = [1,2,3]+[bi for bi in range(4,32+1,4)]
batch_size_slider = gr.Slider(1, 100, value=1, step=1, label="Batch Size", interactive=True)
# batch_size_dropdown = gr.Dropdown(batch_size_list,label="Batch Size", info="",value=batch_size_list[0],interactive=True,allow_custom_value=True)
# learning_rate_textbox = gr.Textbox(label="Learning Rate", value=2e-4,interactive=True)
with gr.Row(elem_classes="white_background"):
learning_rate_slider = gr.Slider(0, 0.01, value=2e-4, step=0.0001, label="Learning Rate", interactive=True)
warmup_steps_slider = gr.Slider(0, 400, value=100, step=10, label="Warmup Steps",
interactive=True)
with gr.Row(elem_classes="white_background"):
optimizer_dropdown = gr.Dropdown(transformer_optimizer_list, label="Optimizer", info="",
value=transformer_optimizer_list[1], interactive=True)
lr_scheduler_list = ["linear","cosine","cosine_with_hard_restarts","polynomial_decay","constant","constant_with_warmup","inverse_sqrt","reduce_on_plateau"]
lr_scheduler_type_dropdown = gr.Dropdown(lr_scheduler_list, label="LR Scheduler Type", info="",
value=lr_scheduler_list[0], interactive=True)
with gr.Row(elem_classes="white_background"):
early_stopping_patience_slider = gr.Slider(0, 50+1, value=0, step=5, label="Early Stopping Patience",
interactive=True)
gradient_accumulation_steps_slider = gr.Slider(1, 50, value=1, step=1,
label="Gradient Accumulation Steps")
with gr.Row(elem_classes="white_background"):
eval_steps_slider = gr.Slider(0, 1000, value=100, step=100, label="eval_steps", interactive=True)
gradient_checkpointing_checkbox = gr.Checkbox(True,label="Gradient Checkpointing",interactive=True)
train_btn = gr.Button("Start Training")
with gr.Column(scale=1, min_width=1):
with gr.Group():
gr.Markdown("## 2.Test",elem_classes="white_background")
training_runs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs')
run_names = os.listdir(training_runs_dir)
run_names.sort(key=lambda file:os.path.getmtime(os.path.join(training_runs_dir,file)))
runs_output_model = []
for run_name in run_names:
run_name_dir = os.path.join(training_runs_dir,run_name)
run_output_model = os.path.join(run_name_dir,"output_model")
if os.path.exists(run_output_model):
run_output_model_names = os.listdir(run_output_model)
for run_output_model_name in run_output_model_names:
if run_output_model_name.find("merged_")>=0:
runs_output_model.append(os.path.join(run_name,"output_model",run_output_model_name, "ori"))
runs_output_model = runs_output_model[::-1]
runs_output_model_dropdown = gr.Dropdown(runs_output_model, label="runs_output_model",
value=runs_output_model[0] if runs_output_model else None, interactive=True)
gr.Markdown("")
gr.Markdown(
"<span> **Note**: Llama2/Mistral Chat Template:<s\>[INST] instruction+input [/INST] output</s\> </span>",
elem_classes="white_background")
with gr.Row():
test_input_textbox = gr.Textbox(label="Input:", interactive=True, value="", lines=4,
scale=4)
generate_text_btn = gr.Button("Generate",scale=1)
finetune_test_using_4bit_quantization_checkbox = gr.Checkbox(True, label="Using 4-bit quantization",
interactive=True, visible=True,
info="Less memory but slower", scale=1
)
# test_prompt = gr.Textbox(label="Prompt:", interactive=False, lines=2, scale=1)
test_output = gr.Textbox(label="Output:", interactive=False,lines=4, scale=1)
# def change_test_input_textbox(test_prefix1_textbox,test_input_textbox,test_prefix2_textbox):
# return gr.update(value=test_prefix1_textbox+test_input_textbox+test_prefix2_textbox)
# test_input_textbox.change(change_test_input_textbox,[test_prefix1_textbox,test_input_textbox,test_prefix2_textbox],test_prompt)
with gr.Group():
gr.Markdown("## 3.Quantization",elem_classes="white_background")
with gr.Row():
quantization_type_list = ["gguf"]
quantization_type_dropdown = gr.Dropdown(quantization_type_list, label="Quantization Type",value=quantization_type_list[0], interactive=True,scale=3)
local_quantization_dataset_dropdown = gr.Dropdown(local_dataset_list, label="Dataset for quantization",
value=local_dataset_list[0] if len(
local_dataset_list) > 0 else None,
interactive=True,
elem_classes="white_background", scale=7,
visible=False)
refresh_local_quantization_dataset_btn = gr.Button("Refresh", scale=2, visible=False)
def click_refresh_local_quantization_dataset_btn():
local_dataset_list, _ = get_local_dataset_list()
return gr.update(choices=local_dataset_list,
value=local_dataset_list[0] if len(local_dataset_list) > 0 else "")
refresh_local_quantization_dataset_btn.click(click_refresh_local_quantization_dataset_btn,[],local_quantization_dataset_dropdown)
with gr.Row():
training_runs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs')
run_names = os.listdir(training_runs_dir)
run_names.sort(key=lambda file: os.path.getmtime(os.path.join(training_runs_dir, file)))
runs_output_model = []
for run_name in run_names:
run_name_dir = os.path.join(training_runs_dir, run_name)
run_output_model = os.path.join(run_name_dir, "output_model")
if os.path.exists(run_output_model):
run_output_model_names = os.listdir(run_output_model)
for run_output_model_name in run_output_model_names:
if run_output_model_name.find("merged_") >= 0:
runs_output_model.append(
os.path.join(run_name, "output_model", run_output_model_name,
"ori"))
runs_output_model = runs_output_model[::-1]
quantization_runs_output_model_dropdown = gr.Dropdown(runs_output_model,
label="runs_output_model",
value=runs_output_model[
0] if runs_output_model else None,
interactive=True, scale=6)
quantize_btn = gr.Button("Quantize", scale=1,visible=False)
if runs_output_model:
model_name = runs_output_model[0].split(os.sep)[-2].split('_')[-1]
quantized_model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs',
os.sep.join(runs_output_model[0].split(os.sep)[0:-1]),
"quantized_" + quantization_type_list[0] + "_" + model_name)
if not os.path.exists(quantized_model_dir):
os.makedirs(quantized_model_dir)
quantization_logging_markdown = gr.Markdown("")
gguf_quantization_markdown0 = gr.Markdown("### GGUF Quantization Instruction:", elem_classes="white_background", visible=True)
gguf_quantization_markdown1 = gr.Markdown(''' 1.Follow the instructions in the llama.cpp to generate a GGUF:[https://github.com/ggerganov/llama.cpp#prepare-data--run](https://github.com/ggerganov/llama.cpp#prepare-data--run),<span style="color:red"> Q4_K_M is recommend</span>''',visible=True)
if runs_output_model:
gguf_quantization_markdown2 = gr.Markdown(f" 2.Convert {runs_output_model[0]} to gguf model",visible=True)
else:
gguf_quantization_markdown2 = gr.Markdown(
f"", visible=True)
gguf_quantization_markdown3 = gr.Markdown(f" 3.Deploy gguf model", visible=False)
else:
quantization_logging_markdown = gr.Markdown("")
gguf_quantization_markdown0 = gr.Markdown("### GGUF Quantization Instruction:", elem_classes="white_background", visible=True)
gguf_quantization_markdown1 = gr.Markdown('''''',visible=True)
gguf_quantization_markdown2 = gr.Markdown(f"",visible=True)
gguf_quantization_markdown3 = gr.Markdown(f"", visible=True)
with gr.Group(visible=False):
gr.Markdown("## 4.Deploy",elem_classes="white_background")
with gr.Row():
deployment_framework_dropdown = gr.Dropdown(["TGI","llama-cpp-python"], label="Deployment Framework",value="TGI", interactive=True)
with gr.Row():
training_runs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs')
run_names = os.listdir(training_runs_dir)
run_names.sort(key=lambda file: os.path.getmtime(os.path.join(training_runs_dir, file)))
# ori_model_runs_output_model = []
tgi_model_format_runs_output_model = []
gguf_model_format_runs_output_model = []
for run_name in run_names:
run_name_dir = os.path.join(training_runs_dir, run_name)
run_output_model = os.path.join(run_name_dir, "output_model")
if os.path.exists(run_output_model):
run_output_model_names = os.listdir(run_output_model)
for run_output_model_name in run_output_model_names:
model_bin_path = os.path.exists(
os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs',
run_name, "output_model", run_output_model_name, "ori",
"pytorch_model.bin"))
if run_output_model_name.find("merged_") >= 0 and model_bin_path:
tgi_model_format_runs_output_model.append(
os.path.join(run_name, "output_model", run_output_model_name, "ori"))
gptq_model_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs',run_name, "output_model", run_output_model_name, "quantized_gptq_"+run_output_model_name.split('_')[-1],
"pytorch_model.bin")
if os.path.exists(gptq_model_path):
tgi_model_format_runs_output_model.append(os.path.join(run_name, "output_model", run_output_model_name, "quantized_gptq_"+run_output_model_name.split('_')[-1]))
gguf_model_dir = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'runs', run_name,
"output_model", run_output_model_name,
"quantized_gguf_" + run_output_model_name.split('_')[-1])
if os.path.exists(gguf_model_dir):
gguf_model_names = os.listdir(gguf_model_dir)
for gguf_model_name in gguf_model_names:
if gguf_model_name.split('.')[-1] == "gguf":
gguf_model_format_runs_output_model.append(
os.path.join(run_name, "output_model",
run_output_model_name, "quantized_gguf_" +
run_output_model_name.split('_')[-1],
gguf_model_name))
tgi_model_format_runs_output_model = tgi_model_format_runs_output_model[::-1]
gguf_model_format_runs_output_model = gguf_model_format_runs_output_model[::-1]
deployment_runs_output_model_dropdown = gr.Dropdown(tgi_model_format_runs_output_model, label="runs_output_model",
value=tgi_model_format_runs_output_model[
0] if tgi_model_format_runs_output_model else None,
interactive=True,scale=6)
refresh_deployment_runs_output_model_btn = gr.Button("Refresh", scale=1, visible=True)
if tgi_model_format_runs_output_model:
model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs',
os.path.dirname(tgi_model_format_runs_output_model[0]))
model_name = os.path.basename(tgi_model_format_runs_output_model[0])
if model_name.rfind("quantized_gptq_") >= 0:
run_server_value = f'''docker run --gpus all --shm-size 1g -p 8080:80 -v {model_dir}:/data ghcr.io/huggingface/text-generation-inference:latest --model-id /data/{model_name} --quantize gptq'''
else:
run_server_value = f'''docker run --gpus all --shm-size 1g -p 8080:80 -v {model_dir}:/data ghcr.io/huggingface/text-generation-inference:latest --model-id /data/{model_name}'''
run_server_script_textbox = gr.Textbox(label="Run Server:", interactive=False,lines=2, scale=1,value=run_server_value)
run_client_value = '''Command-Line Interface(CLI):\ncurl 127.0.0.1:8080/generate -X POST -d '{"inputs":"What is Deep Learning?","parameters":{"max_new_tokens":20}}' -H 'Content-Type: application/json'\n\nPython:\nfrom huggingface_hub import InferenceClient \nclient = InferenceClient(model="http://127.0.0.1:8080")\noutput = client.text_generation(prompt="What is Deep Learning?",max_new_tokens=512)
'''
run_client_script_textbox = gr.Textbox(label="Run Client:", interactive=False, lines=6,scale=1,value=run_client_value)
else:
run_server_script_textbox = gr.Textbox(label="Run Server:", interactive=False,lines=2, scale=1,value="")
run_client_script_textbox = gr.Textbox(label="Run Client:", interactive=False, lines=6,
scale=1, value="")
# deploy_llm_code = gr.Code(code_str, language="shell", lines=5, label="Install Requirements:")
install_requirements_value = '''
### 1.install docker
### 2.Install NVIDIA Container Toolkit
<h4> 2.1 Configure the repository: </h4>
<p> curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg \
&& curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \
sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \
sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list \
&& \
sudo apt-get update </p>
<h4> 2.2 Install the NVIDIA Container Toolkit packages: </h4>
<p> sudo apt-get install -y nvidia-container-toolkit </p>
'''
with gr.Accordion("Install Requirements",open=False) as install_requirements_accordion:
install_requirements_markdown = gr.Markdown(install_requirements_value)
run_llama_cpp_python_code = gr.Code("", language="python", lines=10, label="run_model_using_llama_cpp_python.py",visible=False)
# run_script_textbox = gr.Textbox(label="Install Requirements:", interactive=False, scale=1,value=install_requirements_value)
#dependencies
with gr.TabItem("Tensorboard", id=1) as fdddd:
# training_log_markdown = gr.Markdown('',every=mytestfun)
with gr.Row():
# training_log_textbox = gr.Textbox(label="logging:",value="", interactive=True, lines=2, scale=1)
with gr.Group():
training_log_markdown = gr.Markdown('')
stop_training_btn = gr.Button("Stop Training")
training_runs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs')
run_names = os.listdir(training_runs_dir)
run_names = [run_name for run_name in run_names if os.path.isdir(os.path.join(training_runs_dir,run_name))]
run_names.sort(key=lambda f: os.path.getmtime(os.path.join(training_runs_dir, f)))
# print("dddddddd:",run_names)
with gr.Group():
# with gr.Row():
training_runs_dropdown = gr.Dropdown(run_names, label="Training Runs",value=run_names[0] if run_names else None, interactive=True, scale=1)
delete_text_btn = gr.Button("Delete Run", scale=1)
iframe = f'<iframe src={TENSORBOARD_URL} style="border:none;height:1024px;width:100%">'
tensorboard_html = gr.HTML(iframe)
with gr.Tab("RAG"):
with gr.Row():
with gr.Column(scale=4, min_width=1):
with gr.Group():
gr.Markdown("## ChatBot", elem_classes="white_background")
rag_data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'rag', 'data')
matched_file_list = []
supported_doc_type = ["*.pdf","*.txt","*.docx"]
for doc_type in supported_doc_type:
matched_file_list += glob.glob(os.path.join(rag_data_dir, doc_type), recursive=False)
matched_file_list.sort(key=lambda file: os.path.getmtime(file),reverse=True)
matched_file_name_list = []
for matched_file in matched_file_list:
matched_file_name_list.append(os.path.basename(matched_file))
# chat_data_source_radio_choices = ["Chat With Document",
# f"Chat With Image"]
gr.Markdown("### Chat With Document", elem_classes="white_background")
# chat_data_source_radio = gr.Radio(chat_data_source_radio_choices,
# label="",
# value=chat_data_source_radio_choices[0],
# interactive=True)
with gr.Row():
rag_data_list_dropdown = gr.Dropdown(matched_file_name_list, label=f"Local Documents In {rag_data_dir}",
value=matched_file_name_list[0] if matched_file_name_list else None,
interactive=True,scale=4, min_width=1)
refresh_rag_data_list_btn = gr.Button("Refresh", scale=1, min_width=1)
# if not current_running_model_name:
# model_running_status_markdown = gr.Markdown(f"<span style='color:red'> No modelis running!</span>")
# else:
# model_running_status_markdown = gr.Markdown(f"<span style='color:green'> Model is runing:{current_running_model_name}.</span>")
def click_refresh_rag_data_list_btn():
rag_data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'rag', 'data')
matched_file_list = []
supported_doc_type = ["*.pdf", "*.txt", "*.docx"]
for doc_type in supported_doc_type:
matched_file_list += glob.glob(os.path.join(rag_data_dir, doc_type), recursive=False)
matched_file_list.sort(key=lambda file: os.path.getmtime(file), reverse=True)
matched_file_name_list = []
for matched_file in matched_file_list:
matched_file_name_list.append(os.path.basename(matched_file))
return gr.update(choices=matched_file_name_list,value=matched_file_name_list[0] if matched_file_name_list else None)
refresh_rag_data_list_btn.click(click_refresh_rag_data_list_btn,[],rag_data_list_dropdown)
# def update_model_running_status():
# return gr.update(value=f"<span style='color:red'> {current_running_model_name} is runing!.</span>")
#
# load_model_btn.click(click_load_model_btn,model_list_dropdown,[model_list_dropdown]).success(update_model_running_status,[],model_running_status_markdown)
with gr.Row():
rag_chatbot = gr.Chatbot(value=[],bubble_full_width=False,rtl=False,layout="panel",height=chatbot_height,
avatar_images=((os.path.join(os.path.abspath(''),"pics", "user1.png")), (os.path.join(os.path.abspath(''),"pics", "bot4.png"))),
)
with gr.Row():
rag_input_txtbox = gr.Textbox(
show_label=False,autofocus=True,
placeholder="Enter text and press enter",scale=6)
rag_generate_btn = gr.Button("Generate", scale=1)
rag_stop_btn = gr.Button("Stop", scale=1)
# rag_clear_btn = gr.Button("Clear", scale=1)
rag_model_running_status_markdown = gr.Markdown(
f"### Retrieved Document Chunks",visible=True)
# retrieved_document_chunks_markdown = gr.Markdown(
# f"### Retrieved Document Chunks",visible=True)
retrieved_document_chunks_dataframe = gr.Dataframe(
headers=["ID", "Chunk"],
datatype=["str", "str"],
show_label=False,
value=None
)
with gr.Column(scale=4, min_width=1):
with gr.Group():
gr.Markdown("## Setting", elem_classes="white_background")
with gr.Group():
with gr.Group():
gr.Markdown("### 1.Chunking", elem_classes="white_background")
with gr.Row():
text_splitter_dropdown = gr.Dropdown(["RecursiveCharacterTextSplitter"],
label=f"Text Splitter",
value="RecursiveCharacterTextSplitter",
interactive=True, scale=1, min_width=1)
with gr.Row():
chunk_size_slider = gr.Slider(32, 1024, value=256, step=32, label="Chunk Size",
interactive=True, scale=1)
chunk_overlap_slider = gr.Slider(0, 500, value=20, step=10, label="Chunk Overlap",
interactive=True)
Separators_textbox = gr.Textbox(label="Separators",
value='''["\n\n", "\n", ".", " ", ""]''',
interactive=True,visible=False)
with gr.Group():
gr.Markdown("### 2.Vector Store Retriever", elem_classes="white_background") #
local_embedding_model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),"rag","embedding_models")
local_embedding_model_names = get_hg_model_names_from_dir(local_embedding_model_dir,"embedding_models")
embedding_model_source_radio_choices = ["Download From Huggingface Hub",
f"From Local Dir(hg format:{local_embedding_model_dir})"]
embedding_model_source_radio = gr.Radio(embedding_model_source_radio_choices,
label="Embedding Model Source",
value=embedding_model_source_radio_choices[0],
interactive=True)
with gr.Row():
hub_embedding_model_names_dropdown = gr.Dropdown(embedding_model_names,
label=f"",show_label=False,
value=embedding_model_names[0] if embedding_model_names else None,
interactive=True, scale=4, min_width=1)
download_hub_embedding_model_names_btn = gr.Button("Download", scale=1)
stop_download_hub_embedding_model_names_btn = gr.Button("Stop", scale=1, visible=False)
local_embedding_model_names_dropdown = gr.Dropdown(local_embedding_model_names,
label=f"Embedding Model",show_label=False,
value=local_embedding_model_names[0] if local_embedding_model_names else None,
interactive=True, scale=4, min_width=1,visible=False)
refresh_local_embedding_model_names_btn = gr.Button("Refresh", scale=1,visible=False)
# model_config_path1 = os.path.join(local_embedding_model_dir,
# embedding_model_names[0], "pytorch_model.bin")
# model_config_path2 = os.path.join(local_embedding_model_dir,
# embedding_model_names[0], "model.safetensors")
model_config_path = os.path.join(local_embedding_model_dir,
embedding_model_names[0], "config.json")
if os.path.exists(model_config_path):
download_hub_embedding_model_status_markdown = gr.Markdown(
'<span style="color:green"> This model has already been downloaded to local.</span>')
else:
download_hub_embedding_model_status_markdown = gr.Markdown(
'<span style="color:red"> This model has not been downloaded.</span>')
with gr.Row():
search_top_k_slider = gr.Slider(1, 10, value=3, step=1, label="Search Top K", interactive=True)
search_score_threshold_slider = gr.Slider(0, 1, value=0.5, step=0.1, label="Search Score Threshold",interactive=True)
with gr.Group():
gr.Markdown("### 3.Chat Model", elem_classes="white_background")
local_chat_model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),"models")
runs_model_root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "runs")
# local_chat_model_names = get_hg_model_names_from_dir(local_chat_model_dir)
local_chat_model_names = get_hg_model_names_and_gguf_from_dir(local_chat_model_dir,runs_model_root_dir)
chat_model_source_radio_choices = ["Download From Huggingface Hub",
f"From Local Dir(hg format:{local_chat_model_dir})"]
chat_model_source_radio = gr.Radio(chat_model_source_radio_choices,
label="Chat Model source",show_label=False,
value=chat_model_source_radio_choices[0],
interactive=True)
with gr.Row():
hub_chat_model_names_dropdown = gr.Dropdown(base_model_names,
label=f"Chat Model",show_label=False,allow_custom_value=True,
value=base_model_names[0] if base_model_names else None,
interactive=True, scale=4, min_width=1)
download_hub_chat_model_names_btn = gr.Button("Download", scale=1)
stop_download_hub_chat_model_names_btn = gr.Button("Stop", scale=1, visible=False)
local_chat_model_names_dropdown = gr.Dropdown(local_chat_model_names,
label=f"Chat Model",show_label=False,
value=local_chat_model_names[0] if local_chat_model_names else None,
interactive=True, scale=4, min_width=1,visible=False)
refresh_local_chat_model_names_btn = gr.Button("Refresh", scale=1,visible=False)
rag_using_4bit_quantization_checkbox = gr.Checkbox(True, label="Using 4-bit quantization",
interactive=True, visible=True,
info="Less memory but slower", scale=1
)
if validate_model_path(base_model_names[0])[0]:
download_hub_chat_model_status_markdown = gr.Markdown(
'<span style="color:green"> This model has already been downloaded to local.</span>')
else:
download_hub_chat_model_status_markdown = gr.Markdown(
'<span style="color:red"> This model has not been downloaded.</span>')
with gr.Tab("Setting"):
# with gr.Column(scale=4, min_width=1):
with gr.Group():
gr.Markdown("## Setting", elem_classes="white_background")
with gr.Group():
with gr.Row():
max_new_tokens_slider = gr.Slider(1, 4096, value=256, step=0.1, label="Max New Tokens",
interactive=True)
temperature_slider = gr.Slider(0, 5, value=1, step=0.1, label="Temperature",
interactive=True)
with gr.Row():
top_k_slider = gr.Slider(1, 100, value=50, step=1, label="Top_k",
interactive=True)
top_p_slider = gr.Slider(0, 1, value=1, step=0.1, label="Top_p",
interactive=True)
with gr.Row():
repeat_penalty_slider = gr.Slider(1, 5, value=1, step=0.1, label="Repeat Penalty", interactive=True)
with gr.Row():
chat_history_window_slider = gr.Slider(1, 20, value=3, step=1, label="Chat History Window",
interactive=True)
low_cpu_mem_usage_checkbox = gr.Checkbox(False, label="Low Cpu Mem Usage",interactive=True,visible=False)
Huggingface_hub_token = gr.Textbox(label="Huggingface Hub Token", value="")
def check_local_model_or_dataset_is_empty1(base_model_name_dropdown,Huggingface_hub_token):
if len(base_model_name_dropdown.strip()) == 0:
raise gr.Error("Name is empty!")
try:
login_huggingface(Huggingface_hub_token,base_model_name_dropdown)
except Exception as e:
raise gr.Error(e)
def check_local_model_or_dataset_is_empty2(base_model_name_dropdown,Huggingface_hub_token):
if len(base_model_name_dropdown.strip()) == 0:
raise gr.Error("Name is empty!")
try:
login_huggingface(Huggingface_hub_token,base_model_name_dropdown)
except Exception as e:
raise gr.Error(e)
def check_local_model_or_dataset_is_empty3(base_model_name_dropdown,Huggingface_hub_token):
if len(base_model_name_dropdown.strip()) == 0:
raise gr.Error("Name is empty!")
try:
login_huggingface(Huggingface_hub_token,base_model_name_dropdown)
except Exception as e:
raise gr.Error(e)
def check_local_model_or_dataset_is_empty4(base_model_name_dropdown,Huggingface_hub_token):
if len(base_model_name_dropdown.strip()) == 0:
raise gr.Error("Name is empty!")
try:
login_huggingface(Huggingface_hub_token,base_model_name_dropdown)
except Exception as e:
raise gr.Error(e)
def check_local_model_or_dataset_is_empty5(base_model_name_dropdown,Huggingface_hub_token):
if len(base_model_name_dropdown.strip()) == 0:
raise gr.Error("Name is empty!")
try:
login_huggingface(Huggingface_hub_token,base_model_name_dropdown)
except Exception as e:
raise gr.Error(e)
def download_hub_home_chat_model_postprocess():
return gr.update(visible=True), gr.update(visible=False)
def click_download_hub_home_chat_model_btn():
return gr.update(visible=False), gr.update(visible=True), gr.update(visible=True)
def click_stop_download_hub_home_chat_model_names_btn():
return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
def click_stop_download_hub_home_chat_model_names_btn():
return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
def change_home_chat_model_source_radio(home_chat_model_source_radio, hub_home_chat_model_names_dropdown):
local_home_chat_model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
if home_chat_model_source_radio == "Download From Huggingface Hub":
if not hub_home_chat_model_names_dropdown:
model_download_status = '<span style="color:red"> No model is selected.</span>'
else:
if validate_model_path(hub_home_chat_model_names_dropdown)[0]:
model_download_status = '<span style="color:green"> This model has already been downloaded to local,click load model to run.</span>'
else:
model_download_status = '<span style="color:red"> This model has not been downloaded.</span>'
return gr.update(visible=True), gr.update(visible=False), gr.update(
visible=False), gr.update(visible=True, value=model_download_status), gr.update(
visible=True), gr.update(
visible=False)
else:
model_download_status = ""
return gr.update(visible=False), gr.update(visible=True), gr.update(
visible=True), gr.update(visible=False, value=model_download_status), gr.update(
visible=False), gr.update(
visible=False)
click_download_hub_home_chat_model_names_btn_event = download_hub_home_chat_model_names_btn.click(
check_local_model_or_dataset_is_empty1, [hub_home_chat_model_names_dropdown,Huggingface_hub_token]).success(
click_download_hub_home_chat_model_btn, [],
[download_hub_home_chat_model_names_btn,
stop_download_hub_home_chat_model_names_btn,
download_hub_home_chat_model_status_markdown]).then(
download_model_wrapper, [hub_home_chat_model_names_dropdown, local_home_chat_model_root_dir_textbox],
download_hub_home_chat_model_status_markdown). \
then(download_hub_home_chat_model_postprocess, [],
[download_hub_home_chat_model_names_btn, stop_download_hub_home_chat_model_names_btn])
stop_download_hub_home_chat_model_names_btn.click(click_stop_download_hub_home_chat_model_names_btn, [],
[download_hub_home_chat_model_names_btn,
stop_download_hub_home_chat_model_names_btn,
download_hub_home_chat_model_status_markdown],
cancels=[
click_download_hub_home_chat_model_names_btn_event])
home_chat_model_source_radio.change(change_home_chat_model_source_radio,
[home_chat_model_source_radio, hub_home_chat_model_names_dropdown],
[hub_home_chat_model_names_dropdown, local_home_chat_model_names_dropdown,
refresh_local_home_chat_model_names_btn,
download_hub_home_chat_model_status_markdown,
download_hub_home_chat_model_names_btn,
stop_download_hub_home_chat_model_names_btn],
cancels=[click_download_hub_home_chat_model_names_btn_event])
def change_refresh_local_home_chat_model_names_btn():
local_home_chat_model_names = get_hg_model_names_and_gguf_from_dir(local_home_chat_model_dir,runs_model_root_dir)
return gr.update(choices=local_home_chat_model_names,value = local_home_chat_model_names[0] if local_home_chat_model_names else None)
refresh_local_home_chat_model_names_btn.click(change_refresh_local_home_chat_model_names_btn,[],[local_home_chat_model_names_dropdown])
def change_hub_home_chat_model_names_dropdown(hub_home_chat_model_names_dropdown):
if not hub_home_chat_model_names_dropdown:
return gr.update(visible=True,
value='<span style="color:red"> No model is selected.</span>'), \
gr.update(visible=True), gr.update(visible=False)
if validate_model_path(hub_home_chat_model_names_dropdown)[0]:
return gr.update(
visible=True,
value='<span style="color:green"> This model has already been downloaded to local,click load model to run.</span>'), \
gr.update(visible=True), gr.update(visible=False)
else:
return gr.update(visible=True,
value='<span style="color:red"> This model has not been downloaded.</span>'), \
gr.update(visible=True), gr.update(visible=False)
hub_home_chat_model_names_dropdown.change(change_hub_home_chat_model_names_dropdown,
hub_home_chat_model_names_dropdown,
[download_hub_home_chat_model_status_markdown,
download_hub_home_chat_model_names_btn,
stop_download_hub_home_chat_model_names_btn],
cancels=[click_download_hub_home_chat_model_names_btn_event])
def click_load_home_chat_model_btn(home_chat_model_source_radio, hub_home_chat_model_names_dropdown,
local_home_chat_model_names_dropdown, max_new_tokens_slider,
temperature_slider, top_k_slider, top_p_slider, repeat_penalty_slider,
chat_history_window_slider,using_4bit_quantization_checkbox,low_cpu_mem_usage_checkbox,
progress=gr.Progress()):
if home_chat_model_source_radio == "Download From Huggingface Hub":
cur_model_name = hub_home_chat_model_names_dropdown
else:
cur_model_name = local_home_chat_model_names_dropdown
if not validate_model_path(cur_model_name)[0]:
raise gr.Error(f"Model does not exist!")
global infer_model
global stop_generation_status
stop_generation_status = True
progress(0.6)
if infer_model:
infer_model.free_memory()
infer_model = None
torch.cuda.empty_cache()
yield "Loading model ..."
load_model_status = 0
model_path = validate_model_path(cur_model_name)[1]
if model_path.split('.')[-1] == "gguf":
infer_model = LlamaCppInference(model_path=model_path, max_new_tokens=max_new_tokens_slider,
temperature=temperature_slider,
top_k=top_k_slider, top_p=top_p_slider,
repetition_penalty=repeat_penalty_slider)
load_model_status, msg = infer_model.load_model()
else:
infer_model = HuggingfaceInference(model_path=model_path, max_new_tokens=max_new_tokens_slider,
temperature=temperature_slider,
top_k=top_k_slider, top_p=top_p_slider,
repetition_penalty=repeat_penalty_slider,
using_4bit_quantization=using_4bit_quantization_checkbox,
low_cpu_mem_usage=low_cpu_mem_usage_checkbox)
load_model_status, msg = infer_model.load_model()
if load_model_status == -1:
raise gr.Error(f"Loading model error:{msg}")
if infer_model:
infer_model.free_memory()
infer_model = None
torch.cuda.empty_cache()
return
progress(1.0)
return gr.update()
def update_model_running_status():
global chatbot_history
return gr.update(visible=True,
value=f"<span style='color:green'> Model is runing ...</span>"),chatbot_history,gr.update()
def show_model_running_status():
return gr.update(visible=True)
load_home_chat_model_btn.click(show_model_running_status, [], download_hub_home_chat_model_status_markdown).then(
click_load_home_chat_model_btn, [home_chat_model_source_radio, hub_home_chat_model_names_dropdown,
local_home_chat_model_names_dropdown, max_new_tokens_slider,
temperature_slider, top_k_slider, top_p_slider, repeat_penalty_slider,