Spaces:
Running
Running
pseudotensor
commited on
Commit
•
65121b5
1
Parent(s):
80d4e55
Update with h2oGPT hash 321b64cb3f52f33f91b6052f5edea590b829aaa1
Browse files- app.py +187 -1015
- finetune.py +176 -125
- requirements.txt +2 -1
- stopping.py +0 -112
- utils.py +121 -1
app.py
CHANGED
@@ -1,10 +1,10 @@
|
|
1 |
import functools
|
2 |
-
import inspect
|
3 |
import sys
|
4 |
import os
|
5 |
import traceback
|
6 |
import typing
|
7 |
-
|
|
|
8 |
|
9 |
SEED = 1236
|
10 |
set_seed(SEED)
|
@@ -17,29 +17,21 @@ import pandas as pd
|
|
17 |
import fire
|
18 |
import torch
|
19 |
from peft import PeftModel
|
20 |
-
from transformers import GenerationConfig, StoppingCriteriaList, AutoModel
|
21 |
from accelerate import init_empty_weights, infer_auto_device_map
|
22 |
|
23 |
from prompter import Prompter
|
24 |
|
25 |
-
from finetune import get_loaders, example_data_points, generate_prompt,
|
26 |
-
|
27 |
-
from stopping import CallbackToGenerator, Stream, StoppingCriteriaSub
|
28 |
-
|
29 |
-
is_hf = bool(os.getenv("HUGGINGFACE_SPACES"))
|
30 |
-
is_gpth2oai = bool(os.getenv("GPT_H2O_AI"))
|
31 |
-
is_public = is_hf or is_gpth2oai # multi-user case with fixed model and disclaimer
|
32 |
-
is_low_mem = is_hf # assumes run on 24GB consumer GPU
|
33 |
-
admin_pass = os.getenv("ADMIN_PASS")
|
34 |
-
# will sometimes appear in UI or sometimes actual generation, but maybe better than empty result
|
35 |
-
raise_generate_gpu_exceptions = True
|
36 |
|
37 |
eval_extra_columns = ['prompt', 'response', 'score']
|
38 |
|
|
|
39 |
def main(
|
40 |
load_8bit: bool = False,
|
41 |
load_half: bool = True,
|
42 |
-
infer_devices: bool = True,
|
43 |
base_model: str = '',
|
44 |
tokenizer_base_model: str = '',
|
45 |
lora_weights: str = "",
|
@@ -59,7 +51,6 @@ def main(
|
|
59 |
early_stopping: Union[bool, str] = None,
|
60 |
max_time: float = None,
|
61 |
|
62 |
-
llama_type: bool = None,
|
63 |
debug: bool = False,
|
64 |
save_dir: str = None,
|
65 |
share: bool = True,
|
@@ -74,6 +65,7 @@ def main(
|
|
74 |
gradio_avoid_processing_markdown: bool = False,
|
75 |
chat: bool = True,
|
76 |
chat_history: int = 4096, # character length of chat context/history
|
|
|
77 |
stream_output: bool = True,
|
78 |
show_examples: bool = None,
|
79 |
verbose: bool = False,
|
@@ -84,6 +76,10 @@ def main(
|
|
84 |
# to be able to free GPU memory when model is swapped
|
85 |
login_mode_if_model0: bool = False,
|
86 |
block_gradio_exit: bool = True,
|
|
|
|
|
|
|
|
|
87 |
|
88 |
sanitize_user_prompt: bool = True,
|
89 |
sanitize_bot_response: bool = True,
|
@@ -97,11 +93,23 @@ def main(
|
|
97 |
eval_sharegpt_prompts_only: int = 0,
|
98 |
eval_sharegpt_prompts_only_seed: int = 1234,
|
99 |
eval_sharegpt_as_output: bool = False,
|
|
|
|
|
100 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
# allow set token directly
|
102 |
use_auth_token = os.environ.get("HUGGINGFACE_API_TOKEN", use_auth_token)
|
103 |
|
104 |
if is_public:
|
|
|
105 |
temperature = 0.4
|
106 |
top_p = 0.85
|
107 |
top_k = 70
|
@@ -120,6 +128,11 @@ def main(
|
|
120 |
score_model = os.getenv('SCORE_MODEL', score_model)
|
121 |
if score_model == 'None':
|
122 |
score_model = ''
|
|
|
|
|
|
|
|
|
|
|
123 |
|
124 |
# get defaults
|
125 |
model_lower = base_model.lower()
|
@@ -170,10 +183,10 @@ def main(
|
|
170 |
assert data[i]['conversations'][turn_start + 1]['from'] == 'gpt'
|
171 |
output = data[i]['conversations'][turn_start + 1]['value']
|
172 |
examplenew = example1.copy()
|
173 |
-
assert not chat, "No gradio must use chat=False, uses nochat
|
174 |
examplenew[eval_func_param_names.index('instruction_nochat')] = instruction
|
175 |
examplenew[eval_func_param_names.index('iinput_nochat')] = '' # no input
|
176 |
-
examplenew[eval_func_param_names.index('context')] =
|
177 |
examples.append(examplenew)
|
178 |
responses.append(output)
|
179 |
|
@@ -193,7 +206,10 @@ def main(
|
|
193 |
used_lora_weights)
|
194 |
eval_filename = os.path.join(scoring_path, eval_filename)
|
195 |
|
196 |
-
|
|
|
|
|
|
|
197 |
# ensure was set right above before examples generated
|
198 |
assert not stream_output, "stream_output=True does not make sense with example loop"
|
199 |
import time
|
@@ -205,7 +221,10 @@ def main(
|
|
205 |
if not eval_sharegpt_as_output:
|
206 |
model, tokenizer, device = get_model(**locals())
|
207 |
model_state = [model, tokenizer, device, base_model]
|
208 |
-
fun = partial(evaluate, model_state, debug=debug, save_dir=save_dir
|
|
|
|
|
|
|
209 |
else:
|
210 |
assert eval_sharegpt_prompts_only > 0
|
211 |
|
@@ -230,7 +249,8 @@ def main(
|
|
230 |
print("-" * 105)
|
231 |
# fun yields as generator, so have to iterate over it
|
232 |
# Also means likely do NOT want --stream_output=True, else would show all generations
|
233 |
-
|
|
|
234 |
print(res)
|
235 |
if smodel:
|
236 |
score_with_prompt = False
|
@@ -240,8 +260,11 @@ def main(
|
|
240 |
prompt = prompter.generate_prompt(data_point)
|
241 |
else:
|
242 |
# just raw input and output
|
243 |
-
|
244 |
-
|
|
|
|
|
|
|
245 |
prompt = instruction
|
246 |
cutoff_len = 768 if is_low_mem else 2048
|
247 |
inputs = stokenizer(prompt, res,
|
@@ -251,7 +274,7 @@ def main(
|
|
251 |
try:
|
252 |
score = torch.sigmoid(smodel(**inputs).logits[0]).cpu().detach().numpy()[0]
|
253 |
except torch.cuda.OutOfMemoryError as e:
|
254 |
-
print("GPU OOM: question: %s answer: %s exception: %s" % (prompt, res, str(e)), flush=True)
|
255 |
traceback.print_exc()
|
256 |
score = 0.0
|
257 |
clear_torch_cache()
|
@@ -291,6 +314,22 @@ def main(
|
|
291 |
return eval_filename
|
292 |
|
293 |
if gradio:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
294 |
go_gradio(**locals())
|
295 |
|
296 |
|
@@ -347,6 +386,8 @@ def get_non_lora_model(base_model, model_loader, load_half, model_kwargs, reward
|
|
347 |
device_map = {'': n_gpus - 1}
|
348 |
else:
|
349 |
device_map = {'': min(n_gpus - 1, gpu_id)}
|
|
|
|
|
350 |
|
351 |
load_in_8bit = model_kwargs.get('load_in_8bit', False)
|
352 |
model_kwargs['device_map'] = device_map
|
@@ -373,7 +414,6 @@ def get_model(
|
|
373 |
lora_weights: str = "",
|
374 |
gpu_id: int = 0,
|
375 |
|
376 |
-
llama_type: bool = None,
|
377 |
reward_type: bool = None,
|
378 |
local_files_only: bool = False,
|
379 |
resume_download: bool = True,
|
@@ -392,12 +432,11 @@ def get_model(
|
|
392 |
:param tokenizer_base_model: name/path of tokenizer
|
393 |
:param lora_weights: name/path
|
394 |
:param gpu_id: which GPU (0..n_gpus-1) or allow all GPUs if relevant (-1)
|
395 |
-
:param llama_type: whether LLaMa type model
|
396 |
:param reward_type: reward type model for sequence classification
|
397 |
:param local_files_only: use local files instead of from HF
|
398 |
:param resume_download: resume downloads from HF
|
399 |
:param use_auth_token: assumes user did on CLI `huggingface-cli login` to access private repo
|
400 |
-
:
|
401 |
:param kwargs:
|
402 |
:return:
|
403 |
"""
|
@@ -413,7 +452,16 @@ def get_model(
|
|
413 |
assert base_model.strip(), (
|
414 |
"Please choose a base model with --base_model (CLI) or in Models Tab (gradio)"
|
415 |
)
|
416 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
417 |
model_loader, tokenizer_loader = get_loaders(llama_type=llama_type, model_name=base_model, reward_type=reward_type)
|
418 |
if not tokenizer_base_model:
|
419 |
tokenizer_base_model = base_model
|
@@ -530,937 +578,6 @@ def get_score_model(**kwargs):
|
|
530 |
return smodel, stokenizer, sdevice
|
531 |
|
532 |
|
533 |
-
def go_gradio(**kwargs):
|
534 |
-
# get default model
|
535 |
-
all_kwargs = kwargs.copy()
|
536 |
-
all_kwargs.update(locals())
|
537 |
-
if kwargs.get('base_model') and not kwargs['login_mode_if_model0']:
|
538 |
-
model0, tokenizer0, device = get_model(**all_kwargs)
|
539 |
-
else:
|
540 |
-
# if empty model, then don't load anything, just get gradio up
|
541 |
-
model0, tokenizer0, device = None, None, None
|
542 |
-
model_state0 = [model0, tokenizer0, device, kwargs['base_model']]
|
543 |
-
|
544 |
-
# get score model
|
545 |
-
smodel, stokenizer, sdevice = get_score_model(**all_kwargs)
|
546 |
-
|
547 |
-
if 'mbart-' in kwargs['model_lower']:
|
548 |
-
instruction_label_nochat = "Text to translate"
|
549 |
-
else:
|
550 |
-
instruction_label_nochat = "Instruction"
|
551 |
-
instruction_label = "You (Shift-Enter or push Submit to send message)"
|
552 |
-
|
553 |
-
title = 'h2oGPT'
|
554 |
-
if kwargs['verbose']:
|
555 |
-
description = f"""Model {kwargs['base_model']} Instruct dataset.
|
556 |
-
For more information, visit [the project's website](https://github.com/h2oai/h2ogpt).
|
557 |
-
Command: {str(' '.join(sys.argv))}
|
558 |
-
Hash: {get_githash()}
|
559 |
-
"""
|
560 |
-
else:
|
561 |
-
description = "For more information, visit [the project's website](https://github.com/h2oai/h2ogpt).<br>"
|
562 |
-
if is_public:
|
563 |
-
description += "If this host is busy, try [gpt.h2o.ai 20B](https://gpt.h2o.ai) and [HF Spaces1 12B](https://huggingface.co/spaces/h2oai/h2ogpt-chatbot) and [HF Spaces2 12B](https://huggingface.co/spaces/h2oai/h2ogpt-chatbot2)<br>"
|
564 |
-
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>"""
|
565 |
-
if kwargs['load_8bit']:
|
566 |
-
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>"""
|
567 |
-
description += """<i><li>Conversations may be used to improve h2oGPT. Do not share sensitive information.</i></li>"""
|
568 |
-
description += """<i><li>By using h2oGPT, you accept our [Terms of Service](https://github.com/h2oai/h2ogpt/blob/main/tos.md).</i></li></ul></p>"""
|
569 |
-
|
570 |
-
if kwargs['verbose']:
|
571 |
-
task_info_md = f"""
|
572 |
-
### Task: {kwargs['task_info']}"""
|
573 |
-
else:
|
574 |
-
task_info_md = ''
|
575 |
-
|
576 |
-
css_code = """footer {visibility: hidden;}
|
577 |
-
body{background:linear-gradient(#f5f5f5,#e5e5e5);}
|
578 |
-
body.dark{background:linear-gradient(#0d0d0d,#333333);}"""
|
579 |
-
|
580 |
-
from gradio.themes.utils import Color, colors, fonts, sizes
|
581 |
-
if kwargs['h2ocolors']:
|
582 |
-
h2o_yellow = Color(
|
583 |
-
name="yellow",
|
584 |
-
c50="#fffef2",
|
585 |
-
c100="#fff9e6",
|
586 |
-
c200="#ffecb3",
|
587 |
-
c300="#ffe28c",
|
588 |
-
c400="#ffd659",
|
589 |
-
c500="#fec925",
|
590 |
-
c600="#e6ac00",
|
591 |
-
c700="#bf8f00",
|
592 |
-
c800="#a67c00",
|
593 |
-
c900="#664d00",
|
594 |
-
c950="#403000",
|
595 |
-
)
|
596 |
-
h2o_gray = Color(
|
597 |
-
name="gray",
|
598 |
-
c50="#f2f2f2",
|
599 |
-
c100="#e5e5e5",
|
600 |
-
c200="#cccccc",
|
601 |
-
c300="#b2b2b2",
|
602 |
-
c400="#999999",
|
603 |
-
c500="#7f7f7f",
|
604 |
-
c600="#666666",
|
605 |
-
c700="#4c4c4c",
|
606 |
-
c800="#333333",
|
607 |
-
c900="#191919",
|
608 |
-
c950="#0d0d0d",
|
609 |
-
)
|
610 |
-
colors_dict = dict(primary_hue=h2o_yellow,
|
611 |
-
secondary_hue=h2o_yellow,
|
612 |
-
neutral_hue=h2o_gray,
|
613 |
-
spacing_size=sizes.spacing_md,
|
614 |
-
radius_size=sizes.radius_md,
|
615 |
-
text_size=sizes.text_md,
|
616 |
-
)
|
617 |
-
else:
|
618 |
-
colors_dict = dict(primary_hue=colors.indigo,
|
619 |
-
secondary_hue=colors.indigo,
|
620 |
-
neutral_hue=colors.gray,
|
621 |
-
spacing_size=sizes.spacing_md,
|
622 |
-
radius_size=sizes.radius_md,
|
623 |
-
text_size=sizes.text_md,
|
624 |
-
)
|
625 |
-
|
626 |
-
import gradio as gr
|
627 |
-
|
628 |
-
if kwargs['gradio_avoid_processing_markdown']:
|
629 |
-
from gradio_client import utils as client_utils
|
630 |
-
from gradio.components import Chatbot
|
631 |
-
|
632 |
-
# gradio has issue with taking too long to process input/output for markdown etc.
|
633 |
-
# Avoid for now, allow raw html to render, good enough for chatbot.
|
634 |
-
def _postprocess_chat_messages(self, chat_message: str):
|
635 |
-
if chat_message is None:
|
636 |
-
return None
|
637 |
-
elif isinstance(chat_message, (tuple, list)):
|
638 |
-
filepath = chat_message[0]
|
639 |
-
mime_type = client_utils.get_mimetype(filepath)
|
640 |
-
filepath = self.make_temp_copy_if_needed(filepath)
|
641 |
-
return {
|
642 |
-
"name": filepath,
|
643 |
-
"mime_type": mime_type,
|
644 |
-
"alt_text": chat_message[1] if len(chat_message) > 1 else None,
|
645 |
-
"data": None, # These last two fields are filled in by the frontend
|
646 |
-
"is_file": True,
|
647 |
-
}
|
648 |
-
elif isinstance(chat_message, str):
|
649 |
-
return chat_message
|
650 |
-
else:
|
651 |
-
raise ValueError(f"Invalid message for Chatbot component: {chat_message}")
|
652 |
-
|
653 |
-
Chatbot._postprocess_chat_messages = _postprocess_chat_messages
|
654 |
-
|
655 |
-
dark_js = """() => {
|
656 |
-
if (document.querySelectorAll('.dark').length) {
|
657 |
-
document.querySelectorAll('.dark').forEach(el => el.classList.remove('dark'));
|
658 |
-
} else {
|
659 |
-
document.querySelector('body').classList.add('dark');
|
660 |
-
}
|
661 |
-
}"""
|
662 |
-
|
663 |
-
demo = gr.Blocks(theme=gr.themes.Soft(**colors_dict), css=css_code, title="h2oGPT", analytics_enabled=False)
|
664 |
-
callback = gr.CSVLogger()
|
665 |
-
# css_code = 'body{background-image:url("https://h2o.ai/content/experience-fragments/h2o/us/en/site/header/master/_jcr_content/root/container/header_copy/logo.coreimg.svg/1678976605175/h2o-logo.svg");}'
|
666 |
-
# demo = gr.Blocks(theme='gstaff/xkcd', css=css_code)
|
667 |
-
|
668 |
-
model_options = flatten_list(list(prompt_type_to_model_name.values())) + kwargs['extra_model_options']
|
669 |
-
if kwargs['base_model'].strip() not in model_options:
|
670 |
-
lora_options = [kwargs['base_model'].strip()] + model_options
|
671 |
-
lora_options = kwargs['extra_lora_options']
|
672 |
-
if kwargs['lora_weights'].strip() not in lora_options:
|
673 |
-
lora_options = [kwargs['lora_weights'].strip()] + lora_options
|
674 |
-
# always add in no lora case
|
675 |
-
# add fake space so doesn't go away in gradio dropdown
|
676 |
-
no_lora_str = no_model_str = '[None/Remove]'
|
677 |
-
lora_options = [no_lora_str] + kwargs['extra_lora_options'] # FIXME: why double?
|
678 |
-
# always add in no model case so can free memory
|
679 |
-
# add fake space so doesn't go away in gradio dropdown
|
680 |
-
model_options = [no_model_str] + model_options
|
681 |
-
|
682 |
-
# transcribe, will be detranscribed before use by evaluate()
|
683 |
-
if not kwargs['lora_weights'].strip():
|
684 |
-
kwargs['lora_weights'] = no_lora_str
|
685 |
-
|
686 |
-
if not kwargs['base_model'].strip():
|
687 |
-
kwargs['base_model'] = no_model_str
|
688 |
-
|
689 |
-
# transcribe for gradio
|
690 |
-
kwargs['gpu_id'] = str(kwargs['gpu_id'])
|
691 |
-
|
692 |
-
no_model_msg = 'h2oGPT [ !!! Please Load Model in Models Tab !!! ]'
|
693 |
-
output_label0 = f'h2oGPT [Model: {kwargs.get("base_model")}]' if kwargs.get(
|
694 |
-
'base_model') else no_model_msg
|
695 |
-
output_label0_model2 = no_model_msg
|
696 |
-
|
697 |
-
with demo:
|
698 |
-
# avoid actual model/tokenizer here or anything that would be bad to deepcopy
|
699 |
-
# https://github.com/gradio-app/gradio/issues/3558
|
700 |
-
model_state = gr.State(['model', 'tokenizer', device, kwargs['base_model']])
|
701 |
-
model_state2 = gr.State([None, None, None, None])
|
702 |
-
model_options_state = gr.State([model_options])
|
703 |
-
lora_options_state = gr.State([lora_options])
|
704 |
-
gr.Markdown(
|
705 |
-
f"""
|
706 |
-
<h1 align="center"> {title}</h1>
|
707 |
-
|
708 |
-
{description}
|
709 |
-
{task_info_md}
|
710 |
-
""")
|
711 |
-
if is_hf:
|
712 |
-
gr.HTML(
|
713 |
-
'''<center><a href="https://huggingface.co/spaces/h2oai/h2ogpt-chatbot?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>Duplicate this Space to skip the queue and run in a private space</center>''')
|
714 |
-
|
715 |
-
# go button visible if
|
716 |
-
base_wanted = kwargs['base_model'] != no_model_str and kwargs['login_mode_if_model0']
|
717 |
-
go_btn = gr.Button(value="ENTER", visible=base_wanted, variant="primary")
|
718 |
-
normal_block = gr.Row(visible=not base_wanted)
|
719 |
-
with normal_block:
|
720 |
-
with gr.Tabs():
|
721 |
-
with gr.Row():
|
722 |
-
col_nochat = gr.Column(visible=not kwargs['chat'])
|
723 |
-
with col_nochat: # FIXME: for model comparison, and check rest
|
724 |
-
text_output_nochat = gr.Textbox(lines=5, label=output_label0)
|
725 |
-
instruction_nochat = gr.Textbox(
|
726 |
-
lines=4, label=instruction_label_nochat,
|
727 |
-
placeholder=kwargs['placeholder_instruction'],
|
728 |
-
)
|
729 |
-
iinput_nochat = gr.Textbox(lines=4, label="Input context for Instruction",
|
730 |
-
placeholder=kwargs['placeholder_input'])
|
731 |
-
submit_nochat = gr.Button("Submit")
|
732 |
-
flag_btn_nochat = gr.Button("Flag")
|
733 |
-
if not kwargs['auto_score']:
|
734 |
-
with gr.Column(visible=kwargs['score_model']):
|
735 |
-
score_btn_nochat = gr.Button("Score last prompt & response")
|
736 |
-
score_text_nochat = gr.Textbox("Response Score: NA", show_label=False)
|
737 |
-
else:
|
738 |
-
with gr.Column(visible=kwargs['score_model']):
|
739 |
-
score_text_nochat = gr.Textbox("Response Score: NA", show_label=False)
|
740 |
-
col_chat = gr.Column(visible=kwargs['chat'])
|
741 |
-
with col_chat:
|
742 |
-
with gr.Row():
|
743 |
-
text_output = gr.Chatbot(label=output_label0).style(height=kwargs['height'] or 400)
|
744 |
-
text_output2 = gr.Chatbot(label=output_label0_model2, visible=False).style(
|
745 |
-
height=kwargs['height'] or 400)
|
746 |
-
with gr.Row():
|
747 |
-
with gr.Column(scale=50):
|
748 |
-
instruction = gr.Textbox(
|
749 |
-
lines=4, label=instruction_label,
|
750 |
-
placeholder=kwargs['placeholder_instruction'],
|
751 |
-
)
|
752 |
-
with gr.Row():
|
753 |
-
submit = gr.Button(value='Submit').style(full_width=False, size='sm')
|
754 |
-
stop_btn = gr.Button(value="Stop").style(full_width=False, size='sm')
|
755 |
-
with gr.Row():
|
756 |
-
clear = gr.Button("New Conversation")
|
757 |
-
flag_btn = gr.Button("Flag")
|
758 |
-
if not kwargs['auto_score']: # FIXME: For checkbox model2
|
759 |
-
with gr.Column(visible=kwargs['score_model']):
|
760 |
-
with gr.Row():
|
761 |
-
score_btn = gr.Button("Score last prompt & response").style(
|
762 |
-
full_width=False, size='sm')
|
763 |
-
score_text = gr.Textbox("Response Score: NA", show_label=False)
|
764 |
-
score_res2 = gr.Row(visible=False)
|
765 |
-
with score_res2:
|
766 |
-
score_btn2 = gr.Button("Score last prompt & response 2").style(
|
767 |
-
full_width=False, size='sm')
|
768 |
-
score_text2 = gr.Textbox("Response Score2: NA", show_label=False)
|
769 |
-
else:
|
770 |
-
with gr.Column(visible=kwargs['score_model']):
|
771 |
-
score_text = gr.Textbox("Response Score: NA", show_label=False)
|
772 |
-
score_text2 = gr.Textbox("Response Score2: NA", show_label=False, visible=False)
|
773 |
-
retry = gr.Button("Regenerate")
|
774 |
-
undo = gr.Button("Undo")
|
775 |
-
with gr.TabItem("Input/Output"):
|
776 |
-
with gr.Row():
|
777 |
-
if 'mbart-' in kwargs['model_lower']:
|
778 |
-
src_lang = gr.Dropdown(list(languages_covered().keys()),
|
779 |
-
value=kwargs['src_lang'],
|
780 |
-
label="Input Language")
|
781 |
-
tgt_lang = gr.Dropdown(list(languages_covered().keys()),
|
782 |
-
value=kwargs['tgt_lang'],
|
783 |
-
label="Output Language")
|
784 |
-
with gr.TabItem("Expert"):
|
785 |
-
with gr.Row():
|
786 |
-
with gr.Column():
|
787 |
-
stream_output = gr.components.Checkbox(label="Stream output",
|
788 |
-
value=kwargs['stream_output'])
|
789 |
-
prompt_type = gr.Dropdown(prompt_types_strings,
|
790 |
-
value=kwargs['prompt_type'], label="Prompt Type",
|
791 |
-
visible=not is_public)
|
792 |
-
prompt_type2 = gr.Dropdown(prompt_types_strings,
|
793 |
-
value=kwargs['prompt_type'], label="Prompt Type Model 2",
|
794 |
-
visible=not is_public and False)
|
795 |
-
do_sample = gr.Checkbox(label="Sample", info="Enable sampler, required for use of temperature, top_p, top_k",
|
796 |
-
value=kwargs['do_sample'])
|
797 |
-
temperature = gr.Slider(minimum=0.01, maximum=3,
|
798 |
-
value=kwargs['temperature'],
|
799 |
-
label="Temperature",
|
800 |
-
info="Lower is deterministic (but may lead to repeats), Higher more creative (but may lead to hallucinations)")
|
801 |
-
top_p = gr.Slider(minimum=0, maximum=1,
|
802 |
-
value=kwargs['top_p'], label="Top p",
|
803 |
-
info="Cumulative probability of tokens to sample from")
|
804 |
-
top_k = gr.Slider(
|
805 |
-
minimum=0, maximum=100, step=1,
|
806 |
-
value=kwargs['top_k'], label="Top k",
|
807 |
-
info='Num. tokens to sample from'
|
808 |
-
)
|
809 |
-
max_beams = 8 if not is_low_mem else 2
|
810 |
-
num_beams = gr.Slider(minimum=1, maximum=max_beams, step=1,
|
811 |
-
value=min(max_beams, kwargs['num_beams']), label="Beams",
|
812 |
-
info="Number of searches for optimal overall probability. "
|
813 |
-
"Uses more GPU memory/compute")
|
814 |
-
max_max_new_tokens = 2048 if not is_low_mem else kwargs['max_new_tokens']
|
815 |
-
max_new_tokens = gr.Slider(
|
816 |
-
minimum=1, maximum=max_max_new_tokens, step=1,
|
817 |
-
value=min(max_max_new_tokens, kwargs['max_new_tokens']), label="Max output length",
|
818 |
-
)
|
819 |
-
min_new_tokens = gr.Slider(
|
820 |
-
minimum=0, maximum=max_max_new_tokens, step=1,
|
821 |
-
value=min(max_max_new_tokens, kwargs['min_new_tokens']), label="Min output length",
|
822 |
-
)
|
823 |
-
early_stopping = gr.Checkbox(label="EarlyStopping", info="Stop early in beam search",
|
824 |
-
value=kwargs['early_stopping'])
|
825 |
-
max_max_time = 60 * 5 if not is_low_mem else 60
|
826 |
-
max_time = gr.Slider(minimum=0, maximum=max_max_time, step=1,
|
827 |
-
value=min(max_max_time, kwargs['max_time']), label="Max. time",
|
828 |
-
info="Max. time to search optimal output.")
|
829 |
-
repetition_penalty = gr.Slider(minimum=0.01, maximum=3.0,
|
830 |
-
value=kwargs['repetition_penalty'],
|
831 |
-
label="Repetition Penalty")
|
832 |
-
num_return_sequences = gr.Slider(minimum=1, maximum=10, step=1,
|
833 |
-
value=kwargs['num_return_sequences'],
|
834 |
-
label="Number Returns", info="Must be <= num_beams",
|
835 |
-
visible=not is_public)
|
836 |
-
iinput = gr.Textbox(lines=4, label="Input",
|
837 |
-
placeholder=kwargs['placeholder_input'],
|
838 |
-
visible=not is_public)
|
839 |
-
context = gr.Textbox(lines=3, label="System Pre-Context",
|
840 |
-
info="Directly pre-appended without prompt processing",
|
841 |
-
visible=not is_public and not kwargs['chat'])
|
842 |
-
chat = gr.components.Checkbox(label="Chat mode", value=kwargs['chat'],
|
843 |
-
visible=not is_public)
|
844 |
-
|
845 |
-
with gr.TabItem("Models"):
|
846 |
-
load_msg = "Load-Unload Model/LORA" if not is_public \
|
847 |
-
else "LOAD-UNLOAD DISABLED FOR HOSTED DEMO"
|
848 |
-
load_msg2 = "Load-Unload Model/LORA 2" if not is_public \
|
849 |
-
else "LOAD-UNLOAD DISABLED FOR HOSTED DEMO 2"
|
850 |
-
compare_checkbox = gr.components.Checkbox(label="Compare Mode",
|
851 |
-
value=False, visible=not is_public)
|
852 |
-
with gr.Row():
|
853 |
-
n_gpus = torch.cuda.device_count()
|
854 |
-
n_gpus_list = [str(x) for x in list(range(-1, n_gpus))]
|
855 |
-
with gr.Column():
|
856 |
-
with gr.Row():
|
857 |
-
with gr.Column(scale=50):
|
858 |
-
model_choice = gr.Dropdown(model_options_state.value[0], label="Choose Model",
|
859 |
-
value=kwargs['base_model'])
|
860 |
-
lora_choice = gr.Dropdown(lora_options_state.value[0], label="Choose LORA",
|
861 |
-
value=kwargs['lora_weights'], visible=kwargs['show_lora'])
|
862 |
-
with gr.Column(scale=1):
|
863 |
-
load_model_button = gr.Button(load_msg)
|
864 |
-
model_load8bit_checkbox = gr.components.Checkbox(
|
865 |
-
label="Load 8-bit [Not all models support]",
|
866 |
-
value=kwargs['load_8bit'])
|
867 |
-
model_infer_devices_checkbox = gr.components.Checkbox(
|
868 |
-
label="Infer Devices [If GPU ID=-1 or not Checked, then will spread model over GPUs]",
|
869 |
-
value=kwargs['infer_devices'])
|
870 |
-
model_gpu = gr.Dropdown(n_gpus_list, label="GPU ID [-1 = all GPUs]",
|
871 |
-
value=kwargs['gpu_id'])
|
872 |
-
model_used = gr.Textbox(label="Current Model", value=kwargs['base_model'])
|
873 |
-
lora_used = gr.Textbox(label="Current LORA", value=kwargs['lora_weights'],
|
874 |
-
visible=kwargs['show_lora'])
|
875 |
-
with gr.Row():
|
876 |
-
with gr.Column(scale=50):
|
877 |
-
new_model = gr.Textbox(label="New Model HF name/path")
|
878 |
-
new_lora = gr.Textbox(label="New LORA HF name/path", visible=kwargs['show_lora'])
|
879 |
-
with gr.Column(scale=1):
|
880 |
-
add_model_button = gr.Button("Add new model name")
|
881 |
-
add_lora_button = gr.Button("Add new LORA name", visible=kwargs['show_lora'])
|
882 |
-
col_model2 = gr.Column(visible=False)
|
883 |
-
with col_model2:
|
884 |
-
with gr.Row():
|
885 |
-
with gr.Column(scale=50):
|
886 |
-
model_choice2 = gr.Dropdown(model_options_state.value[0], label="Choose Model 2",
|
887 |
-
value=no_model_str)
|
888 |
-
lora_choice2 = gr.Dropdown(lora_options_state.value[0], label="Choose LORA 2",
|
889 |
-
value=no_lora_str,
|
890 |
-
visible=kwargs['show_lora'])
|
891 |
-
with gr.Column(scale=1):
|
892 |
-
load_model_button2 = gr.Button(load_msg2)
|
893 |
-
model_load8bit_checkbox2 = gr.components.Checkbox(
|
894 |
-
label="Load 8-bit 2 [Not all models support]",
|
895 |
-
value=kwargs['load_8bit'])
|
896 |
-
model_infer_devices_checkbox2 = gr.components.Checkbox(
|
897 |
-
label="Infer Devices 2 [If GPU ID=-1 or not Checked, then will spread model over GPUs]",
|
898 |
-
value=kwargs[
|
899 |
-
'infer_devices'])
|
900 |
-
model_gpu2 = gr.Dropdown(n_gpus_list, label="GPU ID [-1 = all GPUs]",
|
901 |
-
value=kwargs['gpu_id'])
|
902 |
-
# no model/lora loaded ever in model2 by default
|
903 |
-
model_used2 = gr.Textbox(label="Current Model 2", value=no_model_str)
|
904 |
-
lora_used2 = gr.Textbox(label="Current LORA 2", value=no_lora_str,
|
905 |
-
visible=kwargs['show_lora'])
|
906 |
-
with gr.TabItem("System"):
|
907 |
-
admin_row = gr.Row()
|
908 |
-
with admin_row:
|
909 |
-
admin_pass_textbox = gr.Textbox(label="Admin Password", type='password', visible=is_public)
|
910 |
-
admin_btn = gr.Button(value="Admin Access", visible=is_public)
|
911 |
-
system_row = gr.Row(visible=not is_public)
|
912 |
-
with system_row:
|
913 |
-
with gr.Column():
|
914 |
-
with gr.Row():
|
915 |
-
system_btn = gr.Button(value='Get System Info')
|
916 |
-
system_text = gr.Textbox(label='System Info')
|
917 |
-
|
918 |
-
with gr.Row():
|
919 |
-
zip_btn = gr.Button("Zip")
|
920 |
-
zip_text = gr.Textbox(label="Zip file name")
|
921 |
-
file_output = gr.File()
|
922 |
-
with gr.Row():
|
923 |
-
s3up_btn = gr.Button("S3UP")
|
924 |
-
s3up_text = gr.Textbox(label='S3UP result')
|
925 |
-
|
926 |
-
# Get flagged data
|
927 |
-
zip_data1 = functools.partial(zip_data, root_dirs=['flagged_data_points', kwargs['save_dir']])
|
928 |
-
zip_btn.click(zip_data1, inputs=None, outputs=[file_output, zip_text])
|
929 |
-
s3up_btn.click(s3up, inputs=zip_text, outputs=s3up_text)
|
930 |
-
|
931 |
-
def check_admin_pass(x):
|
932 |
-
return gr.update(visible=x == admin_pass)
|
933 |
-
|
934 |
-
def close_admin(x):
|
935 |
-
return gr.update(visible=not (x == admin_pass))
|
936 |
-
|
937 |
-
admin_btn.click(check_admin_pass, inputs=admin_pass_textbox, outputs=system_row) \
|
938 |
-
.then(close_admin, inputs=admin_pass_textbox, outputs=admin_row)
|
939 |
-
|
940 |
-
# Get inputs to evaluate()
|
941 |
-
inputs_list = get_inputs_list(locals(), kwargs['model_lower'])
|
942 |
-
from functools import partial
|
943 |
-
all_kwargs = kwargs.copy()
|
944 |
-
all_kwargs.update(locals())
|
945 |
-
kwargs_evaluate = {k: v for k, v in all_kwargs.items() if k in inputs_kwargs_list}
|
946 |
-
fun = partial(evaluate,
|
947 |
-
**kwargs_evaluate)
|
948 |
-
fun2 = partial(evaluate,
|
949 |
-
**kwargs_evaluate)
|
950 |
-
|
951 |
-
dark_mode_btn = gr.Button("Dark Mode", variant="primary").style(
|
952 |
-
size="sm",
|
953 |
-
)
|
954 |
-
dark_mode_btn.click(
|
955 |
-
None,
|
956 |
-
None,
|
957 |
-
None,
|
958 |
-
_js=dark_js,
|
959 |
-
api_name="dark",
|
960 |
-
)
|
961 |
-
|
962 |
-
# Control chat and non-chat blocks, which can be independently used by chat checkbox swap
|
963 |
-
def col_nochat_fun(x):
|
964 |
-
return gr.Column.update(visible=not x)
|
965 |
-
|
966 |
-
def col_chat_fun(x):
|
967 |
-
return gr.Column.update(visible=x)
|
968 |
-
|
969 |
-
def context_fun(x):
|
970 |
-
return gr.Textbox.update(visible=not x)
|
971 |
-
|
972 |
-
chat.select(col_nochat_fun, chat, col_nochat, api_name="chat_checkbox") \
|
973 |
-
.then(col_chat_fun, chat, col_chat) \
|
974 |
-
.then(context_fun, chat, context)
|
975 |
-
|
976 |
-
# examples after submit or any other buttons for chat or no chat
|
977 |
-
if kwargs['examples'] is not None and kwargs['show_examples']:
|
978 |
-
gr.Examples(examples=kwargs['examples'], inputs=inputs_list)
|
979 |
-
|
980 |
-
# Score
|
981 |
-
def score_last_response(*args, nochat=False, model2=False):
|
982 |
-
""" Similar to user() """
|
983 |
-
args_list = list(args)
|
984 |
-
|
985 |
-
max_length_tokenize = 512 if is_low_mem else 2048
|
986 |
-
cutoff_len = max_length_tokenize * 4 # restrict deberta related to max for LLM
|
987 |
-
|
988 |
-
if not nochat:
|
989 |
-
history = args_list[-1]
|
990 |
-
if history is None:
|
991 |
-
if not model2:
|
992 |
-
# maybe only doing first model, no need to complain
|
993 |
-
print("Bad history in scoring last response, fix for now", flush=True)
|
994 |
-
history = []
|
995 |
-
if smodel is not None and \
|
996 |
-
stokenizer is not None and \
|
997 |
-
sdevice is not None and \
|
998 |
-
history is not None and len(history) > 0 and \
|
999 |
-
history[-1] is not None and \
|
1000 |
-
len(history[-1]) >= 2:
|
1001 |
-
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
|
1002 |
-
|
1003 |
-
question = history[-1][0]
|
1004 |
-
|
1005 |
-
answer = history[-1][1]
|
1006 |
-
else:
|
1007 |
-
return 'Response Score: NA'
|
1008 |
-
else:
|
1009 |
-
answer = args_list[-1]
|
1010 |
-
instruction_nochat_arg_id = eval_func_param_names.index('instruction_nochat')
|
1011 |
-
question = args_list[instruction_nochat_arg_id]
|
1012 |
-
|
1013 |
-
if question is None:
|
1014 |
-
return 'Response Score: Bad Question'
|
1015 |
-
if answer is None:
|
1016 |
-
return 'Response Score: Bad Answer'
|
1017 |
-
|
1018 |
-
question = question[-cutoff_len:]
|
1019 |
-
answer = answer[-cutoff_len:]
|
1020 |
-
|
1021 |
-
inputs = stokenizer(question, answer,
|
1022 |
-
return_tensors="pt",
|
1023 |
-
truncation=True,
|
1024 |
-
max_length=max_length_tokenize).to(smodel.device)
|
1025 |
-
try:
|
1026 |
-
score = torch.sigmoid(smodel(**inputs).logits[0]).cpu().detach().numpy()[0]
|
1027 |
-
except torch.cuda.OutOfMemoryError as e:
|
1028 |
-
print("GPU OOM: question: %s answer: %s exception: %s" % (question, answer, str(e)), flush=True)
|
1029 |
-
del inputs
|
1030 |
-
traceback.print_exc()
|
1031 |
-
clear_torch_cache()
|
1032 |
-
return 'Response Score: GPU OOM'
|
1033 |
-
except (Exception, RuntimeError) as e:
|
1034 |
-
if 'Expected all tensors to be on the same device' in str(e) or \
|
1035 |
-
'expected scalar type Half but found Float' in str(e) or \
|
1036 |
-
'probability tensor contains either' in str(e) or \
|
1037 |
-
'cublasLt ran into an error!' in str(e):
|
1038 |
-
print("GPU Error: question: %s answer: %s exception: %s" % (question, answer, str(e)),
|
1039 |
-
flush=True)
|
1040 |
-
traceback.print_exc()
|
1041 |
-
clear_torch_cache()
|
1042 |
-
return 'Response Score: GPU Error'
|
1043 |
-
else:
|
1044 |
-
raise
|
1045 |
-
os.environ['TOKENIZERS_PARALLELISM'] = 'true'
|
1046 |
-
return 'Response Score: {:.1%}'.format(score)
|
1047 |
-
|
1048 |
-
def noop_score_last_response(*args, **kwargs):
|
1049 |
-
return "Response Score: Disabled"
|
1050 |
-
if kwargs['score_model']:
|
1051 |
-
score_fun = score_last_response
|
1052 |
-
else:
|
1053 |
-
score_fun = noop_score_last_response
|
1054 |
-
|
1055 |
-
score_args = dict(fn=score_fun,
|
1056 |
-
inputs=inputs_list + [text_output],
|
1057 |
-
outputs=[score_text],
|
1058 |
-
)
|
1059 |
-
score_args2 = dict(fn=partial(score_fun, model2=True),
|
1060 |
-
inputs=inputs_list + [text_output2],
|
1061 |
-
outputs=[score_text2],
|
1062 |
-
)
|
1063 |
-
|
1064 |
-
score_args_nochat = dict(fn=partial(score_fun, nochat=True),
|
1065 |
-
inputs=inputs_list + [text_output_nochat],
|
1066 |
-
outputs=[score_text_nochat],
|
1067 |
-
)
|
1068 |
-
if not kwargs['auto_score']:
|
1069 |
-
score_event = score_btn.click(**score_args, queue=stream_output, api_name='score') \
|
1070 |
-
.then(**score_args2, queue=stream_output, api_name='score2')
|
1071 |
-
score_event_nochat = score_btn_nochat.click(**score_args_nochat, queue=stream_output,
|
1072 |
-
api_name='score_nochat')
|
1073 |
-
|
1074 |
-
def user(*args, undo=False, sanitize_user_prompt=True, model2=False):
|
1075 |
-
"""
|
1076 |
-
User that fills history for bot
|
1077 |
-
:param args:
|
1078 |
-
:param undo:
|
1079 |
-
:param sanitize_user_prompt:
|
1080 |
-
:param model2:
|
1081 |
-
:return:
|
1082 |
-
"""
|
1083 |
-
args_list = list(args)
|
1084 |
-
user_message = args_list[0]
|
1085 |
-
input1 = args_list[1]
|
1086 |
-
context1 = args_list[2]
|
1087 |
-
if input1 and not user_message.endswith(':'):
|
1088 |
-
user_message1 = user_message + ":" + input1
|
1089 |
-
elif input1:
|
1090 |
-
user_message1 = user_message + input1
|
1091 |
-
else:
|
1092 |
-
user_message1 = user_message
|
1093 |
-
if sanitize_user_prompt:
|
1094 |
-
from better_profanity import profanity
|
1095 |
-
user_message1 = profanity.censor(user_message1)
|
1096 |
-
|
1097 |
-
history = args_list[-1]
|
1098 |
-
if undo and history:
|
1099 |
-
history.pop()
|
1100 |
-
args_list = args_list[:-1] # FYI, even if unused currently
|
1101 |
-
if history is None:
|
1102 |
-
if not model2:
|
1103 |
-
# no need to complain so often unless model1
|
1104 |
-
print("Bad history, fix for now", flush=True)
|
1105 |
-
history = []
|
1106 |
-
# ensure elements not mixed across models as output,
|
1107 |
-
# even if input is currently same source
|
1108 |
-
history = history.copy()
|
1109 |
-
if undo:
|
1110 |
-
return history
|
1111 |
-
else:
|
1112 |
-
# FIXME: compare, same history for now
|
1113 |
-
return history + [[user_message1, None]]
|
1114 |
-
|
1115 |
-
def bot(*args, retry=False):
|
1116 |
-
"""
|
1117 |
-
bot that consumes history for user input
|
1118 |
-
instruction (from input_list) itself is not consumed by bot
|
1119 |
-
:param args:
|
1120 |
-
:param retry:
|
1121 |
-
:return:
|
1122 |
-
"""
|
1123 |
-
args_list = list(args).copy()
|
1124 |
-
history = args_list[-1] # model_state is -2
|
1125 |
-
if retry and history:
|
1126 |
-
history.pop()
|
1127 |
-
if not history:
|
1128 |
-
print("No history", flush=True)
|
1129 |
-
return
|
1130 |
-
# ensure output will be unique to models
|
1131 |
-
history = history.copy()
|
1132 |
-
instruction1 = history[-1][0]
|
1133 |
-
context1 = ''
|
1134 |
-
if kwargs['chat_history'] > 0:
|
1135 |
-
prompt_type_arg_id = eval_func_param_names.index('prompt_type')
|
1136 |
-
prompt_type1 = args_list[prompt_type_arg_id]
|
1137 |
-
chat_arg_id = eval_func_param_names.index('chat')
|
1138 |
-
chat1 = args_list[chat_arg_id]
|
1139 |
-
context1 = ''
|
1140 |
-
for histi in range(len(history) - 1):
|
1141 |
-
data_point = dict(instruction=history[histi][0], input='', output=history[histi][1])
|
1142 |
-
context1 += generate_prompt(data_point, prompt_type1, chat1, reduced=True)[0].replace(
|
1143 |
-
'<br>', '\n')
|
1144 |
-
if not context1.endswith('\n'):
|
1145 |
-
context1 += '\n'
|
1146 |
-
if context1 and not context1.endswith('\n'):
|
1147 |
-
context1 += '\n' # ensure if terminates abruptly, then human continues on next line
|
1148 |
-
args_list[0] = instruction1 # override original instruction with history from user
|
1149 |
-
# only include desired chat history
|
1150 |
-
args_list[2] = context1[-kwargs['chat_history']:]
|
1151 |
-
model_state1 = args_list[-2]
|
1152 |
-
if model_state1[0] is None or model_state1[0] == no_model_str:
|
1153 |
-
return
|
1154 |
-
args_list = args_list[:-2]
|
1155 |
-
fun1 = partial(evaluate,
|
1156 |
-
model_state1,
|
1157 |
-
**kwargs_evaluate)
|
1158 |
-
try:
|
1159 |
-
for output in fun1(*tuple(args_list)):
|
1160 |
-
bot_message = output
|
1161 |
-
history[-1][1] = bot_message
|
1162 |
-
yield history
|
1163 |
-
except StopIteration:
|
1164 |
-
yield history
|
1165 |
-
except RuntimeError as e:
|
1166 |
-
if "generator raised StopIteration" in str(e):
|
1167 |
-
# assume last entry was bad, undo
|
1168 |
-
history.pop()
|
1169 |
-
yield history
|
1170 |
-
raise
|
1171 |
-
except Exception as e:
|
1172 |
-
# put error into user input
|
1173 |
-
history[-1][0] = "Exception: %s" % str(e)
|
1174 |
-
yield history
|
1175 |
-
raise
|
1176 |
-
return
|
1177 |
-
|
1178 |
-
# NORMAL MODEL
|
1179 |
-
user_args = dict(fn=functools.partial(user, sanitize_user_prompt=kwargs['sanitize_user_prompt']),
|
1180 |
-
inputs=inputs_list + [text_output],
|
1181 |
-
outputs=text_output,
|
1182 |
-
)
|
1183 |
-
bot_args = dict(fn=bot,
|
1184 |
-
inputs=inputs_list + [model_state] + [text_output],
|
1185 |
-
outputs=text_output,
|
1186 |
-
)
|
1187 |
-
retry_bot_args = dict(fn=functools.partial(bot, retry=True),
|
1188 |
-
inputs=inputs_list + [model_state] + [text_output],
|
1189 |
-
outputs=text_output,
|
1190 |
-
)
|
1191 |
-
undo_user_args = dict(fn=functools.partial(user, undo=True),
|
1192 |
-
inputs=inputs_list + [text_output],
|
1193 |
-
outputs=text_output,
|
1194 |
-
)
|
1195 |
-
|
1196 |
-
# MODEL2
|
1197 |
-
user_args2 = dict(fn=functools.partial(user, sanitize_user_prompt=kwargs['sanitize_user_prompt'], model2=True),
|
1198 |
-
inputs=inputs_list + [text_output2],
|
1199 |
-
outputs=text_output2,
|
1200 |
-
)
|
1201 |
-
bot_args2 = dict(fn=bot,
|
1202 |
-
inputs=inputs_list + [model_state2] + [text_output2],
|
1203 |
-
outputs=text_output2,
|
1204 |
-
)
|
1205 |
-
retry_bot_args2 = dict(fn=functools.partial(bot, retry=True),
|
1206 |
-
inputs=inputs_list + [model_state2] + [text_output2],
|
1207 |
-
outputs=text_output2,
|
1208 |
-
)
|
1209 |
-
undo_user_args2 = dict(fn=functools.partial(user, undo=True),
|
1210 |
-
inputs=inputs_list + [text_output2],
|
1211 |
-
outputs=text_output2,
|
1212 |
-
)
|
1213 |
-
|
1214 |
-
def clear_instruct():
|
1215 |
-
return gr.Textbox.update(value='')
|
1216 |
-
|
1217 |
-
if kwargs['auto_score']:
|
1218 |
-
# in case 2nd model, consume instruction first, so can clear quickly
|
1219 |
-
# bot doesn't consume instruction itself, just history from user, so why works
|
1220 |
-
submit_event = instruction.submit(**user_args, queue=stream_output, api_name='instruction') \
|
1221 |
-
.then(**user_args2, queue=stream_output, api_name='instruction2') \
|
1222 |
-
.then(clear_instruct, None, instruction) \
|
1223 |
-
.then(**bot_args, api_name='instruction_bot') \
|
1224 |
-
.then(**score_args, api_name='instruction_bot_score') \
|
1225 |
-
.then(**bot_args2, api_name='instruction_bot2') \
|
1226 |
-
.then(**score_args2, api_name='instruction_bot_score2') \
|
1227 |
-
.then(clear_torch_cache)
|
1228 |
-
submit_event2 = submit.click(**user_args, queue=stream_output, api_name='submit') \
|
1229 |
-
.then(**user_args2, queue=stream_output, api_name='submit2') \
|
1230 |
-
.then(**bot_args, api_name='submit_bot') \
|
1231 |
-
.then(clear_instruct, None, instruction) \
|
1232 |
-
.then(**score_args, api_name='submit_bot_score') \
|
1233 |
-
.then(**bot_args2, api_name='submit_bot2') \
|
1234 |
-
.then(**score_args2, api_name='submit_bot_score2') \
|
1235 |
-
.then(clear_torch_cache)
|
1236 |
-
submit_event3 = retry.click(**user_args, queue=stream_output, api_name='retry') \
|
1237 |
-
.then(**user_args2, queue=stream_output, api_name='retry2') \
|
1238 |
-
.then(clear_instruct, None, instruction) \
|
1239 |
-
.then(**retry_bot_args, api_name='retry_bot') \
|
1240 |
-
.then(**score_args, api_name='retry_bot_score') \
|
1241 |
-
.then(**retry_bot_args2, api_name='retry_bot2') \
|
1242 |
-
.then(**score_args2, api_name='retry_bot_score2') \
|
1243 |
-
.then(clear_torch_cache)
|
1244 |
-
submit_event4 = undo.click(**undo_user_args, queue=stream_output, api_name='undo') \
|
1245 |
-
.then(**score_args, api_name='undo_score') \
|
1246 |
-
.then(**undo_user_args2, queue=stream_output, api_name='undo2') \
|
1247 |
-
.then(**score_args2, api_name='undo_score2') \
|
1248 |
-
.then(clear_instruct, None, instruction)
|
1249 |
-
else:
|
1250 |
-
submit_event = instruction.submit(**user_args, queue=stream_output, api_name='instruction') \
|
1251 |
-
.then(**user_args2, queue=stream_output, api_name='instruction2') \
|
1252 |
-
.then(clear_instruct, None, instruction) \
|
1253 |
-
.then(**bot_args, api_name='instruction_bot') \
|
1254 |
-
.then(**bot_args2, api_name='instruction_bot2') \
|
1255 |
-
.then(clear_torch_cache)
|
1256 |
-
submit_event2 = submit.click(**user_args, queue=stream_output, api_name='submit') \
|
1257 |
-
.then(**user_args2, queue=stream_output, api_name='submit2') \
|
1258 |
-
.then(clear_instruct, None, instruction) \
|
1259 |
-
.then(**bot_args, api_name='submit_bot') \
|
1260 |
-
.then(**bot_args2, api_name='submit_bot2') \
|
1261 |
-
.then(clear_torch_cache)
|
1262 |
-
submit_event3 = retry.click(**user_args, queue=stream_output, api_name='retry') \
|
1263 |
-
.then(**user_args2, queue=stream_output, api_name='retry2') \
|
1264 |
-
.then(clear_instruct, None, instruction) \
|
1265 |
-
.then(**retry_bot_args, api_name='retry_bot') \
|
1266 |
-
.then(**retry_bot_args2, api_name='retry_bot2') \
|
1267 |
-
.then(clear_torch_cache)
|
1268 |
-
submit_event4 = undo.click(**undo_user_args, queue=stream_output, api_name='undo') \
|
1269 |
-
.then(**undo_user_args2, queue=stream_output, api_name='undo2')
|
1270 |
-
|
1271 |
-
# does both models
|
1272 |
-
clear.click(lambda: None, None, text_output, queue=False, api_name='clear') \
|
1273 |
-
.then(lambda: None, None, text_output2, queue=False, api_name='clear2')
|
1274 |
-
# FIXME: compare
|
1275 |
-
submit_event_nochat = submit_nochat.click(fun, inputs=[model_state] + inputs_list,
|
1276 |
-
outputs=text_output_nochat, api_name='submit_nochat') \
|
1277 |
-
.then(**score_args_nochat, api_name='instruction_bot_score_nochat') \
|
1278 |
-
.then(clear_torch_cache)
|
1279 |
-
|
1280 |
-
def load_model(model_name, lora_weights, model_state_old, prompt_type_old, load_8bit, infer_devices, gpu_id):
|
1281 |
-
# ensure old model removed from GPU memory
|
1282 |
-
if kwargs['debug']:
|
1283 |
-
print("Pre-switch pre-del GPU memory: %s" % torch.cuda.memory_allocated(), flush=True)
|
1284 |
-
|
1285 |
-
if isinstance(model_state_old[0], str) and model0 is not None:
|
1286 |
-
# best can do, move model loaded at first to CPU
|
1287 |
-
model0.cpu()
|
1288 |
-
|
1289 |
-
if model_state_old[0] is not None and not isinstance(model_state_old[0], str):
|
1290 |
-
try:
|
1291 |
-
model_state_old[0].cpu()
|
1292 |
-
except Exception as e:
|
1293 |
-
# sometimes hit NotImplementedError: Cannot copy out of meta tensor; no data!
|
1294 |
-
print("Unable to put model on CPU: %s" % str(e), flush=True)
|
1295 |
-
del model_state_old[0]
|
1296 |
-
model_state_old[0] = None
|
1297 |
-
|
1298 |
-
if model_state_old[1] is not None and not isinstance(model_state_old[1], str):
|
1299 |
-
del model_state_old[1]
|
1300 |
-
model_state_old[1] = None
|
1301 |
-
|
1302 |
-
clear_torch_cache()
|
1303 |
-
if kwargs['debug']:
|
1304 |
-
print("Pre-switch post-del GPU memory: %s" % torch.cuda.memory_allocated(), flush=True)
|
1305 |
-
|
1306 |
-
if model_name is None or model_name == no_model_str:
|
1307 |
-
# no-op if no model, just free memory
|
1308 |
-
# no detranscribe needed for model, never go into evaluate
|
1309 |
-
lora_weights = no_lora_str
|
1310 |
-
return [None, None, None, model_name], model_name, lora_weights, prompt_type_old
|
1311 |
-
|
1312 |
-
all_kwargs1 = all_kwargs.copy()
|
1313 |
-
all_kwargs1['base_model'] = model_name.strip()
|
1314 |
-
all_kwargs1['load_8bit'] = load_8bit
|
1315 |
-
all_kwargs1['infer_devices'] = infer_devices
|
1316 |
-
all_kwargs1['gpu_id'] = int(gpu_id) # detranscribe
|
1317 |
-
model_lower = model_name.strip().lower()
|
1318 |
-
if model_lower in inv_prompt_type_to_model_lower:
|
1319 |
-
prompt_type1 = inv_prompt_type_to_model_lower[model_lower]
|
1320 |
-
else:
|
1321 |
-
prompt_type1 = prompt_type_old
|
1322 |
-
|
1323 |
-
# detranscribe
|
1324 |
-
if lora_weights == no_lora_str:
|
1325 |
-
lora_weights = ''
|
1326 |
-
|
1327 |
-
all_kwargs1['lora_weights'] = lora_weights.strip()
|
1328 |
-
model1, tokenizer1, device1 = get_model(**all_kwargs1)
|
1329 |
-
clear_torch_cache()
|
1330 |
-
|
1331 |
-
if kwargs['debug']:
|
1332 |
-
print("Post-switch GPU memory: %s" % torch.cuda.memory_allocated(), flush=True)
|
1333 |
-
return [model1, tokenizer1, device1, model_name], model_name, lora_weights, prompt_type1
|
1334 |
-
|
1335 |
-
def dropdown_prompt_type_list(x):
|
1336 |
-
return gr.Dropdown.update(value=x)
|
1337 |
-
|
1338 |
-
def chatbot_list(x, model_used_in):
|
1339 |
-
return gr.Textbox.update(label=f'h2oGPT [Model: {model_used_in}]')
|
1340 |
-
|
1341 |
-
load_model_args = dict(fn=load_model,
|
1342 |
-
inputs=[model_choice, lora_choice, model_state, prompt_type,
|
1343 |
-
model_load8bit_checkbox, model_infer_devices_checkbox, model_gpu],
|
1344 |
-
outputs=[model_state, model_used, lora_used, prompt_type])
|
1345 |
-
prompt_update_args = dict(fn=dropdown_prompt_type_list, inputs=prompt_type, outputs=prompt_type)
|
1346 |
-
chatbot_update_args = dict(fn=chatbot_list, inputs=[text_output, model_used], outputs=text_output)
|
1347 |
-
nochat_update_args = dict(fn=chatbot_list, inputs=[text_output, model_used], outputs=text_output_nochat)
|
1348 |
-
if not is_public:
|
1349 |
-
load_model_event = load_model_button.click(**load_model_args) \
|
1350 |
-
.then(**prompt_update_args) \
|
1351 |
-
.then(**chatbot_update_args) \
|
1352 |
-
.then(**nochat_update_args) \
|
1353 |
-
.then(clear_torch_cache)
|
1354 |
-
|
1355 |
-
load_model_args2 = dict(fn=load_model,
|
1356 |
-
inputs=[model_choice2, lora_choice2, model_state2, prompt_type2,
|
1357 |
-
model_load8bit_checkbox2, model_infer_devices_checkbox2, model_gpu2],
|
1358 |
-
outputs=[model_state2, model_used2, lora_used2, prompt_type2])
|
1359 |
-
prompt_update_args2 = dict(fn=dropdown_prompt_type_list, inputs=prompt_type2, outputs=prompt_type2)
|
1360 |
-
chatbot_update_args2 = dict(fn=chatbot_list, inputs=[text_output2, model_used2], outputs=text_output2)
|
1361 |
-
if not is_public:
|
1362 |
-
load_model_event2 = load_model_button2.click(**load_model_args2) \
|
1363 |
-
.then(**prompt_update_args2) \
|
1364 |
-
.then(**chatbot_update_args2) \
|
1365 |
-
.then(clear_torch_cache)
|
1366 |
-
|
1367 |
-
def dropdown_model_list(list0, x):
|
1368 |
-
new_state = [list0[0] + [x]]
|
1369 |
-
new_options = [*new_state[0]]
|
1370 |
-
return gr.Dropdown.update(value=x, choices=new_options), \
|
1371 |
-
gr.Dropdown.update(value=x, choices=new_options), \
|
1372 |
-
'', new_state
|
1373 |
-
|
1374 |
-
add_model_event = add_model_button.click(fn=dropdown_model_list,
|
1375 |
-
inputs=[model_options_state, new_model],
|
1376 |
-
outputs=[model_choice, model_choice2, new_model, model_options_state])
|
1377 |
-
|
1378 |
-
def dropdown_lora_list(list0, x, model_used1, lora_used1, model_used2, lora_used2):
|
1379 |
-
new_state = [list0[0] + [x]]
|
1380 |
-
new_options = [*new_state[0]]
|
1381 |
-
# don't switch drop-down to added lora if already have model loaded
|
1382 |
-
x1 = x if model_used1 == no_model_str else lora_used1
|
1383 |
-
x2 = x if model_used2 == no_model_str else lora_used2
|
1384 |
-
return gr.Dropdown.update(value=x1, choices=new_options), \
|
1385 |
-
gr.Dropdown.update(value=x2, choices=new_options), \
|
1386 |
-
'', new_state
|
1387 |
-
|
1388 |
-
add_lora_event = add_lora_button.click(fn=dropdown_lora_list,
|
1389 |
-
inputs=[lora_options_state, new_lora, model_used, lora_used, model_used2, lora_used2],
|
1390 |
-
outputs=[lora_choice, lora_choice2, new_lora, lora_options_state])
|
1391 |
-
|
1392 |
-
go_btn.click(lambda: gr.update(visible=False), None, go_btn, api_name="go") \
|
1393 |
-
.then(lambda: gr.update(visible=True), None, normal_block) \
|
1394 |
-
.then(**load_model_args).then(**prompt_update_args)
|
1395 |
-
|
1396 |
-
def compare_textbox_fun(x):
|
1397 |
-
return gr.Textbox.update(visible=x)
|
1398 |
-
|
1399 |
-
def compare_column_fun(x):
|
1400 |
-
return gr.Column.update(visible=x)
|
1401 |
-
|
1402 |
-
def compare_prompt_fun(x):
|
1403 |
-
return gr.Dropdown.update(visible=x)
|
1404 |
-
|
1405 |
-
compare_checkbox.select(compare_textbox_fun, compare_checkbox, text_output2, api_name="compare_checkbox") \
|
1406 |
-
.then(compare_column_fun, compare_checkbox, col_model2) \
|
1407 |
-
.then(compare_prompt_fun, compare_checkbox, prompt_type2) \
|
1408 |
-
.then(compare_textbox_fun, compare_checkbox, score_text2)
|
1409 |
-
# FIXME: add score_res2 in condition, but do better
|
1410 |
-
|
1411 |
-
# callback for logging flagged input/output
|
1412 |
-
callback.setup(inputs_list + [text_output], "flagged_data_points")
|
1413 |
-
flag_btn.click(lambda *args: callback.flag(args), inputs_list + [text_output], None, preprocess=False,
|
1414 |
-
api_name='flag')
|
1415 |
-
flag_btn_nochat.click(lambda *args: callback.flag(args), inputs_list + [text_output], None, preprocess=False,
|
1416 |
-
api_name='flag_nochat')
|
1417 |
-
|
1418 |
-
def get_system_info():
|
1419 |
-
return gr.Textbox.update(value=system_info_print())
|
1420 |
-
|
1421 |
-
system_event = system_btn.click(get_system_info, outputs=system_text, api_name='system_info')
|
1422 |
-
|
1423 |
-
# don't pass text_output, don't want to clear output, just stop it
|
1424 |
-
# FIXME: have to click once to stop output and second time to stop GPUs going
|
1425 |
-
stop_btn.click(lambda: None, None, None,
|
1426 |
-
cancels=[submit_event_nochat, submit_event, submit_event2, submit_event3],
|
1427 |
-
queue=False, api_name='stop').then(clear_torch_cache)
|
1428 |
-
demo.load(None,None,None, _js=dark_js)
|
1429 |
-
|
1430 |
-
demo.queue(concurrency_count=1)
|
1431 |
-
favicon_path = "h2o-logo.svg"
|
1432 |
-
demo.launch(share=kwargs['share'], server_name="0.0.0.0", show_error=True,
|
1433 |
-
favicon_path=favicon_path, prevent_thread_lock=True) # , enable_queue=True)
|
1434 |
-
print("Started GUI", flush=True)
|
1435 |
-
if kwargs['block_gradio_exit']:
|
1436 |
-
demo.block_thread()
|
1437 |
-
|
1438 |
-
|
1439 |
-
input_args_list = ['model_state']
|
1440 |
-
inputs_kwargs_list = ['debug', 'save_dir', 'hard_stop_list', 'sanitize_bot_response', 'model_state0']
|
1441 |
-
|
1442 |
-
|
1443 |
-
def get_inputs_list(inputs_dict, model_lower):
|
1444 |
-
"""
|
1445 |
-
map gradio objects in locals() to inputs for evaluate().
|
1446 |
-
:param inputs_dict:
|
1447 |
-
:param model_lower:
|
1448 |
-
:return:
|
1449 |
-
"""
|
1450 |
-
inputs_list_names = list(inspect.signature(evaluate).parameters)
|
1451 |
-
inputs_list = []
|
1452 |
-
for k in inputs_list_names:
|
1453 |
-
if k == 'kwargs':
|
1454 |
-
continue
|
1455 |
-
if k in input_args_list + inputs_kwargs_list:
|
1456 |
-
# these are added via partial, not taken as input
|
1457 |
-
continue
|
1458 |
-
if 'mbart-' not in model_lower and k in ['src_lang', 'tgt_lang']:
|
1459 |
-
continue
|
1460 |
-
inputs_list.append(inputs_dict[k])
|
1461 |
-
return inputs_list
|
1462 |
-
|
1463 |
-
|
1464 |
eval_func_param_names = ['instruction',
|
1465 |
'iinput',
|
1466 |
'context',
|
@@ -1509,12 +626,21 @@ def evaluate(
|
|
1509 |
src_lang=None,
|
1510 |
tgt_lang=None,
|
1511 |
debug=False,
|
|
|
1512 |
save_dir=None,
|
1513 |
hard_stop_list=None,
|
1514 |
sanitize_bot_response=True,
|
1515 |
model_state0=None,
|
1516 |
-
|
|
|
|
|
1517 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
1518 |
if debug:
|
1519 |
locals_dict = locals().copy()
|
1520 |
locals_dict.pop('model_state', None)
|
@@ -1555,6 +681,10 @@ def evaluate(
|
|
1555 |
instruction = instruction_nochat
|
1556 |
iinput = iinput_nochat
|
1557 |
|
|
|
|
|
|
|
|
|
1558 |
data_point = dict(context=context, instruction=instruction, input=iinput)
|
1559 |
prompter = Prompter(prompt_type, debug=debug, chat=chat, stream_output=stream_output)
|
1560 |
prompt = prompter.generate_prompt(data_point)
|
@@ -1647,7 +777,6 @@ def evaluate(
|
|
1647 |
num_return_sequences=num_return_sequences,
|
1648 |
renormalize_logits=True,
|
1649 |
remove_invalid_values=True,
|
1650 |
-
**kwargs,
|
1651 |
)
|
1652 |
|
1653 |
gen_kwargs = dict(input_ids=input_ids,
|
@@ -1695,62 +824,64 @@ def evaluate(
|
|
1695 |
else:
|
1696 |
print("WARNING: Special characters in prompt", flush=True)
|
1697 |
if stream_output:
|
1698 |
-
|
1699 |
-
|
1700 |
-
|
1701 |
-
|
1702 |
-
|
1703 |
-
|
1704 |
-
|
1705 |
-
|
1706 |
-
|
1707 |
-
|
1708 |
-
|
1709 |
-
|
1710 |
-
|
1711 |
-
|
1712 |
-
|
1713 |
-
|
1714 |
-
|
1715 |
-
|
1716 |
-
return
|
1717 |
-
except (Exception, RuntimeError) as e:
|
1718 |
-
if 'Expected all tensors to be on the same device' in str(e) or \
|
1719 |
-
'expected scalar type Half but found Float' in str(e) or \
|
1720 |
-
'probability tensor contains either' in str(e) or \
|
1721 |
-
'cublasLt ran into an error!' in str(e):
|
1722 |
-
print(
|
1723 |
-
"GPU Error: prompt: %s inputs_decoded: %s exception: %s" % (prompt, inputs_decoded, str(e)),
|
1724 |
-
flush=True)
|
1725 |
-
traceback.print_exc()
|
1726 |
-
clear_torch_cache()
|
1727 |
-
if raise_generate_gpu_exceptions:
|
1728 |
-
raise
|
1729 |
-
return
|
1730 |
-
else:
|
1731 |
-
raise
|
1732 |
-
|
1733 |
-
decoded_output = None
|
1734 |
-
for output in CallbackToGenerator(generate, callback=None, **gen_kwargs):
|
1735 |
-
decoded_output = decoder(output)
|
1736 |
-
if output[-1] in [tokenizer.eos_token_id]:
|
1737 |
-
if debug:
|
1738 |
-
print("HIT EOS", flush=True)
|
1739 |
-
break
|
1740 |
-
if any(ele in decoded_output for ele in hard_stop_list):
|
1741 |
-
raise StopIteration
|
1742 |
-
yield prompter.get_response(decoded_output, prompt=inputs_decoded,
|
1743 |
sanitize_bot_response=sanitize_bot_response)
|
1744 |
-
if save_dir and decoded_output:
|
1745 |
-
save_generate_output(output=decoded_output, base_model=base_model, save_dir=save_dir)
|
1746 |
else:
|
1747 |
outputs = model.generate(**gen_kwargs)
|
1748 |
outputs = [decoder(s) for s in outputs.sequences]
|
1749 |
yield prompter.get_response(outputs, prompt=inputs_decoded,
|
1750 |
sanitize_bot_response=sanitize_bot_response)
|
1751 |
-
|
1752 |
-
|
1753 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1754 |
|
1755 |
|
1756 |
def get_generate_params(model_lower, chat,
|
@@ -1862,9 +993,9 @@ Philipp: ok, ok you can find everything here. https://huggingface.co/blog/the-pa
|
|
1862 |
num_return_sequences = min(num_beams, num_return_sequences or 1)
|
1863 |
do_sample = False if do_sample is None else do_sample
|
1864 |
else:
|
1865 |
-
temperature = 0.
|
1866 |
-
top_p = 0.
|
1867 |
-
top_k =
|
1868 |
if chat:
|
1869 |
num_beams = num_beams or 1
|
1870 |
else:
|
@@ -1872,7 +1003,7 @@ Philipp: ok, ok you can find everything here. https://huggingface.co/blog/the-pa
|
|
1872 |
max_new_tokens = max_new_tokens or 256
|
1873 |
repetition_penalty = repetition_penalty or 1.07
|
1874 |
num_return_sequences = min(num_beams, num_return_sequences or 1)
|
1875 |
-
do_sample =
|
1876 |
# doesn't include chat, instruction_nochat, iinput_nochat, added later
|
1877 |
params_list = ["", stream_output, prompt_type, temperature, top_p, top_k, num_beams, max_new_tokens, min_new_tokens,
|
1878 |
early_stopping, max_time, repetition_penalty, num_return_sequences, do_sample]
|
@@ -1948,12 +1079,53 @@ def languages_covered():
|
|
1948 |
return covered
|
1949 |
|
1950 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1951 |
def test_test_prompt(prompt_type='instruct', data_point=0):
|
1952 |
example_data_point = example_data_points[data_point]
|
1953 |
example_data_point.pop('output', None)
|
1954 |
return generate_prompt(example_data_point, prompt_type, False, False)
|
1955 |
|
1956 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1957 |
if __name__ == "__main__":
|
1958 |
print("""
|
1959 |
WORLD_SIZE=4 CUDA_VISIBLE_DEVICES="0,1,2,3" torchrun --nproc_per_node=4 --master_port=1234 generate.py --base_model='EleutherAI/gpt-j-6B' --lora_weights=lora-alpaca_6B
|
|
|
1 |
import functools
|
|
|
2 |
import sys
|
3 |
import os
|
4 |
import traceback
|
5 |
import typing
|
6 |
+
|
7 |
+
from utils import set_seed, clear_torch_cache, save_generate_output, NullContext, KThread, wrapped_partial
|
8 |
|
9 |
SEED = 1236
|
10 |
set_seed(SEED)
|
|
|
17 |
import fire
|
18 |
import torch
|
19 |
from peft import PeftModel
|
20 |
+
from transformers import GenerationConfig, StoppingCriteriaList, AutoModel, TextIteratorStreamer
|
21 |
from accelerate import init_empty_weights, infer_auto_device_map
|
22 |
|
23 |
from prompter import Prompter
|
24 |
|
25 |
+
from finetune import get_loaders, example_data_points, generate_prompt, human, bot, inv_prompt_type_to_model_lower
|
26 |
+
from stopping import StoppingCriteriaSub
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
eval_extra_columns = ['prompt', 'response', 'score']
|
29 |
|
30 |
+
|
31 |
def main(
|
32 |
load_8bit: bool = False,
|
33 |
load_half: bool = True,
|
34 |
+
infer_devices: bool = True, # really if to "control" devices now
|
35 |
base_model: str = '',
|
36 |
tokenizer_base_model: str = '',
|
37 |
lora_weights: str = "",
|
|
|
51 |
early_stopping: Union[bool, str] = None,
|
52 |
max_time: float = None,
|
53 |
|
|
|
54 |
debug: bool = False,
|
55 |
save_dir: str = None,
|
56 |
share: bool = True,
|
|
|
65 |
gradio_avoid_processing_markdown: bool = False,
|
66 |
chat: bool = True,
|
67 |
chat_history: int = 4096, # character length of chat context/history
|
68 |
+
chat_context: bool = False, # use default context if human_bot
|
69 |
stream_output: bool = True,
|
70 |
show_examples: bool = None,
|
71 |
verbose: bool = False,
|
|
|
76 |
# to be able to free GPU memory when model is swapped
|
77 |
login_mode_if_model0: bool = False,
|
78 |
block_gradio_exit: bool = True,
|
79 |
+
concurrency_count: int = 1,
|
80 |
+
api_open: bool = False, # don't let API skip queue
|
81 |
+
allow_api: bool = True,
|
82 |
+
input_lines: int = 1,
|
83 |
|
84 |
sanitize_user_prompt: bool = True,
|
85 |
sanitize_bot_response: bool = True,
|
|
|
93 |
eval_sharegpt_prompts_only: int = 0,
|
94 |
eval_sharegpt_prompts_only_seed: int = 1234,
|
95 |
eval_sharegpt_as_output: bool = False,
|
96 |
+
|
97 |
+
hard_stop_list: typing.List[str] = [],
|
98 |
):
|
99 |
+
is_hf = bool(os.getenv("HUGGINGFACE_SPACES"))
|
100 |
+
is_gpth2oai = bool(os.getenv("GPT_H2O_AI"))
|
101 |
+
is_public = is_hf or is_gpth2oai # multi-user case with fixed model and disclaimer
|
102 |
+
is_low_mem = is_hf # assumes run on 24GB consumer GPU
|
103 |
+
admin_pass = os.getenv("ADMIN_PASS")
|
104 |
+
# will sometimes appear in UI or sometimes actual generation, but maybe better than empty result
|
105 |
+
# but becomes unrecoverable sometimes if raise, so just be silent for now
|
106 |
+
raise_generate_gpu_exceptions = not is_public
|
107 |
+
|
108 |
# allow set token directly
|
109 |
use_auth_token = os.environ.get("HUGGINGFACE_API_TOKEN", use_auth_token)
|
110 |
|
111 |
if is_public:
|
112 |
+
input_lines = 1 # ensure set, for ease of use
|
113 |
temperature = 0.4
|
114 |
top_p = 0.85
|
115 |
top_k = 70
|
|
|
128 |
score_model = os.getenv('SCORE_MODEL', score_model)
|
129 |
if score_model == 'None':
|
130 |
score_model = ''
|
131 |
+
concurrency_count = int(os.getenv('CONCURRENCY_COUNT', concurrency_count))
|
132 |
+
api_open = bool(int(os.getenv('API_OPEN', api_open)))
|
133 |
+
allow_api = bool(int(os.getenv('ALLOW_API', allow_api)))
|
134 |
+
|
135 |
+
n_gpus = torch.cuda.device_count()
|
136 |
|
137 |
# get defaults
|
138 |
model_lower = base_model.lower()
|
|
|
183 |
assert data[i]['conversations'][turn_start + 1]['from'] == 'gpt'
|
184 |
output = data[i]['conversations'][turn_start + 1]['value']
|
185 |
examplenew = example1.copy()
|
186 |
+
assert not chat, "No gradio must use chat=False, uses nochat instruct"
|
187 |
examplenew[eval_func_param_names.index('instruction_nochat')] = instruction
|
188 |
examplenew[eval_func_param_names.index('iinput_nochat')] = '' # no input
|
189 |
+
examplenew[eval_func_param_names.index('context')] = get_context(chat_context, prompt_type)
|
190 |
examples.append(examplenew)
|
191 |
responses.append(output)
|
192 |
|
|
|
206 |
used_lora_weights)
|
207 |
eval_filename = os.path.join(scoring_path, eval_filename)
|
208 |
|
209 |
+
# torch.device("cuda") leads to cuda:x cuda:y mismatches for multi-GPU consistently
|
210 |
+
context_class = NullContext() if n_gpus > 1 else torch.device("cuda")
|
211 |
+
|
212 |
+
with context_class:
|
213 |
# ensure was set right above before examples generated
|
214 |
assert not stream_output, "stream_output=True does not make sense with example loop"
|
215 |
import time
|
|
|
221 |
if not eval_sharegpt_as_output:
|
222 |
model, tokenizer, device = get_model(**locals())
|
223 |
model_state = [model, tokenizer, device, base_model]
|
224 |
+
fun = partial(evaluate, model_state, debug=debug, save_dir=save_dir, is_low_mem=is_low_mem,
|
225 |
+
raise_generate_gpu_exceptions=raise_generate_gpu_exceptions,
|
226 |
+
chat_context=chat_context,
|
227 |
+
concurrency_count=concurrency_count)
|
228 |
else:
|
229 |
assert eval_sharegpt_prompts_only > 0
|
230 |
|
|
|
249 |
print("-" * 105)
|
250 |
# fun yields as generator, so have to iterate over it
|
251 |
# Also means likely do NOT want --stream_output=True, else would show all generations
|
252 |
+
gener = fun(*tuple(ex), exi=exi) if eval_sharegpt_as_output else fun(*tuple(ex))
|
253 |
+
for res in gener:
|
254 |
print(res)
|
255 |
if smodel:
|
256 |
score_with_prompt = False
|
|
|
260 |
prompt = prompter.generate_prompt(data_point)
|
261 |
else:
|
262 |
# just raw input and output
|
263 |
+
if eval_sharegpt_prompts_only > 0:
|
264 |
+
# only our own examples have this filled at moment
|
265 |
+
assert iinput in [None, ''], iinput # should be no iinput
|
266 |
+
if not (chat_context and prompt_type == 'human_bot'):
|
267 |
+
assert context in [None, ''], context # should be no context
|
268 |
prompt = instruction
|
269 |
cutoff_len = 768 if is_low_mem else 2048
|
270 |
inputs = stokenizer(prompt, res,
|
|
|
274 |
try:
|
275 |
score = torch.sigmoid(smodel(**inputs).logits[0]).cpu().detach().numpy()[0]
|
276 |
except torch.cuda.OutOfMemoryError as e:
|
277 |
+
print("GPU OOM 1: question: %s answer: %s exception: %s" % (prompt, res, str(e)), flush=True)
|
278 |
traceback.print_exc()
|
279 |
score = 0.0
|
280 |
clear_torch_cache()
|
|
|
314 |
return eval_filename
|
315 |
|
316 |
if gradio:
|
317 |
+
# imported here so don't require gradio to run generate
|
318 |
+
from gradio_runner import go_gradio
|
319 |
+
|
320 |
+
# get default model
|
321 |
+
all_kwargs = locals().copy()
|
322 |
+
if all_kwargs.get('base_model') and not all_kwargs['login_mode_if_model0']:
|
323 |
+
model0, tokenizer0, device = get_model(**all_kwargs)
|
324 |
+
else:
|
325 |
+
# if empty model, then don't load anything, just get gradio up
|
326 |
+
model0, tokenizer0, device = None, None, None
|
327 |
+
model_state0 = [model0, tokenizer0, device, all_kwargs['base_model']]
|
328 |
+
|
329 |
+
# get score model
|
330 |
+
smodel, stokenizer, sdevice = get_score_model(**all_kwargs)
|
331 |
+
score_model_state0 = [smodel, stokenizer, sdevice, score_model]
|
332 |
+
|
333 |
go_gradio(**locals())
|
334 |
|
335 |
|
|
|
386 |
device_map = {'': n_gpus - 1}
|
387 |
else:
|
388 |
device_map = {'': min(n_gpus - 1, gpu_id)}
|
389 |
+
if gpu_id == -1:
|
390 |
+
device_map = {'': 'cuda'}
|
391 |
|
392 |
load_in_8bit = model_kwargs.get('load_in_8bit', False)
|
393 |
model_kwargs['device_map'] = device_map
|
|
|
414 |
lora_weights: str = "",
|
415 |
gpu_id: int = 0,
|
416 |
|
|
|
417 |
reward_type: bool = None,
|
418 |
local_files_only: bool = False,
|
419 |
resume_download: bool = True,
|
|
|
432 |
:param tokenizer_base_model: name/path of tokenizer
|
433 |
:param lora_weights: name/path
|
434 |
:param gpu_id: which GPU (0..n_gpus-1) or allow all GPUs if relevant (-1)
|
|
|
435 |
:param reward_type: reward type model for sequence classification
|
436 |
:param local_files_only: use local files instead of from HF
|
437 |
:param resume_download: resume downloads from HF
|
438 |
:param use_auth_token: assumes user did on CLI `huggingface-cli login` to access private repo
|
439 |
+
:param compile: whether to compile torch model
|
440 |
:param kwargs:
|
441 |
:return:
|
442 |
"""
|
|
|
452 |
assert base_model.strip(), (
|
453 |
"Please choose a base model with --base_model (CLI) or in Models Tab (gradio)"
|
454 |
)
|
455 |
+
|
456 |
+
from transformers import AutoConfig
|
457 |
+
config = AutoConfig.from_pretrained(base_model, use_auth_token=use_auth_token)
|
458 |
+
llama_type_from_config = 'llama' in str(config).lower()
|
459 |
+
llama_type_from_name = "llama" in base_model.lower()
|
460 |
+
llama_type = llama_type_from_config or llama_type_from_name
|
461 |
+
if llama_type:
|
462 |
+
print("Detected as llama type from"
|
463 |
+
" config (%s) or name (%s)" % (llama_type_from_config, llama_type_from_name), flush=True)
|
464 |
+
|
465 |
model_loader, tokenizer_loader = get_loaders(llama_type=llama_type, model_name=base_model, reward_type=reward_type)
|
466 |
if not tokenizer_base_model:
|
467 |
tokenizer_base_model = base_model
|
|
|
578 |
return smodel, stokenizer, sdevice
|
579 |
|
580 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
581 |
eval_func_param_names = ['instruction',
|
582 |
'iinput',
|
583 |
'context',
|
|
|
626 |
src_lang=None,
|
627 |
tgt_lang=None,
|
628 |
debug=False,
|
629 |
+
concurrency_count=None,
|
630 |
save_dir=None,
|
631 |
hard_stop_list=None,
|
632 |
sanitize_bot_response=True,
|
633 |
model_state0=None,
|
634 |
+
is_low_mem=None,
|
635 |
+
raise_generate_gpu_exceptions=None,
|
636 |
+
chat_context=None,
|
637 |
):
|
638 |
+
# ensure passed these
|
639 |
+
assert concurrency_count is not None
|
640 |
+
assert is_low_mem is not None
|
641 |
+
assert raise_generate_gpu_exceptions is not None
|
642 |
+
assert chat_context is not None
|
643 |
+
|
644 |
if debug:
|
645 |
locals_dict = locals().copy()
|
646 |
locals_dict.pop('model_state', None)
|
|
|
681 |
instruction = instruction_nochat
|
682 |
iinput = iinput_nochat
|
683 |
|
684 |
+
if not context:
|
685 |
+
# get hidden context if have one
|
686 |
+
context = get_context(chat_context, prompt_type)
|
687 |
+
|
688 |
data_point = dict(context=context, instruction=instruction, input=iinput)
|
689 |
prompter = Prompter(prompt_type, debug=debug, chat=chat, stream_output=stream_output)
|
690 |
prompt = prompter.generate_prompt(data_point)
|
|
|
777 |
num_return_sequences=num_return_sequences,
|
778 |
renormalize_logits=True,
|
779 |
remove_invalid_values=True,
|
|
|
780 |
)
|
781 |
|
782 |
gen_kwargs = dict(input_ids=input_ids,
|
|
|
824 |
else:
|
825 |
print("WARNING: Special characters in prompt", flush=True)
|
826 |
if stream_output:
|
827 |
+
#skip_prompt = prompt_type != 'plain'
|
828 |
+
skip_prompt = False
|
829 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=skip_prompt)
|
830 |
+
gen_kwargs.update(dict(streamer=streamer))
|
831 |
+
if debug:
|
832 |
+
KThread.show_threads()
|
833 |
+
target_func = generate_with_exceptions
|
834 |
+
if concurrency_count == 1:
|
835 |
+
# otherwise can't do this
|
836 |
+
KThread.kill_threads(target_func.__name__)
|
837 |
+
target = wrapped_partial(generate_with_exceptions, model.generate, prompt, inputs_decoded,
|
838 |
+
raise_generate_gpu_exceptions, **gen_kwargs)
|
839 |
+
thread = KThread(target=target)
|
840 |
+
thread.start()
|
841 |
+
outputs = ""
|
842 |
+
for new_text in streamer:
|
843 |
+
outputs += new_text
|
844 |
+
yield prompter.get_response(outputs, prompt=inputs_decoded,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
845 |
sanitize_bot_response=sanitize_bot_response)
|
|
|
|
|
846 |
else:
|
847 |
outputs = model.generate(**gen_kwargs)
|
848 |
outputs = [decoder(s) for s in outputs.sequences]
|
849 |
yield prompter.get_response(outputs, prompt=inputs_decoded,
|
850 |
sanitize_bot_response=sanitize_bot_response)
|
851 |
+
if save_dir and outputs and len(outputs) >= 1:
|
852 |
+
decoded_output = prompt + outputs[0]
|
853 |
+
save_generate_output(output=decoded_output, base_model=base_model, save_dir=save_dir)
|
854 |
+
|
855 |
+
|
856 |
+
def generate_with_exceptions(func, prompt, inputs_decoded, raise_generate_gpu_exceptions, **kwargs):
|
857 |
+
try:
|
858 |
+
func(**kwargs)
|
859 |
+
except torch.cuda.OutOfMemoryError as e:
|
860 |
+
print("GPU OOM 2: prompt: %s inputs_decoded: %s exception: %s" % (prompt, inputs_decoded, str(e)),
|
861 |
+
flush=True)
|
862 |
+
if kwargs['input_ids'] is not None:
|
863 |
+
kwargs['input_ids'].cpu()
|
864 |
+
kwargs['input_ids'] = None
|
865 |
+
traceback.print_exc()
|
866 |
+
clear_torch_cache()
|
867 |
+
return
|
868 |
+
except (Exception, RuntimeError) as e:
|
869 |
+
if 'Expected all tensors to be on the same device' in str(e) or \
|
870 |
+
'expected scalar type Half but found Float' in str(e) or \
|
871 |
+
'probability tensor contains either' in str(e) or \
|
872 |
+
'cublasLt ran into an error!' in str(e) or \
|
873 |
+
'mat1 and mat2 shapes cannot be multiplied' in str(e):
|
874 |
+
print(
|
875 |
+
"GPU Error: prompt: %s inputs_decoded: %s exception: %s" % (prompt, inputs_decoded, str(e)),
|
876 |
+
flush=True)
|
877 |
+
traceback.print_exc()
|
878 |
+
clear_torch_cache()
|
879 |
+
if raise_generate_gpu_exceptions:
|
880 |
+
raise
|
881 |
+
return
|
882 |
+
else:
|
883 |
+
clear_torch_cache()
|
884 |
+
raise
|
885 |
|
886 |
|
887 |
def get_generate_params(model_lower, chat,
|
|
|
993 |
num_return_sequences = min(num_beams, num_return_sequences or 1)
|
994 |
do_sample = False if do_sample is None else do_sample
|
995 |
else:
|
996 |
+
temperature = 0.4 if temperature is None else temperature
|
997 |
+
top_p = 0.85 if top_p is None else top_p
|
998 |
+
top_k = 70 if top_k is None else top_k
|
999 |
if chat:
|
1000 |
num_beams = num_beams or 1
|
1001 |
else:
|
|
|
1003 |
max_new_tokens = max_new_tokens or 256
|
1004 |
repetition_penalty = repetition_penalty or 1.07
|
1005 |
num_return_sequences = min(num_beams, num_return_sequences or 1)
|
1006 |
+
do_sample = True if do_sample is None else do_sample
|
1007 |
# doesn't include chat, instruction_nochat, iinput_nochat, added later
|
1008 |
params_list = ["", stream_output, prompt_type, temperature, top_p, top_k, num_beams, max_new_tokens, min_new_tokens,
|
1009 |
early_stopping, max_time, repetition_penalty, num_return_sequences, do_sample]
|
|
|
1079 |
return covered
|
1080 |
|
1081 |
|
1082 |
+
def get_context(chat_context, prompt_type):
|
1083 |
+
if chat_context and prompt_type == 'human_bot':
|
1084 |
+
context0 = """<bot>: I am an intelligent, helpful, truthful, and fair assistant named h2oGPT, who will give accurate, balanced, and reliable responses. I will not respond with I don't know or I don't understand.
|
1085 |
+
<human>: I am a human person seeking useful assistance and request all questions be answered completely, and typically expect detailed responses. Give answers in numbered list format if several distinct but related items are being listed."""
|
1086 |
+
else:
|
1087 |
+
context0 = ''
|
1088 |
+
return context0
|
1089 |
+
|
1090 |
+
|
1091 |
def test_test_prompt(prompt_type='instruct', data_point=0):
|
1092 |
example_data_point = example_data_points[data_point]
|
1093 |
example_data_point.pop('output', None)
|
1094 |
return generate_prompt(example_data_point, prompt_type, False, False)
|
1095 |
|
1096 |
|
1097 |
+
def score_qa(smodel, stokenizer, max_length_tokenize, question, answer, cutoff_len):
|
1098 |
+
question = question[-cutoff_len:]
|
1099 |
+
answer = answer[-cutoff_len:]
|
1100 |
+
|
1101 |
+
inputs = stokenizer(question, answer,
|
1102 |
+
return_tensors="pt",
|
1103 |
+
truncation=True,
|
1104 |
+
max_length=max_length_tokenize).to(smodel.device)
|
1105 |
+
try:
|
1106 |
+
score = torch.sigmoid(smodel(**inputs).logits[0]).cpu().detach().numpy()[0]
|
1107 |
+
except torch.cuda.OutOfMemoryError as e:
|
1108 |
+
print("GPU OOM 3: question: %s answer: %s exception: %s" % (question, answer, str(e)), flush=True)
|
1109 |
+
del inputs
|
1110 |
+
traceback.print_exc()
|
1111 |
+
clear_torch_cache()
|
1112 |
+
return 'Response Score: GPU OOM'
|
1113 |
+
except (Exception, RuntimeError) as e:
|
1114 |
+
if 'Expected all tensors to be on the same device' in str(e) or \
|
1115 |
+
'expected scalar type Half but found Float' in str(e) or \
|
1116 |
+
'probability tensor contains either' in str(e) or \
|
1117 |
+
'cublasLt ran into an error!' in str(e):
|
1118 |
+
print("GPU Error: question: %s answer: %s exception: %s" % (question, answer, str(e)),
|
1119 |
+
flush=True)
|
1120 |
+
traceback.print_exc()
|
1121 |
+
clear_torch_cache()
|
1122 |
+
return 'Response Score: GPU Error'
|
1123 |
+
else:
|
1124 |
+
raise
|
1125 |
+
os.environ['TOKENIZERS_PARALLELISM'] = 'true'
|
1126 |
+
return score
|
1127 |
+
|
1128 |
+
|
1129 |
if __name__ == "__main__":
|
1130 |
print("""
|
1131 |
WORLD_SIZE=4 CUDA_VISIBLE_DEVICES="0,1,2,3" torchrun --nproc_per_node=4 --master_port=1234 generate.py --base_model='EleutherAI/gpt-j-6B' --lora_weights=lora-alpaca_6B
|
finetune.py
CHANGED
@@ -1,55 +1,22 @@
|
|
1 |
import os
|
2 |
-
import pathlib
|
3 |
-
import random
|
4 |
-
import shutil
|
5 |
-
import subprocess
|
6 |
import sys
|
7 |
import time
|
8 |
-
from
|
9 |
from typing import List, Union
|
|
|
10 |
import fire
|
11 |
import numpy as np
|
|
|
12 |
import torch
|
13 |
-
from datasets import load_dataset, concatenate_datasets
|
14 |
-
import transformers
|
15 |
-
import torch.distributed as dist
|
16 |
-
|
17 |
-
from peft import (
|
18 |
-
prepare_model_for_int8_training,
|
19 |
-
LoraConfig,
|
20 |
-
get_peft_model,
|
21 |
-
get_peft_model_state_dict,
|
22 |
-
set_peft_model_state_dict,
|
23 |
-
)
|
24 |
-
|
25 |
-
from peft import mapping
|
26 |
-
lora_mappings = mapping.TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING
|
27 |
|
28 |
|
29 |
def log(*args, **kwargs):
|
30 |
if int(os.environ.get("LOCAL_RANK", 0)) == 0:
|
|
|
|
|
31 |
print(*args, **kwargs)
|
32 |
|
33 |
|
34 |
-
try:
|
35 |
-
import neptune
|
36 |
-
from transformers.integrations import NeptuneCallback
|
37 |
-
|
38 |
-
neptune_run = neptune.init_run(
|
39 |
-
source_files=[],
|
40 |
-
)
|
41 |
-
log("Connected to Neptune.")
|
42 |
-
except ImportError:
|
43 |
-
neptune_run = None
|
44 |
-
log("Please pip install neptune for tracking.")
|
45 |
-
except neptune.exceptions.NeptuneMissingApiTokenException:
|
46 |
-
neptune_run = None
|
47 |
-
os.environ["NEPTUNE_MODE"] = 'debug'
|
48 |
-
log("No neptune configured, set NEPTUNE_API_TOKEN env var.")
|
49 |
-
|
50 |
-
from enum import Enum
|
51 |
-
|
52 |
-
|
53 |
class PromptType(Enum):
|
54 |
plain = 0
|
55 |
instruct = 1
|
@@ -87,6 +54,7 @@ prompt_type_to_model_name = {
|
|
87 |
'h2oai/h2ogpt-oasst1-512-12b',
|
88 |
'h2oai/h2ogpt-oasst1-512-20b',
|
89 |
'h2oai/h2ogpt-oig-oasst1-512-6.9b',
|
|
|
90 |
],
|
91 |
'dai_faq': [],
|
92 |
'summarize': [],
|
@@ -134,7 +102,7 @@ def train(
|
|
134 |
tokenizer_base_model: str = None,
|
135 |
# tokenizer_base_model: str = 'EleutherAI/gpt-neox-20b',
|
136 |
|
137 |
-
data_path: str =
|
138 |
data_col_dict: dict = None,
|
139 |
# data_path: str = "./dai_docs.train.json",
|
140 |
prompt_type: Union[str, int] = "plain", # "plain", "instruct", "quality", "human_bot", "dai_faq"
|
@@ -158,6 +126,7 @@ def train(
|
|
158 |
micro_batch_size: int = 4,
|
159 |
gradient_checkpointing=False, # unnecessary with gradient accumulation enabled
|
160 |
fp16=True,
|
|
|
161 |
|
162 |
# general training hyperparams
|
163 |
num_epochs: float = 1,
|
@@ -175,12 +144,14 @@ def train(
|
|
175 |
lora_dropout: float = 0.05,
|
176 |
lora_target_modules: List[str] = None,
|
177 |
llama_type: bool = None,
|
|
|
178 |
|
179 |
# llm hyperparams
|
180 |
train_on_inputs: bool = True, # if False, masks out inputs in loss
|
181 |
group_by_length: bool = False, # if True, faster, but produces an odd training loss curve
|
182 |
resume_from_checkpoint: str = None, # either training checkpoint or final adapter
|
183 |
-
cutoff_len: int =
|
|
|
184 |
|
185 |
# torch training params
|
186 |
ddp: bool = True, # set to False if OOM with True, for multi-GPU model parallelism
|
@@ -190,8 +161,15 @@ def train(
|
|
190 |
warmup_steps: int = 100,
|
191 |
logging_steps: int = 1,
|
192 |
save_steps: int = None, # must be round multiple of eval_steps
|
|
|
193 |
add_eos_token: bool = False,
|
194 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
195 |
# allow set token directly
|
196 |
use_auth_token = os.environ.get("HUGGINGFACE_API_TOKEN", use_auth_token)
|
197 |
|
@@ -211,7 +189,7 @@ def train(
|
|
211 |
if not output_dir:
|
212 |
output_dir = f"{base_model.split('/')[-1]}.{data_path.replace('/', '')}.{num_epochs}_epochs.{get_githash() or 'nogit'}.{run_id}"
|
213 |
if os.path.exists(output_dir) and not resume_from_checkpoint:
|
214 |
-
raise FileExistsError(f"output_dir based on run_id {run_id} already exists. Please pick a different run_id.")
|
215 |
else:
|
216 |
if os.path.exists(output_dir) and not resume_from_checkpoint:
|
217 |
raise FileExistsError(f"output_dir {output_dir} already exists. Please pick a different output_dir, or specify a run_id instead.")
|
@@ -223,6 +201,21 @@ def train(
|
|
223 |
tokenizer_base_model = base_model
|
224 |
if llama_type is None:
|
225 |
llama_type = "llama" in base_model.lower()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
226 |
assert (
|
227 |
base_model
|
228 |
), "Please specify a --base_model, e.g. --base_model='decapoda-research/llama-7b-hf'"
|
@@ -254,7 +247,7 @@ def train(
|
|
254 |
|
255 |
model = model_loader.from_pretrained(
|
256 |
base_model,
|
257 |
-
load_in_8bit=
|
258 |
device_map=device_map,
|
259 |
torch_dtype=torch.float16,
|
260 |
max_memory=max_memory,
|
@@ -268,66 +261,28 @@ def train(
|
|
268 |
model.is_parallelizable = True
|
269 |
model.model_parallel = True
|
270 |
|
271 |
-
tokenizer = tokenizer_loader
|
272 |
-
local_files_only=local_files_only,
|
273 |
-
resume_download=resume_download,
|
274 |
-
use_auth_token=use_auth_token)
|
275 |
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
# e.g. see: https://huggingface.co/transformers/v4.11.3/model_doc/t5.html#inference
|
280 |
-
tokenizer.padding_side = "left" # Allow batched inference
|
281 |
-
|
282 |
-
def tokenize(prompt, add_eos_token=True):
|
283 |
-
# there's probably a way to do this with the tokenizer settings
|
284 |
-
# but again, gotta move fast
|
285 |
-
result = tokenizer(
|
286 |
-
prompt,
|
287 |
-
truncation=True,
|
288 |
-
max_length=cutoff_len,
|
289 |
-
padding=False,
|
290 |
-
return_tensors=None,
|
291 |
)
|
292 |
-
if (
|
293 |
-
result["input_ids"][-1] != tokenizer.eos_token_id
|
294 |
-
and len(result["input_ids"]) < cutoff_len
|
295 |
-
and add_eos_token
|
296 |
-
):
|
297 |
-
result["input_ids"].append(tokenizer.eos_token_id)
|
298 |
-
result["attention_mask"].append(1)
|
299 |
|
300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
301 |
|
302 |
-
|
|
|
|
|
303 |
|
304 |
-
def generate_and_tokenize_prompt(data_point, add_eos=add_eos_token):
|
305 |
-
full_prompt, _, _ = generate_prompt(data_point, prompt_type, False, False)
|
306 |
-
tokenized_full_prompt = tokenize(full_prompt)
|
307 |
-
if not train_on_inputs:
|
308 |
-
user_prompt, _, _ = generate_prompt({**data_point, "output": ""}, prompt_type, False, False)
|
309 |
-
tokenized_user_prompt = tokenize(user_prompt, add_eos_token=add_eos)
|
310 |
-
user_prompt_len = len(tokenized_user_prompt["input_ids"])
|
311 |
-
if add_eos:
|
312 |
-
user_prompt_len -= 1
|
313 |
-
|
314 |
-
# ignore_index=-100 ensures torch/tf don't include padding token id in CrossEntropyLoss
|
315 |
-
tokenized_full_prompt["labels"] = [
|
316 |
-
-100
|
317 |
-
] * user_prompt_len + tokenized_full_prompt["labels"][
|
318 |
-
user_prompt_len:
|
319 |
-
] # could be sped up, probably
|
320 |
-
return tokenized_full_prompt
|
321 |
-
|
322 |
-
if "gpt-neox" not in base_model or True:
|
323 |
-
model = prepare_model_for_int8_training(model)
|
324 |
-
else:
|
325 |
-
model = prepare_model_for_int8_training(
|
326 |
-
model,
|
327 |
-
output_embedding_layer_name="embed_out", # keep output logits in float32
|
328 |
-
layer_norm_names=["layer_norm", "layernorm"], # keep all layer norms in higher precision
|
329 |
-
)
|
330 |
if lora_weights:
|
|
|
331 |
from peft import PeftModel
|
332 |
model = PeftModel.from_pretrained(
|
333 |
model,
|
@@ -338,7 +293,7 @@ def train(
|
|
338 |
resume_download=resume_download,
|
339 |
use_auth_token=use_auth_token,
|
340 |
)
|
341 |
-
|
342 |
if lora_target_modules is None:
|
343 |
base_model_lower = base_model.lower()
|
344 |
if base_model_lower in lora_mappings:
|
@@ -386,7 +341,11 @@ def train(
|
|
386 |
log(f"Checkpoint {checkpoint_name} not found")
|
387 |
|
388 |
print(model)
|
389 |
-
|
|
|
|
|
|
|
|
|
390 |
|
391 |
metrics = {}
|
392 |
for name in supported_metrics:
|
@@ -405,6 +364,7 @@ def train(
|
|
405 |
elif val_set_size < 1.0 and val_set_size != 0:
|
406 |
raise RuntimeError("Fractional validation size not supported.")
|
407 |
|
|
|
408 |
if valid_path:
|
409 |
data = load_dataset("json", data_files={"train": data_path, "valid": valid_path})
|
410 |
else:
|
@@ -427,10 +387,16 @@ def train(
|
|
427 |
else:
|
428 |
data_mix_in = load_dataset(data_mix_in_path)["train"] # can be large
|
429 |
data_mix_in = data_mix_in.rename_columns(data_mix_in_col_dict or {})
|
|
|
|
|
|
|
|
|
|
|
|
|
430 |
|
431 |
# only get as much as we need to balance
|
432 |
valid_size = min(data_mix_in.num_rows // 2, val_set_size or 0)
|
433 |
-
train_size = max(1, min(data_mix_in.num_rows - valid_size,
|
434 |
mixin_small = data_mix_in.train_test_split(
|
435 |
test_size=train_size + valid_size,
|
436 |
shuffle=True, seed=np.random.randint(10000),
|
@@ -486,10 +452,20 @@ def train(
|
|
486 |
|
487 |
assert train_data is not None
|
488 |
|
|
|
|
|
|
|
|
|
489 |
# shuffle and tokenize data
|
490 |
if train_data_mix_in:
|
491 |
train_data = concatenate_datasets([train_data, train_data_mix_in])
|
492 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
493 |
train_set_size = len(train_data)
|
494 |
|
495 |
if valid_data and valid_data_mix_in:
|
@@ -498,7 +474,8 @@ def train(
|
|
498 |
valid_data = valid_data_mix_in
|
499 |
|
500 |
if valid_data:
|
501 |
-
|
|
|
502 |
val_set_size = len(valid_data)
|
503 |
else:
|
504 |
val_set_size = 0
|
@@ -509,6 +486,22 @@ def train(
|
|
509 |
del sample_row_dict['labels']
|
510 |
log("Sample input: %s" % sample_row_dict)
|
511 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
512 |
if neptune_run:
|
513 |
neptune_callback = NeptuneCallback(run=neptune_run)
|
514 |
callbacks = [neptune_callback]
|
@@ -578,6 +571,7 @@ def train(
|
|
578 |
else:
|
579 |
trainer_kwargs = dict()
|
580 |
|
|
|
581 |
trainer = transformers.Trainer(
|
582 |
model=model,
|
583 |
tokenizer=tokenizer,
|
@@ -605,7 +599,7 @@ def train(
|
|
605 |
eval_steps=eval_steps if val_set_size > 0 else None,
|
606 |
save_steps=save_steps,
|
607 |
output_dir=output_dir,
|
608 |
-
save_total_limit=
|
609 |
load_best_model_at_end=True if val_set_size > 0 else False,
|
610 |
ddp_find_unused_parameters=False if ddp else None,
|
611 |
group_by_length=group_by_length,
|
@@ -622,6 +616,8 @@ def train(
|
|
622 |
model.config.use_cache = False
|
623 |
|
624 |
old_state_dict = model.state_dict
|
|
|
|
|
625 |
model.state_dict = (
|
626 |
lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict())
|
627 |
).__get__(model, type(model))
|
@@ -629,7 +625,8 @@ def train(
|
|
629 |
if torch.__version__ >= "2" and sys.platform != "win32":
|
630 |
model = torch.compile(model)
|
631 |
# WIP (not generally replacing layers until pytorch 2.1)
|
632 |
-
|
|
|
633 |
|
634 |
if gpus > 1 and not ddp:
|
635 |
assert trainer.is_model_parallel
|
@@ -649,6 +646,9 @@ def get_loaders(llama_type, model_name, reward_type):
|
|
649 |
from transformers import LlamaForCausalLM, LlamaTokenizer
|
650 |
model_loader = LlamaForCausalLM
|
651 |
tokenizer_loader = LlamaTokenizer
|
|
|
|
|
|
|
652 |
elif 'gpt2' in model_name.lower():
|
653 |
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
654 |
return GPT2LMHeadModel, GPT2Tokenizer
|
@@ -676,31 +676,76 @@ def get_loaders(llama_type, model_name, reward_type):
|
|
676 |
return model_loader, tokenizer_loader
|
677 |
|
678 |
|
679 |
-
def
|
680 |
-
|
681 |
-
|
682 |
-
|
683 |
-
|
684 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
685 |
|
686 |
|
687 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
688 |
"""
|
689 |
-
|
690 |
-
:param
|
|
|
691 |
:return:
|
692 |
"""
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
|
701 |
-
|
702 |
-
|
703 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
704 |
|
705 |
|
706 |
def get_prompt(prompt_type, chat, context, reduced):
|
@@ -765,7 +810,13 @@ Current Time: {}
|
|
765 |
|
766 |
PreInput = None
|
767 |
|
768 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
769 |
|
770 |
terminate_response = [start, PreResponse]
|
771 |
elif prompt_type in [3, "3", "dai_faq"]:
|
@@ -818,7 +869,7 @@ def generate_prompt(data_point, prompt_type, chat, reduced):
|
|
818 |
assert prompt_type in prompt_types, "Bad prompt type: %s" % prompt_type
|
819 |
promptA, promptB, PreInstruct, PreInput, PreResponse, terminate_response = get_prompt(prompt_type, chat, context, reduced)
|
820 |
|
821 |
-
prompt = context
|
822 |
|
823 |
if input and promptA:
|
824 |
prompt += f"""{promptA}"""
|
|
|
1 |
import os
|
|
|
|
|
|
|
|
|
2 |
import sys
|
3 |
import time
|
4 |
+
from functools import partial
|
5 |
from typing import List, Union
|
6 |
+
from enum import Enum
|
7 |
import fire
|
8 |
import numpy as np
|
9 |
+
from utils import get_githash, copy_code
|
10 |
import torch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
|
13 |
def log(*args, **kwargs):
|
14 |
if int(os.environ.get("LOCAL_RANK", 0)) == 0:
|
15 |
+
if 'flush' not in kwargs:
|
16 |
+
kwargs['flush'] = True
|
17 |
print(*args, **kwargs)
|
18 |
|
19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
class PromptType(Enum):
|
21 |
plain = 0
|
22 |
instruct = 1
|
|
|
54 |
'h2oai/h2ogpt-oasst1-512-12b',
|
55 |
'h2oai/h2ogpt-oasst1-512-20b',
|
56 |
'h2oai/h2ogpt-oig-oasst1-512-6.9b',
|
57 |
+
'h2oai/h2ogpt-research-oasst1-512-30b', # private
|
58 |
],
|
59 |
'dai_faq': [],
|
60 |
'summarize': [],
|
|
|
102 |
tokenizer_base_model: str = None,
|
103 |
# tokenizer_base_model: str = 'EleutherAI/gpt-neox-20b',
|
104 |
|
105 |
+
data_path: str = "h2oai/openassistant_oasst1_h2ogpt",
|
106 |
data_col_dict: dict = None,
|
107 |
# data_path: str = "./dai_docs.train.json",
|
108 |
prompt_type: Union[str, int] = "plain", # "plain", "instruct", "quality", "human_bot", "dai_faq"
|
|
|
126 |
micro_batch_size: int = 4,
|
127 |
gradient_checkpointing=False, # unnecessary with gradient accumulation enabled
|
128 |
fp16=True,
|
129 |
+
train_8bit=True,
|
130 |
|
131 |
# general training hyperparams
|
132 |
num_epochs: float = 1,
|
|
|
144 |
lora_dropout: float = 0.05,
|
145 |
lora_target_modules: List[str] = None,
|
146 |
llama_type: bool = None,
|
147 |
+
llama_flash_attn: bool = False,
|
148 |
|
149 |
# llm hyperparams
|
150 |
train_on_inputs: bool = True, # if False, masks out inputs in loss
|
151 |
group_by_length: bool = False, # if True, faster, but produces an odd training loss curve
|
152 |
resume_from_checkpoint: str = None, # either training checkpoint or final adapter
|
153 |
+
cutoff_len: int = 512, # larger values use more memory
|
154 |
+
drop_truncations: bool = False, # if True, drop any truncated long sequences
|
155 |
|
156 |
# torch training params
|
157 |
ddp: bool = True, # set to False if OOM with True, for multi-GPU model parallelism
|
|
|
161 |
warmup_steps: int = 100,
|
162 |
logging_steps: int = 1,
|
163 |
save_steps: int = None, # must be round multiple of eval_steps
|
164 |
+
save_total_limit: int = 3,
|
165 |
add_eos_token: bool = False,
|
166 |
):
|
167 |
+
|
168 |
+
if llama_flash_attn:
|
169 |
+
# Need to call this before importing transformers.
|
170 |
+
from llama_flash_attn_monkey_patch import replace_llama_attn_with_flash_attn
|
171 |
+
replace_llama_attn_with_flash_attn()
|
172 |
+
|
173 |
# allow set token directly
|
174 |
use_auth_token = os.environ.get("HUGGINGFACE_API_TOKEN", use_auth_token)
|
175 |
|
|
|
189 |
if not output_dir:
|
190 |
output_dir = f"{base_model.split('/')[-1]}.{data_path.replace('/', '')}.{num_epochs}_epochs.{get_githash() or 'nogit'}.{run_id}"
|
191 |
if os.path.exists(output_dir) and not resume_from_checkpoint:
|
192 |
+
raise FileExistsError(f"output_dir {output_dir} based on run_id {run_id} already exists. Please pick a different run_id.")
|
193 |
else:
|
194 |
if os.path.exists(output_dir) and not resume_from_checkpoint:
|
195 |
raise FileExistsError(f"output_dir {output_dir} already exists. Please pick a different output_dir, or specify a run_id instead.")
|
|
|
201 |
tokenizer_base_model = base_model
|
202 |
if llama_type is None:
|
203 |
llama_type = "llama" in base_model.lower()
|
204 |
+
if llama_type and llama_flash_attn:
|
205 |
+
import pkg_resources
|
206 |
+
try:
|
207 |
+
pkg_resources.get_distribution('flash_attn')
|
208 |
+
can_do_flash_attn = True
|
209 |
+
except (pkg_resources.DistributionNotFound, pkg_resources.ContextualVersionConflict):
|
210 |
+
can_do_flash_attn = False
|
211 |
+
|
212 |
+
if not can_do_flash_attn:
|
213 |
+
raise RuntimeError("""Flash attention not installed.
|
214 |
+
NOTE: for current pytorch 2.0, flash attention requires installing cuda 11.7 via https://developer.nvidia.com/cuda-11-7-0-download-archive?target_os=Linux&target_arch=x86_64&Distribution=Ubuntu&target_version=20.04&target_type=runfile_local and then when running, to avoid installing driver, docs, samples, just install toolkit. Then when pip installing flash attention do:
|
215 |
+
|
216 |
+
CUDA_HOME=/usr/local/cuda-11.7 pip install flash-attn""")
|
217 |
+
from llama_flash_attn_monkey_patch import replace_llama_attn_with_flash_attn
|
218 |
+
replace_llama_attn_with_flash_attn()
|
219 |
assert (
|
220 |
base_model
|
221 |
), "Please specify a --base_model, e.g. --base_model='decapoda-research/llama-7b-hf'"
|
|
|
247 |
|
248 |
model = model_loader.from_pretrained(
|
249 |
base_model,
|
250 |
+
load_in_8bit=train_8bit,
|
251 |
device_map=device_map,
|
252 |
torch_dtype=torch.float16,
|
253 |
max_memory=max_memory,
|
|
|
261 |
model.is_parallelizable = True
|
262 |
model.model_parallel = True
|
263 |
|
264 |
+
tokenizer = get_tokenizer(tokenizer_loader, tokenizer_base_model, local_files_only, resume_download, use_auth_token)
|
|
|
|
|
|
|
265 |
|
266 |
+
if train_8bit:
|
267 |
+
from peft import (
|
268 |
+
prepare_model_for_int8_training,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
269 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
270 |
|
271 |
+
if "gpt-neox" not in base_model or True:
|
272 |
+
model = prepare_model_for_int8_training(model)
|
273 |
+
else:
|
274 |
+
model = prepare_model_for_int8_training(
|
275 |
+
model,
|
276 |
+
output_embedding_layer_name="embed_out", # keep output logits in float32
|
277 |
+
layer_norm_names=["layer_norm", "layernorm"], # keep all layer norms in higher precision
|
278 |
+
)
|
279 |
|
280 |
+
from peft import LoraConfig, get_peft_model, set_peft_model_state_dict, utils
|
281 |
+
lora_mappings = utils.TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy()
|
282 |
+
lora_mappings['distilgpt2'] = ["c_attn"]
|
283 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
284 |
if lora_weights:
|
285 |
+
|
286 |
from peft import PeftModel
|
287 |
model = PeftModel.from_pretrained(
|
288 |
model,
|
|
|
293 |
resume_download=resume_download,
|
294 |
use_auth_token=use_auth_token,
|
295 |
)
|
296 |
+
elif lora_r > 0:
|
297 |
if lora_target_modules is None:
|
298 |
base_model_lower = base_model.lower()
|
299 |
if base_model_lower in lora_mappings:
|
|
|
341 |
log(f"Checkpoint {checkpoint_name} not found")
|
342 |
|
343 |
print(model)
|
344 |
+
try:
|
345 |
+
# only for PeftModel
|
346 |
+
model.print_trainable_parameters() # Be more transparent about the % of trainable params.
|
347 |
+
except:
|
348 |
+
pass
|
349 |
|
350 |
metrics = {}
|
351 |
for name in supported_metrics:
|
|
|
364 |
elif val_set_size < 1.0 and val_set_size != 0:
|
365 |
raise RuntimeError("Fractional validation size not supported.")
|
366 |
|
367 |
+
from datasets import load_dataset, concatenate_datasets
|
368 |
if valid_path:
|
369 |
data = load_dataset("json", data_files={"train": data_path, "valid": valid_path})
|
370 |
else:
|
|
|
387 |
else:
|
388 |
data_mix_in = load_dataset(data_mix_in_path)["train"] # can be large
|
389 |
data_mix_in = data_mix_in.rename_columns(data_mix_in_col_dict or {})
|
390 |
+
mix_in_rows = int(num_rows * data_mix_in_factor)
|
391 |
+
|
392 |
+
if mix_in_rows > data_mix_in.num_rows:
|
393 |
+
# duplicate rows if mix-in is smaller than required
|
394 |
+
log("Duplicating mixin to compensate for its size for training size and mixin fraction")
|
395 |
+
data_mix_in = concatenate_datasets([data_mix_in] * int(np.ceil(mix_in_rows / data_mix_in.num_rows)))
|
396 |
|
397 |
# only get as much as we need to balance
|
398 |
valid_size = min(data_mix_in.num_rows // 2, val_set_size or 0)
|
399 |
+
train_size = max(1, min(data_mix_in.num_rows - valid_size, mix_in_rows))
|
400 |
mixin_small = data_mix_in.train_test_split(
|
401 |
test_size=train_size + valid_size,
|
402 |
shuffle=True, seed=np.random.randint(10000),
|
|
|
452 |
|
453 |
assert train_data is not None
|
454 |
|
455 |
+
generate_and_tokenize_prompt_fun = partial(generate_and_tokenize_prompt, prompt_type=prompt_type,
|
456 |
+
train_on_inputs=train_on_inputs, add_eos_token=add_eos_token,
|
457 |
+
cutoff_len=cutoff_len, tokenizer=tokenizer)
|
458 |
+
|
459 |
# shuffle and tokenize data
|
460 |
if train_data_mix_in:
|
461 |
train_data = concatenate_datasets([train_data, train_data_mix_in])
|
462 |
+
log("Tokenizing %s training rows" % train_data.num_rows)
|
463 |
+
train_data = train_data.shuffle().map(generate_and_tokenize_prompt_fun, num_proc=os.cpu_count() // torch.cuda.device_count())
|
464 |
+
if drop_truncations:
|
465 |
+
log("avoid keeping truncated cases to avoid contaminating model with truncation cases. Original size: %s" % train_data.num_rows)
|
466 |
+
prune_long_sequences_func = partial(prune_long_sequences, cutoff_len=cutoff_len)
|
467 |
+
train_data = train_data.filter(prune_long_sequences_func, num_proc=os.cpu_count() // torch.cuda.device_count())
|
468 |
+
log("avoid keeping truncated cases to avoid contaminating model with truncation cases. New size: %s" % train_data.num_rows)
|
469 |
train_set_size = len(train_data)
|
470 |
|
471 |
if valid_data and valid_data_mix_in:
|
|
|
474 |
valid_data = valid_data_mix_in
|
475 |
|
476 |
if valid_data:
|
477 |
+
log("Tokenizing %s validation rows" % valid_data.num_rows)
|
478 |
+
valid_data = valid_data.shuffle().map(generate_and_tokenize_prompt_fun, num_proc=os.cpu_count() // torch.cuda.device_count())
|
479 |
val_set_size = len(valid_data)
|
480 |
else:
|
481 |
val_set_size = 0
|
|
|
486 |
del sample_row_dict['labels']
|
487 |
log("Sample input: %s" % sample_row_dict)
|
488 |
|
489 |
+
try:
|
490 |
+
import neptune
|
491 |
+
from transformers.integrations import NeptuneCallback
|
492 |
+
|
493 |
+
neptune_run = neptune.init_run(
|
494 |
+
source_files=[],
|
495 |
+
)
|
496 |
+
log("Connected to Neptune.")
|
497 |
+
except ImportError:
|
498 |
+
neptune_run = None
|
499 |
+
log("Please pip install neptune for tracking.")
|
500 |
+
except neptune.exceptions.NeptuneMissingApiTokenException:
|
501 |
+
neptune_run = None
|
502 |
+
os.environ["NEPTUNE_MODE"] = 'debug'
|
503 |
+
log("No neptune configured, set NEPTUNE_API_TOKEN env var.")
|
504 |
+
|
505 |
if neptune_run:
|
506 |
neptune_callback = NeptuneCallback(run=neptune_run)
|
507 |
callbacks = [neptune_callback]
|
|
|
571 |
else:
|
572 |
trainer_kwargs = dict()
|
573 |
|
574 |
+
import transformers
|
575 |
trainer = transformers.Trainer(
|
576 |
model=model,
|
577 |
tokenizer=tokenizer,
|
|
|
599 |
eval_steps=eval_steps if val_set_size > 0 else None,
|
600 |
save_steps=save_steps,
|
601 |
output_dir=output_dir,
|
602 |
+
save_total_limit=save_total_limit,
|
603 |
load_best_model_at_end=True if val_set_size > 0 else False,
|
604 |
ddp_find_unused_parameters=False if ddp else None,
|
605 |
group_by_length=group_by_length,
|
|
|
616 |
model.config.use_cache = False
|
617 |
|
618 |
old_state_dict = model.state_dict
|
619 |
+
from peft import get_peft_model_state_dict
|
620 |
+
|
621 |
model.state_dict = (
|
622 |
lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict())
|
623 |
).__get__(model, type(model))
|
|
|
625 |
if torch.__version__ >= "2" and sys.platform != "win32":
|
626 |
model = torch.compile(model)
|
627 |
# WIP (not generally replacing layers until pytorch 2.1)
|
628 |
+
if not llama_flash_attn:
|
629 |
+
torch.backends.cuda.enable_flash_sdp(True)
|
630 |
|
631 |
if gpus > 1 and not ddp:
|
632 |
assert trainer.is_model_parallel
|
|
|
646 |
from transformers import LlamaForCausalLM, LlamaTokenizer
|
647 |
model_loader = LlamaForCausalLM
|
648 |
tokenizer_loader = LlamaTokenizer
|
649 |
+
elif 'distilgpt2' in model_name.lower():
|
650 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
651 |
+
return AutoModelForCausalLM, AutoTokenizer
|
652 |
elif 'gpt2' in model_name.lower():
|
653 |
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
654 |
return GPT2LMHeadModel, GPT2Tokenizer
|
|
|
676 |
return model_loader, tokenizer_loader
|
677 |
|
678 |
|
679 |
+
def get_tokenizer(tokenizer_loader, tokenizer_base_model, local_files_only, resume_download, use_auth_token):
|
680 |
+
tokenizer = tokenizer_loader.from_pretrained(tokenizer_base_model,
|
681 |
+
local_files_only=local_files_only,
|
682 |
+
resume_download=resume_download,
|
683 |
+
use_auth_token=use_auth_token)
|
684 |
+
|
685 |
+
tokenizer.pad_token_id = 0 # different from the eos token
|
686 |
+
# when generating, we will use the logits of right-most token to predict the next token
|
687 |
+
# so the padding should be on the left,
|
688 |
+
# e.g. see: https://huggingface.co/transformers/v4.11.3/model_doc/t5.html#inference
|
689 |
+
tokenizer.padding_side = "left" # Allow batched inference
|
690 |
+
|
691 |
+
return tokenizer
|
692 |
|
693 |
|
694 |
+
def tokenize(prompt, tokenizer, cutoff_len, add_eos_token=False):
|
695 |
+
# there's probably a way to do this with the tokenizer settings
|
696 |
+
# but again, gotta move fast
|
697 |
+
result = tokenizer(
|
698 |
+
prompt,
|
699 |
+
truncation=True,
|
700 |
+
max_length=cutoff_len,
|
701 |
+
padding=False,
|
702 |
+
return_tensors=None,
|
703 |
+
)
|
704 |
+
if (
|
705 |
+
result["input_ids"][-1] != tokenizer.eos_token_id
|
706 |
+
and len(result["input_ids"]) < cutoff_len
|
707 |
+
and add_eos_token
|
708 |
+
):
|
709 |
+
result["input_ids"].append(tokenizer.eos_token_id)
|
710 |
+
result["attention_mask"].append(1)
|
711 |
+
|
712 |
+
result["labels"] = result["input_ids"].copy()
|
713 |
+
|
714 |
+
return result
|
715 |
+
|
716 |
+
|
717 |
+
def prune_long_sequences(data_point, cutoff_len=None):
|
718 |
"""
|
719 |
+
Prune if too long for tokenizer, so truncation doesn't lead training to learn from truncated language
|
720 |
+
:param data_point:
|
721 |
+
:param cutoff_len:
|
722 |
:return:
|
723 |
"""
|
724 |
+
assert cutoff_len is not None
|
725 |
+
return len(data_point['input_ids']) < cutoff_len
|
726 |
+
|
727 |
+
|
728 |
+
def generate_and_tokenize_prompt(data_point, prompt_type=None, train_on_inputs=False, add_eos_token=False,
|
729 |
+
cutoff_len=None, tokenizer=None):
|
730 |
+
assert prompt_type is not None
|
731 |
+
assert cutoff_len is not None
|
732 |
+
assert tokenizer is not None
|
733 |
+
full_prompt, _, _ = generate_prompt(data_point, prompt_type, False, False)
|
734 |
+
tokenized_full_prompt = tokenize(full_prompt, tokenizer, cutoff_len, add_eos_token=add_eos_token)
|
735 |
+
if not train_on_inputs:
|
736 |
+
user_prompt, _, _ = generate_prompt({**data_point, "output": ""}, prompt_type, False, False)
|
737 |
+
tokenized_user_prompt = tokenize(user_prompt, tokenizer, cutoff_len, add_eos_token=add_eos_token)
|
738 |
+
user_prompt_len = len(tokenized_user_prompt["input_ids"])
|
739 |
+
if add_eos_token:
|
740 |
+
user_prompt_len -= 1
|
741 |
+
|
742 |
+
# ignore_index=-100 ensures torch/tf don't include padding token id in CrossEntropyLoss
|
743 |
+
tokenized_full_prompt["labels"] = [
|
744 |
+
-100
|
745 |
+
] * user_prompt_len + tokenized_full_prompt["labels"][
|
746 |
+
user_prompt_len:
|
747 |
+
] # could be sped up, probably
|
748 |
+
return tokenized_full_prompt
|
749 |
|
750 |
|
751 |
def get_prompt(prompt_type, chat, context, reduced):
|
|
|
810 |
|
811 |
PreInput = None
|
812 |
|
813 |
+
if reduced:
|
814 |
+
# when making context, want it to appear as-if LLM generated, which starts with space after :
|
815 |
+
PreResponse = bot + ' '
|
816 |
+
else:
|
817 |
+
# normally LLM adds space after this, because was how trained.
|
818 |
+
# if add space here, non-unique tokenization will often make LLM produce wrong output
|
819 |
+
PreResponse = bot
|
820 |
|
821 |
terminate_response = [start, PreResponse]
|
822 |
elif prompt_type in [3, "3", "dai_faq"]:
|
|
|
869 |
assert prompt_type in prompt_types, "Bad prompt type: %s" % prompt_type
|
870 |
promptA, promptB, PreInstruct, PreInput, PreResponse, terminate_response = get_prompt(prompt_type, chat, context, reduced)
|
871 |
|
872 |
+
prompt = context if not reduced else ''
|
873 |
|
874 |
if input and promptA:
|
875 |
prompt += f"""{promptA}"""
|
requirements.txt
CHANGED
@@ -19,9 +19,10 @@ pandas==2.0.0
|
|
19 |
matplotlib==3.7.1
|
20 |
loralib==0.1.1
|
21 |
bitsandbytes==0.38.1
|
22 |
-
git+https://github.com/huggingface/peft.git@
|
23 |
transformers==4.28.1
|
24 |
tokenizers==0.13.3
|
|
|
25 |
|
26 |
# optional for generate
|
27 |
pynvml==11.5.0
|
|
|
19 |
matplotlib==3.7.1
|
20 |
loralib==0.1.1
|
21 |
bitsandbytes==0.38.1
|
22 |
+
git+https://github.com/huggingface/peft.git@e8f66b8a425eced6c592089d40b8d33d82c2b2f0
|
23 |
transformers==4.28.1
|
24 |
tokenizers==0.13.3
|
25 |
+
APScheduler==3.10.1
|
26 |
|
27 |
# optional for generate
|
28 |
pynvml==11.5.0
|
stopping.py
CHANGED
@@ -25,115 +25,3 @@ class StoppingCriteriaSub(StoppingCriteria):
|
|
25 |
# print("Tokens: %s" % input_ids[0].cpu().numpy(), flush=True)
|
26 |
# print("Stop Tokens: %s" % [x.cpu().numpy() for x in self.stops], flush=True)
|
27 |
return False
|
28 |
-
|
29 |
-
|
30 |
-
class Stream(StoppingCriteria):
|
31 |
-
"""
|
32 |
-
This class can be used to callback during generation. Keep
|
33 |
-
in mind for decoder-only type of transformers, this will include the initial prompted tokens.
|
34 |
-
|
35 |
-
Args:
|
36 |
-
func (`callable`):
|
37 |
-
A callable function to apply on first input in list every iteration of generation
|
38 |
-
"""
|
39 |
-
|
40 |
-
def __init__(self, func=None):
|
41 |
-
self.func = func
|
42 |
-
|
43 |
-
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
44 |
-
if self.func is not None:
|
45 |
-
# only consume first of multiple responses
|
46 |
-
self.func(input_ids[0])
|
47 |
-
return False
|
48 |
-
|
49 |
-
|
50 |
-
class CallbackToGenerator(collections.abc.Generator):
|
51 |
-
"""
|
52 |
-
A generator wrapper for a function that invokes a callback multiple times.
|
53 |
-
|
54 |
-
Calling `send` on the generator emits a value from one callback, and returns
|
55 |
-
the next.
|
56 |
-
|
57 |
-
Note this starts a background thread
|
58 |
-
"""
|
59 |
-
|
60 |
-
def __init__(self, func, *args, callback=None, **kwargs):
|
61 |
-
self.func = func
|
62 |
-
self.args = args
|
63 |
-
self.kwargs = kwargs
|
64 |
-
self.callback = callback
|
65 |
-
|
66 |
-
self._ready_queue = Queue(1)
|
67 |
-
self._done_queue = Queue(1)
|
68 |
-
self._done_holder = [False]
|
69 |
-
|
70 |
-
# local to avoid reference cycles
|
71 |
-
ready_queue = self._ready_queue
|
72 |
-
done_queue = self._done_queue
|
73 |
-
done_holder = self._done_holder
|
74 |
-
|
75 |
-
def val_callback(value):
|
76 |
-
done_queue.put((False, value))
|
77 |
-
cmd, val = ready_queue.get()
|
78 |
-
if cmd == 'send':
|
79 |
-
return val
|
80 |
-
elif cmd == 'throw':
|
81 |
-
raise val
|
82 |
-
else:
|
83 |
-
assert False # pragma: no cover
|
84 |
-
|
85 |
-
def thread_func():
|
86 |
-
while True:
|
87 |
-
cmd, val = ready_queue.get()
|
88 |
-
if cmd == 'send' and val is not None:
|
89 |
-
done_queue.put((True, TypeError("can't send non-None value to a just-started generator")))
|
90 |
-
continue
|
91 |
-
break
|
92 |
-
try:
|
93 |
-
if cmd == 'throw':
|
94 |
-
raise val
|
95 |
-
ret = func(callback=val_callback, **self.kwargs)
|
96 |
-
raise StopIteration(ret) if ret is not None else StopIteration
|
97 |
-
except BaseException as e:
|
98 |
-
done_holder[0] = True
|
99 |
-
done_queue.put((True, e))
|
100 |
-
|
101 |
-
self._thread = Thread(target=thread_func)
|
102 |
-
self._thread.start()
|
103 |
-
|
104 |
-
def _put(self, *args):
|
105 |
-
if self._done_holder[0]:
|
106 |
-
raise StopIteration
|
107 |
-
self._ready_queue.put(args)
|
108 |
-
is_exception, val = self._done_queue.get()
|
109 |
-
if is_exception:
|
110 |
-
try:
|
111 |
-
raise val
|
112 |
-
finally:
|
113 |
-
# prevent val's traceback containing a reference cycle
|
114 |
-
del val
|
115 |
-
else:
|
116 |
-
return val
|
117 |
-
|
118 |
-
def send(self, value):
|
119 |
-
return self._put('send', value)
|
120 |
-
|
121 |
-
def throw(self, exc):
|
122 |
-
return self._put('throw', exc)
|
123 |
-
|
124 |
-
def close(self):
|
125 |
-
try:
|
126 |
-
self.throw(GeneratorExit)
|
127 |
-
except StopIteration:
|
128 |
-
self._thread.join()
|
129 |
-
except GeneratorExit:
|
130 |
-
self._thread.join()
|
131 |
-
except BaseException:
|
132 |
-
self._thread.join()
|
133 |
-
raise
|
134 |
-
else:
|
135 |
-
# yielded again, can't clean up the thread
|
136 |
-
raise RuntimeError('Task with callback ignored GeneratorExit')
|
137 |
-
|
138 |
-
def __del__(self):
|
139 |
-
self.close()
|
|
|
25 |
# print("Tokens: %s" % input_ids[0].cpu().numpy(), flush=True)
|
26 |
# print("Stop Tokens: %s" % [x.cpu().numpy() for x in self.stops], flush=True)
|
27 |
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils.py
CHANGED
@@ -1,6 +1,12 @@
|
|
|
|
1 |
import os
|
2 |
import gc
|
|
|
3 |
import random
|
|
|
|
|
|
|
|
|
4 |
import time
|
5 |
import traceback
|
6 |
import zipfile
|
@@ -8,7 +14,6 @@ from datetime import datetime
|
|
8 |
import filelock
|
9 |
import numpy as np
|
10 |
import pandas as pd
|
11 |
-
import torch
|
12 |
|
13 |
|
14 |
def set_seed(seed: int):
|
@@ -16,6 +21,7 @@ def set_seed(seed: int):
|
|
16 |
Sets the seed of the entire notebook so results are the same every time we run.
|
17 |
This is for REPRODUCIBILITY.
|
18 |
"""
|
|
|
19 |
np.random.seed(seed)
|
20 |
random_state = np.random.RandomState(seed)
|
21 |
random.seed(seed)
|
@@ -39,12 +45,18 @@ def flatten_list(lis):
|
|
39 |
|
40 |
|
41 |
def clear_torch_cache():
|
|
|
42 |
if torch.cuda.is_available:
|
43 |
torch.cuda.empty_cache()
|
44 |
torch.cuda.ipc_collect()
|
45 |
gc.collect()
|
46 |
|
47 |
|
|
|
|
|
|
|
|
|
|
|
48 |
def system_info():
|
49 |
import psutil
|
50 |
|
@@ -184,3 +196,111 @@ def _s3up(filename):
|
|
184 |
)
|
185 |
if ret in [None, '']:
|
186 |
return "Successfully uploaded %s" % filename
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import functools
|
2 |
import os
|
3 |
import gc
|
4 |
+
import pathlib
|
5 |
import random
|
6 |
+
import shutil
|
7 |
+
import subprocess
|
8 |
+
import sys
|
9 |
+
import threading
|
10 |
import time
|
11 |
import traceback
|
12 |
import zipfile
|
|
|
14 |
import filelock
|
15 |
import numpy as np
|
16 |
import pandas as pd
|
|
|
17 |
|
18 |
|
19 |
def set_seed(seed: int):
|
|
|
21 |
Sets the seed of the entire notebook so results are the same every time we run.
|
22 |
This is for REPRODUCIBILITY.
|
23 |
"""
|
24 |
+
import torch
|
25 |
np.random.seed(seed)
|
26 |
random_state = np.random.RandomState(seed)
|
27 |
random.seed(seed)
|
|
|
45 |
|
46 |
|
47 |
def clear_torch_cache():
|
48 |
+
import torch
|
49 |
if torch.cuda.is_available:
|
50 |
torch.cuda.empty_cache()
|
51 |
torch.cuda.ipc_collect()
|
52 |
gc.collect()
|
53 |
|
54 |
|
55 |
+
def get_torch_allocated():
|
56 |
+
import torch
|
57 |
+
return torch.cuda.memory_allocated()
|
58 |
+
|
59 |
+
|
60 |
def system_info():
|
61 |
import psutil
|
62 |
|
|
|
196 |
)
|
197 |
if ret in [None, '']:
|
198 |
return "Successfully uploaded %s" % filename
|
199 |
+
|
200 |
+
|
201 |
+
def get_githash():
|
202 |
+
try:
|
203 |
+
githash = subprocess.run(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE).stdout.decode('utf-8')[0:-1]
|
204 |
+
except:
|
205 |
+
githash = ''
|
206 |
+
return githash
|
207 |
+
|
208 |
+
|
209 |
+
def copy_code(run_id):
|
210 |
+
"""
|
211 |
+
copy code to track changes
|
212 |
+
:param run_id:
|
213 |
+
:return:
|
214 |
+
"""
|
215 |
+
rnd_num = str(random.randint(0, 2 ** 31))
|
216 |
+
run_id = 'run_' + str(run_id)
|
217 |
+
os.makedirs(run_id, exist_ok=True)
|
218 |
+
me_full = os.path.join(pathlib.Path(__file__).parent.resolve(), __file__)
|
219 |
+
me_file = os.path.basename(__file__)
|
220 |
+
new_me = os.path.join(run_id, me_file + '_' + get_githash())
|
221 |
+
if os.path.isfile(new_me):
|
222 |
+
new_me = os.path.join(run_id, me_file + '_' + get_githash() + '_' + rnd_num)
|
223 |
+
shutil.copy(me_full, new_me)
|
224 |
+
else:
|
225 |
+
shutil.copy(me_full, new_me)
|
226 |
+
|
227 |
+
|
228 |
+
class NullContext(threading.local):
|
229 |
+
"""No-op context manager, executes block without doing any additional processing.
|
230 |
+
|
231 |
+
Used as a stand-in if a particular block of code is only sometimes
|
232 |
+
used with a normal context manager:
|
233 |
+
"""
|
234 |
+
def __init__(self, *args, **kwargs):
|
235 |
+
pass
|
236 |
+
|
237 |
+
def __enter__(self):
|
238 |
+
return self
|
239 |
+
|
240 |
+
def __exit__(self, exc_type, exc_value, exc_traceback):
|
241 |
+
self.finally_act()
|
242 |
+
|
243 |
+
def finally_act(self):
|
244 |
+
pass
|
245 |
+
|
246 |
+
|
247 |
+
class KThread(threading.Thread):
|
248 |
+
"""Thread with a kill method."""
|
249 |
+
|
250 |
+
def __init__(self, *args, **keywords):
|
251 |
+
threading.Thread.__init__(self, *args, **keywords)
|
252 |
+
self.killed = False
|
253 |
+
|
254 |
+
def start(self):
|
255 |
+
"""Start the thread."""
|
256 |
+
self.__run_backup = self.run
|
257 |
+
self.run = self.__run # Force the Thread to install our trace.
|
258 |
+
threading.Thread.start(self)
|
259 |
+
|
260 |
+
def __run(self):
|
261 |
+
"""install trace."""
|
262 |
+
sys.settrace(self.globaltrace)
|
263 |
+
self.__run_backup()
|
264 |
+
self.run = self.__run_backup
|
265 |
+
|
266 |
+
def globaltrace(self, frame, why, arg):
|
267 |
+
if why == 'call':
|
268 |
+
return self.localtrace
|
269 |
+
else:
|
270 |
+
return None
|
271 |
+
|
272 |
+
def localtrace(self, frame, why, arg):
|
273 |
+
if self.killed:
|
274 |
+
if why == 'line':
|
275 |
+
raise SystemExit()
|
276 |
+
return self.localtrace
|
277 |
+
|
278 |
+
def kill(self):
|
279 |
+
self.killed = True
|
280 |
+
|
281 |
+
@staticmethod
|
282 |
+
def show_threads():
|
283 |
+
for thread in threading.enumerate():
|
284 |
+
print(thread.name, flush=True)
|
285 |
+
|
286 |
+
@staticmethod
|
287 |
+
def kill_threads(name):
|
288 |
+
for thread in threading.enumerate():
|
289 |
+
if name in thread.name:
|
290 |
+
print(thread)
|
291 |
+
print("Trying to kill %s" % thread.ident)
|
292 |
+
thread.kill()
|
293 |
+
print(thread)
|
294 |
+
|
295 |
+
|
296 |
+
def wrapped_partial(func, *args, **kwargs):
|
297 |
+
"""
|
298 |
+
Give partial properties of normal function, like __name__ attribute etc.
|
299 |
+
:param func:
|
300 |
+
:param args:
|
301 |
+
:param kwargs:
|
302 |
+
:return:
|
303 |
+
"""
|
304 |
+
partial_func = functools.partial(func, *args, **kwargs)
|
305 |
+
functools.update_wrapper(partial_func, func)
|
306 |
+
return partial_func
|