File size: 2,787 Bytes
e7439a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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)