Spaces:
Runtime error
Runtime error
import gradio as gr | |
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig | |
import torch | |
# تنظیمات بهینهسازی برای اجرا روی رم 16GB | |
quantization_config = BitsAndBytesConfig( | |
load_in_4bit=True, | |
bnb_4bit_compute_dtype=torch.float16, | |
bnb_4bit_quant_type="nf4", | |
bnb_4bit_use_double_quant=True, | |
) | |
# بارگذاری مدل با تنظیمات بهینهسازی | |
model_name = "meta-llama/Llama-3.1-8B-Instruct" | |
tokenizer = AutoTokenizer.from_pretrained(model_name) | |
model = AutoModelForCausalLM.from_pretrained( | |
model_name, | |
quantization_config=quantization_config, | |
device_map="auto" | |
) | |
def generate_response(prompt, max_new_tokens=512, temperature=0.7): | |
""" | |
تولید پاسخ بر اساس ورودی کاربر | |
""" | |
# کدگذاری ورودی کاربر | |
inputs = tokenizer(prompt, return_tensors="pt").to(model.device) | |
# تولید پاسخ | |
outputs = model.generate( | |
**inputs, | |
max_new_tokens=max_new_tokens, | |
temperature=temperature, | |
do_sample=True, | |
pad_token_id=tokenizer.eos_token_id | |
) | |
# تبدیل خروجی به متن | |
response = tokenizer.decode(outputs[0], skip_special_tokens=True) | |
# حذف prompt از پاسخ | |
response = response[len(prompt):].strip() | |
return response | |
# رابط Gradio | |
with gr.Blocks(title="چت بات Llama-3.1-8B-Instruct") as demo: | |
gr.Markdown(""" | |
# چت بات با مدل Llama-3.1-8B-Instruct | |
این مدل با بهینهسازی برای اجرا روی سیستمهای با رم محدود (16GB) پیادهسازی شده است. | |
""") | |
with gr.Row(): | |
with gr.Column(): | |
user_input = gr.Textbox(label="پیام شما", lines=5, placeholder="پیام خود را اینجا بنویسید...") | |
with gr.Accordion("تنظیمات پیشرفته", open=False): | |
max_tokens = gr.Slider(64, 1024, value=512, step=32, label="حداکثر طول پاسخ") | |
temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="دمای پاسخ (خلاقیت)") | |
submit_btn = gr.Button("ارسال") | |
with gr.Column(): | |
output_text = gr.Textbox(label="پاسخ مدل", lines=10, interactive=False) | |
# رویدادها | |
submit_btn.click( | |
fn=generate_response, | |
inputs=[user_input, max_tokens, temperature], | |
outputs=output_text | |
) | |
# امکان ارسال با Enter | |
user_input.submit( | |
fn=generate_response, | |
inputs=[user_input, max_tokens, temperature], | |
outputs=output_text | |
) | |
# اجرای برنامه | |
if __name__ == "__main__": | |
demo.launch(share=False) |