Spaces:
Runtime error
Runtime error
Update app.py
Browse files12 unmodified lines1314151616171819165 unmodified lines18518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848918812 unmodified lines
# --- NEW: Descriptive System Prompt ---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"# --- END NEW SYSTEM PROMPT ---# --- END SYSTEM PROMPT ---
# --- NEW: Online Learning Hyperparameter ---ONLINE_LEARNING_EPOCHS = 1 # Changed from 5 to 1165 unmodified lines return ""
# Online update uses sanitized English-only inputs# MODIFICATION: Added conversation_context argumentdef online_update(model, input_sentence, target_response, max_seq_len, search_context="", conversation_context=""): """ Performs a fixed number of training steps (epochs), incorporating sanitized English-only search context. This is where the model learns from the user's turn. """ # 1. Validation Check: Ensure we only learn from responses that are clean and English-like. 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"]) is_not_repetitive = not check_repetition(target_response, max_repeat=2) if not is_response_clean or not is_not_repetitive: print("Skipping online update: Target response is non-English, corrupted, or highly repetitive.") return
prefix_text = "" if search_context: # 2. Incorporate Web Context for Learning prefix_text = f"According to a search result: {to_ascii(search_context)}. " # MODIFICATION: Prepend conversation context to the prompt context_prefix = f"{conversation_context} " if conversation_context else ""
# Combine System Instruction, Conversation Context, Search Context, and User Prompt full_prompt_text = f"{SYSTEM_INSTRUCTION} {context_prefix}{prefix_text} {input_sentence}" full_prompt_text = to_ascii(full_prompt_text)
prompt_tokens = indexes_from_sentence(voc, full_prompt_text)[:-1] # Sanitize response sanitized_response = to_ascii(target_response) response_tokens = indexes_from_sentence(voc, sanitized_response)[1:]
# Create the training sequence: [SYSTEM] [CONTEXT] [USER PROMPT] [MODEL REPLY] [EOS] full_sequence_ids = prompt_tokens + response_tokens input_ids = full_sequence_ids[:-1] target_ids = full_sequence_ids[1:]
if len(input_ids) < 2 or len(input_ids) != len(target_ids) or len(input_ids) > max_seq_len: print(f"Skipping online update. Sequence length: {len(input_ids)}") return
input_tensor = torch.tensor(input_ids, dtype=torch.long, device=device).unsqueeze(0) target_tensor = torch.tensor(target_ids, dtype=torch.long, device=device)
L = input_tensor.size(1)
model.train() causal = make_bool_causal_mask(L, device) # Loop 1 time for a fixed number of learning epochs last_loss = 0.0 for epoch in range(ONLINE_LEARNING_EPOCHS): optimizer.zero_grad() # FIX: Changed src_key_padding_mask to key_padding_mask to match GPT.forward signature logits = model(input_tensor, mask=causal, key_padding_mask=None) loss = criterion(logits.squeeze(0), target_tensor) loss.backward() optimizer.step() last_loss = loss.item() model.eval() print(f"Online update performed over {ONLINE_LEARNING_EPOCHS} epochs. Final Loss: {last_loss:.4f}")
# MODIFICATION: Added conversation_context argumentdef generate_response(prompt, search_context="", conversation_context=""): # Reject non-English inputs early if not is_english_like(prompt): return "Please use English. Non-English input was detected."
prefix_text = "" if search_context: prefix_text = f"According to a search result: {to_ascii(search_context)}. " # MODIFICATION: Prepend conversation context to the prompt context_prefix = f"{conversation_context} " if conversation_context else ""
# Combine System Instruction, Conversation Context, Search Context, and User Prompt full_input = f"{SYSTEM_INSTRUCTION} {context_prefix}{prefix_text} {prompt}" full_input = to_ascii(full_input)
gpt_model.eval()
initial_tokens = indexes_from_sentence(voc, full_input) input_tensor = torch.tensor(initial_tokens, dtype=torch.long, device=device).unsqueeze(0) max_total_len = len(initial_tokens) + max_length generated = []
with torch.no_grad(): for _ in range(max_length): L = input_tensor.size(1) causal = make_bool_causal_mask(L, device) padmask = (input_tensor == voc.word2index[voc.PAD]) logits = gpt_model(input_tensor, mask=causal, key_padding_mask=padmask) last = logits[:, -1, :].float()
topk_vals, topk_idx = torch.topk(last, k_sampling) topk_vals = torch.clamp(topk_vals, min=-30.0, max=30.0) probs = F.softmax(topk_vals, dim=-1).float()
# Retry sampling until we pick an English-like token or hit attempts cap attempts = 0 next_id = None while attempts < 5: # Use multionmial sampling to select a token pick_rel = torch.multinomial(probs, 1).item() candidate_id = topk_idx.squeeze(0)[pick_rel].item() candidate_word = voc.index2word.get(candidate_id, voc.UNK)
# English-only token check: must be ASCII and pass tokenizer (letters/digits/punct) token_ok = is_english_like(candidate_word, min_alpha_ratio=0.1, max_non_ascii=0) if candidate_id == voc.word2index[voc.EOS]: next_id = candidate_id break if token_ok: next_id = candidate_id break
attempts += 1
if next_id is None: # Fallback to UNK if no English-like token found next_id = voc.word2index[voc.UNK]
if next_id == voc.word2index[voc.EOS]: break generated.append(next_id) input_tensor = torch.cat( [input_tensor, torch.tensor([[next_id]], device=device, dtype=torch.long)], dim=1 )
words = [voc.index2word.get(t, voc.UNK) for t in generated] # Sanitize assembled text to ASCII English-only text = " ".join(words) text = to_ascii(text) text = re.sub(r"\s+([,.!?;:])", r"\1", text) text = text.strip()
if not text or check_repetition(text): return "I couldn't generate a stable English response. Please try a shorter or clearer prompt in English." return text
# --- NEW GRADIO FUNCTION TO HANDLE FEEDBACK ---def process_feedback(history, rating): """ Handles feedback from the client. Only triggers online_update (training) for "Good Response". For "Bad Response", it logs the event but skips training. """ if not history or not history[-1][1]: return history, "Cannot process feedback: No recent AI response found."
last_user_message, last_ai_response = history[-1] # 1. Log the event (always) print(f"\n--- FEEDBACK RECEIVED ---") print(f"Rating: {rating}") print(f"User Prompt: '{last_user_message}'") print(f"AI Response: '{last_ai_response}'") print(f"-------------------------\n")
if rating == "Good Response": # 2. Extract conversation context from previous turn (if available) conversation_context = "" if len(history) >= 2 and history[-2][1]: last_user, last_ai = history[-2] conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
# 3. Trigger online update (training) only for good responses # NOTE: We skip searching again, assuming the previous generation step included search if needed. # This keeps the training focused on the interaction itself. online_update( gpt_model, last_user_message, last_ai_response, max_length, search_context="", # Search context needs to be cached/passed if required for learning conversation_context=conversation_context ) feedback_message = f"Thanks for the **Good Response** rating! I just learned from that. Keep the good prompts coming! ✨" elif rating == "Bad Response": # 4. Skip training for bad responses to avoid confusing the model with unstable/undesired data. feedback_message = f"Acknowledged **Bad Response** feedback. I will try to be better! 🛠️"
else: feedback_message = "Unknown rating received." return history, feedback_message# --- END NEW GRADIO FUNCTION ---
with gr.Blocks(title="OkemoLLM") as demo: gr.Markdown("# OkemoLLM (English-only, Online Learning & Web Search Enabled with 1-Turn Context)") chat = gr.Chatbot(height=500) msg = gr.Textbox(placeholder="Type your message…", label="Message") clear = gr.Button("Clear")
def on_submit(user_message, history): # NOTE: This function receives the *final* instructional prompt from the web app
# 1. Determine if this is a regeneration/enhancement instruction is_instruction = any(user_message.lower().startswith(p) for p in ["please generate", "provide a much more detailed", "provide a different"]) # 2. Extract the clean message for the model input match = re.search(r':\s*"(.+?)"$', user_message) if is_instruction and match: clean_user_message = match.group(1).strip() model_prompt = user_message # Use the full instruction for generation else: clean_user_message = user_message model_prompt = user_message
# 3. CONTEXT EXTRACTION: Get the previous turn (User + AI) conversation_context = "" # The last element of history is usually the current, incomplete user turn (user_message, None) # unless it's a regeneration request. We want the turn *before* the current one. context_history = history if is_instruction else history[:-1]
if context_history and context_history[-1][1]: last_user, last_ai = context_history[-1] # Format: "User: [message] Response: [reply]" # Use to_ascii to ensure the context string is clean before being tokenized later conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}" print(f"Context included: {conversation_context}")
# 4. Enforce English-only input for the *clean* message (before adding instructions) if not is_english_like(clean_user_message): history = history + [(clean_user_message, "Please use English. Non-English input was detected.")] return history, ""
search_needed = "?" in clean_user_message or any( clean_user_message.lower().startswith(q) for q in ["what is", "who is", "how to"] )
search_context_text = "" if search_needed: search_context_text = perform_web_search(clean_user_message)
# 5. Generate response using the appropriate (potentially instructional) prompt if not is_instruction: history = history + [(clean_user_message, None)] # MODIFICATION: Pass conversation_context to generator reply = generate_response(model_prompt, search_context=search_context_text, conversation_context=conversation_context)
# 6. Skip automatic training on submit. Training now only occurs via the 'Good Response' button. # if not is_instruction: # online_update(...)
# 7. Update the history: Use the clean user message, regardless of the prompt sent to the model. history[-1] = (clean_user_message, reply) return history, ""
msg.submit(on_submit, inputs=[msg, chat], outputs=[chat, msg]) clear.click(lambda: [], None, chat) # --- NEW: Gradio Endpoint for Feedback --- # This single endpoint handles both good and bad responses demo.queue().custom_component( process_feedback, inputs=[chat, gr.State("Good Response")], # Initial value for State is ignored, but structure needed outputs=[chat, gr.Textbox(visible=False)] # outputs updated history and a message to the status textbox ).as_custom_function( # NOTE: The client-side JS needs to be updated to call '/process_feedback' and pass the rating. # However, for stability within Gradio, we define two specific API endpoints the client can use. # Since Gradio doesn't easily allow passing a fixed parameter value in the endpoint mapping, # we will define two distinct functions mapping to the same core logic for the client. # The client will call /feedback_good or /feedback_bad, which will run this function. # 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. # For simplicity and to match the client's original intent, we'll use simple Gradio interfaces. name="feedback_endpoint" )
if __name__ == "__main__": # Define separate, simple Gradio interfaces that the client can hit to simulate the fixed feedback payload with gr.Blocks() as feedback_interface: gr.Interface( fn=lambda h: process_feedback(h, "Good Response"), inputs=gr.State([]), outputs=[gr.State([]), gr.Textbox()], api_name="feedback_good", # Client calls /run/feedback_good live=False, allow_flagging="never", ) gr.Interface( fn=lambda h: process_feedback(h, "Bad Response"), inputs=gr.State([]), outputs=[gr.State([]), gr.Textbox()], api_name="feedback_bad", # Client calls /run/feedback_bad live=False, allow_flagging="never", ) # We launch the main app demo, but the feedback endpoints are registered via their interfaces. demo.launch()# MODIFICATIONapp.py+2-303