| import torch |
| from peft import PeftModel |
| from transformers import AutoModelForCausalLM, AutoTokenizer, LlamaTokenizer, StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer |
|
|
| model_name = "../llama/llama_weight/Llama-2-7b-hf" |
| adapters_name = '../ctranslate2/checkpoint/base' |
|
|
| print(f"Starting to load the model {model_name} into memory") |
|
|
| m = AutoModelForCausalLM.from_pretrained( |
| model_name, |
| |
| torch_dtype=torch.float16, |
| device_map="auto" |
| ) |
| print("finishend load model") |
| m = PeftModel.from_pretrained(m, adapters_name) |
| m = m.merge_and_unload() |
| print("finished merge model") |
| tok = LlamaTokenizer.from_pretrained(model_name) |
| tok.model_max_length=8192 |
| |
|
|
| stop_token_ids = [0] |
|
|
| print(f"Successfully loaded the model {model_name} into memory") |
|
|
|
|
| import datetime |
| import os |
| from threading import Event, Thread |
| from uuid import uuid4 |
|
|
| import gradio as gr |
| import requests |
|
|
| max_new_tokens = 1536 |
| start_message = """A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.""" |
|
|
| ORCA_PROMPT_DICT={"prompt_no_input":( |
| "### System:\n" |
| "You are an AI assistant that follows instruction extremely well. Help as much as you can." |
| "\n\n### User:\n" |
| ), |
| "prompt_input":( |
| "### System:\n" |
| "You are an AI assistant that follows instruction extremely well. Help as much as you can.\n\n" |
| "### User:\n" |
| "{instruction}" |
| "\n\n### Input:\n" |
| "{input}" |
| "\n\n### Response:" |
| )} |
|
|
| ORCA_PROMPT_DICT={"prompt_no_input":( |
| "### System:\n" |
| "You are an AI assistant that follows instruction extremely well. Help as much as you can.") |
| } |
|
|
| PROMPT_DICT = { |
| "prompt_input": ( |
| "Below is an instruction that describes a task, paired with an input that provides further context. " |
| "Write a response that appropriately completes the request.\n\n" |
| "### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:" |
| ), |
| "prompt_no_input": ( |
| "Below is an instruction that describes a task. " |
| "Write a response that appropriately completes the request.\n\n" |
| "{instruction}\n\n### Response:" |
| ), |
| } |
|
|
|
|
| llama2_prompt ={ "prompt_no_input":"""[INST] <<SYS>> |
| You are a helpful, respectful and honest assistant.Help as much as you can. |
| <</SYS>> |
| |
| {instruction} [/INST] """} |
|
|
| class StopOnTokens(StoppingCriteria): |
| def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: |
| for stop_id in stop_token_ids: |
| if input_ids[0][-1] == stop_id: |
| return True |
| return False |
|
|
|
|
| def convert_history_to_text(history): |
| if len(history) > 10: |
| print("*"*30) |
| print("回话超过10轮,重新启动新的会话") |
| history = history[10:] |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| start_msg = llama2_prompt['prompt_no_input'].format_map({"instruction":history[0][0]}) |
| if len(history) > 1: |
| start_msg = start_msg + history[0][1] + "</s>" |
| for dialogue_his in history[1:-1]: |
| start_msg += f"<s>[INST] {dialogue_his[0]}[/INST]" |
| start_msg += f"{dialogue_his[1]}</s>" |
| if len(history) > 1: |
| start_msg += f"<s> [INST] {history[-1][0]} [/INST]" |
| print(f"input msg:{start_msg}") |
| return start_msg |
|
|
|
|
| def log_conversation(conversation_id, history, messages, generate_kwargs): |
| logging_url = os.getenv("LOGGING_URL", None) |
| if logging_url is None: |
| return |
|
|
| timestamp = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") |
|
|
| data = { |
| "conversation_id": conversation_id, |
| "timestamp": timestamp, |
| "history": history, |
| "messages": messages, |
| "generate_kwargs": generate_kwargs, |
| } |
|
|
| try: |
| print(f"data:{data}") |
| requests.post(logging_url, json=data) |
| except requests.exceptions.RequestException as e: |
| print(f"Error logging conversation: {e}") |
|
|
|
|
| def user(message, history): |
| |
| return "", history + [[message, ""]] |
|
|
|
|
| def bot(history, temperature, top_p, top_k, repetition_penalty, conversation_id): |
| print(f"history: {history}") |
| |
| stop = StopOnTokens() |
|
|
| |
| messages = convert_history_to_text(history) |
|
|
| |
| input_ids = tok(messages, return_tensors="pt").input_ids |
| input_ids = input_ids.to(m.device) |
| streamer = TextIteratorStreamer(tok, timeout=10.0, skip_prompt=True, skip_special_tokens=True) |
| generate_kwargs = dict( |
| input_ids=input_ids, |
| max_new_tokens=max_new_tokens, |
| temperature=temperature, |
| do_sample=temperature > 0.0, |
| top_p=top_p, |
| top_k=top_k, |
| num_beams=1, |
| repetition_penalty=repetition_penalty, |
| streamer=streamer, |
| stopping_criteria=StoppingCriteriaList([stop]), |
| ) |
|
|
| stream_complete = Event() |
|
|
| def generate_and_signal_complete(): |
| m.generate(**generate_kwargs) |
| stream_complete.set() |
|
|
| def log_after_stream_complete(): |
| stream_complete.wait() |
| log_conversation( |
| conversation_id, |
| history, |
| messages, |
| { |
| "top_k": top_k, |
| "top_p": top_p, |
| "temperature": temperature, |
| "repetition_penalty": repetition_penalty, |
| }, |
| ) |
|
|
| t1 = Thread(target=generate_and_signal_complete) |
| t1.start() |
|
|
| t2 = Thread(target=log_after_stream_complete) |
| t2.start() |
|
|
| |
| partial_text = "" |
| for new_text in streamer: |
| partial_text += new_text |
| history[-1][1] = partial_text |
| yield history |
|
|
|
|
| def get_uuid(): |
| return str(uuid4()) |
|
|
|
|
| with gr.Blocks( |
| theme=gr.themes.Soft(), |
| css=".disclaimer {font-variant-caps: all-small-caps;}", |
| ) as demo: |
| conversation_id = gr.State(get_uuid) |
| gr.Markdown( |
| """得物客服智能机器人 |
| """ |
| ) |
| chatbot = gr.Chatbot().style(height=500) |
| with gr.Row(): |
| with gr.Column(): |
| msg = gr.Textbox( |
| label="Chat Message Box", |
| placeholder="聊天输入框", |
| show_label=False, |
| ).style(container=False) |
| with gr.Column(): |
| with gr.Row(): |
| submit = gr.Button("Submit") |
| stop = gr.Button("Stop") |
| clear = gr.Button("Clear") |
| with gr.Row(): |
| with gr.Accordion("Advanced Options:", open=False): |
| with gr.Row(): |
| with gr.Column(): |
| with gr.Row(): |
| temperature = gr.Slider( |
| label="Temperature", |
| value=0.8, |
| minimum=0.0, |
| maximum=1.0, |
| step=0.1, |
| interactive=True, |
| info="Higher values produce more diverse outputs", |
| ) |
| with gr.Column(): |
| with gr.Row(): |
| top_p = gr.Slider( |
| label="Top-p (nucleus sampling)", |
| value=0.83, |
| minimum=0.0, |
| maximum=1, |
| step=0.01, |
| interactive=True, |
| info=( |
| "Sample from the smallest possible set of tokens whose cumulative probability " |
| "exceeds top_p. Set to 1 to disable and sample from all tokens." |
| ), |
| ) |
| with gr.Column(): |
| with gr.Row(): |
| top_k = gr.Slider( |
| label="Top-k", |
| value=4, |
| minimum=0.0, |
| maximum=200, |
| step=1, |
| interactive=True, |
| info="Sample from a shortlist of top-k tokens — 0 to disable and sample from all tokens.", |
| ) |
| with gr.Column(): |
| with gr.Row(): |
| repetition_penalty = gr.Slider( |
| label="Repetition Penalty", |
| value=1.3, |
| minimum=1.0, |
| maximum=2.0, |
| step=0.1, |
| interactive=True, |
| info="Penalize repetition — 1.0 to disable.", |
| ) |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| with gr.Row(): |
| gr.Markdown( |
| "免责声明:该模型可能会产生与事实不符的输出,不应依赖该模型来产生与事实相符的信息。模型在各种公共数据集以及得物一些商品信息进行训练。尽管做了大量的数据清洗,但是模型的输出结果还可能存在一些问题", |
| elem_classes=["disclaimer"], |
| ) |
| with gr.Row(): |
| gr.Markdown( |
| "算法二组", |
| elem_classes=["disclaimer"], |
| ) |
|
|
| submit_event = msg.submit( |
| fn=user, |
| inputs=[msg, chatbot], |
| outputs=[msg, chatbot], |
| queue=False, |
| ).then( |
| fn=bot, |
| inputs=[ |
| chatbot, |
| temperature, |
| top_p, |
| top_k, |
| repetition_penalty, |
| conversation_id, |
| ], |
| outputs=chatbot, |
| queue=True, |
| ) |
| submit_click_event = submit.click( |
| fn=user, |
| inputs=[msg, chatbot], |
| outputs=[msg, chatbot], |
| queue=False, |
| ).then( |
| fn=bot, |
| inputs=[ |
| chatbot, |
| temperature, |
| top_p, |
| top_k, |
| repetition_penalty, |
| conversation_id, |
| ], |
| outputs=chatbot, |
| queue=True, |
| ) |
| stop.click( |
| fn=None, |
| inputs=None, |
| outputs=None, |
| cancels=[submit_event, submit_click_event], |
| queue=False, |
| ) |
| clear.click(lambda: None, None, chatbot, queue=False) |
|
|
|
|
| demo.queue(max_size=128, concurrency_count=2) |
|
|
| demo.launch(share=True) |