forked from h2oai/h2ogpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gradio_runner.py
2245 lines (2026 loc) · 123 KB
/
gradio_runner.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 copy
import functools
import inspect
import itertools
import json
import os
import pprint
import random
import shutil
import sys
import time
import traceback
import typing
import uuid
import filelock
import pandas as pd
import requests
import tabulate
from gradio_ui.css import get_css
from gradio_ui.prompt_form import make_prompt_form, make_chatbots
# This is a hack to prevent Gradio from phoning home when it gets imported
os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False'
def my_get(url, **kwargs):
print('Gradio HTTP request redirected to localhost :)', flush=True)
kwargs.setdefault('allow_redirects', True)
return requests.api.request('get', 'http://127.0.0.1/', **kwargs)
original_get = requests.get
requests.get = my_get
import gradio as gr
requests.get = original_get
def fix_pydantic_duplicate_validators_error():
try:
from pydantic import class_validators
class_validators.in_ipython = lambda: True # type: ignore[attr-defined]
except ImportError:
pass
fix_pydantic_duplicate_validators_error()
from enums import DocumentChoices, no_model_str, no_lora_str, no_server_str
from gradio_themes import H2oTheme, SoftTheme, get_h2o_title, get_simple_title, get_dark_js, spacing_xsm, radius_xsm, \
text_xsm
from prompter import prompt_type_to_model_name, prompt_types_strings, inv_prompt_type_to_model_lower, non_hf_types, \
get_prompt
from utils import get_githash, flatten_list, zip_data, s3up, clear_torch_cache, get_torch_allocated, system_info_print, \
ping, get_short_name, get_url, makedirs, get_kwargs, remove, system_info, ping_gpu
from generate import get_model, languages_covered, evaluate, eval_func_param_names, score_qa, langchain_modes, \
inputs_kwargs_list, scratch_base_dir, evaluate_from_str, no_default_param_names, \
eval_func_param_names_defaults, get_max_max_new_tokens, get_minmax_top_k_docs, history_to_context
from apscheduler.schedulers.background import BackgroundScheduler
def fix_text_for_gradio(text, fix_new_lines=False, fix_latex_dollars=True):
if fix_latex_dollars:
ts = text.split('```')
for parti, part in enumerate(ts):
inside = parti % 2 == 1
if not inside:
ts[parti] = ts[parti].replace('$', '﹩')
text = '```'.join(ts)
if fix_new_lines:
# let Gradio handle code, since got improved recently
## FIXME: below conflicts with Gradio, but need to see if can handle multiple \n\n\n etc. properly as is.
# ensure good visually, else markdown ignores multiple \n
# handle code blocks
ts = text.split('```')
for parti, part in enumerate(ts):
inside = parti % 2 == 1
if not inside:
ts[parti] = ts[parti].replace('\n', '<br>')
text = '```'.join(ts)
return text
def go_gradio(**kwargs):
allow_api = kwargs['allow_api']
is_public = kwargs['is_public']
is_hf = kwargs['is_hf']
memory_restriction_level = kwargs['memory_restriction_level']
n_gpus = kwargs['n_gpus']
admin_pass = kwargs['admin_pass']
model_state0 = kwargs['model_state0']
model_states = kwargs['model_states']
score_model_state0 = kwargs['score_model_state0']
dbs = kwargs['dbs']
db_type = kwargs['db_type']
visible_langchain_modes = kwargs['visible_langchain_modes']
allow_upload_to_user_data = kwargs['allow_upload_to_user_data']
allow_upload_to_my_data = kwargs['allow_upload_to_my_data']
enable_sources_list = kwargs['enable_sources_list']
enable_url_upload = kwargs['enable_url_upload']
enable_text_upload = kwargs['enable_text_upload']
use_openai_embedding = kwargs['use_openai_embedding']
hf_embedding_model = kwargs['hf_embedding_model']
enable_captions = kwargs['enable_captions']
captions_model = kwargs['captions_model']
enable_ocr = kwargs['enable_ocr']
caption_loader = kwargs['caption_loader']
# easy update of kwargs needed for evaluate() etc.
queue = True
allow_upload = allow_upload_to_user_data or allow_upload_to_my_data
kwargs.update(locals())
if 'mbart-' in kwargs['model_lower']:
instruction_label_nochat = "Text to translate"
else:
instruction_label_nochat = "Instruction (Shift-Enter or push Submit to send message," \
" use Enter for multiple input lines)"
title = 'h2oGPT'
if 'h2ogpt-research' in kwargs['base_model']:
title += " [Research demonstration]"
more_info = """For more information, visit our GitHub pages: [h2oGPT](https://github.com/h2oai/h2ogpt) and [H2O-LLMStudio](https://github.com/h2oai/h2o-llmstudio)<br>"""
if is_public:
more_info += """<iframe src="https://ghbtns.com/github-btn.html?user=h2oai&repo=h2ogpt&type=star&count=true&size=small" frameborder="0" scrolling="0" width="150" height="20" title="GitHub"></iframe>"""
if kwargs['verbose']:
description = f"""Model {kwargs['base_model']} Instruct dataset.
For more information, visit our GitHub pages: [h2oGPT](https://github.com/h2oai/h2ogpt) and [H2O LLM Studio](https://github.com/h2oai/h2o-llmstudio).
Command: {str(' '.join(sys.argv))}
Hash: {get_githash()}
"""
else:
description = more_info
description += "If this host is busy, try [LLaMa 65B](https://llama.h2o.ai), [Falcon 40B](https://gpt.h2o.ai), [Falcon 40B](http://falcon.h2o.ai), [HF Spaces1 12B](https://huggingface.co/spaces/h2oai/h2ogpt-chatbot) or [HF Spaces2 12B](https://huggingface.co/spaces/h2oai/h2ogpt-chatbot2)<br>"
description += """<p>By using h2oGPT, you accept our [Terms of Service](https://github.com/h2oai/h2ogpt/blob/main/docs/tos.md)</p>"""
if is_hf:
description += '''<a href="https://huggingface.co/spaces/h2oai/h2ogpt-chatbot?duplicate=true"><img src="https://bit.ly/3gLdBN6" style="white-space: nowrap" alt="Duplicate Space"></a>'''
if kwargs['verbose']:
task_info_md = f"""
### Task: {kwargs['task_info']}"""
else:
task_info_md = ''
css_code = get_css(kwargs)
if kwargs['gradio_offline_level'] >= 0:
# avoid GoogleFont that pulls from internet
if kwargs['gradio_offline_level'] == 1:
# front end would still have to download fonts or have cached it at some point
base_font = 'Source Sans Pro'
else:
base_font = 'Helvetica'
theme_kwargs = dict(font=(base_font, 'ui-sans-serif', 'system-ui', 'sans-serif'),
font_mono=('IBM Plex Mono', 'ui-monospace', 'Consolas', 'monospace'))
else:
theme_kwargs = dict()
if kwargs['gradio_size'] == 'xsmall':
theme_kwargs.update(dict(spacing_size=spacing_xsm, text_size=text_xsm, radius_size=radius_xsm))
elif kwargs['gradio_size'] == 'small':
theme_kwargs.update(dict(spacing_size=gr.themes.sizes.spacing_sm, text_size=gr.themes.sizes.text_sm,
radius_size=gr.themes.sizes.spacing_sm))
elif kwargs['gradio_size'] == 'large':
theme_kwargs.update(dict(spacing_size=gr.themes.sizes.spacing_lg, text_size=gr.themes.sizes.text_lg),
radius_size=gr.themes.sizes.spacing_lg)
elif kwargs['gradio_size'] == 'medium':
theme_kwargs.update(dict(spacing_size=gr.themes.sizes.spacing_md, text_size=gr.themes.sizes.text_md,
radius_size=gr.themes.sizes.spacing_md))
theme = H2oTheme(**theme_kwargs) if kwargs['h2ocolors'] else SoftTheme(**theme_kwargs)
demo = gr.Blocks(theme=theme, css=css_code, title="h2oGPT", analytics_enabled=False)
callback = gr.CSVLogger()
model_options = flatten_list(list(prompt_type_to_model_name.values())) + kwargs['extra_model_options']
if kwargs['base_model'].strip() not in model_options:
model_options = [kwargs['base_model'].strip()] + model_options
lora_options = kwargs['extra_lora_options']
if kwargs['lora_weights'].strip() not in lora_options:
lora_options = [kwargs['lora_weights'].strip()] + lora_options
server_options = kwargs['extra_server_options']
if kwargs['inference_server'].strip() not in server_options:
server_options = [kwargs['inference_server'].strip()] + server_options
if os.getenv('OPENAI_API_KEY'):
if 'openai_chat' not in server_options:
server_options += ['openai_chat']
if 'openai' not in server_options:
server_options += ['openai']
# always add in no lora case
# add fake space so doesn't go away in gradio dropdown
model_options = [no_model_str] + model_options
lora_options = [no_lora_str] + lora_options
server_options = [no_server_str] + server_options
# always add in no model case so can free memory
# add fake space so doesn't go away in gradio dropdown
# transcribe, will be detranscribed before use by evaluate()
if not kwargs['base_model'].strip():
kwargs['base_model'] = no_model_str
if not kwargs['lora_weights'].strip():
kwargs['lora_weights'] = no_lora_str
if not kwargs['inference_server'].strip():
kwargs['inference_server'] = no_server_str
# transcribe for gradio
kwargs['gpu_id'] = str(kwargs['gpu_id'])
no_model_msg = 'h2oGPT [ !!! Please Load Model in Models Tab !!! ]'
output_label0 = f'h2oGPT [Model: {kwargs.get("base_model")}]' if kwargs.get(
'base_model') else no_model_msg
output_label0_model2 = no_model_msg
default_kwargs = {k: kwargs[k] for k in eval_func_param_names_defaults}
for k in no_default_param_names:
default_kwargs[k] = ''
with demo:
# avoid actual model/tokenizer here or anything that would be bad to deepcopy
# https://github.com/gradio-app/gradio/issues/3558
model_state = gr.State(
dict(model='model', tokenizer='tokenizer', device=kwargs['device'],
base_model=kwargs['base_model'],
tokenizer_base_model=kwargs['tokenizer_base_model'],
lora_weights=kwargs['lora_weights'],
inference_server=kwargs['inference_server'],
prompt_type=kwargs['prompt_type'],
prompt_dict=kwargs['prompt_dict'],
)
)
model_state2 = gr.State(kwargs['model_state_none'].copy())
model_options_state = gr.State([model_options])
lora_options_state = gr.State([lora_options])
server_options_state = gr.State([server_options])
my_db_state = gr.State([None, None])
chat_state = gr.State({})
# make user default first and default choice, dedup
docs_state00 = kwargs['document_choice'] + [x.name for x in list(DocumentChoices)]
docs_state0 = []
[docs_state0.append(x) for x in docs_state00 if x not in docs_state0]
docs_state = gr.State(docs_state0) # first is chosen as default
gr.Markdown(f"""
{get_h2o_title(title) if kwargs['h2ocolors'] else get_simple_title(title)}
{description}
{task_info_md}
""")
if is_hf:
gr.HTML(
)
# go button visible if
base_wanted = kwargs['base_model'] != no_model_str and kwargs['login_mode_if_model0']
go_btn = gr.Button(value="ENTER", visible=base_wanted, variant="primary")
normal_block = gr.Row(visible=not base_wanted)
with normal_block:
with gr.Tabs():
with gr.Row():
col_nochat = gr.Column(visible=not kwargs['chat'])
with col_nochat: # FIXME: for model comparison, and check rest
if kwargs['langchain_mode'] == 'Disabled':
text_output_nochat = gr.Textbox(lines=5, label=output_label0, show_copy_button=True)
else:
# text looks a bit worse, but HTML links work
text_output_nochat = gr.HTML(label=output_label0)
instruction_nochat = gr.Textbox(
lines=kwargs['input_lines'],
label=instruction_label_nochat,
placeholder=kwargs['placeholder_instruction'],
)
iinput_nochat = gr.Textbox(lines=4, label="Input context for Instruction",
placeholder=kwargs['placeholder_input'])
submit_nochat = gr.Button("Submit")
flag_btn_nochat = gr.Button("Flag")
with gr.Column(visible=kwargs['score_model']):
score_text_nochat = gr.Textbox("Response Score: NA", show_label=False)
col_chat = gr.Column(visible=kwargs['chat'])
with col_chat:
text_output, text_output2, text_outputs = make_chatbots(output_label0, output_label0_model2,
**kwargs)
instruction, submit, stop_btn = make_prompt_form(kwargs)
with gr.Row():
clear = gr.Button("Save Chat / New Chat")
flag_btn = gr.Button("Flag")
with gr.Column(visible=kwargs['score_model']):
score_texts = []
for model_state_lock in kwargs['model_states']:
score_texts.append(gr.Textbox("Response Score: NA", show_label=False,
visible=bool(kwargs['model_lock'])))
score_text = gr.Textbox("Response Score: NA", show_label=False,
visible=not kwargs['model_lock'])
score_text2 = gr.Textbox("Response Score2: NA", show_label=False,
visible=False and not kwargs['model_lock'])
retry_btn = gr.Button("Regenerate")
undo = gr.Button("Undo")
submit_nochat_api = gr.Button("Submit nochat API", visible=False)
inputs_dict_str = gr.Textbox(label='API input for nochat', show_label=False, visible=False)
text_output_nochat_api = gr.Textbox(lines=5, label='API nochat output', visible=False,
show_copy_button=True)
with gr.TabItem("Chat"):
with gr.Row():
if 'mbart-' in kwargs['model_lower']:
src_lang = gr.Dropdown(list(languages_covered().keys()),
value=kwargs['src_lang'],
label="Input Language")
tgt_lang = gr.Dropdown(list(languages_covered().keys()),
value=kwargs['tgt_lang'],
label="Output Language")
radio_chats = gr.Radio(value=None, label="Saved Chats", visible=True, interactive=True,
type='value')
with gr.Row():
clear_chat_btn = gr.Button(value="Clear Chat", visible=True, size='sm')
export_chats_btn = gr.Button(value="Export Chats to Download", size='sm')
remove_chat_btn = gr.Button(value="Remove Selected Chat", visible=True, size='sm')
add_to_chats_btn = gr.Button("Import Chats from Upload", size='sm')
with gr.Row():
chats_file = gr.File(interactive=False, label="Download Exported Chats")
chatsup_output = gr.File(label="Upload Chat File(s)",
file_types=['.json'],
file_count='multiple',
elem_id="warning", elem_classes="feedback")
with gr.TabItem("Data Source"):
langchain_readme = get_url('https://github.com/h2oai/h2ogpt/blob/main/docs/README_LangChain.md',
from_str=True)
gr.HTML(value=f"""LangChain Support Disabled<p>
Run:<p>
<code>
python generate.py --langchain_mode=MyData
</code>
<p>
For more options see: {langchain_readme}""",
visible=kwargs['langchain_mode'] == 'Disabled', interactive=False)
data_row1 = gr.Row(visible=kwargs['langchain_mode'] != 'Disabled')
with data_row1:
if is_hf:
# don't show 'wiki' since only usually useful for internal testing at moment
no_show_modes = ['Disabled', 'wiki']
else:
no_show_modes = ['Disabled']
allowed_modes = visible_langchain_modes.copy()
allowed_modes = [x for x in allowed_modes if x in dbs]
allowed_modes += ['ChatLLM', 'LLM']
if allow_upload_to_my_data and 'MyData' not in allowed_modes:
allowed_modes += ['MyData']
if allow_upload_to_user_data and 'UserData' not in allowed_modes:
allowed_modes += ['UserData']
langchain_mode = gr.Radio(
[x for x in langchain_modes if x in allowed_modes and x not in no_show_modes],
value=kwargs['langchain_mode'],
label="Data Collection of Sources",
visible=kwargs['langchain_mode'] != 'Disabled')
data_row2 = gr.Row(visible=kwargs['langchain_mode'] != 'Disabled')
with data_row2:
with gr.Column(scale=50):
document_choice = gr.Dropdown(docs_state.value,
label="Choose Subset of Doc(s) in Collection [click get sources to update]",
value=docs_state.value[0],
interactive=True,
multiselect=True,
)
with gr.Row(visible=kwargs['langchain_mode'] != 'Disabled' and enable_sources_list):
get_sources_btn = gr.Button(value="Get Sources", scale=0, size='sm')
show_sources_btn = gr.Button(value="Show Sources", scale=0, size='sm')
refresh_sources_btn = gr.Button(value="Refresh Sources", scale=0, size='sm')
# import control
if kwargs['langchain_mode'] != 'Disabled':
from gpt_langchain import file_types, have_arxiv
else:
have_arxiv = False
file_types = []
upload_row = gr.Row(visible=kwargs['langchain_mode'] != 'Disabled' and allow_upload,
equal_height=False)
with upload_row:
with gr.Column():
file_types_str = '[' + ' '.join(file_types) + ']'
fileup_output = gr.File(label=f'Upload {file_types_str}',
file_types=file_types,
file_count="multiple",
elem_id="warning", elem_classes="feedback")
with gr.Row():
add_to_shared_db_btn = gr.Button("Add File(s) to UserData",
visible=allow_upload_to_user_data,
elem_id='small_btn')
add_to_my_db_btn = gr.Button("Add File(s) to Scratch MyData",
visible=allow_upload_to_my_data,
elem_id='small_btn' if allow_upload_to_user_data else None,
size='sm' if not allow_upload_to_user_data else None)
with gr.Column(
visible=kwargs['langchain_mode'] != 'Disabled' and allow_upload and enable_url_upload):
url_label = 'URL (http/https) or ArXiv:' if have_arxiv else 'URL (http/https)'
url_text = gr.Textbox(label=url_label, interactive=True)
with gr.Row():
url_user_btn = gr.Button(value='Add URL content to Shared UserData',
visible=allow_upload_to_user_data, elem_id='small_btn')
url_my_btn = gr.Button(value='Add URL content to Scratch MyData',
visible=allow_upload_to_my_data,
elem_id='small_btn' if allow_upload_to_user_data else None,
size='sm' if not allow_upload_to_user_data else None)
with gr.Column(
visible=kwargs['langchain_mode'] != 'Disabled' and allow_upload and enable_text_upload):
user_text_text = gr.Textbox(label='Paste Text [Shift-Enter more lines]', interactive=True)
with gr.Row():
user_text_user_btn = gr.Button(value='Add Text to Shared UserData',
visible=allow_upload_to_user_data,
elem_id='small_btn')
user_text_my_btn = gr.Button(value='Add Text to Scratch MyData',
visible=allow_upload_to_my_data,
elem_id='small_btn' if allow_upload_to_user_data else None,
size='sm' if not allow_upload_to_user_data else None)
with gr.Column(visible=False):
# WIP:
with gr.Row(visible=False, equal_height=False):
github_textbox = gr.Textbox(label="Github URL")
with gr.Row(visible=True):
github_shared_btn = gr.Button(value="Add Github to Shared UserData",
visible=allow_upload_to_user_data,
elem_id='small_btn')
github_my_btn = gr.Button(value="Add Github to Scratch MyData",
visible=allow_upload_to_my_data, elem_id='small_btn')
sources_row3 = gr.Row(visible=kwargs['langchain_mode'] != 'Disabled' and enable_sources_list,
equal_height=False)
with sources_row3:
with gr.Column(scale=1):
file_source = gr.File(interactive=False,
label="Download File w/Sources [click get sources to make file]")
with gr.Column(scale=2):
pass
sources_row = gr.Row(visible=kwargs['langchain_mode'] != 'Disabled' and enable_sources_list,
equal_height=False)
with sources_row:
sources_text = gr.HTML(label='Sources Added', interactive=False)
with gr.TabItem("Expert"):
with gr.Row():
with gr.Column():
stream_output = gr.components.Checkbox(label="Stream output",
value=kwargs['stream_output'])
prompt_type = gr.Dropdown(prompt_types_strings,
value=kwargs['prompt_type'], label="Prompt Type",
visible=not kwargs['model_lock'],
interactive=not is_public,
)
prompt_type2 = gr.Dropdown(prompt_types_strings,
value=kwargs['prompt_type'], label="Prompt Type Model 2",
visible=False and not kwargs['model_lock'],
interactive=not is_public)
do_sample = gr.Checkbox(label="Sample",
info="Enable sampler, required for use of temperature, top_p, top_k",
value=kwargs['do_sample'])
temperature = gr.Slider(minimum=0.01, maximum=3,
value=kwargs['temperature'],
label="Temperature",
info="Lower is deterministic (but may lead to repeats), Higher more creative (but may lead to hallucinations)")
top_p = gr.Slider(minimum=1e-3, maximum=1.0 - 1e-3,
value=kwargs['top_p'], label="Top p",
info="Cumulative probability of tokens to sample from")
top_k = gr.Slider(
minimum=1, maximum=100, step=1,
value=kwargs['top_k'], label="Top k",
info='Num. tokens to sample from'
)
# FIXME: https://github.com/h2oai/h2ogpt/issues/106
if os.getenv('TESTINGFAIL'):
max_beams = 8 if not (memory_restriction_level or is_public) else 1
else:
max_beams = 1
num_beams = gr.Slider(minimum=1, maximum=max_beams, step=1,
value=min(max_beams, kwargs['num_beams']), label="Beams",
info="Number of searches for optimal overall probability. "
"Uses more GPU memory/compute",
interactive=False)
max_max_new_tokens = get_max_max_new_tokens(model_state0, **kwargs)
max_new_tokens = gr.Slider(
minimum=1, maximum=max_max_new_tokens, step=1,
value=min(max_max_new_tokens, kwargs['max_new_tokens']), label="Max output length",
)
min_new_tokens = gr.Slider(
minimum=0, maximum=max_max_new_tokens, step=1,
value=min(max_max_new_tokens, kwargs['min_new_tokens']), label="Min output length",
)
max_new_tokens2 = gr.Slider(
minimum=1, maximum=max_max_new_tokens, step=1,
value=min(max_max_new_tokens, kwargs['max_new_tokens']), label="Max output length 2",
visible=False and not kwargs['model_lock'],
)
min_new_tokens2 = gr.Slider(
minimum=0, maximum=max_max_new_tokens, step=1,
value=min(max_max_new_tokens, kwargs['min_new_tokens']), label="Min output length 2",
visible=False and not kwargs['model_lock'],
)
early_stopping = gr.Checkbox(label="EarlyStopping", info="Stop early in beam search",
value=kwargs['early_stopping'])
max_time = gr.Slider(minimum=0, maximum=kwargs['max_max_time'], step=1,
value=min(kwargs['max_max_time'],
kwargs['max_time']), label="Max. time",
info="Max. time to search optimal output.")
repetition_penalty = gr.Slider(minimum=0.01, maximum=3.0,
value=kwargs['repetition_penalty'],
label="Repetition Penalty")
num_return_sequences = gr.Slider(minimum=1, maximum=10, step=1,
value=kwargs['num_return_sequences'],
label="Number Returns", info="Must be <= num_beams",
interactive=not is_public)
iinput = gr.Textbox(lines=4, label="Input",
placeholder=kwargs['placeholder_input'],
interactive=not is_public)
context = gr.Textbox(lines=3, label="System Pre-Context",
info="Directly pre-appended without prompt processing",
interactive=not is_public)
chat = gr.components.Checkbox(label="Chat mode", value=kwargs['chat'],
visible=not kwargs['model_lock'],
interactive=not is_public,
)
count_chat_tokens_btn = gr.Button(value="Count Chat Tokens",
visible=not is_public and not kwargs['model_lock'],
interactive=not is_public)
chat_token_count = gr.Textbox(label="Chat Token Count", value=None,
visible=not is_public and not kwargs['model_lock'],
interactive=False)
chunk = gr.components.Checkbox(value=kwargs['chunk'],
label="Whether to chunk documents",
info="For LangChain",
visible=kwargs['langchain_mode'] != 'Disabled',
interactive=not is_public)
min_top_k_docs, max_top_k_docs, label_top_k_docs = get_minmax_top_k_docs(is_public)
top_k_docs = gr.Slider(minimum=min_top_k_docs, maximum=max_top_k_docs, step=1,
value=kwargs['top_k_docs'],
label=label_top_k_docs,
info="For LangChain",
visible=kwargs['langchain_mode'] != 'Disabled',
interactive=not is_public)
chunk_size = gr.Number(value=kwargs['chunk_size'],
label="Chunk size for document chunking",
info="For LangChain (ignored if chunk=False)",
minimum=128,
maximum=2048,
visible=kwargs['langchain_mode'] != 'Disabled',
interactive=not is_public,
precision=0)
with gr.TabItem("Models"):
model_lock_msg = gr.Textbox(lines=1, label="Model Lock Notice",
placeholder="Started in model_lock mode, no model changes allowed.",
visible=bool(kwargs['model_lock']), interactive=False)
load_msg = "Load-Unload Model/LORA [unload works if did not use --base_model]" if not is_public \
else "LOAD-UNLOAD DISABLED FOR HOSTED DEMO"
load_msg2 = "Load-Unload Model/LORA 2 [unload works if did not use --base_model]" if not is_public \
else "LOAD-UNLOAD DISABLED FOR HOSTED DEMO 2"
variant_load_msg = 'primary' if not is_public else 'secondary'
compare_checkbox = gr.components.Checkbox(label="Compare Mode",
value=kwargs['model_lock'],
visible=not is_public and not kwargs['model_lock'])
with gr.Row():
n_gpus_list = [str(x) for x in list(range(-1, n_gpus))]
with gr.Column():
with gr.Row():
with gr.Column(scale=20, visible=not kwargs['model_lock']):
model_choice = gr.Dropdown(model_options_state.value[0], label="Choose Model",
value=kwargs['base_model'])
lora_choice = gr.Dropdown(lora_options_state.value[0], label="Choose LORA",
value=kwargs['lora_weights'], visible=kwargs['show_lora'])
server_choice = gr.Dropdown(server_options_state.value[0], label="Choose Server",
value=kwargs['inference_server'], visible=not is_public)
with gr.Column(scale=1, visible=not kwargs['model_lock']):
load_model_button = gr.Button(load_msg, variant=variant_load_msg, scale=0,
size='sm', interactive=not is_public)
model_load8bit_checkbox = gr.components.Checkbox(
label="Load 8-bit [requires support]",
value=kwargs['load_8bit'], interactive=not is_public)
model_infer_devices_checkbox = gr.components.Checkbox(
label="Choose Devices [If not Checked, use all GPUs]",
value=kwargs['infer_devices'], interactive=not is_public)
model_gpu = gr.Dropdown(n_gpus_list,
label="GPU ID [-1 = all GPUs, if Choose is enabled]",
value=kwargs['gpu_id'], interactive=not is_public)
model_used = gr.Textbox(label="Current Model", value=kwargs['base_model'],
interactive=False)
lora_used = gr.Textbox(label="Current LORA", value=kwargs['lora_weights'],
visible=kwargs['show_lora'], interactive=False)
server_used = gr.Textbox(label="Current Server",
value=kwargs['inference_server'],
visible=bool(kwargs['inference_server']) and not is_public,
interactive=False)
prompt_dict = gr.Textbox(label="Prompt (or Custom)",
value=pprint.pformat(kwargs['prompt_dict'], indent=4),
interactive=not is_public, lines=4)
col_model2 = gr.Column(visible=False)
with col_model2:
with gr.Row():
with gr.Column(scale=20, visible=not kwargs['model_lock']):
model_choice2 = gr.Dropdown(model_options_state.value[0], label="Choose Model 2",
value=no_model_str)
lora_choice2 = gr.Dropdown(lora_options_state.value[0], label="Choose LORA 2",
value=no_lora_str,
visible=kwargs['show_lora'])
server_choice2 = gr.Dropdown(server_options_state.value[0], label="Choose Server 2",
value=no_server_str,
visible=not is_public)
with gr.Column(scale=1, visible=not kwargs['model_lock']):
load_model_button2 = gr.Button(load_msg2, variant=variant_load_msg, scale=0,
size='sm', interactive=not is_public)
model_load8bit_checkbox2 = gr.components.Checkbox(
label="Load 8-bit 2 [requires support]",
value=kwargs['load_8bit'], interactive=not is_public)
model_infer_devices_checkbox2 = gr.components.Checkbox(
label="Choose Devices 2 [If not Checked, use all GPUs]",
value=kwargs[
'infer_devices'], interactive=not is_public)
model_gpu2 = gr.Dropdown(n_gpus_list,
label="GPU ID 2 [-1 = all GPUs, if choose is enabled]",
value=kwargs['gpu_id'], interactive=not is_public)
# no model/lora loaded ever in model2 by default
model_used2 = gr.Textbox(label="Current Model 2", value=no_model_str,
interactive=False)
lora_used2 = gr.Textbox(label="Current LORA 2", value=no_lora_str,
visible=kwargs['show_lora'], interactive=False)
server_used2 = gr.Textbox(label="Current Server 2", value=no_server_str,
interactive=False,
visible=not is_public)
prompt_dict2 = gr.Textbox(label="Prompt (or Custom) 2",
value=pprint.pformat(kwargs['prompt_dict'], indent=4),
interactive=not is_public, lines=4)
with gr.Row(visible=not kwargs['model_lock']):
with gr.Column(scale=50):
new_model = gr.Textbox(label="New Model name/path", interactive=not is_public)
with gr.Column(scale=50):
new_lora = gr.Textbox(label="New LORA name/path", visible=kwargs['show_lora'],
interactive=not is_public)
with gr.Column(scale=50):
new_server = gr.Textbox(label="New Server url:port", interactive=not is_public)
with gr.Row():
add_model_lora_server_button = gr.Button("Add new Model, Lora, Server url:port", scale=0,
size='sm', interactive=not is_public)
with gr.TabItem("System"):
admin_row = gr.Row()
with admin_row:
admin_pass_textbox = gr.Textbox(label="Admin Password", type='password', visible=is_public)
admin_btn = gr.Button(value="Admin Access", visible=is_public)
system_row = gr.Row(visible=not is_public)
with system_row:
with gr.Column():
with gr.Row():
system_btn = gr.Button(value='Get System Info')
system_text = gr.Textbox(label='System Info', interactive=False, show_copy_button=True)
system_input = gr.Textbox(label='System Info Dict', interactive=True,
visible=False, show_copy_button=True)
with gr.Row():
zip_btn = gr.Button("Zip")
zip_text = gr.Textbox(label="Zip file name", interactive=False)
file_output = gr.File(interactive=False, label="Zip file to Download")
with gr.Row():
s3up_btn = gr.Button("S3UP")
s3up_text = gr.Textbox(label='S3UP result', interactive=False)
with gr.TabItem("Disclaimers"):
description = ""
description += """<p><b> DISCLAIMERS: </b><ul><i><li>The model was trained on The Pile and other data, which may contain objectionable content. Use at own risk.</i></li>"""
if kwargs['load_8bit']:
description += """<i><li> Model is loaded in 8-bit and has other restrictions on this host. UX can be worse than non-hosted version.</i></li>"""
description += """<i><li>Conversations may be used to improve h2oGPT. Do not share sensitive information.</i></li>"""
if 'h2ogpt-research' in kwargs['base_model']:
description += """<i><li>Research demonstration only, not used for commercial purposes.</i></li>"""
description += """<i><li>By using h2oGPT, you accept our <a href="https://github.com/h2oai/h2ogpt/blob/main/docs/tos.md">Terms of Service</a></i></li></ul></p>"""
gr.Markdown(value=description, show_label=False, interactive=False)
# Get flagged data
zip_data1 = functools.partial(zip_data, root_dirs=['flagged_data_points', kwargs['save_dir']])
zip_btn.click(zip_data1, inputs=None, outputs=[file_output, zip_text], queue=False,
api_name='zip_data' if allow_api else None)
s3up_btn.click(s3up, inputs=zip_text, outputs=s3up_text, queue=False,
api_name='s3up_data' if allow_api else None)
def make_add_visible(x):
return gr.update(visible=x is not None)
def clear_file_list():
return None
def make_invisible():
return gr.update(visible=False)
def make_visible():
return gr.update(visible=True)
def update_radio_to_user():
return gr.update(value='UserData')
# Add to UserData
update_user_db_func = functools.partial(update_user_db,
dbs=dbs, db_type=db_type, langchain_mode='UserData',
use_openai_embedding=use_openai_embedding,
hf_embedding_model=hf_embedding_model,
enable_captions=enable_captions,
captions_model=captions_model,
enable_ocr=enable_ocr,
caption_loader=caption_loader,
verbose=kwargs['verbose'],
user_path=kwargs['user_path'],
)
# note for update_user_db_func output is ignored for db
eventdb1 = add_to_shared_db_btn.click(update_user_db_func,
inputs=[fileup_output, my_db_state, add_to_shared_db_btn,
add_to_my_db_btn,
chunk, chunk_size],
outputs=[add_to_shared_db_btn, add_to_my_db_btn, sources_text],
queue=queue,
api_name='add_to_shared' if allow_api and allow_upload_to_user_data else None) \
.then(clear_file_list, outputs=fileup_output, queue=queue) \
.then(update_radio_to_user, inputs=None, outputs=langchain_mode, queue=queue)
# .then(make_invisible, outputs=add_to_shared_db_btn, queue=queue)
# .then(make_visible, outputs=upload_button, queue=queue)
def clear_textbox():
return gr.Textbox.update(value='')
update_user_db_url_func = functools.partial(update_user_db_func, is_url=True)
eventdb2 = url_user_btn.click(update_user_db_url_func,
inputs=[url_text, my_db_state, add_to_shared_db_btn, add_to_my_db_btn,
chunk, chunk_size],
outputs=[add_to_shared_db_btn, add_to_my_db_btn, sources_text], queue=queue,
api_name='add_url_to_shared' if allow_api and allow_upload_to_user_data else None) \
.then(clear_textbox, outputs=url_text, queue=queue) \
.then(update_radio_to_user, inputs=None, outputs=langchain_mode, queue=queue)
update_user_db_txt_func = functools.partial(update_user_db_func, is_txt=True)
eventdb3 = user_text_user_btn.click(update_user_db_txt_func,
inputs=[user_text_text, my_db_state, add_to_shared_db_btn, add_to_my_db_btn,
chunk, chunk_size],
outputs=[add_to_shared_db_btn, add_to_my_db_btn, sources_text], queue=queue,
api_name='add_text_to_shared' if allow_api and allow_upload_to_user_data else None) \
.then(clear_textbox, outputs=user_text_text, queue=queue) \
.then(update_radio_to_user, inputs=None, outputs=langchain_mode, queue=queue)
# Add to MyData
def update_radio_to_my():
return gr.update(value='MyData')
update_my_db_func = functools.partial(update_user_db, dbs=dbs, db_type=db_type, langchain_mode='MyData',
use_openai_embedding=use_openai_embedding,
hf_embedding_model=hf_embedding_model,
enable_captions=enable_captions,
captions_model=captions_model,
enable_ocr=enable_ocr,
caption_loader=caption_loader,
verbose=kwargs['verbose'],
user_path=kwargs['user_path'],
)
eventdb4 = add_to_my_db_btn.click(update_my_db_func,
inputs=[fileup_output, my_db_state, add_to_shared_db_btn, add_to_my_db_btn,
chunk, chunk_size],
outputs=[my_db_state, add_to_shared_db_btn, add_to_my_db_btn, sources_text],
queue=queue,
api_name='add_to_my' if allow_api and allow_upload_to_my_data else None) \
.then(clear_file_list, outputs=fileup_output, queue=queue) \
.then(update_radio_to_my, inputs=None, outputs=langchain_mode, queue=queue)
# .then(make_invisible, outputs=add_to_shared_db_btn, queue=queue)
# .then(make_visible, outputs=upload_button, queue=queue)
update_my_db_url_func = functools.partial(update_my_db_func, is_url=True)
eventdb5 = url_my_btn.click(update_my_db_url_func,
inputs=[url_text, my_db_state, add_to_shared_db_btn, add_to_my_db_btn,
chunk, chunk_size],
outputs=[my_db_state, add_to_shared_db_btn, add_to_my_db_btn, sources_text],
queue=queue,
api_name='add_url_to_my' if allow_api and allow_upload_to_my_data else None) \
.then(clear_textbox, outputs=url_text, queue=queue) \
.then(update_radio_to_my, inputs=None, outputs=langchain_mode, queue=queue)
update_my_db_txt_func = functools.partial(update_my_db_func, is_txt=True)
eventdb6 = user_text_my_btn.click(update_my_db_txt_func,
inputs=[user_text_text, my_db_state, add_to_shared_db_btn, add_to_my_db_btn,
chunk, chunk_size],
outputs=[my_db_state, add_to_shared_db_btn, add_to_my_db_btn, sources_text],
queue=queue,
api_name='add_txt_to_my' if allow_api and allow_upload_to_my_data else None) \
.then(clear_textbox, outputs=user_text_text, queue=queue) \
.then(update_radio_to_my, inputs=None, outputs=langchain_mode, queue=queue)
get_sources1 = functools.partial(get_sources, dbs=dbs, docs_state0=docs_state0)
# if change collection source, must clear doc selections from it to avoid inconsistency
def clear_doc_choice():
return gr.Dropdown.update(choices=docs_state0, value=[docs_state0[0]])
langchain_mode.change(clear_doc_choice, inputs=None, outputs=document_choice)
def update_dropdown(x):
return gr.Dropdown.update(choices=x, value=[docs_state0[0]])
eventdb7 = get_sources_btn.click(get_sources1, inputs=[my_db_state, langchain_mode],
outputs=[file_source, docs_state],
queue=queue,
api_name='get_sources' if allow_api else None) \
.then(fn=update_dropdown, inputs=docs_state, outputs=document_choice)
# show button, else only show when add. Could add to above get_sources for download/dropdown, but bit much maybe
show_sources1 = functools.partial(get_source_files_given_langchain_mode, dbs=dbs)
eventdb8 = show_sources_btn.click(fn=show_sources1, inputs=[my_db_state, langchain_mode], outputs=sources_text,
api_name='show_sources' if allow_api else None)
# Get inputs to evaluate() and make_db()
# don't deepcopy, can contain model itself
all_kwargs = kwargs.copy()
all_kwargs.update(locals())
refresh_sources1 = functools.partial(update_and_get_source_files_given_langchain_mode,
**get_kwargs(update_and_get_source_files_given_langchain_mode,
exclude_names=['db1', 'langchain_mode'],
**all_kwargs))
eventdb9 = refresh_sources_btn.click(fn=refresh_sources1, inputs=[my_db_state, langchain_mode],
outputs=sources_text,
api_name='refresh_sources' if allow_api else None)
def check_admin_pass(x):
return gr.update(visible=x == admin_pass)
def close_admin(x):
return gr.update(visible=not (x == admin_pass))
admin_btn.click(check_admin_pass, inputs=admin_pass_textbox, outputs=system_row, queue=False) \
.then(close_admin, inputs=admin_pass_textbox, outputs=admin_row, queue=False)
inputs_list, inputs_dict = get_inputs_list(all_kwargs, kwargs['model_lower'], model_id=1)
inputs_list2, inputs_dict2 = get_inputs_list(all_kwargs, kwargs['model_lower'], model_id=2)
from functools import partial
kwargs_evaluate = {k: v for k, v in all_kwargs.items() if k in inputs_kwargs_list}
# ensure present
for k in inputs_kwargs_list:
assert k in kwargs_evaluate, "Missing %s" % k
def evaluate_gradio(*args1, **kwargs1):
for res_dict in evaluate(*args1, **kwargs1):
if kwargs['langchain_mode'] == 'Disabled':
yield fix_text_for_gradio(res_dict['response'])
else:
yield '<br>' + fix_text_for_gradio(res_dict['response'])
fun = partial(evaluate_gradio,
**kwargs_evaluate)
fun2 = partial(evaluate_gradio,
**kwargs_evaluate)
fun_with_dict_str = partial(evaluate_from_str,
default_kwargs=default_kwargs,
**kwargs_evaluate
)
dark_mode_btn = gr.Button("Dark Mode", variant="primary", size="sm")
# FIXME: Could add exceptions for non-chat but still streaming
exception_text = gr.Textbox(value="", visible=kwargs['chat'], label='Chat Exceptions', interactive=False)
dark_mode_btn.click(
None,
None,
None,
_js=get_dark_js(),
api_name="dark" if allow_api else None,
queue=False,
)
# Control chat and non-chat blocks, which can be independently used by chat checkbox swap
def col_nochat_fun(x):
return gr.Column.update(visible=not x)
def col_chat_fun(x):
return gr.Column.update(visible=bool(x))
def context_fun(x):
return gr.Textbox.update(visible=not x)
chat.select(col_nochat_fun, chat, col_nochat, api_name="chat_checkbox" if allow_api else None) \
.then(col_chat_fun, chat, col_chat) \
.then(context_fun, chat, context) \
.then(col_chat_fun, chat, exception_text)
# examples after submit or any other buttons for chat or no chat
if kwargs['examples'] is not None and kwargs['show_examples']:
gr.Examples(examples=kwargs['examples'], inputs=inputs_list)
# Score
def score_last_response(*args, nochat=False, num_model_lock=0):
try:
if num_model_lock > 0:
# then lock way
args_list = list(args).copy()
outputs = args_list[-num_model_lock:]
score_texts1 = []
for output in outputs:
# same input, put into form good for _score_last_response()
args_list[-1] = output
score_texts1.append(
_score_last_response(*tuple(args_list), nochat=nochat, num_model_lock=num_model_lock))
if len(score_texts1) > 1:
return tuple(score_texts1)
else:
return score_texts1[0]
else:
return _score_last_response(*args, nochat=nochat, num_model_lock=num_model_lock)
finally:
clear_torch_cache()
def _score_last_response(*args, nochat=False, num_model_lock=0):
""" Similar to user() """
args_list = list(args)
if memory_restriction_level > 0:
max_length_tokenize = 768 - 256 if memory_restriction_level <= 2 else 512 - 256
else:
max_length_tokenize = 2048 - 256
cutoff_len = max_length_tokenize * 4 # restrict deberta related to max for LLM
smodel = score_model_state0['model']
stokenizer = score_model_state0['tokenizer']
sdevice = score_model_state0['device']
if not nochat:
history = args_list[-1]
if history is None:
history = []
if smodel is not None and \
stokenizer is not None and \
sdevice is not None and \
history is not None and len(history) > 0 and \
history[-1] is not None and \
len(history[-1]) >= 2:
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
question = history[-1][0]
answer = history[-1][1]
else:
return 'Response Score: NA'
else:
answer = args_list[-1]
instruction_nochat_arg_id = eval_func_param_names.index('instruction_nochat')
question = args_list[instruction_nochat_arg_id]
if question is None:
return 'Response Score: Bad Question'
if answer is None:
return 'Response Score: Bad Answer'
try:
score = score_qa(smodel, stokenizer, max_length_tokenize, question, answer, cutoff_len)
finally:
clear_torch_cache()
if isinstance(score, str):
return 'Response Score: NA'
return 'Response Score: {:.1%}'.format(score)
def noop_score_last_response(*args, **kwargs):
return "Response Score: Disabled"
if kwargs['score_model']:
score_fun = score_last_response
else:
score_fun = noop_score_last_response
score_args = dict(fn=score_fun,
inputs=inputs_list + [text_output],
outputs=[score_text],
)
score_args2 = dict(fn=partial(score_fun),
inputs=inputs_list2 + [text_output2],
outputs=[score_text2],
)
score_fun_func = functools.partial(score_fun, num_model_lock=len(text_outputs))
all_score_args = dict(fn=score_fun_func,
inputs=inputs_list + text_outputs,
outputs=score_texts,
)
score_args_nochat = dict(fn=partial(score_fun, nochat=True),
inputs=inputs_list + [text_output_nochat],
outputs=[score_text_nochat],
)
def update_history(*args, undo=False, retry=False, sanitize_user_prompt=True):
"""
User that fills history for bot
:param args:
:param undo:
:param sanitize_user_prompt:
:param model2:
:return:
"""
args_list = list(args)
user_message = args_list[eval_func_param_names.index('instruction')] # chat only
input1 = args_list[eval_func_param_names.index('iinput')] # chat only
prompt_type1 = args_list[eval_func_param_names.index('prompt_type')]
if not prompt_type1:
# shouldn't have to specify if CLI launched model
prompt_type1 = kwargs['prompt_type']