Spaces:
Runtime error
Runtime error
Update app.py
Browse files10 unmodified lines11121314151646 unmodified lines63646566676852 unmodified lines1211221231241251261279 unmodified lines13713813914014114214323 unmodified lines1671681691701711721731741 unmodified line17617717817918018118218330 unmodified lines21421521621721821922022122222322422522622722822925 unmodified lines25525625725825926026127 unmodified lines28929029129229329429529610 unmodified lines30730830931031131231331431531 unmodified lines34734834935035135210 unmodified linesos.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"class Voc:def __init__(self):self.PAD, self.SOS, self.EOS, self.UNK, self.SYSTEM = "<PAD>", "<SOS>", "<EOS>", "<UNK>", "<SYSTEM>"46 unmodified linesratio = (letters / total) if total > 0 else 0.0return ratio >= min_alpha_ratioclass PositionalEncoding(nn.Module):def __init__(self, d_model, max_len=5000):super().__init__()52 unmodified linesdropout = 0.1max_length = 256k_sampling = 20LEARNING_RATE = 1e-5voc = Voc()gpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)9 unmodified linesdropout = 0.1max_length = 256k_sampling = 20LEARNING_RATE = 1e-3 # Increased from 1e-5 for rapid online learninggpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)# Only load state if we have a real checkpoint23 unmodified linesThis 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.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"]):print("Skipping online update: Target response is non-English or corrupted.")returnprefix_text = ""1 unmodified line# 2. Incorporate Web Context for Learningprefix_text = f"According to a search result: {to_ascii(search_context)}. "# Sanitize promptfull_prompt_text = to_ascii(prefix_text + input_sentence)prompt_tokens = indexes_from_sentence(voc, full_prompt_text)[:-1]# Sanitize response30 unmodified linesdef generate_response(prompt, search_context=""):# Reject non-English inputs earlyif not is_english_like(prompt):return "Please use English. Non-English input was detected."full_input = promptif search_context:prefix_text = f"According to a search result: {to_ascii(search_context)}. "# 2. Incorporate Web Context for Generationfull_input = prefix_text + prompt# Sanitize to ASCII English-only before tokenizingfull_input = to_ascii(full_input)gpt_model.eval()25 unmodified linescandidate_word = voc.index2word.get(candidate_id, voc.UNK)# English-only token check: must be ASCII and pass tokenizer (letters/digits/punct)candidate_ascii = to_ascii(candidate_word)token_ok = is_english_like(candidate_word, min_alpha_ratio=0.1, max_non_ascii=0)if candidate_id == voc.word2index[voc.EOS]:27 unmodified linestext = re.sub(r"\s+([,.!?;:])", r"\1", text)text = text.strip()if not text:return "I couldn't generate an English response. Please try a shorter or clearer prompt in English."return textwith gr.Blocks(title="OkemoLLM") as demo:10 unmodified linesis_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# This requires reversing the formatting added in the JavaScript (if possible)# For regeneration, the actual prompt is inside quotes: '...: "clean prompt"'# Heuristic: Find content inside the last pair of quotes, assuming it's the original promptmatch = re.search(r':\s*"(.+?)"$', user_message)31 unmodified linesonline_update(gpt_model, clean_user_message, reply, max_length, search_context=search_context_text)# 6. Update the history: Use the clean user message, regardless of the prompt sent to the model.history[-1] = (clean_user_message, reply)return history, ""10 unmodified lines111213141516171819202146 unmodified lines6869707172737475767778798081828384858652 unmodified lines1391401411421431441451469 unmodified lines15615715815916016116216323 unmodified lines1871881891901911921931941951961971 unmodified line19920020120220320420520620730 unmodified lines23823924024124224324424524624724824925025125225325 unmodified lines27928028128228328427 unmodified lines31231331431531631731831910 unmodified lines33033133233333433531 unmodified lines36736836937037137237310 unmodified linesos.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"# --- 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 ---class Voc:def __init__(self):self.PAD, self.SOS, self.EOS, self.UNK, self.SYSTEM = "<PAD>", "<SOS>", "<EOS>", "<UNK>", "<SYSTEM>"46 unmodified linesratio = (letters / total) if total > 0 else 0.0return ratio >= min_alpha_ratiodef check_repetition(text: str, max_repeat: int = 2):"""Checks if any single token is repeated more than max_repeat times consecutively."""tokens = tokenize(text)if not tokens:return False# Check for consecutive triples (or more) of the same tokenfor i in range(len(tokens) - max_repeat):if all(tokens[i] == tokens[j] for j in range(i, i + max_repeat + 1)):return Truereturn Falseclass PositionalEncoding(nn.Module):def __init__(self, d_model, max_len=5000):super().__init__()52 unmodified linesdropout = 0.1max_length = 256k_sampling = 20# Safer default LEARNING_RATELEARNING_RATE = 1e-5voc = Voc()gpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)9 unmodified linesdropout = 0.1max_length = 256k_sampling = 20# Using the safer LEARNING_RATE here as wellLEARNING_RATE = 1e-5gpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)# Only load state if we have a real checkpoint23 unmodified linesThis 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.")returnprefix_text = ""1 unmodified line# 2. Incorporate Web Context for Learningprefix_text = f"According to a search result: {to_ascii(search_context)}. "# Combine System Instruction, Search Context, and User Promptfull_prompt_text = f"{SYSTEM_INSTRUCTION} {prefix_text} {input_sentence}"full_prompt_text = to_ascii(full_prompt_text)prompt_tokens = indexes_from_sentence(voc, full_prompt_text)[:-1]# Sanitize response30 unmodified linesdef generate_response(prompt, search_context=""):# Reject non-English inputs early# Note: We check the prompt *before* adding the system instruction, as the instruction is always English.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)}. "# Combine System Instruction, Search Context, and User Promptfull_input = f"{SYSTEM_INSTRUCTION} {prefix_text} {prompt}"full_input = to_ascii(full_input)gpt_model.eval()25 unmodified linescandidate_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]:27 unmodified linestext = 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 textwith gr.Blocks(title="OkemoLLM") as demo:10 unmodified linesis_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# Heuristic: Find content inside the last pair of quotes, assuming it's the original promptmatch = re.search(r':\s*"(.+?)"$', user_message)31 unmodified linesonline_update(gpt_model, clean_user_message, reply, max_length, search_context=search_context_text)# 6. Update the history: Use the clean user message, regardless of the prompt sent to the model.# This is CRITICAL: it overwrites whatever the server returned in the user slot.history[-1] = (clean_user_message, reply)return history, ""
app.py+38-17