ar12c commited on
Commit
bd1aa9d
·
verified ·
1 Parent(s): efd6bbf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -17
app.py CHANGED
@@ -11,6 +11,11 @@ from collections import defaultdict
11
 
12
  os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
13
 
 
 
 
 
 
14
  class Voc:
15
  def __init__(self):
16
  self.PAD, self.SOS, self.EOS, self.UNK, self.SYSTEM = "<PAD>", "<SOS>", "<EOS>", "<UNK>", "<SYSTEM>"
@@ -63,6 +68,19 @@ def is_english_like(text: str, min_alpha_ratio: float = 0.6, max_non_ascii: int
63
  ratio = (letters / total) if total > 0 else 0.0
64
  return ratio >= min_alpha_ratio
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  class PositionalEncoding(nn.Module):
67
  def __init__(self, d_model, max_len=5000):
68
  super().__init__()
@@ -121,7 +139,8 @@ if not os.path.exists(CHECKPOINT_PATH):
121
  dropout = 0.1
122
  max_length = 256
123
  k_sampling = 20
124
- LEARNING_RATE = 1e-5
 
125
 
126
  voc = Voc()
127
  gpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)
@@ -137,7 +156,8 @@ else:
137
  dropout = 0.1
138
  max_length = 256
139
  k_sampling = 20
140
- LEARNING_RATE = 1e-3 # Increased from 1e-5 for rapid online learning
 
141
 
142
  gpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)
143
  # Only load state if we have a real checkpoint
