|
|
|
|
|
import os |
|
import gradio as gr |
|
import torch |
|
from transformers import AutoModelForCausalLM, AutoTokenizer |
|
from transformers import StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer |
|
from transformers import is_torch_npu_available |
|
from threading import Thread |
|
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-7B-Chat") |
|
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen1.5-7B-Chat", torch_dtype=torch.bfloat16) |
|
if is_torch_npu_available(): |
|
model.to("npu:0") |
|
elif torch.cuda.is_available(): |
|
mode.to("cuda:0") |
|
|
|
|
|
class StopOnTokens(StoppingCriteria): |
|
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: |
|
stop_ids = [2] |
|
for stop_id in stop_ids: |
|
if input_ids[0][-1] == stop_id: |
|
return True |
|
return False |
|
|
|
|
|
def predict(message, history): |
|
|
|
|
|
stop = StopOnTokens() |
|
conversation = [] |
|
|
|
for user, assistant in history: |
|
conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}]) |
|
|
|
conversation.append({"role": "user", "content": message}) |
|
print(f'>>>conversation={conversation}', flush=True) |
|
prompt = tokenizer.apply_chat_template(conversation, tokenize=False, add_generation_prompt=True) |
|
model_inputs = tokenizer(prompt, return_tensors="pt").to(model.device) |
|
streamer = TextIteratorStreamer(tokenizer, timeout=100., skip_prompt=True, skip_special_tokens=True) |
|
generate_kwargs = dict( |
|
model_inputs, |
|
streamer=streamer, |
|
max_new_tokens=1024, |
|
do_sample=True, |
|
top_p=0.95, |
|
top_k=50, |
|
temperature=0.7, |
|
repetition_penalty=1.0, |
|
num_beams=1, |
|
stopping_criteria=StoppingCriteriaList([stop]) |
|
) |
|
t = Thread(target=model.generate, kwargs=generate_kwargs) |
|
t.start() |
|
partial_message = "" |
|
for new_token in streamer: |
|
partial_message += new_token |
|
if '</s>' in partial_message: |
|
break |
|
yield partial_message |
|
|
|
|
|
|
|
gr.ChatInterface(predict, |
|
title="Qwen1.5 0.5B Chat Demo", |
|
description="Warning. All answers are generated and may contain inaccurate information.", |
|
examples=['How do you cook fish?', 'Who is the president of the United States?'] |
|
).launch() |
|
|
|
|