code5ecure commited on
Commit
270ede6
·
verified ·
1 Parent(s): c4d2e49

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -7
app.py CHANGED
@@ -1,10 +1,12 @@
1
  import torch
2
- from transformers import BertLMHeadModel, AutoTokenizer, TrainingArguments, Trainer
3
  import numpy as np
4
  import gradio as gr
5
  from opacus import PrivacyEngine
6
  from torch.utils.data import Dataset
7
  from torch.optim import AdamW
 
 
8
 
9
  # Disable torch.compile to avoid meta device issues
10
  torch._dynamo.config.suppress_errors = True
@@ -13,10 +15,10 @@ torch.set_default_dtype(torch.float32)
13
  # Set device explicitly
14
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
 
16
- # Load ParsBERT model and tokenizer
17
- model_name = "HooshvareLab/bert-base-parsbert-uncased"
18
  tokenizer = AutoTokenizer.from_pretrained(model_name)
19
- model = BertLMHeadModel.from_pretrained(model_name, is_decoder=True).to(device)
20
 
21
  # Differential Privacy parameters
22
  epsilon = 1.0 # Privacy budget
@@ -26,6 +28,11 @@ sensitivity = 1.0 # Sensitivity of the query
26
  # Simple memory for conversation history
27
  conversation_history = []
28
 
 
 
 
 
 
29
  # Custom Dataset for training data
30
  class ChatDataset(Dataset):
31
  def __init__(self, data):
@@ -42,6 +49,7 @@ class ChatDataset(Dataset):
42
 
43
  # Load training data from training_data.txt in the root directory
44
  def load_training_data():
 
45
  try:
46
  with open("training_data.txt", "r", encoding="utf-8") as file:
47
  texts = [line.strip() for line in file if line.strip()]
@@ -54,13 +62,27 @@ def load_training_data():
54
  print(f"Error reading training_data.txt: {e}")
55
  return []
56
 
 
 
 
 
 
 
 
 
 
 
57
  # Fine-tune model with differential privacy
58
  def train_model():
 
59
  texts = load_training_data()
60
  if not texts:
61
  print("No training data available. Skipping training.")
62
  return
63
 
 
 
 
64
  train_dataset = ChatDataset(texts)
65
 
66
  training_args = TrainingArguments(
@@ -126,8 +148,20 @@ def chat(message, history):
126
  # Set model to evaluation mode for inference
127
  model.eval()
128
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  # Tokenize input
130
- inputs = tokenizer(message, return_tensors="pt", padding=True, truncation=True, max_length=128).to(device)
131
 
132
  # Generate response with model using beam search
133
  with torch.no_grad():
@@ -152,8 +186,8 @@ train_model()
152
  # Gradio interface
153
  iface = gr.ChatInterface(
154
  fn=chat,
155
- title="ParsBERT Chatbot with Differential Privacy",
156
- description="Chat with a fine-tuned ParsBERT model using training_data.txt from the root directory."
157
  )
158
 
159
  if __name__ == "__main__":
 
1
  import torch
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer
3
  import numpy as np
4
  import gradio as gr
5
  from opacus import PrivacyEngine
6
  from torch.utils.data import Dataset
7
  from torch.optim import AdamW
8
+ from sentence_transformers import SentenceTransformer
9
+ import faiss
10
 
11
  # Disable torch.compile to avoid meta device issues
12
  torch._dynamo.config.suppress_errors = True
 
15
  # Set device explicitly
16
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
17
 
18
+ # Load LLaMA 2 Persian model and tokenizer
19
+ model_name = "sinarashidi/llama-2-7b-chat-persian"
20
  tokenizer = AutoTokenizer.from_pretrained(model_name)
21
+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32).to(device)
22
 
23
  # Differential Privacy parameters
24
  epsilon = 1.0 # Privacy budget
 
28
  # Simple memory for conversation history
29
  conversation_history = []
30
 
31
+ # RAG components
32
+ embedder = None
33
+ index = None
34
+ texts = []
35
+
36
  # Custom Dataset for training data
37
  class ChatDataset(Dataset):
38
  def __init__(self, data):
 
49
 
50
  # Load training data from training_data.txt in the root directory
51
  def load_training_data():
52
+ global texts
53
  try:
54
  with open("training_data.txt", "r", encoding="utf-8") as file:
55
  texts = [line.strip() for line in file if line.strip()]
 
62
  print(f"Error reading training_data.txt: {e}")
63
  return []
64
 
65
+ # Build RAG index
66
+ def build_rag_index(texts):
67
+ global embedder, index
68
+ embedder = SentenceTransformer('xmanii/maux-gte-persian')
69
+ embeddings = embedder.encode(texts, convert_to_tensor=True).cpu().numpy()
70
+ dimension = embeddings.shape[1]
71
+ index = faiss.IndexFlatL2(dimension)
72
+ index.add(embeddings)
73
+ return embedder, index
74
+
75
  # Fine-tune model with differential privacy
76
  def train_model():
77
+ global texts, embedder, index
78
  texts = load_training_data()
79
  if not texts:
80
  print("No training data available. Skipping training.")
81
  return
82
 
83
+ # Build RAG index
84
+ build_rag_index(texts)
85
+
86
  train_dataset = ChatDataset(texts)
87
 
88
  training_args = TrainingArguments(
 
148
  # Set model to evaluation mode for inference
149
  model.eval()
150
 
151
+ # RAG retrieval
152
+ if embedder and index:
153
+ query_emb = embedder.encode(message, convert_to_tensor=True).cpu().numpy()
154
+ D, I = index.search(query_emb, k=3)
155
+ retrieved = [texts[i] for i in I[0] if i >= 0 and i < len(texts)]
156
+ context = "\n".join(retrieved)
157
+ else:
158
+ context = ""
159
+
160
+ # Prepare prompt with context
161
+ prompt = f"Context: {context}\nUser: {message}\nBot:"
162
+
163
  # Tokenize input
164
+ inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=128).to(device)
165
 
166
  # Generate response with model using beam search
167
  with torch.no_grad():
 
186
  # Gradio interface
187
  iface = gr.ChatInterface(
188
  fn=chat,
189
+ title="LLaMA 2 Persian Chatbot with Differential Privacy and RAG",
190
+ description="Chat with a fine-tuned LLaMA 2 Persian model using training_data.txt from the root directory with RAG."
191
  )
192
 
193
  if __name__ == "__main__":