code5ecure commited on
Commit
050cb6f
·
verified ·
1 Parent(s): fa6e0cc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -68
app.py CHANGED
@@ -1,79 +1,88 @@
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",
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
- میتونی حرف بزنی
21
- """
22
- max_new_tokens = int(max_new_tokens)
23
- temperature = float(temperature)
24
- top_p = float(top_p)
25
-
26
- def _run(tokens):
27
- return generator(
28
- prompt,
29
- max_new_tokens=tokens, # مستقل از طول ورودی
30
- do_sample=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- )[0]["generated_text"]
34
-
35
- try:
36
- return _run(max_new_tokens)
37
- except torch.cuda.OutOfMemoryError:
38
- # تلاش مجدد با نصف مقدار
39
- try:
40
- torch.cuda.empty_cache()
41
- smaller = max(32, max_new_tokens // 2)
42
- return _run(smaller) + "\n\n[⚠️ حافظه کم بود؛ خروجی با توکن‌های کمتر تولید شد. اگر باز هم مشکل داری، مقدار max_new_tokens را کمتر کن یا از مدل کوچک‌تر استفاده کن.]"
43
- except Exception:
44
- torch.cuda.empty_cache()
45
- return "⚠️ خطای حافظه (OOM). لطفاً مقدار max_new_tokens را کاهش بده یا از مدل کوچک‌تر/سخت‌افزار قوی‌تر استفاده کن."
46
- except RuntimeError as e:
47
- # برخی OOMها RuntimeError هستند
48
- if "out of memory" in str(e).lower():
49
- try:
50
- torch.cuda.empty_cache()
51
- smaller = max(32, max_new_tokens // 2)
52
- return _run(smaller) + "\n\n[⚠️ حافظه کم بود؛ خروجی با توکن‌های کمتر تولید شد. اگر باز هم مشکل داری، مقدار max_new_tokens را کمتر کن یا از مدل کوچک‌تر استفاده کن.]"
53
- except Exception:
54
- torch.cuda.empty_cache()
55
- return "⚠️ خطای حافظه (OOM). لطفاً مقدار max_new_tokens را کاهش بده یا از مدل کوچک‌تر/سخت‌افزار قوی‌تر استفاده کن."
56
- # سایر خطاها
57
- return f"❌ خطا: {e}"
58
- except Exception as e:
59
- return f"❌ خطا: {e}"
60
-
61
- with gr.Blocks(title="TinyLlama Chat") as demo:
 
 
 
 
 
 
 
 
 
62
  gr.Markdown(
63
- "## TinyLlama Chat\n"
64
- "پرامپتت را بنویس و پاسخ بگیر.\n\n"
65
- "**نکته:** اگر خطای حافظه دیدی، مقدار `max_new_tokens` را کم کن یا مدل کوچک‌تری انتخاب کن."
66
  )
67
- with gr.Row():
68
- prompt = gr.Textbox(label="Prompt", lines=4)
69
- with gr.Row():
70
- max_new_tokens = gr.Slider(16, 512, value=150, step=1, label="max_new_tokens")
71
- temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.05, label="temperature")
72
- top_p = gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="top_p")
73
- btn = gr.Button("تولید پاسخ")
74
  output = gr.Textbox(label="خروجی", lines=12)
75
-
76
- btn.click(generate_text, [prompt, max_new_tokens, temperature, top_p], output)
77
 
78
  if __name__ == "__main__":
79
  demo.launch()
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
  import torch
4
+ from torch.utils.data import DataLoader, Dataset
5
+ from torch.nn import CrossEntropyLoss
6
+ from opacus import PrivacyEngine
7
 
8
+ MODEL_NAME = "HooshvareLab/gpt2-fa"
 
9
 
10
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
11
+ model = AutoModelForCausalLM.from_pretrained(MODEL_NAME)
12
+ device = "cuda" if torch.cuda.is_available() else "cpu"
13
+ model.to(device)
14
+
15
+
16
+ # ---------- Dataset ساده برای PyTorch ----------
17
+ class UserDataset(Dataset):
18
+ def __init__(self, texts, tokenizer, max_length=128):
19
+ self.examples = [tokenizer(t, truncation=True, padding="max_length", max_length=max_length, return_tensors="pt") for t in texts]
20
+
21
+ def __len__(self):
22
+ return len(self.examples)
23
+
24
+ def __getitem__(self, idx):
25
+ item = self.examples[idx]
26
+ return {
27
+ "input_ids": item["input_ids"].squeeze(0),
28
+ "attention_mask": item["attention_mask"].squeeze(0)
29
+ }
30
+
31
+
32
+ # ---------- تابع آموزش با DP ----------
33
+ def fine_tune_dp(prompt, user_text, epochs=1, lr=5e-5, max_new_tokens=150, batch_size=1):
34
+ dataset = UserDataset([user_text], tokenizer)
35
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
36
+
37
+ optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
38
+ criterion = CrossEntropyLoss(ignore_index=tokenizer.pad_token_id)
39
+
40
+ # ---------- فعال کردن Differential Privacy ----------
41
+ privacy_engine = PrivacyEngine(
42
+ model,
43
+ sample_rate=batch_size / len(dataset),
44
+ noise_multiplier=1.0,
45
+ max_grad_norm=1.0,
46
+ )
47
+ privacy_engine.attach(optimizer)
48
+
49
+ model.train()
50
+ for epoch in range(epochs):
51
+ for batch in dataloader:
52
+ input_ids = batch["input_ids"].to(device)
53
+ attention_mask = batch["attention_mask"].to(device)
54
+
55
+ outputs = model(input_ids, attention_mask=attention_mask)
56
+ logits = outputs.logits
57
+
58
+ loss = criterion(logits.view(-1, logits.size(-1)), input_ids.view(-1))
59
+ optimizer.zero_grad()
60
+ loss.backward()
61
+ optimizer.step()
62
+
63
+ # ---------- تولید متن بعد از آموزش ----------
64
+ model.eval()
65
+ input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
66
+ with torch.no_grad():
67
+ output = model.generate(input_ids, max_new_tokens=max_new_tokens, do_sample=True)
68
+ return tokenizer.decode(output[0], skip_special_tokens=True)
69
+
70
+
71
+ # ---------- رابط گریدیو ----------
72
+ with gr.Blocks(title="چت بات فارسی با DP") as demo:
73
  gr.Markdown(
74
+ "## چت بات فارسی با یادگیری امن\n"
75
+ "متن آموزشی خود را بده و پاسخ بگیر.\n"
76
+ "گرادیان‌ها با Differential Privacy محافظت می‌شوند؛ داده واقعی کاربر لو نمی‌رود."
77
  )
78
+ prompt = gr.Textbox(label="Prompt", lines=4)
79
+ user_text = gr.Textbox(label="متن آموزشی برای مدل", lines=4)
80
+ epochs = gr.Slider(1, 3, value=1, step=1, label="تعداد Epochها")
81
+ max_new_tokens = gr.Slider(16, 512, value=150, step=1, label="max_new_tokens")
82
+ btn = gr.Button("تولید پاسخ با یادگیری امن")
 
 
83
  output = gr.Textbox(label="خروجی", lines=12)
84
+
85
+ btn.click(fine_tune_dp, [prompt, user_text, epochs, max_new_tokens], output)
86
 
87
  if __name__ == "__main__":
88
  demo.launch()