ar12c commited on
Commit
f725527
·
verified ·
1 Parent(s): bce22bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -51
app.py CHANGED
@@ -10,35 +10,16 @@ import torch.nn.functional as F
10
  import torch.optim as optim
11
  import gradio as gr
12
 
 
13
  os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
14
 
 
15
  SYSTEM_INSTRUCTION = "You are a friendly and concise general-purpose AI assistant named OkemoLLM. You only respond in English. Keep your answers brief unless the user asks you to elaborate or think longer. Be silly"
16
  ONLINE_LEARNING_EPOCHS = 1
17
 
18
-
19
- class Voc:
20
- def __init__(self):
21
- self.PAD, self.SOS, self.EOS, self.UNK, self.SYSTEM = "<PAD>", "<SOS>", "<EOS>", "<UNK>", "<SYSTEM>"
22
- self.word2index = {self.PAD: 0, self.SOS: 1, self.EOS: 2, self.UNK: 3, self.SYSTEM: 4}
23
- self.index2word = {0: self.PAD, 1: self.SOS, 2: self.EOS, 3: self.UNK, 4: self.SYSTEM}
24
- self.n_words = 5
25
-
26
- @staticmethod
27
- def load_from_checkpoint(checkpoint):
28
- voc = Voc()
29
- voc.word2index = checkpoint["voc_word2index"]
30
- voc.index2word = checkpoint["voc_index2word"]
31
- voc.n_words = len(voc.word2index)
32
- if "special_tokens" in checkpoint:
33
- tokens = checkpoint["special_tokens"]
34
- voc.PAD = tokens.get("PAD", "<PAD>")
35
- voc.SOS = tokens.get("SOS", "<SOS>")
36
- voc.EOS = tokens.get("EOS", "<EOS>")
37
- voc.UNK = tokens.get("UNK", "<UNK>")
38
- voc.SYSTEM = tokens.get("SYSTEM", "<SYSTEM>")
39
- return voc
40
-
41
-
42
  _WORD_TOKEN_CHARS = r"a-z0-9\'\-"
43
  _SPLIT_PUNCT = r"\.\,\!\?\:\;\(\)\[\]\{\}\"\/\\@#\$%\^&\*\+\<>=~`"
44
  _token_re = re.compile(rf"[{_WORD_TOKEN_CHARS}]+|[{_SPLIT_PUNCT}]", flags=re.IGNORECASE)
@@ -73,7 +54,39 @@ def check_repetition(text: str, max_repeat: int = 2):
73
  return True
74
  return False
75
 
 
 
 
 
 
 
 
 
 
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  class PositionalEncoding(nn.Module):
78
  def __init__(self, d_model, max_len=5000):
79
  super().__init__()
@@ -87,7 +100,6 @@ class PositionalEncoding(nn.Module):
87
  def forward(self, x):
88
  return x + self.pe[:, : x.size(1), :]
89
 
90
-
91
  class GPT(nn.Module):
92
  def __init__(self, n_words, d_model, n_layers, n_head, d_ff, dropout=0.1):
93
  super().__init__()
@@ -97,6 +109,7 @@ class GPT(nn.Module):
97
  enc_layer = nn.TransformerEncoderLayer(d_model, n_head, d_ff, dropout, batch_first=True)
98
  self.transformer = nn.TransformerEncoder(enc_layer, n_layers)
99
  self.fc = nn.Linear(d_model, n_words, bias=False)
 
100
  self.fc.weight = self.embedding.weight
101
 
102
  def forward(self, x, mask=None, key_padding_mask=None):
@@ -106,16 +119,12 @@ class GPT(nn.Module):
106
  out = self.transformer(x, mask=mask, src_key_padding_mask=key_padding_mask)
107
  return self.fc(out)
108
 
109
-
110
- def indexes_from_sentence(voc, sentence):
111
- sanitized = " ".join(tokenize(sentence))
112
- prompt_tokens = [voc.SYSTEM] + tokenize(sanitized)
113
- return [voc.word2index.get(tok, voc.word2index[voc.UNK]) for tok in prompt_tokens] + [voc.word2index[voc.EOS]]
114
-
115
  def make_bool_causal_mask(sz, device):
116
  return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)
117
 
118
-
 
 
119
  device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")
120
 
121
  CHECKPOINT_PATH = "checkpoint.pth"
@@ -126,7 +135,7 @@ if not os.path.exists(CHECKPOINT_PATH):
126
  "voc_index2word": Voc().index2word,
127
  "gpt_model_state_dict": None
128
  }
129
-
130
  d_model = 768
131
  n_head = 48
132
  d_ff = 768
@@ -138,7 +147,6 @@ if not os.path.exists(CHECKPOINT_PATH):
138
 