@@ -167,8 +187,11 @@ def online_update(model, input_sentence, target_response, max_seq_len, search_co
167
  This is where the model learns from the user's turn.
168
  """
169
  # 1. Validation Check: Ensure we only learn from responses that are clean and English-like.
170
- if not is_english_like(target_response, min_alpha_ratio=0.7) or any(t in target_response for t in [voc.UNK, "i couldn't generate"]):
171
- print("Skipping online update: Target response is non-English or corrupted.")
 
 
 
172
  return
173
 
174
  prefix_text = ""
@@ -176,8 +199,9 @@ def online_update(model, input_sentence, target_response, max_seq_len, search_co
176
  # 2. Incorporate Web Context for Learning
177
  prefix_text = f"According to a search result: {to_ascii(search_context)}. "
178
 
179
- # Sanitize prompt
180
- full_prompt_text = to_ascii(prefix_text + input_sentence)
 
181
 
182
  prompt_tokens = indexes_from_sentence(voc, full_prompt_text)[:-1]
183
  # Sanitize response
@@ -214,16 +238,16 @@ def online_update(model, input_sentence, target_response, max_seq_len, search_co
214
 
215
  def generate_response(prompt, search_context=""):
216
  # Reject non-English inputs early
 
217
  if not is_english_like(prompt):
218
  return "Please use English. Non-English input was detected."
219
 
220
- full_input = prompt
221
  if search_context:
222
  prefix_text = f"According to a search result: {to_ascii(search_context)}. "
223
- # 2. Incorporate Web Context for Generation
224
- full_input = prefix_text + prompt
225
-
226
- # Sanitize to ASCII English-only before tokenizing
227
  full_input = to_ascii(full_input)
228
 
229
  gpt_model.eval()
@@ -255,7 +279,6 @@ def generate_response(prompt, search_context=""):
255
  candidate_word = voc.index2word.get(candidate_id, voc.UNK)
256
 
257
  # English-only token check: must be ASCII and pass tokenizer (letters/digits/punct)
258
- candidate_ascii = to_ascii(candidate_word)
259
  token_ok = is_english_like(candidate_word, min_alpha_ratio=0.1, max_non_ascii=0)
260
 
261
  if candidate_id == voc.word2index[voc.EOS]:
@@ -289,8 +312,8 @@ def generate_response(prompt, search_context=""):
289
  text = re.sub(r"\s+([,.!?;:])", r"\1", text)
290
  text = text.strip()
291
 
292
- if not text:
293
- return "I couldn't generate an English response. Please try a shorter or clearer prompt in English."
294
  return text
295
 
296
  with gr.Blocks(title="OkemoLLM") as demo:
@@ -307,9 +330,6 @@ with gr.Blocks(title="OkemoLLM") as demo:
307
  is_instruction = any(user_message.lower().startswith(p) for p in ["please generate", "provide a much more detailed", "provide a different"])
308
 
309
  # 2. Extract the clean message for the model input
310
- # This requires reversing the formatting added in the JavaScript (if possible)
311
- # For regeneration, the actual prompt is inside quotes: '...: "clean prompt"'
312
-
313
  # Heuristic: Find content inside the last pair of quotes, assuming it's the original prompt
314
  match = re.search(r':\s*"(.+?)"$', user_message)
315
 
@@ -347,6 +367,7 @@ with gr.Blocks(title="OkemoLLM") as demo:
347
  online_update(gpt_model, clean_user_message, reply, max_length, search_context=search_context_text)
348
 
349
  # 6. Update the history: Use the clean user message, regardless of the prompt sent to the model.
 
350
  history[-1] = (clean_user_message, reply)
351
  return history, ""
352
 
 
11
 
12
  os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
13
 
14
+ # --- NEW: Descriptive System Prompt ---
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
+ # --- END NEW SYSTEM PROMPT ---
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>"
 
68
  ratio = (letters / total) if total > 0 else 0.0
69
  return ratio >= min_alpha_ratio
70
 
71
+ def check_repetition(text: str, max_repeat: int = 2):
72
+ """Checks if any single token is repeated more than max_repeat times consecutively."""
73
+ tokens = tokenize(text)
74
+ if not tokens:
75
+ return False
76
+
77
+ # Check for consecutive triples (or more) of the same token
78
+ for i in range(len(tokens) - max_repeat):
79
+ if all(tokens[i] == tokens[j] for j in range(i, i + max_repeat + 1)):
80
+ return True
81
+ return False
82
+
83
+
84
  class PositionalEncoding(nn.Module):
85
  def __init__(self, d_model, max_len=5000):
86
  super().__init__()
 
139
  dropout = 0.1
140
  max_length = 256
141
  k_sampling = 20
142
+ # Safer default LEARNING_RATE
143
+ LEARNING_RATE = 1e-5
144
 
145
  voc = Voc()
146
  gpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)
 
156
  dropout = 0.1
157
  max_length = 256
158
  k_sampling = 20
159
+ # Using the safer LEARNING_RATE here as well
160
+ LEARNING_RATE = 1e-5
161
 
162
  gpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)
163
  # Only load state if we have a real checkpoint
 
187
  This is where the model learns from the user's turn.
188
  """
189
  # 1. Validation Check: Ensure we only learn from responses that are clean and English-like.
190
+ 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"])
191
+ is_not_repetitive = not check_repetition(target_response, max_repeat=2)
192
+
193
+ if not is_response_clean or not is_not_repetitive:
194
+ print("Skipping online update: Target response is non-English, corrupted, or highly repetitive.")
195
  return
196
 
197
  prefix_text = ""
 
199
  # 2. Incorporate Web Context for Learning
200
  prefix_text = f"According to a search result: {to_ascii(search_context)}. "
201
 
202
+ # Combine System Instruction, Search Context, and User Prompt
203
+ full_prompt_text = f"{SYSTEM_INSTRUCTION} {prefix_text} {input_sentence}"
204
+ full_prompt_text = to_ascii(full_prompt_text)
205
 
206
  prompt_tokens = indexes_from_sentence(voc, full_prompt_text)[:-1]
207
  # Sanitize response
 
238
 
239
  def generate_response(prompt, search_context=""):
240
  # Reject non-English inputs early
241
+ # Note: We check the prompt *before* adding the system instruction, as the instruction is always English.
242
  if not is_english_like(prompt):
243
  return "Please use English. Non-English input was detected."
244
 
245
+ prefix_text = ""
246
  if search_context:
247
  prefix_text = f"According to a search result: {to_ascii(search_context)}. "
248
+
249
+ # Combine System Instruction, Search Context, and User Prompt
250
+ full_input = f"{SYSTEM_INSTRUCTION} {prefix_text} {prompt}"
 
251
  full_input = to_ascii(full_input)
252
 
253
  gpt_model.eval()
 
279
  candidate_word = voc.index2word.get(candidate_id, voc.UNK)
280
 
281
  # English-only token check: must be ASCII and pass tokenizer (letters/digits/punct)
 
282
  token_ok = is_english_like(candidate_word, min_alpha_ratio=0.1, max_non_ascii=0)
283
 
284
  if candidate_id == voc.word2index[voc.EOS]:
 
312
  text = re.sub(r"\s+([,.!?;:])", r"\1", text)
313
  text = text.strip()
314
 
315
+ if not text or check_repetition(text):
316
+ return "I couldn't generate a stable English response. Please try a shorter or clearer prompt in English."
317
  return text
318
 
319
  with gr.Blocks(title="OkemoLLM") as demo:
 
330
  is_instruction = any(user_message.lower().startswith(p) for p in ["please generate", "provide a much more detailed", "provide a different"])
331
 
332
  # 2. Extract the clean message for the model input
 
 
 
333
  # Heuristic: Find content inside the last pair of quotes, assuming it's the original prompt
334
  match = re.search(r':\s*"(.+?)"$', user_message)
335
 
 
367
  online_update(gpt_model, clean_user_message, reply, max_length, search_context=search_context_text)
368
 
369
  # 6. Update the history: Use the clean user message, regardless of the prompt sent to the model.
370
+ # This is CRITICAL: it overwrites whatever the server returned in the user slot.
371
  history[-1] = (clean_user_message, reply)
372
  return history, ""
373