Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,88 +1,94 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 3 |
import torch
|
| 4 |
-
from
|
| 5 |
-
from torch.
|
| 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(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 13 |
model.to(device)
|
| 14 |
|
|
|
|
| 15 |
|
| 16 |
-
# ----------
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
def __len__(self):
|
| 22 |
return len(self.examples)
|
| 23 |
|
| 24 |
def __getitem__(self, idx):
|
| 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 |
model.train()
|
| 50 |
-
for
|
| 51 |
-
for batch in
|
| 52 |
-
|
| 53 |
-
|
| 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 |
-
|
|
|
|
| 73 |
gr.Markdown(
|
|
|
|
| 74 |
"## چت بات فارسی با یادگیری امن\n"
|
| 75 |
-
"
|
| 76 |
-
"
|
| 77 |
)
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
btn
|
| 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()
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import torch
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, AdamW
|
| 4 |
+
from torch.utils.data import Dataset, DataLoader
|
| 5 |
from opacus import PrivacyEngine
|
| 6 |
|
| 7 |
+
# ---------------------
|
| 8 |
+
# تنظیمات مدل
|
| 9 |
+
# ---------------------
|
| 10 |
MODEL_NAME = "HooshvareLab/gpt2-fa"
|
|
|
|
| 11 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 12 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 13 |
+
MODEL_NAME,
|
| 14 |
+
device_map="auto",
|
| 15 |
+
torch_dtype="auto"
|
| 16 |
+
)
|
| 17 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 18 |
model.to(device)
|
| 19 |
|
| 20 |
+
generator = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0 if device=="cuda" else -1)
|
| 21 |
|
| 22 |
+
# ---------------------
|
| 23 |
+
# Dataset ساده
|
| 24 |
+
# ---------------------
|
| 25 |
+
class TextDataset(Dataset):
|
| 26 |
+
def __init__(self, file_path, tokenizer, max_length=128):
|
| 27 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 28 |
+
lines = f.read().splitlines()
|
| 29 |
+
self.examples = [tokenizer.encode(line, truncation=True, max_length=max_length) for line in lines]
|
| 30 |
|
| 31 |
def __len__(self):
|
| 32 |
return len(self.examples)
|
| 33 |
|
| 34 |
def __getitem__(self, idx):
|
| 35 |
+
return torch.tensor(self.examples[idx])
|
| 36 |
+
|
| 37 |
+
# بارگذاری داده آموزشی
|
| 38 |
+
train_dataset = TextDataset("training_data.txt", tokenizer)
|
| 39 |
+
train_loader = DataLoader(train_dataset, batch_size=2, shuffle=True)
|
| 40 |
+
|
| 41 |
+
# ---------------------
|
| 42 |
+
# تنظیمات بهینهساز و DP
|
| 43 |
+
# ---------------------
|
| 44 |
+
optimizer = AdamW(model.parameters(), lr=5e-5)
|
| 45 |
+
privacy_engine = PrivacyEngine(
|
| 46 |
+
model,
|
| 47 |
+
batch_size=2,
|
| 48 |
+
sample_size=len(train_dataset),
|
| 49 |
+
alphas=[10, 100],
|
| 50 |
+
noise_multiplier=1.0,
|
| 51 |
+
max_grad_norm=1.0,
|
| 52 |
+
)
|
| 53 |
+
privacy_engine.attach(optimizer)
|
| 54 |
+
|
| 55 |
+
# ---------------------
|
| 56 |
+
# تابع تولید متن
|
| 57 |
+
# ---------------------
|
| 58 |
+
def generate_and_learn(prompt, max_new_tokens=150, temperature=0.7, top_p=0.9, train_steps=1):
|
| 59 |
+
# تولید متن
|
| 60 |
+
output_text = generator(prompt, max_new_tokens=int(max_new_tokens),
|
| 61 |
+
do_sample=True, temperature=float(temperature),
|
| 62 |
+
top_p=float(top_p))[0]["generated_text"]
|
| 63 |
+
|
| 64 |
+
# یادگیری incremental روی داده آموزشی
|
| 65 |
model.train()
|
| 66 |
+
for _ in range(train_steps):
|
| 67 |
+
for batch in train_loader:
|
| 68 |
+
batch = batch.to(device)
|
| 69 |
+
outputs = model(batch, labels=batch)
|
| 70 |
+
loss = outputs.loss
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
optimizer.zero_grad()
|
| 72 |
loss.backward()
|
| 73 |
optimizer.step()
|
| 74 |
|
| 75 |
+
return output_text + "\n\n[✅ مدل بعد از یادگیری incremental بروزرسانی شد]"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
# ---------------------
|
| 78 |
+
# رابط Gradio
|
| 79 |
+
# ---------------------
|
| 80 |
+
with gr.Blocks(title="چت بات فارسی با یادگیری امن") as demo:
|
| 81 |
gr.Markdown(
|
| 82 |
+
"<div dir='rtl'>"
|
| 83 |
"## چت بات فارسی با یادگیری امن\n"
|
| 84 |
+
"یک Prompt وارد کنید و پاسخ مدل را دریافت کنید. مدل قابلیت یادگیری incremental با **DP** دارد."
|
| 85 |
+
"</div>"
|
| 86 |
)
|
| 87 |
+
prompt_box = gr.Textbox(label="Prompt", lines=4)
|
| 88 |
+
btn = gr.Button("تولید پاسخ")
|
| 89 |
+
output_box = gr.Textbox(label="خروجی", lines=12)
|
| 90 |
+
|
| 91 |
+
btn.click(generate_and_learn, inputs=prompt_box, outputs=output_box)
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
if __name__ == "__main__":
|
| 94 |
demo.launch()
|