code5ecure commited on
Commit
db5b1e8
·
verified ·
1 Parent(s): 31de5c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -15
app.py CHANGED
@@ -1,35 +1,80 @@
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
 
3
 
4
- MODEL_NAME = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
5
 
 
6
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
7
- model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto")
 
 
 
 
8
 
 
9
  generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
10
 
11
  def generate_text(prompt, max_new_tokens, temperature, top_p):
12
- result = generator(
13
- prompt,
14
- max_new_tokens=int(max_new_tokens),
15
- do_sample=True,
16
- temperature=float(temperature),
17
- top_p=float(top_p),
18
- )[0]["generated_text"]
19
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  with gr.Blocks(title="TinyLlama Chat") as demo:
22
- gr.Markdown("## TinyLlama Chat\nگوش به زنگ م.")
 
 
 
 
23
  with gr.Row():
24
- prompt = gr.Textbox(label="Prompt", lines=4, placeholder="مثال: درباره گل‌های آفریقا بگو...")
25
  with gr.Row():
26
  max_new_tokens = gr.Slider(16, 512, value=150, step=1, label="max_new_tokens")
27
  temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.05, label="temperature")
28
  top_p = gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="top_p")
29
- btn = gr.Button("جواب بده")
30
- output = gr.Textbox(label="یاور : ", lines=10)
31
 
32
  btn.click(generate_text, [prompt, max_new_tokens, temperature, top_p], output)
33
 
34
  if __name__ == "__main__":
35
- demo.launch()
 
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
3
+ import torch
4
 
5
+ MODEL_NAME = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" # در صورت نیاز مدل کوچک‌تر انتخاب کنید
6
 
7
+ # بارگذاری مدل و توکنایزر
8
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
9
+ model = AutoModelForCausalLM.from_pretrained(
10
+ MODEL_NAME,
11
+ device_map="auto", # GPU اگر باشد استفاده می‌کند
12
+ torch_dtype="auto" # دقت مناسب سخت‌افزار
13
+ )
14
 
15
+ # ساخت پایپلاین تولید متن
16
  generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
17
 
18
  def generate_text(prompt, max_new_tokens, temperature, top_p):
19
+ """
20
+ تولید پاسخ با استفاده از max_new_tokens (مستقل از طول ورودی).
21
+ در صورت خطای حافظه، یک بار با نصف max_new_tokens تلاش مجدد می‌کند.
22
+ """
23
+ max_new_tokens = int(max_new_tokens)
24
+ temperature = float(temperature)
25
+ top_p = float(top_p)
26
+
27
+ def _run(tokens):
28
+ return generator(
29
+ prompt,
30
+ max_new_tokens=tokens, # مستقل از طول ورودی
31
+ do_sample=True,
32
+ temperature=temperature,
33
+ top_p=top_p,
34
+ )[0]["generated_text"]
35
+
36
+ try:
37
+ return _run(max_new_tokens)
38
+ except torch.cuda.OutOfMemoryError:
39
+ # تلاش مجدد با نصف مقدار
40
+ try:
41
+ torch.cuda.empty_cache()
42
+ smaller = max(32, max_new_tokens // 2)
43
+ return _run(smaller) + "\n\n[⚠️ حافظه کم بود؛ خروجی با توکن‌های کمتر تولید شد. اگر باز هم مشکل داری، مقدار max_new_tokens را کمتر کن یا از مدل کوچک‌تر استفاده کن.]"
44
+ except Exception:
45
+ torch.cuda.empty_cache()
46
+ return "⚠️ خطای حافظه (OOM). لطفاً مقدار max_new_tokens را کاهش بده یا از مدل کوچک‌تر/سخت‌افزار قوی‌تر استفاده کن."
47
+ except RuntimeError as e:
48
+ # برخی OOMها RuntimeError هستند
49
+ if "out of memory" in str(e).lower():
50
+ try:
51
+ torch.cuda.empty_cache()
52
+ smaller = max(32, max_new_tokens // 2)
53
+ return _run(smaller) + "\n\n[⚠️ حافظه کم بود؛ خروجی با توکن‌های کمتر تولید شد. اگر باز هم مشکل داری، مقدار max_new_tokens را کمتر کن یا از مدل کوچک‌تر استفاده کن.]"
54
+ except Exception:
55
+ torch.cuda.empty_cache()
56
+ return "⚠️ خطای حافظه (OOM). لطفاً مقدار max_new_tokens را کاهش بده یا از مدل کوچک‌تر/سخت‌افزار قوی‌تر استفاده کن."
57
+ # سایر خطاها
58
+ return f"❌ خطا: {e}"
59
+ except Exception as e:
60
+ return f"❌ خطا: {e}"
61
 
62
  with gr.Blocks(title="TinyLlama Chat") as demo:
63
+ gr.Markdown(
64
+ "## TinyLlama Chat\n"
65
+ "پرامپتت را بنویس و پاسخ بگیر.\n\n"
66
+ "**نکته:** اگر خطای حافظه دیدی، مقدار `max_new_tokens` را کم کن یا مدل کوچک‌تری انتخاب کن."
67
+ )
68
  with gr.Row():
69
+ prompt = gr.Textbox(label="Prompt", lines=4, placeholder="مثال: درباره گل‌های آفریقا بگو…")
70
  with gr.Row():
71
  max_new_tokens = gr.Slider(16, 512, value=150, step=1, label="max_new_tokens")
72
  temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.05, label="temperature")
73
  top_p = gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="top_p")
74
+ btn = gr.Button("تولید پاسخ")
75
+ output = gr.Textbox(label="خروجی", lines=12)
76
 
77
  btn.click(generate_text, [prompt, max_new_tokens, temperature, top_p], output)
78
 
79
  if __name__ == "__main__":
80
+ demo.launch()