139
  voc = Voc()
140
  gpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)
141
-
142
  else:
143
  checkpoint = torch.load(CHECKPOINT_PATH, map_location=device)
144
  voc = Voc.load_from_checkpoint(checkpoint)
@@ -150,6 +158,7 @@ else:
150
  dropout = 0.1
151
  max_length = 512
152
  k_sampling = 20
 
153
  LEARNING_RATE = 1e-6
154
 
155
  gpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)
@@ -159,7 +168,9 @@ else:
159
  optimizer = optim.Adam(gpt_model.parameters(), lr=LEARNING_RATE)
160
  criterion = nn.CrossEntropyLoss(ignore_index=voc.word2index[voc.PAD])
161
 
162
-
 
 
163
  def perform_web_search(query):
164
  print(f"**Web Search Triggered for:** '{query}'")
165
  query_lower = query.lower()
@@ -170,9 +181,13 @@ def perform_web_search(query):
170
  else:
171
  return ""
172
 
173
-
 
 
174
  def online_update(model, input_sentence, target_response, max_seq_len, search_context="", conversation_context=""):
175
- is_response_clean = is_english_like(target_response, min_alpha_ratio=0.7) and not any(t in target_response for t in [voc.UNK, "i couldn't generate"])
 
 
176
  is_not_repetitive = not check_repetition(target_response, max_repeat=2)
177
 
178
  if not is_response_clean or not is_not_repetitive:
@@ -216,7 +231,9 @@ def online_update(model, input_sentence, target_response, max_seq_len, search_co
216
  model.eval()
217
  print(f"Online update performed over {ONLINE_LEARNING_EPOCHS} epochs. Final Loss: {last_loss:.4f}")
218
 
219
-
 
 
220
  def generate_response(prompt, search_context="", conversation_context=""):
221
  if not is_english_like(prompt):
222
  return "Please use English. Non-English input was detected."
@@ -288,7 +305,9 @@ def generate_response(prompt, search_context="", conversation_context=""):
288
  return "I couldn't generate a stable English response. Please try a shorter or clearer prompt in English."
289
  return text
290
 
291
-
 
 
292
  def process_feedback(history, rating):
293
  if not history or not history[-1][1]:
294
  return history, "Cannot process feedback: No recent AI response found."
@@ -314,16 +333,17 @@ def process_feedback(history, rating):
314
  search_context="",
315
  conversation_context=conversation_context
316
  )
317
- feedback_message = f"Thanks for the **Good Response** rating! I just learned from that. Keep the good prompts coming! ✨"
318
-
319
  elif rating == "Bad Response":
320
- feedback_message = f"Acknowledged **Bad Response** feedback. I will try to be better! 🛠️"
321
  else:
322
  feedback_message = "Unknown rating received."
323
 
324
  return history, feedback_message
325
 
326
-
 
 
327
  def on_submit(user_message, history, uploaded_file, web_search_enabled):
328
  if history is None:
329
  history = []
@@ -376,9 +396,9 @@ def on_submit(user_message, history, uploaded_file, web_search_enabled):
376
  history[-1][1] = reply
377
  return history, ""
378
 
379
-
380
- # --- Gradio UI & API ---
381
-
382
  with gr.Blocks(title="OkemoLLM") as demo:
383
  gr.Markdown("# OkemoLLM (English-only, Online Learning & Web Search Enabled with 1-Turn Context)")
384
  chat = gr.Chatbot(height=500)
@@ -398,6 +418,7 @@ with gr.Blocks(title="OkemoLLM") as demo:
398
  updated_history = (history or []) + [[message, None]]
399
  return updated_history, ""
400
 
 
401
  msg.submit(
402
  add_user_message_to_history,
403
  [msg, chat, uploaded_file_state, web_search_enabled_state],
@@ -422,6 +443,7 @@ with gr.Blocks(title="OkemoLLM") as demo:
422
 
423
  clear.click(lambda: [], None, chat, queue=False)
424
 
 
425
  def feedback_good_wrapper(history_state):
426
  return process_feedback(history_state, "Good Response")
427
 
@@ -447,14 +469,10 @@ with gr.Blocks(title="OkemoLLM") as demo:
447
  )
448
 
449
  # Public API endpoint for chat.js: /chat_submit
450
- # Accepts: [msg:str, chat:list[list[str,str]], uploaded_file:File|None, web_enabled:bool]
451
- # Returns: [updated_history:list[list[str,str]], status_msg:str]
452
  def chat_submit_api(msg_value, chat_value, uploaded_file_value, web_enabled_value):
453
- # Step 1: mirror UI: add_user_message_to_history -> returns (history, "")
454
  updated_history, _ = add_user_message_to_history(
455
  msg_value, chat_value or [], uploaded_file_value, web_enabled_value
456
  )
