forked from h2oai/h2ogpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate.py
1556 lines (1418 loc) · 73.1 KB
/
generate.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 ast
import functools
import glob
import inspect
import queue
import shutil
import sys
import os
import time
import traceback
import typing
from datetime import datetime
import filelock
import psutil
from loaders import get_loaders
from utils import set_seed, clear_torch_cache, save_generate_output, NullContext, wrapped_partial, EThread, get_githash, \
import_matplotlib, get_device, makedirs
import_matplotlib()
from matplotlib import pyplot as plt
SEED = 1236
set_seed(SEED)
os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1'
from typing import Union
import numpy as np
import pandas as pd
import fire
import torch
from peft import PeftModel
from transformers import GenerationConfig, AutoModel, TextIteratorStreamer
from accelerate import init_empty_weights, infer_auto_device_map
from prompter import Prompter, inv_prompt_type_to_model_lower
from stopping import get_stopping
eval_extra_columns = ['prompt', 'response', 'score']
langchain_modes = ['Disabled', 'ChatLLM', 'LLM', 'All', 'wiki', 'wiki_full', 'UserData', 'MyData', 'github h2oGPT',
'DriverlessAI docs']
scratch_base_dir = '/tmp/'
def main(
load_8bit: bool = False,
load_half: bool = True,
infer_devices: bool = True,
base_model: str = '',
tokenizer_base_model: str = '',
lora_weights: str = "",
gpu_id: int = 0,
prompt_type: Union[int, str] = None,
# input to generation
temperature: float = None,
top_p: float = None,
top_k: int = None,
num_beams: int = None,
repetition_penalty: float = None,
num_return_sequences: int = None,
do_sample: bool = None,
max_new_tokens: int = None,
min_new_tokens: int = None,
early_stopping: Union[bool, str] = None,
max_time: float = None,
debug: bool = False,
save_dir: str = None,
share: bool = True,
local_files_only: bool = False,
resume_download: bool = True,
use_auth_token: Union[str, bool] = False,
trust_remote_code: Union[str, bool] = True,
offload_folder: str = "offline_folder",
src_lang: str = "English",
tgt_lang: str = "Russian",
gradio: bool = True,
gradio_avoid_processing_markdown: bool = False,
chat: bool = True,
chat_context: bool = False,
stream_output: bool = True,
show_examples: bool = None,
verbose: bool = False,
h2ocolors: bool = True,
height: int = 400,
show_lora: bool = True,
login_mode_if_model0: bool = False,
block_gradio_exit: bool = True,
concurrency_count: int = 1,
api_open: bool = False,
allow_api: bool = True,
input_lines: int = 1,
auth: typing.List[typing.Tuple[str, str]] = None,
sanitize_user_prompt: bool = True,
sanitize_bot_response: bool = True,
extra_model_options: typing.List[str] = [],
extra_lora_options: typing.List[str] = [],
score_model: str = 'OpenAssistant/reward-model-deberta-v3-large-v2',
auto_score: bool = True,
eval_sharegpt_prompts_only: int = 0,
eval_sharegpt_prompts_only_seed: int = 1234,
eval_sharegpt_as_output: bool = False,
langchain_mode: str = 'Disabled',
visible_langchain_modes: list = ['UserData', 'MyData'],
user_path: str = None,
load_db_if_exists: bool = True,
keep_sources_in_context: bool = False,
db_type: str = 'chroma',
use_openai_embedding: bool = False,
use_openai_model: bool = False,
hf_embedding_model: str = "sentence-transformers/all-MiniLM-L6-v2",
allow_upload_to_user_data: bool = True,
allow_upload_to_my_data: bool = True,
enable_url_upload: bool = True,
enable_text_upload: bool = True,
enable_sources_list: bool = True,
chunk: bool = True,
chunk_size: int = 512,
top_k_docs: int = 4,
n_jobs: int = -1,
enable_captions: bool = True,
captions_model: str = "Salesforce/blip-image-captioning-base",
pre_load_caption_model: bool = False,
caption_gpu: bool = True,
enable_ocr: bool = False,
):
"""
:param load_8bit: load model in 8-bit using bitsandbytes
:param load_half: load model in float16
:param infer_devices: whether to control devices with gpu_id. If False, then spread across GPUs
:param base_model: model HF-type name
:param tokenizer_base_model: tokenizer HF-type name
:param lora_weights: LORA weights path/HF link
:param gpu_id: if infer_devices, then use gpu_id for cuda device ID, or auto mode if gpu_id != -1
:param prompt_type: type of prompt, usually matched to fine-tuned model or plain for foundational model
:param temperature: generation temperature
:param top_p: generation top_p
:param top_k: generation top_k
:param num_beams: generation number of beams
:param repetition_penalty: generation repetition penalty
:param num_return_sequences: generation number of sequences (1 forced for chat)
:param do_sample: generation sample
:param max_new_tokens: generation max new tokens
:param min_new_tokens: generation min tokens
:param early_stopping: generation early stopping
:param max_time: maximum time to allow for generation
:param debug: enable debug mode
:param save_dir: directory chat data is saved to
:param share: whether to share the gradio app with sharable URL
:param local_files_only: whether to only use local files instead of doing to HF for models
:param resume_download: whether to resume downloads from HF for models
:param use_auth_token: whether to use HF auth token (requires CLI did huggingface-cli login before)
:param trust_remote_code: whether to use trust any code needed for HF model
:param offload_folder: path for spilling model onto disk
:param src_lang: source languages to include if doing translation (None = all)
:param tgt_lang: target languages to include if doing translation (None = all)
:param gradio: whether to enable gradio, or to enable benchmark mode
:param gradio_avoid_processing_markdown:
:param chat: whether to enable chat mode with chat history
:param chat_context: whether to use extra helpful context if human_bot
:param stream_output: whether to stream output from generate
:param show_examples: whether to show clickable examples in gradio
:param verbose: whether to show verbose prints
:param h2ocolors: whether to use H2O.ai theme
:param height: height of chat window
:param show_lora: whether to show LORA options in UI (expert so can be hard to understand)
:param login_mode_if_model0: set to True to load --base_model after client logs in, to be able to free GPU memory when model is swapped
:param block_gradio_exit: whether to block gradio exit (used for testing)
:param concurrency_count: gradio concurrency count (1 is optimal for LLMs)
:param api_open: If False, don't let API calls skip gradio queue
:param allow_api: whether to allow API calls at all to gradio server
:param input_lines: how many input lines to show for chat box (>1 forces shift-enter for submit, else enter is submit)
:param auth: gradio auth for launcher in form [(user1, pass1), (user2, pass2), ...]
e.g. --auth=[('jon','password')] with no spaces
:param sanitize_user_prompt: whether to remove profanity from user input
:param sanitize_bot_response: whether to remove profanity and repeat lines from bot output
:param extra_model_options: extra models to show in list in gradio
:param extra_lora_options: extra LORA to show in list in gradio
:param score_model: which model to score responses (None means no scoring)
:param auto_score: whether to automatically score responses
:param eval_sharegpt_prompts_only: for no gradio benchmark, if using ShareGPT prompts for eval
:param eval_sharegpt_prompts_only_seed: for no gradio benchmark, if seed for ShareGPT sampling
:param eval_sharegpt_as_output: for no gradio benchmark, whether to test ShareGPT output itself
:param langchain_mode: Data source to include. Choose "UserData" to only consume files from make_db.py.
WARNING: wiki_full requires extra data processing via read_wiki_full.py and requires really good workstation to generate db, unless already present.
:param user_path: user path to glob from to generate db for vector search, for 'UserData' langchain mode
:param visible_langchain_modes: dbs to generate at launch to be ready for LLM
Can be up to ['wiki', 'wiki_full', 'UserData', 'MyData', 'github h2oGPT', 'DriverlessAI docs']
But wiki_full is expensive and requires preparation
To allow scratch space only live in session, add 'MyData' to list
Default: If only want to consume local files, e.g. prepared by make_db.py, only include ['UserData']
FIXME: Avoid 'All' for now, not implemented
:param load_db_if_exists: Whether to load chroma db if exists or re-generate db
:param keep_sources_in_context: Whether to keep url sources in context, not helpful usually
:param db_type: 'faiss' for in-memory or 'chroma' for persisted on disk
:param use_openai_embedding: Whether to use OpenAI embeddings for vector db
:param use_openai_model: Whether to use OpenAI model for use with vector db
:param hf_embedding_model: Which HF embedding model to use for vector db
:param allow_upload_to_user_data: Whether to allow file uploads to update shared vector db
:param allow_upload_to_my_data: Whether to allow file uploads to update scratch vector db
:param enable_url_upload: Whether to allow upload from URL
:param enable_text_upload: Whether to allow uplaod of text
:param enable_sources_list: Whether to allow list (or download for non-shared db) of list of sources for chosen db
:param chunk: Whether to chunk data (True unless know data is already optimally chunked)
:param chunk_size: Size of chunks, with typically top-4 passed to LLM, so neesd to be in context length
:param top_k_docs: number of chunks to give LLM
:param n_jobs: Number of processors to use when consuming documents (-1 = all, is default)
:param enable_captions: Whether to support captions using BLIP for image files as documents, then preloads that model
:param captions_model: Which model to use for captions.
captions_model: int = "Salesforce/blip-image-captioning-base", # continue capable
captions_model: str = "Salesforce/blip2-flan-t5-xl", # question/answer capable, 16GB state
captions_model: int = "Salesforce/blip2-flan-t5-xxl", # question/answer capable, 60GB state
Note: opt-based blip2 are not permissive license due to opt and Meta license restrictions
:param pre_load_caption_model: Whether to preload caption model, or load after forking parallel doc loader
parallel loading disabled if preload and have images, to prevent deadlocking on cuda context
Recommended if using larger caption model
:param caption_gpu: If support caption, then use GPU if exists
:param enable_ocr: Whether to support OCR on images
:return:
"""
is_hf = bool(os.getenv("HUGGINGFACE_SPACES"))
is_gpth2oai = bool(os.getenv("GPT_H2O_AI"))
is_public = is_hf or is_gpth2oai # multi-user case with fixed model and disclaimer
is_low_mem = is_hf # assumes run on 24GB consumer GPU
admin_pass = os.getenv("ADMIN_PASS")
# will sometimes appear in UI or sometimes actual generation, but maybe better than empty result
# but becomes unrecoverable sometimes if raise, so just be silent for now
raise_generate_gpu_exceptions = True
# allow set token directly
use_auth_token = os.environ.get("HUGGINGFACE_API_TOKEN", use_auth_token)
allow_upload_to_user_data = bool(os.environ.get("allow_upload_to_user_data", allow_upload_to_user_data))
allow_upload_to_my_data = bool(os.environ.get("allow_upload_to_my_data", allow_upload_to_my_data))
height = os.environ.get("HEIGHT", height)
# allow enabling langchain via ENV
# FIRST PLACE where LangChain referenced, but no imports related to it
langchain_mode = os.environ.get("LANGCHAIN_MODE", langchain_mode)
assert langchain_mode in langchain_modes, "Invalid langchain_mode %s" % langchain_mode
visible_langchain_modes = ast.literal_eval(os.environ.get("visible_langchain_modes", str(visible_langchain_modes)))
if langchain_mode not in visible_langchain_modes and langchain_mode in langchain_modes:
visible_langchain_modes += [langchain_mode]
if is_public:
allow_upload_to_user_data = False
input_lines = 1 # ensure set, for ease of use
temperature = 0.2 if temperature is None else temperature
top_p = 0.85 if top_p is None else top_p
top_k = 70 if top_k is None else top_k
if is_hf:
do_sample = True if do_sample is None else do_sample
else:
# by default don't sample, too chatty
do_sample = False if do_sample is None else do_sample
if is_low_mem:
if not base_model:
base_model = 'h2oai/h2ogpt-oasst1-512-12b'
# don't set load_8bit if passed base_model, doesn't always work so can't just override
load_8bit = True
else:
base_model = 'h2oai/h2ogpt-oasst1-512-20b' if not base_model else base_model
if is_low_mem:
load_8bit = True
if is_hf:
# must override share if in spaces
share = False
save_dir = os.getenv('SAVE_DIR', save_dir)
score_model = os.getenv('SCORE_MODEL', score_model)
if score_model == 'None':
score_model = ''
concurrency_count = int(os.getenv('CONCURRENCY_COUNT', concurrency_count))
api_open = bool(int(os.getenv('API_OPEN', api_open)))
allow_api = bool(int(os.getenv('ALLOW_API', allow_api)))
n_gpus = torch.cuda.device_count() if torch.cuda.is_available else 0
if n_gpus == 0:
gpu_id = None
load_8bit = False
load_half = False
infer_devices = False
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.enabled = False
torch.set_default_dtype(torch.float32)
if psutil.virtual_memory().available < 94 * 1024 ** 3:
# 12B uses ~94GB
# 6.9B uses ~47GB
base_model = 'h2oai/h2ogpt-oig-oasst1-512-6_9b' if not base_model else base_model
# get defaults
model_lower = base_model.lower()
if not gradio:
# force, else not single response like want to look at
stream_output = False
# else prompt removal can mess up output
chat = False
# hard-coded defaults
first_para = False
text_limit = None
if offload_folder:
makedirs(offload_folder)
placeholder_instruction, placeholder_input, \
stream_output, show_examples, \
prompt_type, temperature, top_p, top_k, num_beams, \
max_new_tokens, min_new_tokens, early_stopping, max_time, \
repetition_penalty, num_return_sequences, \
do_sample, \
src_lang, tgt_lang, \
examples, \
task_info = \
get_generate_params(model_lower, chat,
stream_output, show_examples,
prompt_type, temperature, top_p, top_k, num_beams,
max_new_tokens, min_new_tokens, early_stopping, max_time,
repetition_penalty, num_return_sequences,
do_sample,
top_k_docs,
)
locals_dict = locals()
locals_print = '\n'.join(['%s: %s' % (k, v) for k, v in locals_dict.items()])
print(f"Generating model with params:\n{locals_print}", flush=True)
print("Command: %s\nHash: %s" % (str(' '.join(sys.argv)), get_githash()), flush=True)
if langchain_mode != "Disabled":
# SECOND PLACE where LangChain referenced, but all imports are kept local so not required
from gpt_langchain import prep_langchain, get_some_dbs_from_hf
if is_hf:
get_some_dbs_from_hf()
dbs = {}
for langchain_mode1 in visible_langchain_modes:
if langchain_mode1 in ['MyData']:
# don't use what is on disk, remove it instead
for gpath1 in glob.glob(os.path.join(scratch_base_dir, 'db_dir_%s*' % langchain_mode1)):
if os.path.isdir(gpath1):
print("Removing old MyData: %s" % gpath1, flush=True)
shutil.rmtree(gpath1)
continue
if langchain_mode1 in ['All']:
# FIXME: All should be avoided until scans over each db, shouldn't be separate db
continue
persist_directory1 = 'db_dir_%s' % langchain_mode1 # single place, no special names for each case
db = prep_langchain(persist_directory1, load_db_if_exists, db_type, use_openai_embedding,
langchain_mode1, user_path,
hf_embedding_model,
kwargs_make_db=locals())
dbs[langchain_mode1] = db
# remove None db's so can just rely upon k in dbs for if hav db
dbs = {k: v for k, v in dbs.items() if v is not None}
else:
dbs = {}
# import control
if os.environ.get("TEST_LANGCHAIN_IMPORT"):
assert 'gpt_langchain' not in sys.modules, "Dev bug, import of langchain when should not have"
assert 'langchain' not in sys.modules, "Dev bug, import of langchain when should not have"
if not gradio:
if eval_sharegpt_prompts_only > 0:
# override default examples with shareGPT ones for human-level eval purposes only
eval_filename = 'ShareGPT_V3_unfiltered_cleaned_split_no_imsorry.json'
if not os.path.isfile(eval_filename):
os.system(
'wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/resolve/main/%s' % eval_filename)
import json
data = json.load(open(eval_filename, 'rt'))
# focus on data that starts with human, else likely chopped from other data
turn_start = 0 # odd in general
data = [x for x in data if len(x['conversations']) > turn_start + 1 and
x['conversations'][turn_start]['from'] == 'human' and
x['conversations'][turn_start + 1]['from'] == 'gpt']
np.random.seed(eval_sharegpt_prompts_only_seed)
example1 = examples[-1] # pick reference example
examples = []
responses = []
for i in list(np.random.randint(0, len(data), size=eval_sharegpt_prompts_only)):
assert data[i]['conversations'][turn_start]['from'] == 'human'
instruction = data[i]['conversations'][turn_start]['value']
assert data[i]['conversations'][turn_start + 1]['from'] == 'gpt'
output = data[i]['conversations'][turn_start + 1]['value']
examplenew = example1.copy()
assert not chat, "No gradio must use chat=False, uses nochat instruct"
examplenew[eval_func_param_names.index('instruction_nochat')] = instruction
examplenew[eval_func_param_names.index('iinput_nochat')] = '' # no input
examplenew[eval_func_param_names.index('context')] = get_context(chat_context, prompt_type)
examples.append(examplenew)
responses.append(output)
num_examples = len(examples)
scoring_path = 'scoring'
os.makedirs(scoring_path, exist_ok=True)
if eval_sharegpt_as_output:
used_base_model = 'gpt35'
used_lora_weights = ''
else:
used_base_model = str(base_model.split('/')[-1])
used_lora_weights = str(lora_weights.split('/')[-1])
eval_filename = "df_scores_%s_%s_%s_%s_%s_%s.parquet" % (num_examples, eval_sharegpt_prompts_only,
eval_sharegpt_prompts_only_seed,
eval_sharegpt_as_output,
used_base_model,
used_lora_weights)
eval_filename = os.path.join(scoring_path, eval_filename)
# torch.device("cuda") leads to cuda:x cuda:y mismatches for multi-GPU consistently
device = 'cpu' if n_gpus == 0 else 'cuda'
context_class = NullContext if n_gpus > 1 or n_gpus == 0 else torch.device
with context_class(device):
# ensure was set right above before examples generated
assert not stream_output, "stream_output=True does not make sense with example loop"
import time
from functools import partial
# get score model
smodel, stokenizer, sdevice = get_score_model(**locals())
if not eval_sharegpt_as_output:
model, tokenizer, device = get_model(**locals())
model_state = [model, tokenizer, device, base_model]
kwargs_evaluate = {k: v for k, v in locals().items() if k in inputs_kwargs_list}
my_db_state = [None]
fun = partial(evaluate, model_state, my_db_state, **kwargs_evaluate)
else:
assert eval_sharegpt_prompts_only > 0
def get_response(*args, exi=0):
# assumes same ordering of examples and responses
yield responses[exi]
fun = get_response
t0 = time.time()
score_dump = []
for exi, ex in enumerate(examples):
instruction = ex[eval_func_param_names.index('instruction_nochat')]
iinput = ex[eval_func_param_names.index('iinput_nochat')]
context = ex[eval_func_param_names.index('context')]
clear_torch_cache()
print("")
print("START" + "=" * 100)
print("Question: %s %s" % (instruction, ('input=%s' % iinput if iinput else '')))
print("-" * 105)
# fun yields as generator, so have to iterate over it
# Also means likely do NOT want --stream_output=True, else would show all generations
gener = fun(*tuple(ex), exi=exi) if eval_sharegpt_as_output else fun(*tuple(ex))
for res in gener:
print(res)
if smodel:
score_with_prompt = False
if score_with_prompt:
data_point = dict(instruction=instruction, input=iinput, context=context)
prompter = Prompter(prompt_type, debug=debug, chat=chat, stream_output=stream_output)
prompt = prompter.generate_prompt(data_point)
else:
# just raw input and output
if eval_sharegpt_prompts_only > 0:
# only our own examples have this filled at moment
assert iinput in [None, ''], iinput # should be no iinput
if not (chat_context and prompt_type == 'human_bot'):
assert context in [None, ''], context # should be no context
prompt = instruction
cutoff_len = 768 if is_low_mem else 2048
inputs = stokenizer(prompt, res,
return_tensors="pt",
truncation=True,
max_length=cutoff_len)
try:
score = torch.sigmoid(smodel(**inputs).logits[0].float()).cpu().detach().numpy()[0]
except torch.cuda.OutOfMemoryError as e:
print("GPU OOM 1: question: %s answer: %s exception: %s" % (prompt, res, str(e)),
flush=True)
traceback.print_exc()
score = 0.0
clear_torch_cache()
except (Exception, RuntimeError) as e:
if 'Expected all tensors to be on the same device' in str(e) or \
'expected scalar type Half but found Float' in str(e) or \
'probability tensor contains either' in str(e) or \
'cublasLt ran into an error!' in str(e):
print("GPU error: question: %s answer: %s exception: %s" % (prompt, res, str(e)),
flush=True)
traceback.print_exc()
score = 0.0
clear_torch_cache()
else:
raise
print("SCORE %s: %s" % (exi, score), flush=True)
score_dump.append(ex + [prompt, res, score])
# dump every score in case abort
df_scores = pd.DataFrame(score_dump,
columns=eval_func_param_names + eval_extra_columns)
df_scores.to_parquet(eval_filename, index=False)
# plot histogram so far
plt.figure(figsize=(10, 10))
plt.hist(df_scores['score'], bins=20)
score_avg = np.mean(df_scores['score'])
score_median = np.median(df_scores['score'])
plt.title("Score avg: %s median: %s" % (score_avg, score_median))
plt.savefig(eval_filename.replace('.parquet', '.png'))
plt.close()
print("END" + "=" * 102)
print("")
t2 = time.time()
print("Time taken so far: %.4f about %.4g per example" % (t2 - t0, (t2 - t0) / (1 + exi)))
t1 = time.time()
print("Total time taken: %.4f about %.4g per example" % (t1 - t0, (t1 - t0) / num_examples))
return eval_filename
if gradio:
# imported here so don't require gradio to run generate
from gradio_runner import go_gradio
# get default model
all_kwargs = locals().copy()
if all_kwargs.get('base_model') and not all_kwargs['login_mode_if_model0']:
model0, tokenizer0, device = get_model(**all_kwargs)
else:
# if empty model, then don't load anything, just get gradio up
model0, tokenizer0, device = None, None, None
model_state0 = [model0, tokenizer0, device, all_kwargs['base_model']]
# get score model
smodel, stokenizer, sdevice = get_score_model(**all_kwargs)
score_model_state0 = [smodel, stokenizer, sdevice, score_model]
if enable_captions:
if pre_load_caption_model:
from image_captions import H2OImageCaptionLoader
caption_loader = H2OImageCaptionLoader(caption_gpu=caption_gpu).load_model()
else:
caption_loader = 'gpu' if caption_gpu else 'cpu'
else:
caption_loader = False
go_gradio(**locals())
def get_non_lora_model(base_model, model_loader, load_half, model_kwargs, reward_type,
gpu_id=0,
use_auth_token=False,
trust_remote_code=True,
offload_folder=None,
triton_attn=False,
long_sequence=True,
):
"""
Ensure model gets on correct device
:param base_model:
:param model_loader:
:param load_half:
:param model_kwargs:
:param reward_type:
:param gpu_id:
:param use_auth_token:
:param trust_remote_code:
:param offload_folder:
:param triton_attn:
:param long_sequence:
:return:
"""
with init_empty_weights():
from transformers import AutoConfig
config = AutoConfig.from_pretrained(base_model, use_auth_token=use_auth_token,
trust_remote_code=trust_remote_code,
offload_folder=offload_folder)
if triton_attn and 'mpt-' in base_model.lower():
config.attn_config['attn_impl'] = 'triton'
if long_sequence:
if 'mpt-7b-storywriter' in base_model.lower():
config.update({"max_seq_len": 83968})
if 'mosaicml/mpt-7b-chat' in base_model.lower():
config.update({"max_seq_len": 4096})
if issubclass(config.__class__, tuple(AutoModel._model_mapping.keys())):
model = AutoModel.from_config(
config,
)
else:
# can't infer
model = None
if model is not None:
# NOTE: Can specify max_memory={0: max_mem, 1: max_mem}, to shard model
# NOTE: Some models require avoiding sharding some layers,
# then would pass no_split_module_classes and give list of those layers.
device_map = infer_auto_device_map(
model,
dtype=torch.float16 if load_half else torch.float32,
)
if hasattr(model, 'model'):
device_map_model = infer_auto_device_map(
model.model,
dtype=torch.float16 if load_half else torch.float32,
)
device_map.update(device_map_model)
else:
device_map = "auto"
n_gpus = torch.cuda.device_count() if torch.cuda.is_available else 0
if n_gpus > 0:
if gpu_id >= 0:
# FIXME: If really distributes model, tend to get things like: ValueError: gpt_neox.embed_in.weight doesn't have any device set.
# So avoid for now, just put on first GPU, unless score_model, put on last
if reward_type:
device_map = {'': n_gpus - 1}
else:
device_map = {'': min(n_gpus - 1, gpu_id)}
if gpu_id == -1:
device_map = {'': 'cuda'}
else:
device_map = {'': 'cpu'}
model_kwargs['load_in_8bit'] = False
print('device_map: %s' % device_map, flush=True)
load_in_8bit = model_kwargs.get('load_in_8bit', False)
model_kwargs['device_map'] = device_map
if load_in_8bit or not load_half:
model = model_loader.from_pretrained(
base_model,
config=config,
**model_kwargs,
)
else:
model = model_loader.from_pretrained(
base_model,
config=config,
**model_kwargs,
).half()
return model
def get_model(
load_8bit: bool = False,
load_half: bool = True,
infer_devices: bool = True,
base_model: str = '',
tokenizer_base_model: str = '',
lora_weights: str = "",
gpu_id: int = 0,
reward_type: bool = None,
local_files_only: bool = False,
resume_download: bool = True,
use_auth_token: Union[str, bool] = False,
trust_remote_code: bool = True,
offload_folder: str = None,
compile: bool = True,
**kwargs,
):
"""
:param load_8bit: load model in 8-bit, not supported by all models
:param load_half: load model in 16-bit
:param infer_devices: Use torch infer of optimal placement of layers on devices (for non-lora case)
For non-LORA case, False will spread shards across multiple GPUs, but this can lead to cuda:x cuda:y mismatches
So it is not the default
:param base_model: name/path of base model
:param tokenizer_base_model: name/path of tokenizer
:param lora_weights: name/path
:param gpu_id: which GPU (0..n_gpus-1) or allow all GPUs if relevant (-1)
:param reward_type: reward type model for sequence classification
:param local_files_only: use local files instead of from HF
:param resume_download: resume downloads from HF
:param use_auth_token: assumes user did on CLI `huggingface-cli login` to access private repo
:param trust_remote_code: trust code needed by model
:param offload_folder: offload folder
:param compile: whether to compile torch model
:param kwargs:
:return:
"""
print("Get %s model" % base_model, flush=True)
if base_model in ['llama', 'gptj']:
from gpt4all_llm import get_model_tokenizer_gpt4all
model, tokenizer, device = get_model_tokenizer_gpt4all(base_model)
return model, tokenizer, device
if lora_weights is not None and lora_weights.strip():
print("Get %s lora weights" % lora_weights, flush=True)
device = get_device()
if 'gpt2' in base_model.lower():
# RuntimeError: where expected condition to be a boolean tensor, but got a tensor with dtype Half
load_8bit = False
assert base_model.strip(), (
"Please choose a base model with --base_model (CLI) or in Models Tab (gradio)"
)
from transformers import AutoConfig
config = AutoConfig.from_pretrained(base_model, use_auth_token=use_auth_token,
trust_remote_code=trust_remote_code,
offload_folder=offload_folder)
llama_type_from_config = 'llama' in str(config).lower()
llama_type_from_name = "llama" in base_model.lower()
llama_type = llama_type_from_config or llama_type_from_name
if llama_type:
print("Detected as llama type from"
" config (%s) or name (%s)" % (llama_type_from_config, llama_type_from_name), flush=True)
model_loader, tokenizer_loader = get_loaders(llama_type=llama_type, model_name=base_model, reward_type=reward_type)
if not tokenizer_base_model:
tokenizer_base_model = base_model
if tokenizer_loader is not None and not isinstance(tokenizer_loader, str):
tokenizer = tokenizer_loader.from_pretrained(tokenizer_base_model,
local_files_only=local_files_only,
resume_download=resume_download,
use_auth_token=use_auth_token,
trust_remote_code=trust_remote_code,
offload_folder=offload_folder,
)
else:
tokenizer = tokenizer_loader
if isinstance(tokenizer, str):
# already a pipeline, tokenizer_loader is string for task
model = model_loader(tokenizer,
model=base_model,
device=0 if device == "cuda" else -1,
torch_dtype=torch.float16 if device == 'cuda' else torch.float32)
else:
assert device in ["cuda", "cpu"], "Unsupported device %s" % device
model_kwargs = dict(local_files_only=local_files_only,
torch_dtype=torch.float16 if device == 'cuda' else torch.float32,
resume_download=resume_download,
use_auth_token=use_auth_token,
trust_remote_code=trust_remote_code,
offload_folder=offload_folder,
)
if 'mbart-' not in base_model.lower() and 'mpt-' not in base_model.lower():
model_kwargs.update(dict(load_in_8bit=load_8bit,
device_map={"": 0} if load_8bit and device == 'cuda' else "auto",
))
if 'mpt-' in base_model.lower() and gpu_id >= 0:
model_kwargs.update(dict(device_map={"": gpu_id} if device == 'cuda' else "cpu"))
if 'OpenAssistant/reward-model'.lower() in base_model.lower():
# FIXME: could put on other GPUs
model_kwargs['device_map'] = {"": 0} if device == 'cuda' else {"": 'cpu'}
model_kwargs.pop('torch_dtype', None)
if not lora_weights:
with torch.device(device):
if infer_devices:
model = get_non_lora_model(base_model, model_loader, load_half, model_kwargs, reward_type,
gpu_id=gpu_id,
use_auth_token=use_auth_token,
trust_remote_code=trust_remote_code,
offload_folder=offload_folder,
)
else:
if load_half and not load_8bit:
model = model_loader.from_pretrained(
base_model,
**model_kwargs).half()
else:
model = model_loader.from_pretrained(
base_model,
**model_kwargs)
elif load_8bit:
model = model_loader.from_pretrained(
base_model,
**model_kwargs
)
model = PeftModel.from_pretrained(
model,
lora_weights,
torch_dtype=torch.float16 if device == 'cuda' else torch.float32,
local_files_only=local_files_only,
resume_download=resume_download,
use_auth_token=use_auth_token,
trust_remote_code=trust_remote_code,
offload_folder=offload_folder,
device_map={"": 0} if device == 'cuda' else {"": 'cpu'}, # seems to be required
)
else:
with torch.device(device):
model = model_loader.from_pretrained(
base_model,
**model_kwargs
)
model = PeftModel.from_pretrained(
model,
lora_weights,
torch_dtype=torch.float16 if device == 'cuda' else torch.float32,
local_files_only=local_files_only,
resume_download=resume_download,
use_auth_token=use_auth_token,
trust_remote_code=trust_remote_code,
offload_folder=offload_folder,
device_map="auto",
)
if load_half:
model.half()
# unwind broken decapoda-research config
if llama_type:
model.config.pad_token_id = tokenizer.pad_token_id = 0 # unk
model.config.bos_token_id = 1
model.config.eos_token_id = 2
if 'gpt2' in base_model.lower():
# add special tokens that otherwise all share the same id
tokenizer.add_special_tokens({'bos_token': '<bos>',
'eos_token': '<eos>',
'pad_token': '<pad>'})
if not isinstance(tokenizer, str):
model.eval()
if torch.__version__ >= "2" and sys.platform != "win32" and compile:
model = torch.compile(model)
return model, tokenizer, device
def get_score_model(**kwargs):
# score model
if kwargs.get('score_model') is not None and kwargs.get('score_model').strip():
score_all_kwargs = kwargs.copy()
score_all_kwargs['load_8bit'] = False
score_all_kwargs['load_half'] = False
score_all_kwargs['base_model'] = kwargs.get('score_model').strip()
score_all_kwargs['tokenizer_base_model'] = ''
score_all_kwargs['lora_weights'] = ''
score_all_kwargs['llama_type'] = False
score_all_kwargs['compile'] = False
smodel, stokenizer, sdevice = get_model(**score_all_kwargs)
else:
smodel, stokenizer, sdevice = None, None, None
return smodel, stokenizer, sdevice
eval_func_param_names = ['instruction',
'iinput',
'context',
'stream_output',
'prompt_type',
'temperature',
'top_p',
'top_k',
'num_beams',
'max_new_tokens',
'min_new_tokens',
'early_stopping',
'max_time',
'repetition_penalty',
'num_return_sequences',
'do_sample',
'chat',
'instruction_nochat',
'iinput_nochat',
'langchain_mode',
'top_k_docs',
'document_choice',
]
def evaluate(
model_state,
my_db_state,
# START NOTE: Examples must have same order of parameters
instruction,
iinput,
context,
stream_output,
prompt_type,
temperature,
top_p,
top_k,
num_beams,
max_new_tokens,
min_new_tokens,
early_stopping,
max_time,
repetition_penalty,
num_return_sequences,
do_sample,
chat,
instruction_nochat,
iinput_nochat,
langchain_mode,
top_k_docs,
document_choice,
# END NOTE: Examples must have same order of parameters
src_lang=None,
tgt_lang=None,
debug=False,
concurrency_count=None,
save_dir=None,
sanitize_bot_response=True,
model_state0=None,
is_low_mem=None,
raise_generate_gpu_exceptions=None,
chat_context=None,
lora_weights=None,
load_db_if_exists=True,
dbs=None,
user_path=None,
use_openai_embedding=None,
use_openai_model=None,
hf_embedding_model=None,
chunk=None,
chunk_size=None,
db_type=None,
n_jobs=None,
first_para=None,
text_limit=None,
):
# ensure passed these
assert concurrency_count is not None
assert is_low_mem is not None
assert raise_generate_gpu_exceptions is not None
assert chat_context is not None
assert use_openai_embedding is not None
assert use_openai_model is not None
assert hf_embedding_model is not None
assert chunk is not None
assert chunk_size is not None
assert db_type is not None
assert top_k_docs is not None and isinstance(top_k_docs, int)
assert n_jobs is not None
assert first_para is not None
if debug:
locals_dict = locals().copy()
locals_dict.pop('model_state', None)
locals_dict.pop('model_state0', None)
print(locals_dict)
no_model_msg = "Please choose a base model with --base_model (CLI) or in Models Tab (gradio).\nThen start New Conversation"
if model_state0 is None:
# e.g. for no gradio case, set dummy value, else should be set
model_state0 = [None, None, None, None]
if model_state is not None and len(model_state) == 4 and not isinstance(model_state[0], str):
# try to free-up original model (i.e. list was passed as reference)
if model_state0 is not None and model_state0[0] is not None:
model_state0[0].cpu()
model_state0[0] = None
# try to free-up original tokenizer (i.e. list was passed as reference)
if model_state0 is not None and model_state0[1] is not None:
model_state0[1] = None
clear_torch_cache()
model, tokenizer, device, base_model = model_state
elif model_state0 is not None and len(model_state0) == 4 and model_state0[0] is not None:
assert isinstance(model_state[0], str)
model, tokenizer, device, base_model = model_state0
else:
raise AssertionError(no_model_msg)
if base_model is None:
raise AssertionError(no_model_msg)
assert base_model.strip(), no_model_msg
assert model, "Model is missing"
assert tokenizer, "Tokenizer is missing"
# choose chat or non-chat mode
if not chat:
instruction = instruction_nochat
iinput = iinput_nochat
if not context:
# get hidden context if have one
context = get_context(chat_context, prompt_type)
prompter = Prompter(prompt_type, debug=debug, chat=chat, stream_output=stream_output)
data_point = dict(context=context, instruction=instruction, input=iinput)
prompt = prompter.generate_prompt(data_point)
# THIRD PLACE where LangChain referenced, but imports only occur if enabled and have db to use
assert langchain_mode in langchain_modes, "Invalid langchain_mode %s" % langchain_mode
if langchain_mode in ['MyData'] and my_db_state is not None and len(my_db_state) > 0 and my_db_state[0] is not None:
db1 = my_db_state[0]
elif dbs is not None and langchain_mode in dbs:
db1 = dbs[langchain_mode]
else:
db1 = None
if langchain_mode not in [False, 'Disabled', 'ChatLLM', 'LLM'] and db1 is not None or base_model in ['llama', 'gptj']:
query = instruction if not iinput else "%s\n%s" % (instruction, iinput)
outr = ""
# use smaller cut_distanct for wiki_full since so many matches could be obtained, and often irrelevant unless close
from gpt_langchain import run_qa_db
for r in run_qa_db(query=query,