code5ecure commited on
Commit
0e318c6
·
verified ·
1 Parent(s): ffa11fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -34
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import torch
 
2
  from transformers import AutoTokenizer, AutoModelForMaskedLM, pipeline
3
  from opacus import PrivacyEngine
4
  import gradio as gr
@@ -8,13 +9,9 @@ import gradio as gr
8
  # ===========================
9
  model_name = "HooshvareLab/bert-base-parsbert-uncased"
10
  tokenizer = AutoTokenizer.from_pretrained(model_name)
 
11
 
12
- # حل ارور padding
13
- if tokenizer.pad_token is None:
14
- tokenizer.add_special_tokens({'pad_token': '[PAD]'})
15
  model = AutoModelForMaskedLM.from_pretrained(model_name)
16
- model.resize_token_embeddings(len(tokenizer))
17
-
18
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
19
  model.to(device)
20
 
@@ -24,50 +21,67 @@ model.to(device)
24
  with open("training_data.txt", "r", encoding="utf-8") as f:
25
  texts = [line.strip() for line in f if line.strip()]
26
 
27
- # توکنایز کردن
28
- encodings = tokenizer(texts, truncation=True, padding=True, max_length=128, return_tensors="pt")
29
- input_ids = encodings["input_ids"].to(device)
 
 
 
 
 
 
 
 
 
 
30
 
31
  # ===========================
32
- # تعریف PrivacyEngine برای DP
33
  # ===========================
34
  optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5)
35
 
36
- privacy_engine = PrivacyEngine(
37
- model,
38
- sample_rate=0.1, # درصد داده‌های هر batch
39
- noise_multiplier=1.0, # میزان نویز برای DP
 
40
  max_grad_norm=1.0,
 
41
  )
42
- privacy_engine.attach(optimizer)
43
 
44
  # ===========================
45
  # آموزش incremental (یک epoch ساده)
46
  # ===========================
47
  def train_step():
48
  model.train()
49
- optimizer.zero_grad()
50
- outputs = model(input_ids, labels=input_ids)
51
- loss = outputs.loss
52
- loss.backward()
53
- optimizer.step()
54
- return loss.item()
 
 
 
 
 
 
 
55
 
56
  # ===========================
57
- # تابع تولید پاسخ (با masked LM)
58
  # ===========================
59
- def generate_text(prompt, max_length=50):
60
- # توکنایز prompt
61
- input_ids_prompt = tokenizer.encode(prompt, return_tensors="pt").to(device)
62
- # آموزش incremental روی داده داخلی
63
- loss = train_step()
64
- # تولید متن ساده با روش greedy
65
- model.eval()
66
- with torch.no_grad():
67
- outputs = model(input_ids_prompt)
68
- predictions = torch.argmax(outputs.logits, dim=-1)
69
- generated_text = tokenizer.decode(predictions[0], skip_special_tokens=True)
70
- return f"{generated_text}\n\n(مدل به صورت incremental روی داده‌های داخلی آموزش داده شد. DP فعال است)"
71
 
72
  # ===========================
73
  # رابط کاربری Gradio (RTL)
@@ -77,6 +91,6 @@ with gr.Blocks() as demo:
77
  prompt_input = gr.Textbox(label="متن خود را وارد کنید:", placeholder="اینجا بنویسید...", lines=3)
78
  output = gr.Textbox(label="پاسخ مدل:", lines=8)
79
  btn = gr.Button("ارسال")
80
- btn.click(generate_text, inputs=prompt_input, outputs=output)
81
 
82
  demo.launch()
 
1
  import torch
2
+ from torch.utils.data import DataLoader, Dataset
3
  from transformers import AutoTokenizer, AutoModelForMaskedLM, pipeline
4
  from opacus import PrivacyEngine
5
  import gradio as gr
 
9
  # ===========================
10
  model_name = "HooshvareLab/bert-base-parsbert-uncased"
11
  tokenizer = AutoTokenizer.from_pretrained(model_name)
12
+ tokenizer.pad_token = tokenizer.eos_token # حل ارور padding
13
 
 
 
 
14
  model = AutoModelForMaskedLM.from_pretrained(model_name)
 
 
15
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
16
  model.to(device)
17
 
 
21
  with open("training_data.txt", "r", encoding="utf-8") as f:
22
  texts = [line.strip() for line in f if line.strip()]
23
 
24
+ # ===========================
25
+ # Dataset و DataLoader
26
+ # ===========================
27
+ class TextDataset(Dataset):
28
+ def __init__(self, texts, tokenizer, max_length=128):
29
+ self.encodings = tokenizer(texts, truncation=True, padding=True, max_length=max_length, return_tensors="pt")
30
+ def __len__(self):
31
+ return self.encodings.input_ids.size(0)
32
+ def __getitem__(self, idx):
33
+ return {"input_ids": self.encodings.input_ids[idx], "attention_mask": self.encodings.attention_mask[idx], "labels": self.encodings.input_ids[idx]}
34
+
35
+ dataset = TextDataset(texts, tokenizer)
36
+ data_loader = DataLoader(dataset, batch_size=4, shuffle=True)
37
 
38
  # ===========================
39
+ # تعریف Optimizer و PrivacyEngine
40
  # ===========================
41
  optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5)
42
 
43
+ privacy_engine = PrivacyEngine()
44
+ model, optimizer, data_loader = privacy_engine.make_private(
45
+ module=model,
46
+ optimizer=optimizer,
47
+ data_loader=data_loader,
48
  max_grad_norm=1.0,
49
+ noise_multiplier=1.0,
50
  )
 
51
 
52
  # ===========================
53
  # آموزش incremental (یک epoch ساده)
54
  # ===========================
55
  def train_step():
56
  model.train()
57
+ total_loss = 0
58
+ for batch in data_loader:
59
+ input_ids = batch["input_ids"].to(device)
60
+ attention_mask = batch["attention_mask"].to(device)
61
+ labels = batch["labels"].to(device)
62
+
63
+ optimizer.zero_grad()
64
+ outputs = model(input_ids, attention_mask=attention_mask, labels=labels)
65
+ loss = outputs.loss
66
+ loss.backward()
67
+ optimizer.step()
68
+ total_loss += loss.item()
69
+ return total_loss / len(data_loader)
70
 
71
  # ===========================
72
+ # تابع تولید پاسخ
73
  # ===========================
74
+ generator = pipeline(
75
+ task="text-generation",
76
+ model=model,
77
+ tokenizer=tokenizer,
78
+ device=0 if torch.cuda.is_available() else -1
79
+ )
80
+
81
+ def chat(prompt):
82
+ loss = train_step() # آموزش incremental روی داده داخلی قبل از تولید پاسخ
83
+ result = generator(prompt, max_length=128, do_sample=True, temperature=0.8)
84
+ return f"{result[0]['generated_text']}\n\n(مدل به صورت incremental روی داده‌های داخلی آموزش داده شد. DP فعال است)"
 
85
 
86
  # ===========================
87
  # رابط کاربری Gradio (RTL)
 
91
  prompt_input = gr.Textbox(label="متن خود را وارد کنید:", placeholder="اینجا بنویسید...", lines=3)
92
  output = gr.Textbox(label="پاسخ مدل:", lines=8)
93
  btn = gr.Button("ارسال")
94
+ btn.click(chat, inputs=prompt_input, outputs=output)
95
 
96
  demo.launch()