457
- # Step 2: on_submit -> returns (history, "")
458
  final_history, status_msg = on_submit(
459
  msg_value, updated_history, uploaded_file_value, web_enabled_value
460
  )
@@ -477,4 +495,4 @@ with gr.Blocks(title="OkemoLLM") as demo:
477
  allow_flagging="never",
478
  )
479
 
480
- demo.queue(api_open=True).launch()
 
10
  import torch.optim as optim
11
  import gradio as gr
12
 
13
+ # Ensure MPS fallback on macOS
14
  os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
15
 
16
+ # System prompt and online learning epochs
17
  SYSTEM_INSTRUCTION = "You are a friendly and concise general-purpose AI assistant named OkemoLLM. You only respond in English. Keep your answers brief unless the user asks you to elaborate or think longer. Be silly"
18
  ONLINE_LEARNING_EPOCHS = 1
19
 
20
+ # -------------------------------
21
+ # Tokenization & English-only utils
22
+ # -------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  _WORD_TOKEN_CHARS = r"a-z0-9\'\-"
24
  _SPLIT_PUNCT = r"\.\,\!\?\:\;\(\)\[\]\{\}\"\/\\@#\$%\^&\*\+\<>=~`"
25
  _token_re = re.compile(rf"[{_WORD_TOKEN_CHARS}]+|[{_SPLIT_PUNCT}]", flags=re.IGNORECASE)
 
54
  return True
55
  return False
56
 
57
+ # -------------------------------
58
+ # Vocabulary
59
+ # -------------------------------
60
+ class Voc:
61
+ def __init__(self):
62
+ self.PAD, self.SOS, self.EOS, self.UNK, self.SYSTEM = "<PAD>", "<SOS>", "<EOS>", "<UNK>", "<SYSTEM>"
63
+ self.word2index = {self.PAD: 0, self.SOS: 1, self.EOS: 2, self.UNK: 3, self.SYSTEM: 4}
64
+ self.index2word = {0: self.PAD, 1: self.SOS, 2: self.EOS, 3: self.UNK, 4: self.SYSTEM}
65
+ self.n_words = 5
66
 
67
+ @staticmethod
68
+ def load_from_checkpoint(checkpoint):
69
+ voc = Voc()
70
+ voc.word2index = checkpoint["voc_word2index"]
71
+ voc.index2word = checkpoint["voc_index2word"]
72
+ voc.n_words = len(voc.word2index)
73
+ if "special_tokens" in checkpoint:
74
+ tokens = checkpoint["special_tokens"]
75
+ voc.PAD = tokens.get("PAD", "<PAD>")
76
+ voc.SOS = tokens.get("SOS", "<SOS>")
77
+ voc.EOS = tokens.get("EOS", "<EOS>")
78
+ voc.UNK = tokens.get("UNK", "<UNK>")
79
+ voc.SYSTEM = tokens.get("SYSTEM", "<SYSTEM>")
80
+ return voc
81
+
82
+ def indexes_from_sentence(voc, sentence):
83
+ sanitized = " ".join(tokenize(sentence))
84
+ prompt_tokens = [voc.SYSTEM] + tokenize(sanitized)
85
+ return [voc.word2index.get(tok, voc.word2index[voc.UNK]) for tok in prompt_tokens] + [voc.word2index[voc.EOS]]
86
+
87
+ # -------------------------------
88
+ # Model
89
+ # -------------------------------
90
  class PositionalEncoding(nn.Module):
91
  def __init__(self, d_model, max_len=5000):
92
  super().__init__()
 
100
  def forward(self, x):
101
  return x + self.pe[:, : x.size(1), :]
102
 
 
103
  class GPT(nn.Module):
104
  def __init__(self, n_words, d_model, n_layers, n_head, d_ff, dropout=0.1):
105
  super().__init__()
 
109
  enc_layer = nn.TransformerEncoderLayer(d_model, n_head, d_ff, dropout, batch_first=True)
110
  self.transformer = nn.TransformerEncoder(enc_layer, n_layers)
111
  self.fc = nn.Linear(d_model, n_words, bias=False)
112
+ # Tie weights
113
  self.fc.weight = self.embedding.weight
114
 
115
  def forward(self, x, mask=None, key_padding_mask=None):
 
119
  out = self.transformer(x, mask=mask, src_key_padding_mask=key_padding_mask)
120
  return self.fc(out)
121
 
 
 
 
 
 
 
122
  def make_bool_causal_mask(sz, device):
123
  return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)
124
 
125
+ # -------------------------------
126
+ # Device & Checkpoint
127
+ # -------------------------------
128
  device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")
129
 
130
  CHECKPOINT_PATH = "checkpoint.pth"
 
