ar12c commited on
Commit
79bae03
·
verified ·
1 Parent(s): 641b2bd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +2 -303
app.py CHANGED
@@ -13,7 +13,7 @@ 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
  # --- NEW: Online Learning Hyperparameter ---
19
  ONLINE_LEARNING_EPOCHS = 1 # Changed from 5 to 1
@@ -185,305 +185,4 @@ def perform_web_search(query):
185
  return ""
186
 
187
  # Online update uses sanitized English-only inputs
188
- # MODIFICATION: Added conversation_context argument
189
- def online_update(model, input_sentence, target_response, max_seq_len, search_context="", conversation_context=""):
190
- """
191
- Performs a fixed number of training steps (epochs), incorporating sanitized English-only search context.
192
- This is where the model learns from the user's turn.
193
- """
194
- # 1. Validation Check: Ensure we only learn from responses that are clean and English-like.
195
- 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"])
196
- is_not_repetitive = not check_repetition(target_response, max_repeat=2)
197
-
198
- if not is_response_clean or not is_not_repetitive:
199
- print("Skipping online update: Target response is non-English, corrupted, or highly repetitive.")
200
- return
201
-
202
- prefix_text = ""
203
- if search_context:
204
- # 2. Incorporate Web Context for Learning
205
- prefix_text = f"According to a search result: {to_ascii(search_context)}. "
206
-
207
- # MODIFICATION: Prepend conversation context to the prompt
208
- context_prefix = f"{conversation_context} " if conversation_context else ""
209
-
210
- # Combine System Instruction, Conversation Context, Search Context, and User Prompt
211
- full_prompt_text = f"{SYSTEM_INSTRUCTION} {context_prefix}{prefix_text} {input_sentence}"
212
- full_prompt_text = to_ascii(full_prompt_text)
213
-
214
- prompt_tokens = indexes_from_sentence(voc, full_prompt_text)[:-1]
215
- # Sanitize response
216
- sanitized_response = to_ascii(target_response)
217
- response_tokens = indexes_from_sentence(voc, sanitized_response)[1:]
218
-
219
- # Create the training sequence: [SYSTEM] [CONTEXT] [USER PROMPT] [MODEL REPLY] [EOS]
220
- full_sequence_ids = prompt_tokens + response_tokens
221
- input_ids = full_sequence_ids[:-1]
222
- target_ids = full_sequence_ids[1:]
223
-
224
- if len(input_ids) < 2 or len(input_ids) != len(target_ids) or len(input_ids) > max_seq_len:
225
- print(f"Skipping online update. Sequence length: {len(input_ids)}")
226
- return
227
-
228
- input_tensor = torch.tensor(input_ids, dtype=torch.long, device=device).unsqueeze(0)
229
- target_tensor = torch.tensor(target_ids, dtype=torch.long, device=device)
230
-
231
- L = input_tensor.size(1)
232
-
233
- model.train()
234
- causal = make_bool_causal_mask(L, device)
235
-
236
- # Loop 1 time for a fixed number of learning epochs
237
- last_loss = 0.0
238
- for epoch in range(ONLINE_LEARNING_EPOCHS):
239
- optimizer.zero_grad()
240
-
241
- # FIX: Changed src_key_padding_mask to key_padding_mask to match GPT.forward signature
242
- logits = model(input_tensor, mask=causal, key_padding_mask=None)
243
- loss = criterion(logits.squeeze(0), target_tensor)
244
-
245
- loss.backward()
246
- optimizer.step()
247
- last_loss = loss.item()
248
-
249
- model.eval()
250
- print(f"Online update performed over {ONLINE_LEARNING_EPOCHS} epochs. Final Loss: {last_loss:.4f}")
251
-
252
- # MODIFICATION: Added conversation_context argument
253
- def generate_response(prompt, search_context="", conversation_context=""):
254
- # Reject non-English inputs early
255
- if not is_english_like(prompt):
256
- return "Please use English. Non-English input was detected."
257
-
258
- prefix_text = ""
259
- if search_context:
260
- prefix_text = f"According to a search result: {to_ascii(search_context)}. "
261
-
262
- # MODIFICATION: Prepend conversation context to the prompt
263
- context_prefix = f"{conversation_context} " if conversation_context else ""
264
-
265
- # Combine System Instruction, Conversation Context, Search Context, and User Prompt
266
- full_input = f"{SYSTEM_INSTRUCTION} {context_prefix}{prefix_text} {prompt}"
267
- full_input = to_ascii(full_input)
268
-
269
- gpt_model.eval()
270
-
271
- initial_tokens = indexes_from_sentence(voc, full_input)
272
- input_tensor = torch.tensor(initial_tokens, dtype=torch.long, device=device).unsqueeze(0)
273
- max_total_len = len(initial_tokens) + max_length
274
- generated = []
275
-
276
- with torch.no_grad():
277
- for _ in range(max_length):
278
- L = input_tensor.size(1)
279
- causal = make_bool_causal_mask(L, device)
280
- padmask = (input_tensor == voc.word2index[voc.PAD])
281
- logits = gpt_model(input_tensor, mask=causal, key_padding_mask=padmask)
282
- last = logits[:, -1, :].float()
283
-
284
- topk_vals, topk_idx = torch.topk(last, k_sampling)
285
- topk_vals = torch.clamp(topk_vals, min=-30.0, max=30.0)
286
- probs = F.softmax(topk_vals, dim=-1).float()
287
-
288
- # Retry sampling until we pick an English-like token or hit attempts cap
289
- attempts = 0
290
- next_id = None
291
- while attempts < 5:
292
- # Use multionmial sampling to select a token
293
- pick_rel = torch.multinomial(probs, 1).item()
294
- candidate_id = topk_idx.squeeze(0)[pick_rel].item()
295
- candidate_word = voc.index2word.get(candidate_id, voc.UNK)
296
-
297
- # English-only token check: must be ASCII and pass tokenizer (letters/digits/punct)
298
- token_ok = is_english_like(candidate_word, min_alpha_ratio=0.1, max_non_ascii=0)
299
-
300
- if candidate_id == voc.word2index[voc.EOS]:
301
- next_id = candidate_id
302
- break
303
- if token_ok:
304
- next_id = candidate_id
305
- break
306
-
307
- attempts += 1
308
-
309
- if next_id is None:
310
- # Fallback to UNK if no English-like token found
311
- next_id = voc.word2index[voc.UNK]
312
-
313
- if next_id == voc.word2index[voc.EOS]:
314
- break
315
-
316
- generated.append(next_id)
317
- input_tensor = torch.cat(
318
- [input_tensor, torch.tensor([[next_id]], device=device, dtype=torch.long)],
319
- dim=1
320
- )
321
-
322
- words = [voc.index2word.get(t, voc.UNK) for t in generated]
323
- # Sanitize assembled text to ASCII English-only
324
- text = " ".join(words)
325
- text = to_ascii(text)
326
- text = re.sub(r"\s+([,.!?;:])", r"\1", text)
327
- text = text.strip()
328
-
329
- if not text or check_repetition(text):
330
- return "I couldn't generate a stable English response. Please try a shorter or clearer prompt in English."
331
- return text
332
-
333
-
334
- # --- NEW GRADIO FUNCTION TO HANDLE FEEDBACK ---
335
- def process_feedback(history, rating):
336
- """
337
- Handles feedback from the client. Only triggers online_update (training) for "Good Response".
338
- For "Bad Response", it logs the event but skips training.
339
- """
340
- if not history or not history[-1][1]:
341
- return history, "Cannot process feedback: No recent AI response found."
342
-
343
- last_user_message, last_ai_response = history[-1]
344
-
345
- # 1. Log the event (always)
346
- print(f"\n--- FEEDBACK RECEIVED ---")
347
- print(f"Rating: {rating}")
348
- print(f"User Prompt: '{last_user_message}'")
349
- print(f"AI Response: '{last_ai_response}'")
350
- print(f"-------------------------\n")
351
-
352
- if rating == "Good Response":
353
- # 2. Extract conversation context from previous turn (if available)
354
- conversation_context = ""
355
- if len(history) >= 2 and history[-2][1]:
356
- last_user, last_ai = history[-2]
357
- conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
358
-
359
- # 3. Trigger online update (training) only for good responses
360
- # NOTE: We skip searching again, assuming the previous generation step included search if needed.
361
- # This keeps the training focused on the interaction itself.
362
- online_update(
363
- gpt_model,
364
- last_user_message,
365
- last_ai_response,
366
- max_length,
367
- search_context="", # Search context needs to be cached/passed if required for learning
368
- conversation_context=conversation_context
369
- )
370
- feedback_message = f"Thanks for the **Good Response** rating! I just learned from that. Keep the good prompts coming! ✨"
371
-
372
- elif rating == "Bad Response":
373
- # 4. Skip training for bad responses to avoid confusing the model with unstable/undesired data.
374
- feedback_message = f"Acknowledged **Bad Response** feedback. I will try to be better! 🛠️"
375
-
376
- else:
377
- feedback_message = "Unknown rating received."
378
-
379
- return history, feedback_message
380
- # --- END NEW GRADIO FUNCTION ---
381
-
382
-
383
- with gr.Blocks(title="OkemoLLM") as demo:
384
- gr.Markdown("# OkemoLLM (English-only, Online Learning & Web Search Enabled with 1-Turn Context)")
385
- chat = gr.Chatbot(height=500)
386
- msg = gr.Textbox(placeholder="Type your message…", label="Message")
387
- clear = gr.Button("Clear")
388
-
389
- def on_submit(user_message, history):
390
- # NOTE: This function receives the *final* instructional prompt from the web app
391
-
392
- # 1. Determine if this is a regeneration/enhancement instruction
393
- is_instruction = any(user_message.lower().startswith(p) for p in ["please generate", "provide a much more detailed", "provide a different"])
394
-
395
- # 2. Extract the clean message for the model input
396
- match = re.search(r':\s*"(.+?)"$', user_message)
397
-
398
- if is_instruction and match:
399
- clean_user_message = match.group(1).strip()
400
- model_prompt = user_message # Use the full instruction for generation
401
- else:
402
- clean_user_message = user_message
403
- model_prompt = user_message
404
-
405
- # 3. CONTEXT EXTRACTION: Get the previous turn (User + AI)
406
- conversation_context = ""
407
- # The last element of history is usually the current, incomplete user turn (user_message, None)
408
- # unless it's a regeneration request. We want the turn *before* the current one.
409
- context_history = history if is_instruction else history[:-1]
410
-
411
- if context_history and context_history[-1][1]:
412
- last_user, last_ai = context_history[-1]
413
- # Format: "User: [message] Response: [reply]"
414
- # Use to_ascii to ensure the context string is clean before being tokenized later
415
- conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
416
- print(f"Context included: {conversation_context}")
417
-
418
-
419
- # 4. Enforce English-only input for the *clean* message (before adding instructions)
420
- if not is_english_like(clean_user_message):
421
- history = history + [(clean_user_message, "Please use English. Non-English input was detected.")]
422
- return history, ""
423
-
424
- search_needed = "?" in clean_user_message or any(
425
- clean_user_message.lower().startswith(q) for q in ["what is", "who is", "how to"]
426
- )
427
-
428
- search_context_text = ""
429
- if search_needed:
430
- search_context_text = perform_web_search(clean_user_message)
431
-
432
- # 5. Generate response using the appropriate (potentially instructional) prompt
433
- if not is_instruction:
434
- history = history + [(clean_user_message, None)]
435
-
436
- # MODIFICATION: Pass conversation_context to generator
437
- reply = generate_response(model_prompt, search_context=search_context_text, conversation_context=conversation_context)
438
-
439
- # 6. Skip automatic training on submit. Training now only occurs via the 'Good Response' button.
440
- # if not is_instruction:
441
- # online_update(...)
442
-
443
- # 7. Update the history: Use the clean user message, regardless of the prompt sent to the model.
444
- history[-1] = (clean_user_message, reply)
445
- return history, ""
446
-
447
- msg.submit(on_submit, inputs=[msg, chat], outputs=[chat, msg])
448
- clear.click(lambda: [], None, chat)
449
-
450
- # --- NEW: Gradio Endpoint for Feedback ---
451
- # This single endpoint handles both good and bad responses
452
- demo.queue().custom_component(
453
- process_feedback,
454
- inputs=[chat, gr.State("Good Response")], # Initial value for State is ignored, but structure needed
455
- outputs=[chat, gr.Textbox(visible=False)] # outputs updated history and a message to the status textbox
456
- ).as_custom_function(
457
- # NOTE: The client-side JS needs to be updated to call '/process_feedback' and pass the rating.
458
- # However, for stability within Gradio, we define two specific API endpoints the client can use.
459
- # Since Gradio doesn't easily allow passing a fixed parameter value in the endpoint mapping,
460
- # we will define two distinct functions mapping to the same core logic for the client.
461
- # The client will call /feedback_good or /feedback_bad, which will run this function.
462
- # Since we cannot easily pass 'Good Response' or 'Bad Response' as a fixed argument in the custom component structure in Gradio Blocks, we will implement this via two separate, simple Gradio interface calls outside of the Blocks structure, or rely on the client to call /predict with the rating.
463
- # For simplicity and to match the client's original intent, we'll use simple Gradio interfaces.
464
- name="feedback_endpoint"
465
- )
466
-
467
- if __name__ == "__main__":
468
- # Define separate, simple Gradio interfaces that the client can hit to simulate the fixed feedback payload
469
- with gr.Blocks() as feedback_interface:
470
- gr.Interface(
471
- fn=lambda h: process_feedback(h, "Good Response"),
472
- inputs=gr.State([]),
473
- outputs=[gr.State([]), gr.Textbox()],
474
- api_name="feedback_good", # Client calls /run/feedback_good
475
- live=False,
476
- allow_flagging="never",
477
-
478
- )
479
- gr.Interface(
480
- fn=lambda h: process_feedback(h, "Bad Response"),
481
- inputs=gr.State([]),
482
- outputs=[gr.State([]), gr.Textbox()],
483
- api_name="feedback_bad", # Client calls /run/feedback_bad
484
- live=False,
485
- allow_flagging="never",
486
- )
487
-
488
- # We launch the main app demo, but the feedback endpoints are registered via their interfaces.
489
- demo.launch()
 
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 SYSTEM PROMPT ---
17
 
18
  # --- NEW: Online Learning Hyperparameter ---
19
  ONLINE_LEARNING_EPOCHS = 1 # Changed from 5 to 1
 
185
  return ""
186
 
187
  # Online update uses sanitized English-only inputs
188
+ # MODIFICATION