Spaces:
Runtime error
Runtime error
Update app.py
Browse files10 unmodified lines111213141516178 unmodified lines26272829303132331 unmodified line35363738394041424344454647486 unmodified lines55565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662710 unmodified linesimport unicodedataimport requestsfrom datetime import datetimefrom typing import Dict, List, Tuple, Optional, Anyimport torchimport torch.nn as nn8 unmodified lines# Config# ---------------------SYSTEM_INSTRUCTION: str = ("You are a friendly, helpful, concise AI assistant named Okemo Language Model (OLM). ""Default to clear, short answers; elaborate only when asked.")ONLINE_LEARNING_EPOCHS: int = 51 unmodified line# Fallback defaults (used only when no checkpoint exists)DEFAULTS: Dict[str, Any] = {"d_model": 768,"n_head": 48,"d_ff": 768,"n_layers": 12,"dropout": 0.1,"max_length": 512,"k_sampling": 20,"LEARNING_RATE": 1e-6,}# Web search provider (Tavily). Keep key in environment.6 unmodified lines# Helpers# ---------------------def to_ascii(text: Optional[str]) -> str:"""Normalize to NFKC and ensure str."""return unicodedata.normalize("NFKC", text or "")# Simple tokenizer: words or punctuation_TOKEN_RE = re.compile(r"\w+|[^\w\s]", flags=re.UNICODE)def tokenize(text: str) -> List[str]:"""Lowercase, ASCII-normalized tokenization into words and punctuation units."""txt = to_ascii(text)return _TOKEN_RE.findall(txt.lower())def check_repetition(text: str, max_repeat: int = 2) -> bool:"""Detect exact token repetition runs longer than max_repeat."""tokens = tokenize(text)if not tokens or max_repeat < 1:return Falsefor i in range(len(tokens) - max_repeat):if all(tokens[i] == tokens[j] for j in range(i, i + max_repeat + 1)):return Truereturn False# ---------------------# Vocabulary# ---------------------class Voc:"""Lightweight vocabulary storing special tokens and bidirectional maps."""def __init__(self) -> None:self.PAD, self.SOS, self.EOS, self.UNK, self.SYSTEM = "<PAD>", "<SOS>", "<EOS>", "<UNK>", "<SYSTEM>"self.word2index: Dict[str, int] = {self.PAD: 0, self.SOS: 1, self.EOS: 2, self.UNK: 3, self.SYSTEM: 4}self.index2word: Dict[int, str] = {0: self.PAD, 1: self.SOS, 2: self.EOS, 3: self.UNK, 4: self.SYSTEM}self.n_words: int = 5@staticmethoddef load_from_checkpoint(ckpt: Dict[str, Any]) -> "Voc":voc = Voc()if "voc_word2index" in ckpt and "voc_index2word" in ckpt:voc.word2index = ckpt["voc_word2index"]voc.index2word = ckpt["voc_index2word"]voc.n_words = len(voc.word2index)if "special_tokens" in ckpt:tokens = ckpt["special_tokens"]voc.PAD = tokens.get("PAD", voc.PAD)voc.SOS = tokens.get("SOS", voc.SOS)voc.EOS = tokens.get("EOS", voc.EOS)voc.UNK = tokens.get("UNK", voc.UNK)voc.SYSTEM = tokens.get("SYSTEM", voc.SYSTEM)return vocdef add_sentence(self, sentence: str) -> None:for word in tokenize(sentence):if word not in self.word2index:idx = self.n_wordsself.word2index[word] = idxself.index2word[idx] = wordself.n_words += 1# ---------------------# Model# ---------------------class PositionalEncoding(nn.Module):"""Sinusoidal positional encoding used by Transformer."""def __init__(self, d_model: int, max_len: int = 5000) -> None:super().__init__()pe = torch.zeros(max_len, d_model)position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))pe[:, 0::2] = torch.sin(position * div_term)pe[:, 1::2] = torch.cos(position * div_term)self.register_buffer("pe", pe.unsqueeze(0))def forward(self, x: torch.Tensor) -> torch.Tensor:return x + self.pe[:, : x.size(1), :]class GPT(nn.Module):"""Minimal GPT-like model using nn.TransformerEncoder with weight tying."""def __init__(self, n_words: int, d_model: int, n_layers: int, n_head: int, d_ff: int, dropout: float = 0.1) -> None:super().__init__()self.embedding = nn.Embedding(n_words, d_model)self.pos = PositionalEncoding(d_model)self.norm = nn.LayerNorm(d_model)enc_layer = nn.TransformerEncoderLayer(d_model, n_head, d_ff, dropout, batch_first=True)self.transformer = nn.TransformerEncoder(enc_layer, n_layers)self.fc = nn.Linear(d_model, n_words, bias=False)self.fc.weight = self.embedding.weight # weight tyingdef forward(self,x: torch.Tensor,mask: Optional[torch.Tensor] = None,key_padding_mask: Optional[torch.Tensor] = None,) -> torch.Tensor:x = self.embedding(x)x = self.pos(x)x = self.norm(x)out = self.transformer(x, mask=mask, src_key_padding_mask=key_padding_mask)return self.fc(out)# ---------------------# Training utils# ---------------------def indexes_from_sentence(voc: Voc, sentence: str) -> List[int]:sanitized = " ".join(tokenize(sentence))prompt_tokens = [voc.SYSTEM] + tokenize(sanitized)return [voc.word2index.get(tok, voc.word2index[voc.UNK]) for tok in prompt_tokens] + [voc.word2index[voc.EOS]]def make_bool_causal_mask(sz: int, device: torch.device) -> torch.Tensor:return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)# ---------------------# Device# ---------------------device: torch.device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")# ---------------------# Checkpoint-aware init# ---------------------def load_checkpoint_or_defaults(path: str) -> Tuple[Dict[str, Any], Dict[str, Any], Voc, GPT, optim.Optimizer]:if os.path.exists(path):ckpt = torch.load(path, map_location=device)hp = {"d_model": ckpt.get("d_model", DEFAULTS["d_model"]),"n_head": ckpt.get("n_head", DEFAULTS["n_head"]),"d_ff": ckpt.get("d_ff", DEFAULTS["d_ff"]),"n_layers": ckpt.get("n_layers", DEFAULTS["n_layers"]),"dropout": ckpt.get("dropout", DEFAULTS["dropout"]),"max_length": ckpt.get("max_length", DEFAULTS["max_length"]),"k_sampling": ckpt.get("k_sampling", DEFAULTS["k_sampling"]),"LEARNING_RATE": ckpt.get("LEARNING_RATE", DEFAULTS["LEARNING_RATE"]),}voc = Voc.load_from_checkpoint(ckpt)model = GPT(voc.n_words, hp["d_model"], hp["n_layers"], hp["n_head"], hp["d_ff"], hp["dropout"]).to(device)if ckpt.get("gpt_model_state_dict") is not None:model.load_state_dict(ckpt["gpt_model_state_dict"], strict=True)model.fc.weight = model.embedding.weightoptimizer = optim.Adam(model.parameters(), lr=hp["LEARNING_RATE"])if "optimizer_state_dict" in ckpt:try:optimizer.load_state_dict(ckpt["optimizer_state_dict"])except Exception as e:print(f"Warning: Failed to load optimizer state: {e}. Starting fresh.")return ckpt, hp, voc, model, optimizerelse:print("WARNING: No checkpoint found. Initializing with defaults.")hp = DEFAULTS.copy()voc = Voc()model = GPT(voc.n_words, hp["d_model"], hp["n_layers"], hp["n_head"], hp["d_ff"], hp["dropout"]).to(device)optimizer = optim.Adam(model.parameters(), lr=hp["LEARNING_RATE"])return {}, hp, voc, model, optimizercheckpoint, HP, voc, gpt_model, optimizer = load_checkpoint_or_defaults(CHECKPOINT_PATH)criterion = nn.CrossEntropyLoss(ignore_index=voc.word2index[voc.PAD])# --- Added logic: Save initial state if no checkpoint was found to ensure .pth exists ---if not os.path.exists(CHECKPOINT_PATH):print("Saving initial checkpoint with default settings.")# The initial voc will only contain special tokens, but it's a valid starting pointsave_checkpoint(gpt_model, optimizer, voc, CHECKPOINT_PATH)# ---------------------------------------------------------------------------------------# ---------------------# Save checkpoint# ---------------------def save_checkpoint(model: GPT, optimizer: optim.Optimizer, voc: Voc, path: str) -> None:print(f"Saving model checkpoint to {path}...")ckpt = {"voc_word2index": voc.word2index,"voc_index2word": voc.index2word,"gpt_model_state_dict": model.state_dict(),"optimizer_state_dict": optimizer.state_dict(),"d_model": HP["d_model"],"n_head": HP["n_head"],"d_ff": HP["d_ff"],"n_layers": HP["n_layers"],"dropout": HP["dropout"],"max_length": HP["max_length"],"k_sampling": HP["k_sampling"],"LEARNING_RATE": HP["LEARNING_RATE"],}try:torch.save(ckpt, path)print("Checkpoint saved successfully.")except Exception as e:print(f"ERROR: Failed to save checkpoint: {e}")# ---------------------# Web search (only with <WEB>)# ---------------------def perform_web_search(query: str) -> str:if not TAVILY_API_KEY:return ""try:resp = requests.post("https://api.tavily.com/search",json={"api_key": TAVILY_API_KEY, "query": query, "include_answer": False, "max_results": 5},timeout=8,)resp.raise_for_status()data = resp.json()results = data.get("results", [])snippets: List[str] = []for r in results[:3]:title = (r.get("title") or "").strip()snippet = (r.get("content") or "").strip()url = (r.get("url") or "").strip()if title or snippet:snippets.append(f"{title}: {snippet} (Source: {url})")return to_ascii(" | ".join(snippets))except Exception as e:print(f"Search failed: {e}")return ""def should_search(user_text: str) -> bool:return bool(WEB_TAG_RE.search(user_text or ""))# ---------------------# Generation# ---------------------def generate_response(prompt: str, search_context: str = "", conversation_context: str = "") -> str:prefix_text = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""context_prefix = f"{conversation_context} " if conversation_context else ""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)generated: List[int] = []temperature = 0.8# min_tokens = 24 # The variable for forced generation is no longer usedvocab_eos = voc.word2index[voc.EOS]vocab_pad = voc.word2index[voc.PAD]with torch.no_grad():for step in range(HP["max_length"]):L = input_tensor.size(1)causal = make_bool_causal_mask(L, device)padmask = (input_tensor == vocab_pad)logits = gpt_model(input_tensor, mask=causal, key_padding_mask=padmask)last = logits[:, -1, :].float() / max(temperature, 1e-3)k = max(1, int(HP["k_sampling"]))topk_vals, topk_idx = torch.topk(last, k)probs = F.softmax(topk_vals, dim=-1).float()pick_rel = torch.multinomial(probs, 1).item()candidate_id = topk_idx.squeeze(0)[pick_rel].item()# The logic that forces generation past min_tokens has been removed to improve generation quality.# if candidate_id == vocab_eos and step < min_tokens:# candidate_id = topk_idx.squeeze(0)[0].item()if candidate_id == vocab_eos:breakgenerated.append(candidate_id)next_token = torch.tensor([[candidate_id]], device=device, dtype=torch.long)input_tensor = torch.cat([input_tensor, next_token], dim=1)words = [voc.index2word.get(t, voc.UNK) for t in generated]filtered_words = [w for w in words if w not in [voc.PAD, voc.SOS, voc.EOS, voc.UNK, voc.SYSTEM]]text = " ".join(filtered_words)text = to_ascii(text)text = re.sub(r"\s+([,.!?;:])", r"\1", text).strip()if not text or check_repetition(text):return "I got lost in the data tubes! Perhaps ask me something a little sillier? 🤪"return text# ---------------------# Online learning (feedback)# ---------------------def online_update(model: GPT,input_sentence: str,target_response: str,max_seq_len: int,search_context: str = "",file_context: str = "",conversation_context: str = "",) -> None:is_response_clean = 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 corrupted or highly repetitive.")returnprefix_search = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""prefix_file = f"Based on the attached file: {to_ascii(file_context)}. " if file_context else ""context_prefix = f"{conversation_context} " if conversation_context else ""full_prompt_text = f"{SYSTEM_INSTRUCTION} {context_prefix}{prefix_search}{prefix_file}{input_sentence}"full_prompt_text = to_ascii(full_prompt_text)prompt_tokens = indexes_from_sentence(voc, full_prompt_text)[:-1]sanitized_response = to_ascii(target_response)response_tokens = indexes_from_sentence(voc, sanitized_response)[1:]full_sequence_ids = prompt_tokens + response_tokensinput_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)}")returninput_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)last_loss = 0.0for _ in range(ONLINE_LEARNING_EPOCHS):optimizer.zero_grad()logits = model(input_tensor, mask=causal, key_padding_mask=None)loss = criterion(logits.squeeze(0), target_tensor)loss.backward()torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)optimizer.step()last_loss = loss.item()model.eval()print(f"Online update done. Final Loss: {last_loss:.4f}")def process_feedback(history: List[List[Optional[str]]], rating: str) -> Tuple[List[List[Optional[str]]], str]:if not isinstance(history, list):return [], "Cannot process feedback: history not a list."if not history or not (isinstance(history[-1], list) and len(history[-1]) == 2 and isinstance(history[-1][1], str)):return history, "Cannot process feedback: No recent AI response found."last_user_message, last_ai_response = history[-1][0], history[-1][1]file_context_text = ""file_match = re.search(r"\(Attached: (.*?)\)", last_user_message or "")if file_match:file_name = file_match.group(1)file_context_text = f"The user provided a file named '{file_name}'."clean_user_message = to_ascii(last_user_message or "")clean_user_message = re.sub(r'\(Attached:.*?\)', '', clean_user_message).strip()clean_user_message = re.sub(r'\[IMAGE_PREVIEW_URL:.*?]', '', clean_user_message).strip()search_context_text = ""if rating == "Good Response":conversation_context = ""if len(history) >= 2 and isinstance(history[-2], list) and len(history[-2]) == 2 and isinstance(history[-2][1], str):last_user, last_ai = history[-2][0], history[-2][1]conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"online_update(gpt_model,clean_user_message,last_ai_response,HP["max_length"],search_context=search_context_text,file_context=file_context_text,conversation_context=conversation_context,)save_checkpoint(gpt_model, optimizer, voc, CHECKPOINT_PATH)feedback_message = "Thanks for the Good Response rating! Learned from that turn. ✨"elif rating == "Bad Response":feedback_message = "Acknowledged Bad Response feedback. 🛠️"else:feedback_message = "Unknown rating received."return history, feedback_messagedef feedback_good(history_state: List[List[Optional[str]]]) -> Tuple[List[List[Optional[str]]], str]:history_state, feedback_message = process_feedback(history_state, "Good Response")return history_state, feedback_messagedef feedback_bad(history_state: List[List[Optional[str]]]) -> Tuple[List[List[Optional[str]]], str]:history_state, feedback_message = process_feedback(history_state, "Bad Response")return history_state, feedback_messagedef feedback_bad_with_prompt(history_state: List[List[Optional[str]]], suggested_prompt: str) -> Tuple[List[List[Optional[str]]], str]:log_path = "bad_feedback_log.txt"try:with open(log_path, "a", encoding="utf-8") as f:f.write(f"\n--- {datetime.now()} ---\nSuggested Prompt:\n{suggested_prompt}\n\n")except Exception as e:print(f"Failed to log feedback: {e}")process_feedback(history_state, "Bad Response")return history_state, f"Recorded:\n“{suggested_prompt}”"# ---------------------# Core request handling# ---------------------def _extract_file_context(uploaded_file: Optional[Any]) -> str:if not uploaded_file:return ""file_name = uploaded_file.name.split("/")[-1]return f"The user has provided a file named '{file_name}'. Analyze or respond to the user's prompt about this file."def _build_conversation_context(history: List[List[Optional[str]]], is_instruction: bool) -> str:context_history = history[:-1] if not is_instruction else historyif context_history and isinstance(context_history[-1], list) and len(context_history[-1]) == 2 and isinstance(context_history[-1][1], str):last_user, last_ai = context_history[-1][0], context_history[-1][1]return f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"return ""def _is_instruction_turn(user_message: str) -> bool:prefixes = ("please generate", "provide a much more detailed", "provide a different")return any((user_message or "").lower().startswith(p) for p in prefixes)def on_submit(user_message: str,history: Optional[List[List[Optional[str]]]],uploaded_file: Optional[Any],web_search_enabled_flag_unused: bool = True,) -> Tuple[List[List[Optional[str]]], str]:history = history or []file_context = _extract_file_context(uploaded_file)is_instruction = _is_instruction_turn(user_message or "")clean_user_message = user_message or ""quoted_match = re.search(r':\s*"(.+?)"$', clean_user_message)if is_instruction and quoted_match:clean_user_message = quoted_match.group(1).strip()model_prompt = user_messageelse:model_prompt = user_messageclean_user_message = re.sub(r'\(Attached:.*?\)', '', clean_user_message).strip()clean_user_message = re.sub(r'\[IMAGE_PREVIEW_URL:.*?]', '', clean_user_message).strip()conversation_context = _build_conversation_context(history, is_instruction)search_context_text = ""if should_search(clean_user_message):query_for_search = WEB_TAG_RE.sub("", clean_user_message).strip()search_context_text = perform_web_search(query_for_search)# Modified to suppress "No Search" messagedisplay_search_result = (f"🔍 **Search Result Used:** {search_context_text}" if search_context_textelse "")final_model_prompt = f"{file_context} {model_prompt}" if file_context else model_promptfinal_model_prompt = WEB_TAG_RE.sub("", final_model_prompt or "").strip()reply = generate_response(final_model_prompt,search_context=search_context_text,conversation_context=conversation_context,)if history and isinstance(history[-1], list) and len(history[-1]) == 2 and history[-1][1] is None:history[-1][1] = reply if isinstance(reply, str) else str(reply)return history, display_search_result# ---------------------# Gradio app# ---------------------with gr.Blocks(title="OkemoLLM") as demo:gr.Markdown("# OkemoLLM (<WEB> gated web search, checkpoint-aware) 🌐")search_status_display = gr.Markdown("🔍 Search status will appear here.")chat = gr.Chatbot(height=500)with gr.Row():with gr.Column(scale=4):msg = gr.Textbox(placeholder='Type your message… Add "<WEB>" to use web search for this turn.',label="Message",elem_id="okemo-input-textbox")uploaded_file_state = gr.File(label="Uploaded File", visible=False, elem_id="uploaded_file_state")web_search_enabled_state = gr.Checkbox(label="Frontend Search Toggle (ignored; use <WEB>)", value=True)clear = gr.Button("Clear")send_trigger = gr.Button(visible=False, elem_id="okemo-send-button-trigger")def add_user_message_to_history(message: str, history: Optional[List[List[Optional[str]]]], file_ref: Optional[Any], web_enabled: bool):history = history or []return history + [[message, None]], "..."msg.submit(add_user_message_to_history,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat, search_status_display],queue=False).then(on_submit,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat, search_status_display],queue=False)send_trigger.click(add_user_message_to_history,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat, search_status_display],queue=False).then(on_submit,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat, search_status_display],queue=False)clear.click(lambda: [], None, chat, queue=False)# Public API endpointsdef chat_submit_api(msg_value: str,chat_value: Optional[List[List[Optional[str]]]],uploaded_file_value: Optional[Any],web_enabled_value: bool,):updated_history = chat_value or []updated_history.append([msg_value, None])final_history, status_msg = on_submit(msg_value, updated_history, uploaded_file_value, web_enabled_value)return final_history, status_msggr.Interface(fn=chat_submit_api,inputs=[gr.Textbox(label="Message"),gr.State(value=[]),gr.File(label="Uploaded File"),gr.Checkbox(label="Web Search Enabled (ignored; use <WEB>)", value=True),],outputs=[gr.State(value=[]),gr.Textbox(visible=False),],api_name="on_submit",live=False,allow_flagging="never",)gr.Interface(fn=feedback_good,inputs=[gr.State(value=[])],outputs=[gr.State(value=[]), gr.Textbox()],api_name="feedback_good",live=False,allow_flagging="never",)gr.Interface(fn=feedback_bad,inputs=[gr.State(value=[])],outputs=[gr.State(value=[]), gr.Textbox()],api_name="feedback_bad",live=False,allow_flagging="never",)gr.Interface(fn=feedback_bad_with_prompt,inputs=[gr.State(value=[]), gr.Textbox(label="Suggested Prompt")],outputs=[gr.State(value=[]), gr.Textbox()],api_name="feedback_bad_with_prompt",live=False,allow_flagging="never",)if __name__ == "__main__":demo.queue(api_open=True).launch(ssr_mode=False)10 unmodified lines111213141516178 unmodified lines26272829303132331 unmodified line35363738394041424344454647486 unmodified lines55565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065110 unmodified linesimport unicodedataimport requestsfrom datetime import datetimefrom typing import Dict, List, Tuple, Optional, Any, Iteratorimport torchimport torch.nn as nn8 unmodified lines# Config# ---------------------SYSTEM_INSTRUCTION: str = ("You are a friendly, helpful, concise AI assistant named Okemo Language Model (OLM). ""Default to clear, short answers; elaborate only when asked.")ONLINE_LEARNING_EPOCHS: int = 51 unmodified line# Fallback defaults (used only when no checkpoint exists)DEFAULTS: Dict[str, Any] = {"d_model": 768,"n_head": 48,"d_ff": 768,"n_layers": 12,"dropout": 0.1,"max_length": 512,"k_sampling": 20,"LEARNING_RATE": 1e-6,}# Web search provider (Tavily). Keep key in environment.6 unmodified lines# Helpers# ---------------------def to_ascii(text: Optional[str]) -> str:"""Normalize to NFKC and ensure str."""return unicodedata.normalize("NFKC", text or "")# Simple tokenizer: words or punctuation_TOKEN_RE = re.compile(r"\w+|[^\w\s]", flags=re.UNICODE)def tokenize(text: str) -> List[str]:"""Lowercase, ASCII-normalized tokenization into words and punctuation units."""txt = to_ascii(text)return _TOKEN_RE.findall(txt.lower())def check_repetition(text: str, max_repeat: int = 2) -> bool:"""Detect exact token repetition runs longer than max_repeat."""tokens = tokenize(text)if not tokens or max_repeat < 1:return Falsefor i in range(len(tokens) - max_repeat):if all(tokens[i] == tokens[j] for j in range(i, i + max_repeat + 1)):return Truereturn False# ---------------------# Vocabulary# ---------------------class Voc:"""Lightweight vocabulary storing special tokens and bidirectional maps."""def __init__(self) -> None:self.PAD, self.SOS, self.EOS, self.UNK, self.SYSTEM = "<PAD>", "<SOS>", "<EOS>", "<UNK>", "<SYSTEM>"self.word2index: Dict[str, int] = {self.PAD: 0, self.SOS: 1, self.EOS: 2, self.UNK: 3, self.SYSTEM: 4}self.index2word: Dict[int, str] = {0: self.PAD, 1: self.SOS, 2: self.EOS, 3: self.UNK, 4: self.SYSTEM}self.n_words: int = 5@staticmethoddef load_from_checkpoint(ckpt: Dict[str, Any]) -> "Voc":voc = Voc()if "voc_word2index" in ckpt and "voc_index2word" in ckpt:voc.word2index = ckpt["voc_word2index"]voc.index2word = ckpt["voc_index2word"]voc.n_words = len(voc.word2index)if "special_tokens" in ckpt:tokens = ckpt["special_tokens"]voc.PAD = tokens.get("PAD", voc.PAD)voc.SOS = tokens.get("SOS", voc.SOS)voc.EOS = tokens.get("EOS", voc.EOS)voc.UNK = tokens.get("UNK", voc.UNK)voc.SYSTEM = tokens.get("SYSTEM", voc.SYSTEM)return vocdef add_sentence(self, sentence: str) -> None:for word in tokenize(sentence):if word not in self.word2index:idx = self.n_wordsself.word2index[word] = idxself.index2word[idx] = wordself.n_words += 1# ---------------------# Model# ---------------------class PositionalEncoding(nn.Module):"""Sinusoidal positional encoding used by Transformer."""def __init__(self, d_model: int, max_len: int = 5000) -> None:super().__init__()pe = torch.zeros(max_len, d_model)position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))pe[:, 0::2] = torch.sin(position * div_term)pe[:, 1::2] = torch.cos(position * div_term)self.register_buffer("pe", pe.unsqueeze(0))def forward(self, x: torch.Tensor) -> torch.Tensor:return x + self.pe[:, : x.size(1), :]class GPT(nn.Module):"""Minimal GPT-like model using nn.TransformerEncoder with weight tying."""def __init__(self, n_words: int, d_model: int, n_layers: int, n_head: int, d_ff: int, dropout: float = 0.1) -> None:super().__init__()self.embedding = nn.Embedding(n_words, d_model)self.pos = PositionalEncoding(d_model)self.norm = nn.LayerNorm(d_model)enc_layer = nn.TransformerEncoderLayer(d_model, n_head, d_ff, dropout, batch_first=True)self.transformer = nn.TransformerEncoder(enc_layer, n_layers)self.fc = nn.Linear(d_model, n_words, bias=False)self.fc.weight = self.embedding.weight # weight tyingdef forward(self,x: torch.Tensor,mask: Optional[torch.Tensor] = None,key_padding_mask: Optional[torch.Tensor] = None,) -> torch.Tensor:x = self.embedding(x)x = self.pos(x)x = self.norm(x)out = self.transformer(x, mask=mask, src_key_padding_mask=key_padding_mask)return self.fc(out)# ---------------------# Training utils# ---------------------def indexes_from_sentence(voc: Voc, sentence: str) -> List[int]:sanitized = " ".join(tokenize(sentence))prompt_tokens = [voc.SYSTEM] + tokenize(sanitized)return [voc.word2index.get(tok, voc.word2index[voc.UNK]) for tok in prompt_tokens] + [voc.word2index[voc.EOS]]def make_bool_causal_mask(sz: int, device: torch.device) -> torch.Tensor:return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)# ---------------------# Device# ---------------------device: torch.device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")# ---------------------# Checkpoint-aware init# ---------------------def load_checkpoint_or_defaults(path: str) -> Tuple[Dict[str, Any], Dict[str, Any], Voc, GPT, optim.Optimizer]:if os.path.exists(path):ckpt = torch.load(path, map_location=device)hp = {"d_model": ckpt.get("d_model", DEFAULTS["d_model"]),"n_head": ckpt.get("n_head", DEFAULTS["n_head"]),"d_ff": ckpt.get("d_ff", DEFAULTS["d_ff"]),"n_layers": ckpt.get("n_layers", DEFAULTS["n_layers"]),"dropout": ckpt.get("dropout", DEFAULTS["dropout"]),"max_length": ckpt.get("max_length", DEFAULTS["max_length"]),"k_sampling": ckpt.get("k_sampling", DEFAULTS["k_sampling"]),"LEARNING_RATE": ckpt.get("LEARNING_RATE", DEFAULTS["LEARNING_RATE"]),}voc = Voc.load_from_checkpoint(ckpt)model = GPT(voc.n_words, hp["d_model"], hp["n_layers"], hp["n_head"], hp["d_ff"], hp["dropout"]).to(device)if ckpt.get("gpt_model_state_dict") is not None:model.load_state_dict(ckpt["gpt_model_state_dict"], strict=True)model.fc.weight = model.embedding.weightoptimizer = optim.Adam(model.parameters(), lr=hp["LEARNING_RATE"])if "optimizer_state_dict" in ckpt:try:optimizer.load_state_dict(ckpt["optimizer_state_dict"])except Exception as e:print(f"Warning: Failed to load optimizer state: {e}. Starting fresh.")return ckpt, hp, voc, model, optimizerelse:print("WARNING: No checkpoint found. Initializing with defaults.")hp = DEFAULTS.copy()voc = Voc()model = GPT(voc.n_words, hp["d_model"], hp["n_layers"], hp["n_head"], hp["d_ff"], hp["dropout"]).to(device)optimizer = optim.Adam(model.parameters(), lr=hp["LEARNING_RATE"])return {}, hp, voc, model, optimizercheckpoint, HP, voc, gpt_model, optimizer = load_checkpoint_or_defaults(CHECKPOINT_PATH)criterion = nn.CrossEntropyLoss(ignore_index=voc.word2index[voc.PAD])# --- Added logic: Save initial state if no checkpoint was found to ensure .pth exists ---if not os.path.exists(CHECKPOINT_PATH):print("Saving initial checkpoint with default settings.")# The initial voc will only contain special tokens, but it's a valid starting pointsave_checkpoint(gpt_model, optimizer, voc, CHECKPOINT_PATH)# ---------------------------------------------------------------------------------------# ---------------------# Save checkpoint# ---------------------def save_checkpoint(model: GPT, optimizer: optim.Optimizer, voc: Voc, path: str) -> None:print(f"Saving model checkpoint to {path}...")ckpt = {"voc_word2index": voc.word2index,"voc_index2word": voc.index2word,"gpt_model_state_dict": model.state_dict(),"optimizer_state_dict": optimizer.state_dict(),"d_model": HP["d_model"],"n_head": HP["n_head"],"d_ff": HP["d_ff"],"n_layers": HP["n_layers"],"dropout": HP["dropout"],"max_length": HP["max_length"],"k_sampling": HP["k_sampling"],"LEARNING_RATE": HP["LEARNING_RATE"],}try:torch.save(ckpt, path)print("Checkpoint saved successfully.")except Exception as e:print(f"ERROR: Failed to save checkpoint: {e}")# ---------------------# Web search (only with <WEB>)# ---------------------def perform_web_search(query: str) -> str:if not TAVILY_API_KEY:return ""try:resp = requests.post("https://api.tavily.com/search",json={"api_key": TAVILY_API_KEY, "query": query, "include_answer": False, "max_results": 5},timeout=8,)resp.raise_for_status()data = resp.json()results = data.get("results", [])snippets: List[str] = []for r in results[:3]:title = (r.get("title") or "").strip()snippet = (r.get("content") or "").strip()url = (r.get("url") or "").strip()if title or snippet:snippets.append(f"{title}: {snippet} (Source: {url})")return to_ascii(" | ".join(snippets))except Exception as e:print(f"Search failed: {e}")return ""def should_search(user_text: str) -> bool:return bool(WEB_TAG_RE.search(user_text or ""))# ---------------------# Generation# ---------------------def generate_response(prompt: str, search_context: str = "", conversation_context: str = "") -> Iterator[str]:"""Generator function that yields the generated word tokens."""prefix_text = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""context_prefix = f"{conversation_context} " if conversation_context else ""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)generated_token_ids: List[int] = [] # Use this to check for repetition latertemperature = 0.8vocab_eos = voc.word2index[voc.EOS]vocab_pad = voc.word2index[voc.PAD]with torch.no_grad():for step in range(HP["max_length"]):L = input_tensor.size(1)causal = make_bool_causal_mask(L, device)padmask = (input_tensor == vocab_pad)logits = gpt_model(input_tensor, mask=causal, key_padding_mask=padmask)last = logits[:, -1, :].float() / max(temperature, 1e-3)k = max(1, int(HP["k_sampling"]))topk_vals, topk_idx = torch.topk(last, k)probs = F.softmax(topk_vals, dim=-1).float()pick_rel = torch.multinomial(probs, 1).item()candidate_id = topk_idx.squeeze(0)[pick_rel].item()if candidate_id == vocab_eos:breakgenerated_token_ids.append(candidate_id)next_token = torch.tensor([[candidate_id]], device=device, dtype=torch.long)input_tensor = torch.cat([input_tensor, next_token], dim=1)# Yield the generated word token for streamingword = voc.index2word.get(candidate_id, voc.UNK)if word not in [voc.PAD, voc.SOS, voc.EOS, voc.UNK, voc.SYSTEM]:yield word + " " # Yield with space for cleaner UI streaming# ---------------------# Online learning (feedback)# ---------------------def online_update(model: GPT,input_sentence: str,target_response: str,max_seq_len: int,search_context: str = "",file_context: str = "",conversation_context: str = "",) -> None:is_response_clean = 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 corrupted or highly repetitive.")returnprefix_search = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""prefix_file = f"Based on the attached file: {to_ascii(file_context)}. " if file_context else ""context_prefix = f"{conversation_context} " if conversation_context else ""full_prompt_text = f"{SYSTEM_INSTRUCTION} {context_prefix}{prefix_search}{prefix_file}{input_sentence}"full_prompt_text = to_ascii(full_prompt_text)prompt_tokens = indexes_from_sentence(voc, full_prompt_text)[:-1]sanitized_response = to_ascii(target_response)response_tokens = indexes_from_sentence(voc, sanitized_response)[1:]full_sequence_ids = prompt_tokens + response_tokensinput_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)}")returninput_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)last_loss = 0.0for _ in range(ONLINE_LEARNING_EPOCHS):optimizer.zero_grad()logits = model(input_tensor, mask=causal, key_padding_mask=None)loss = criterion(logits.squeeze(0), target_tensor)loss.backward()torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)optimizer.step()last_loss = loss.item()model.eval()print(f"Online update done. Final Loss: {last_loss:.4f}")def process_feedback(history: List[List[Optional[str]]], rating: str) -> Tuple[List[List[Optional[str]]], str]:if not isinstance(history, list):return [], "Cannot process feedback: history not a list."if not history or not (isinstance(history[-1], list) and len(history[-1]) == 2 and isinstance(history[-1][1], str)):return history, "Cannot process feedback: No recent AI response found."last_user_message, last_ai_response = history[-1][0], history[-1][1]file_context_text = ""file_match = re.search(r"\(Attached: (.*?)\)", last_user_message or "")if file_match:file_name = file_match.group(1)file_context_text = f"The user provided a file named '{file_name}'."clean_user_message = to_ascii(last_user_message or "")clean_user_message = re.sub(r'\(Attached:.*?\)', '', clean_user_message).strip()clean_user_message = re.sub(r'\[IMAGE_PREVIEW_URL:.*?]', '', clean_user_message).strip()search_context_text = ""if rating == "Good Response":conversation_context = ""if len(history) >= 2 and isinstance(history[-2], list) and len(history[-2]) == 2 and isinstance(history[-2][1], str):last_user, last_ai = history[-2][0], history[-2][1]conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"online_update(gpt_model,clean_user_message,last_ai_response,HP["max_length"],search_context=search_context_text,file_context=file_context_text,conversation_context=conversation_context,)save_checkpoint(gpt_model, optimizer, voc, CHECKPOINT_PATH)feedback_message = "Thanks for the Good Response rating! Learned from that turn. ✨"elif rating == "Bad Response":feedback_message = "Acknowledged Bad Response feedback. 🛠️"else:feedback_message = "Unknown rating received."return history, feedback_messagedef feedback_good(history_state: List[List[Optional[str]]]) -> Tuple[List[List[Optional[str]]], str]:history_state, feedback_message = process_feedback(history_state, "Good Response")return history_state, feedback_messagedef feedback_bad(history_state: List[List[Optional[str]]]) -> Tuple[List[List[Optional[str]]], str]:history_state, feedback_message = process_feedback(history_state, "Bad Response")return history_state, feedback_messagedef feedback_bad_with_prompt(history_state: List[List[Optional[str]]], suggested_prompt: str) -> Tuple[List[List[Optional[str]]], str]:log_path = "bad_feedback_log.txt"try:with open(log_path, "a", encoding="utf-8") as f:f.write(f"\n--- {datetime.now()} ---\nSuggested Prompt:\n{suggested_prompt}\n\n")except Exception as e:print(f"Failed to log feedback: {e}")process_feedback(history_state, "Bad Response")return history_state, f"Recorded:\n“{suggested_prompt}”"# ---------------------# Core request handling# ---------------------def _extract_file_context(uploaded_file: Optional[Any]) -> str:if not uploaded_file:return ""file_name = uploaded_file.name.split("/")[-1]return f"The user has provided a file named '{file_name}'. Analyze or respond to the user's prompt about this file."def _build_conversation_context(history: List[List[Optional[str]]], is_instruction: bool) -> str:context_history = history[:-1] if not is_instruction else historyif context_history and isinstance(context_history[-1], list) and len(context_history[-1]) == 2 and isinstance(context_history[-1][1], str):last_user, last_ai = context_history[-1][0], context_history[-1][1]return f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"return ""def _is_instruction_turn(user_message: str) -> bool:prefixes = ("please generate", "provide a much more detailed", "provide a different")return any((user_message or "").lower().startswith(p) for p in prefixes)def on_submit(user_message: str,history: Optional[List[List[Optional[str]]]],uploaded_file: Optional[Any],web_search_enabled_flag_unused: bool = True,) -> Iterator[Tuple[List[List[Optional[str]]], str]]:"""Handles the request and yields incremental updates for streaming."""history = history or []file_context = _extract_file_context(uploaded_file)is_instruction = _is_instruction_turn(user_message or "")clean_user_message = user_message or ""quoted_match = re.search(r':\s*"(.+?)"$', clean_user_message)if is_instruction and quoted_match:clean_user_message = quoted_match.group(1).strip()model_prompt = user_messageelse:model_prompt = user_messageclean_user_message = re.sub(r'\(Attached:.*?\)', '', clean_user_message).strip()clean_user_message = re.sub(r'\[IMAGE_PREVIEW_URL:.*?]', '', clean_user_message).strip()conversation_context = _build_conversation_context(history, is_instruction)search_context_text = ""if should_search(clean_user_message):query_for_search = WEB_TAG_RE.sub("", clean_user_message).strip()search_context_text = perform_web_search(query_for_search)display_search_result = (f"🔍 **Search Result Used:** {search_context_text}" if search_context_textelse "")final_model_prompt = f"{file_context} {model_prompt}" if file_context else model_promptfinal_model_prompt = WEB_TAG_RE.sub("", final_model_prompt or "").strip()# --- Streaming Logic ---response_generator = generate_response(final_model_prompt,search_context=search_context_text,conversation_context=conversation_context,)full_reply_text = ""status_message = display_search_result or "Thinking..."last_user_message = history[-1][0] if history and history[-1][0] else clean_user_messagefor token in response_generator:full_reply_text += token# Update the last message in history with the partial responseif history and history[-1][1] is None:history[-1][1] = full_reply_textelif history:# Ensure we don't accidentally lose the user message if it was stripped before submithistory[-1][0] = last_user_messagehistory[-1][1] = full_reply_text# Yield the current state for streaming to the frontendyield history, status_message# --- Final Formatting and Completion ---# Final formatting/cleanupfull_reply_text = to_ascii(full_reply_text)full_reply_text = re.sub(r"\s+([,.!?;:])", r"\1", full_reply_text).strip()# Final checksif not full_reply_text or check_repetition(full_reply_text):final_reply = "I got lost in the data tubes! Perhaps ask me something a little sillier? 🤪"status_message = display_search_result or "Error: Response was blocked."else:final_reply = full_reply_textstatus_message = display_search_result or "Response complete."# Final update to history (in case of an error or final cleanup)if history:history[-1][1] = final_replyyield history, status_message# ---------------------# Gradio app# ---------------------with gr.Blocks(title="OkemoLLM") as demo:gr.Markdown("# OkemoLLM (<WEB> gated web search, checkpoint-aware) 🌐")search_status_display = gr.Markdown("🔍 Search status will appear here.")chat = gr.Chatbot(height=500)with gr.Row():with gr.Column(scale=4):msg = gr.Textbox(placeholder='Type your message… Add "<WEB>" to use web search for this turn.',label="Message",elem_id="okemo-input-textbox")uploaded_file_state = gr.File(label="Uploaded File", visible=False, elem_id="uploaded_file_state")web_search_enabled_state = gr.Checkbox(label="Frontend Search Toggle (ignored; use <WEB>)", value=True)clear = gr.Button("Clear")send_trigger = gr.Button(visible=False, elem_id="okemo-send-button-trigger")def add_user_message_to_history(message: str, history: Optional[List[List[Optional[str]]]], file_ref: Optional[Any], web_enabled: bool):history = history or []return history + [[message, None]], "..."msg.submit(add_user_message_to_history,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat, search_status_display],queue=False).then(on_submit,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat, search_status_display] # REMOVED: queue=False to enable streaming)send_trigger.click(add_user_message_to_history,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat, search_status_display],queue=False).then(on_submit,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat, search_status_display] # REMOVED: queue=False to enable streaming)clear.click(lambda: [], None, chat, queue=False)# Public API endpointsdef chat_submit_api(msg_value: str,chat_value: Optional[List[List[Optional[str]]]],uploaded_file_value: Optional[Any],web_enabled_value: bool,):updated_history = chat_value or []updated_history.append([msg_value, None])# Call generator and return the final statefinal_history, status_msg = list(on_submit(msg_value, updated_history, uploaded_file_value, web_enabled_value))[-1]return final_history, status_msggr.Interface(fn=chat_submit_api,inputs=[gr.Textbox(label="Message"),gr.State(value=[]),gr.File(label="Uploaded File"),gr.Checkbox(label="Web Search Enabled (ignored; use <WEB>)", value=True),],outputs=[gr.State(value=[]),gr.Textbox(visible=False),],api_name="on_submit",live=False,allow_flagging="never",)gr.Interface(fn=feedback_good,inputs=[gr.State(value=[])],outputs=[gr.State(value=[]), gr.Textbox()],api_name="feedback_good",live=False,allow_flagging="never",)gr.Interface(fn=feedback_bad,inputs=[gr.State(value=[])],outputs=[gr.State(value=[]), gr.Textbox()],api_name="feedback_bad",live=False,allow_flagging="never",)gr.Interface(fn=feedback_bad_with_prompt,inputs=[gr.State(value=[]), gr.Textbox(label="Suggested Prompt")],outputs=[gr.State(value=[]), gr.Textbox()],api_name="feedback_bad_with_prompt",live=False,allow_flagging="never",)if __name__ == "__main__":demo.queue(api_open=True).launch(ssr_mode=False)
app.py+511-487