135
  "voc_index2word": Voc().index2word,
136
  "gpt_model_state_dict": None
137
  }
138
+ # Safe defaults
139
  d_model = 768
140
  n_head = 48
141
  d_ff = 768
 
147
 
148
  voc = Voc()
149
  gpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)
 
150
  else:
151
  checkpoint = torch.load(CHECKPOINT_PATH, map_location=device)
152
  voc = Voc.load_from_checkpoint(checkpoint)
 
158
  dropout = 0.1
159
  max_length = 512
160
  k_sampling = 20
161
+ # Keep low LR even when checkpoint exists to avoid instability
162
  LEARNING_RATE = 1e-6
163
 
164
  gpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)
 
168
  optimizer = optim.Adam(gpt_model.parameters(), lr=LEARNING_RATE)
169
  criterion = nn.CrossEntropyLoss(ignore_index=voc.word2index[voc.PAD])
170
 
171
+ # -------------------------------
172
+ # Mocked web search (ASCII English only)
173
+ # -------------------------------
174
  def perform_web_search(query):
175
  print(f"**Web Search Triggered for:** '{query}'")
176
  query_lower = query.lower()
 
181
  else:
182
  return ""
183
 
184
+ # -------------------------------
185
+ # Online learning
186
+ # -------------------------------
187
  def online_update(model, input_sentence, target_response, max_seq_len, search_context="", conversation_context=""):
188
+ is_response_clean = is_english_like(target_response, min_alpha_ratio=0.7) and not any(
189
+ t in target_response for t in [voc.UNK, "i couldn't generate"]
190
+ )
191
  is_not_repetitive = not check_repetition(target_response, max_repeat=2)
192
 
193
  if not is_response_clean or not is_not_repetitive:
 
231
  model.eval()
232
  print(f"Online update performed over {ONLINE_LEARNING_EPOCHS} epochs. Final Loss: {last_loss:.4f}")
233
 
234
+ # -------------------------------
235
+ # Response generation
236
+ # -------------------------------
237
  def generate_response(prompt, search_context="", conversation_context=""):
238
  if not is_english_like(prompt):
239
  return "Please use English. Non-English input was detected."
 
305
  return "I couldn't generate a stable English response. Please try a shorter or clearer prompt in English."
306
  return text
307
 
308
+ # -------------------------------
309
+ # Feedback handling
310
+ # -------------------------------
311
  def process_feedback(history, rating):
312
  if not history or not history[-1][1]:
313
  return history, "Cannot process feedback: No recent AI response found."
 
333
  search_context="",
334
  conversation_context=conversation_context
335
  )
336
+ feedback_message = "Thanks for the **Good Response** rating! I just learned from that. Keep the good prompts coming! ✨"
 
337
  elif rating == "Bad Response":
338
+ feedback_message = "Acknowledged **Bad Response** feedback. I will try to be better! 🛠️"
339
  else:
340
  feedback_message = "Unknown rating received."
341
 
342
  return history, feedback_message
343
 
344
+ # -------------------------------
345
+ # Submit handling (UI + API shared)
346
+ # -------------------------------
347
  def on_submit(user_message, history, uploaded_file, web_search_enabled):
348
  if history is None:
349
  history = []
 
396
  history[-1][1] = reply
397
  return history, ""
398
 
399
+ # -------------------------------
400
+ # Gradio UI & API
401
+ # -------------------------------
402
  with gr.Blocks(title="OkemoLLM") as demo:
403
  gr.Markdown("# OkemoLLM (English-only, Online Learning & Web Search Enabled with 1-Turn Context)")
404
  chat = gr.Chatbot(height=500)
 
418
  updated_history = (history or []) + [[message, None]]
419
  return updated_history, ""
420
 
421
+ # UI submit chain mirrors API
422
  msg.submit(
423
  add_user_message_to_history,
424
  [msg, chat, uploaded_file_state, web_search_enabled_state],
 
443
 
444
  clear.click(lambda: [], None, chat, queue=False)
445
 
446
+ # Feedback endpoints
447
  def feedback_good_wrapper(history_state):
448
  return process_feedback(history_state, "Good Response")
449
 
 
469
  )
470
 
471
  # Public API endpoint for chat.js: /chat_submit
 
 
472
  def chat_submit_api(msg_value, chat_value, uploaded_file_value, web_enabled_value):
 
473
  updated_history, _ = add_user_message_to_history(
474
  msg_value, chat_value or [], uploaded_file_value, web_enabled_value
475
  )
 
476
  final_history, status_msg = on_submit(
477
  msg_value, updated_history, uploaded_file_value, web_enabled_value
478
  )
 
495
  allow_flagging="never",
496
  )
497
 
498
+ demo.queue(api_open=True).launch()