ar12c commited on
Commit
326427c
·
verified ·
1 Parent(s): 5d934d0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -42
app.py CHANGED
@@ -208,7 +208,7 @@ def train_model(
208
  global start_iteration, checkpoint, HP
209
 
210
  if not full_prompt_text or not desired_response_text:
211
- # If no desired response is given, return 0 loss, but don't train.
212
  return 0.0, start_iteration
213
 
214
  old_n_words = voc.n_words
@@ -222,9 +222,10 @@ def train_model(
222
  resize_model_if_needed(model, voc.n_words, HP["d_model"])
223
 
224
  # 2. Prepare Data: Input is Full Prompt, Target is Desired Response
225
- input_ids = indexes_from_sentence(full_prompt_text) # Includes SYSTEM token
226
- target_ids = indexes_from_sentence(desired_response_text) # Includes SYSTEM token
227
- target_ids = target_ids[1:] + [voc.word2index[voc.EOS]] # Remove the starting SYSTEM token, add EOS
 
228
 
229
  combined_ids = input_ids + target_ids
230
 
@@ -329,13 +330,14 @@ def generate_response(prompt: str) -> Iterator[str]:
329
  """Token-by-token streaming response generator."""
330
  gpt_model.eval()
331
 
 
332
  input_ids = indexes_from_sentence(voc, prompt)
333
 
334
  input_tensor = torch.tensor(input_ids, dtype=torch.long, device=device).unsqueeze(0)
335
  generated_token_ids = []
336
 
337
  # --- Inference Parameters ---
338
- temperature = 0.8
339
  top_k = HP.get("k_sampling", 200)
340
  # ----------------------------
341
 
@@ -391,11 +393,11 @@ def generate_response(prompt: str) -> Iterator[str]:
391
  yield word + " "
392
 
393
  # ------------------------
394
- # Core Chat Handler (STABLE INFERENCE)
395
  # ------------------------
396
  def on_submit(user_message: str, history: Optional[List[List[str]]], train_input_state: Dict[str, str], *_):
397
  """
398
- Token-by-token chat handler. Performs stable inference.
399
  """
400
  history = history or []
401
  user_message = re.sub(r'\(Attached:.*?\)|\[IMAGE_PREVIEW_URL:.*?]', '', user_message or "").strip()
@@ -409,10 +411,9 @@ def on_submit(user_message: str, history: Optional[List[List[str]]], train_input
409
  raw = perform_web_search(query)
410
  search_summary = prepare_web_content(raw)
411
 
412
- # Prepare the FULL PROMPT for generation (ONLY user content + web context)
413
- # The persona is implied by the presence of the SYSTEM token added by indexes_from_sentence.
414
- prefix = f"Web context: {search_summary}. " if search_summary else ""
415
- full_prompt = f"{prefix}{user_message}"
416
 
417
  # Store state data for the training interface and next turns
418
  current_state["full_prompt"] = full_prompt
@@ -449,19 +450,20 @@ def on_submit(user_message: str, history: Optional[List[List[str]]], train_input
449
  def feedback_train(history: List[List[str]], desired_response: str) -> str:
450
  """
451
  Endpoint for training the model based on explicit bad feedback and a desired response.
452
- This function is used by the Manual Training panel.
453
  """
454
  global start_iteration
455
 
456
  if not desired_response.strip():
457
- return "Warning: Training aborted. No desired response (Ground Truth) provided."
 
 
458
 
459
  if not history or not history[-1][0]:
460
  return "Error: Chat history is empty or missing user prompt. Cannot train."
461
 
462
  # 1. Reconstruct the full context for the training step
463
  last_user_prompt_raw = history[-1][0]
464
- # CRITICAL: We combine the full system instruction with the user's input for the TRAINING STEP.
465
  full_training_input = f"{SYSTEM_INSTRUCTION} {last_user_prompt_raw}"
466
 
467
  try:
@@ -470,18 +472,6 @@ def feedback_train(history: List[List[str]], desired_response: str) -> str:
470
  except Exception as e:
471
  return f"❌ Training Failed: {e}. Check server logs."
472
 
473
- # ------------------------
474
- # API Endpoint for Simple Logging (Used by Bad Feedback Modal without desired response)
475
- # ------------------------
476
- def simple_bad_feedback_log(history: List[List[str]], message: str) -> str:
477
- """
478
- Endpoint for logging simple bad feedback (no training).
479
- """
480
- if history and history[-1][0]:
481
- print(f"--- LOGGING BAD FEEDBACK --- User: {history[-1][0]} | AI: {history[-1][1]} | Reason: {message}")
482
- return "Bad response logged successfully."
483
- return "Bad response logged successfully (No context found)."
484
-
485
  # ------------------------
486
  # Gradio Interface
487
  # ------------------------
@@ -500,12 +490,7 @@ with gr.Blocks(title="OkemoLLM") as demo:
500
 
501
  gr.Markdown("---")
502
  gr.Markdown("## ⚙️ Manual Feedback Training")
503
- gr.Markdown("**Training is only initiated when you click 'Perform Manual Feedback Training' below.**")
504
-
505
- # --- Hidden component used to expose the /feedback_bad endpoint to the JS client ---
506
- hidden_input_bad_log = gr.Textbox(visible=False, label="Log Input")
507
- hidden_output_bad_log = gr.Textbox(visible=False, label="Log Output")
508
- # ----------------------------------------------------------------------------------
509
 
510
  with gr.Column():
511
  # Defining the train_status component here
@@ -541,16 +526,9 @@ with gr.Blocks(title="OkemoLLM") as demo:
541
  train_status
542
  )
543
 
544
- # Connect the hidden component to the simple logging function to expose /feedback_bad
545
- # This is the stable way to expose the endpoint required by the JS client.
546
- hidden_input_bad_log.change(
547
- simple_bad_feedback_log,
548
- [chat, hidden_input_bad_log], # Use chat component for history and the hidden input for the message
549
- hidden_output_bad_log,
550
- api_name="feedback_bad", # Explicitly names the API endpoint for the JS client
551
- show_progress="hidden" # Hide progress bar for this background function
552
- )
553
 
554
 
555
  if __name__ == "__main__":
556
- demo.queue(api_open=True).launch(ssr_mode=False)
 
208
  global start_iteration, checkpoint, HP
209
 
210
  if not full_prompt_text or not desired_response_text:
211
+ # NOTE: This should only be called when desired_response_text is provided by the GUI
212
  return 0.0, start_iteration
213
 
214
  old_n_words = voc.n_words
 
222
  resize_model_if_needed(model, voc.n_words, HP["d_model"])
223
 
224
  # 2. Prepare Data: Input is Full Prompt, Target is Desired Response
225
+ input_ids = indexes_from_sentence(voc, full_prompt_text)
226
+ target_ids = indexes_from_sentence(voc, desired_response_text)
227
+ # Target sequence starts after the SYSTEM token
228
+ target_ids = target_ids[1:] + [voc.word2index[voc.EOS]]
229
 
230
  combined_ids = input_ids + target_ids
231
 
 
330
  """Token-by-token streaming response generator."""
331
  gpt_model.eval()
332
 
333
+ # NOTE: The full prompt string is passed, and indexing prepends the SYSTEM token
334
  input_ids = indexes_from_sentence(voc, prompt)
335
 
336
  input_tensor = torch.tensor(input_ids, dtype=torch.long, device=device).unsqueeze(0)
337
  generated_token_ids = []
338
 
339
  # --- Inference Parameters ---
340
+ temperature = 0.8
341
  top_k = HP.get("k_sampling", 200)
342
  # ----------------------------
343
 
 
393
  yield word + " "
394
 
395
  # ------------------------
396
+ # Core Chat Handler (REGULAR INFERENCE ONLY)
397
  # ------------------------
398
  def on_submit(user_message: str, history: Optional[List[List[str]]], train_input_state: Dict[str, str], *_):
399
  """
400
+ Token-by-token chat handler. Performs regular inference.
401
  """
402
  history = history or []
403
  user_message = re.sub(r'\(Attached:.*?\)|\[IMAGE_PREVIEW_URL:.*?]', '', user_message or "").strip()
 
411
  raw = perform_web_search(query)
412
  search_summary = prepare_web_content(raw)
413
 
414
+ # Prepare the FULL PROMPT for generation
415
+ prefix = f"The provided web context is: {search_summary}. " if search_summary else ""
416
+ full_prompt = f"{SYSTEM_INSTRUCTION} {prefix}{user_message}"
 
417
 
418
  # Store state data for the training interface and next turns
419
  current_state["full_prompt"] = full_prompt
 
450
  def feedback_train(history: List[List[str]], desired_response: str) -> str:
451
  """
452
  Endpoint for training the model based on explicit bad feedback and a desired response.
453
+ This function is used by the Manual Training panel and is called by the JS Bad Feedback button.
454
  """
455
  global start_iteration
456
 
457
  if not desired_response.strip():
458
+ # NOTE: This only logs a status if the desired response is empty.
459
+ # The JS client should handle simple logging if needed.
460
+ return "Warning: Training skipped. Provide a desired response to train."
461
 
462
  if not history or not history[-1][0]:
463
  return "Error: Chat history is empty or missing user prompt. Cannot train."
464
 
465
  # 1. Reconstruct the full context for the training step
466
  last_user_prompt_raw = history[-1][0]
 
467
  full_training_input = f"{SYSTEM_INSTRUCTION} {last_user_prompt_raw}"
468
 
469
  try:
 
472
  except Exception as e:
473
  return f"❌ Training Failed: {e}. Check server logs."
474
 
 
 
 
 
 
 
 
 
 
 
 
 
475
  # ------------------------
476
  # Gradio Interface
477
  # ------------------------
 
490
 
491
  gr.Markdown("---")
492
  gr.Markdown("## ⚙️ Manual Feedback Training")
493
+ gr.Markdown("Use this section to train the model with a **correct answer** after a poor response. The Bad Feedback button in the chat also triggers this function.")
 
 
 
 
 
494
 
495
  with gr.Column():
496
  # Defining the train_status component here
 
526
  train_status
527
  )
528
 
529
+ # --- Removing the simple logging endpoint and relying on 'feedback_train' ---
530
+ # The JS will send an empty string to /feedback_train, which the Python function handles by skipping training.
 
 
 
 
 
 
 
531
 
532
 
533
  if __name__ == "__main__":
534
+ demo.queue(api_open=True).launch(ssr_mode=False)