Spaces:
Sleeping
Sleeping
# app.py | |
import torch | |
import gradio as gr | |
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer | |
# 1️⃣ Cấu hình và load model + tokenizer | |
model_path = "vinai/PhoGPT-4B-Chat" | |
config = AutoConfig.from_pretrained(model_path, trust_remote_code=True) | |
config.init_device = "cpu" if torch.cuda.is_available() else "cpu" | |
# Nếu có FlashAttention, bật thêm: | |
# config.attn_config['attn_impl'] = 'flash' | |
model = AutoModelForCausalLM.from_pretrained( | |
model_path, | |
config=config, | |
torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32, | |
trust_remote_code=True, | |
) | |
model.eval() | |
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) | |
# 2️⃣ Hàm chat theo template “### Câu hỏi / ### Trả lời” | |
PROMPT_TEMPLATE = "### Câu hỏi: {instruction}\n### Trả lời:" | |
def respond(message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p): | |
# 2.1 — Gom system message và history vào messages list | |
messages = [{"role": "system", "content": system_message}] | |
for u, b in history: | |
if u: | |
messages.append({"role": "user", "content": u}) | |
if b: | |
messages.append({"role": "assistant", "content": b}) | |
messages.append({"role": "user", "content": message}) | |
# 2.2 — Tạo prompt chuẩn | |
prompt = tokenizer.apply_chat_template( | |
messages, | |
tokenize=False, | |
add_generation_prompt=True | |
) | |
# 2.3 — Tokenize và đưa lên device | |
inputs = tokenizer(prompt, return_tensors="pt") | |
inputs = {k: v.to(model.device) for k, v in inputs.items()} | |
# 2.4 — Sinh text | |
outputs = model.generate( | |
**inputs, | |
max_new_tokens=max_tokens, | |
temperature=temperature, | |
top_p=top_p, | |
do_sample=True, | |
eos_token_id=tokenizer.eos_token_id, | |
pad_token_id=tokenizer.pad_token_id, | |
) | |
# 2.5 — Decode và tách phần assistant trả lời | |
full = tokenizer.decode(outputs[0], skip_special_tokens=True) | |
response = full.replace(prompt, "").strip() | |
# yield response | |
# 2.6 — Cập nhật history và trả về | |
# history.append((message, response)) | |
# return history | |
# 3️⃣ Giao diện Gradio | |
demo = gr.ChatInterface( | |
respond, | |
additional_inputs=[ | |
gr.Textbox("Bạn là một chatbot tiếng Việt thân thiện.", label="System message"), | |
gr.Slider(1, 2048, value=512, step=1, label="Max new tokens"), | |
gr.Slider(0.1, 4.0, value=0.7, step=0.1, label="Temperature"), | |
gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"), | |
], | |
) | |
if __name__ == "__main__": | |
demo.launch() | |