Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import math
|
| 3 |
import re
|
|
@@ -26,6 +28,7 @@ class Voc:
|
|
| 26 |
self.word2index = {self.PAD: 0, self.SOS: 1, self.EOS: 2, self.UNK: 3, self.SYSTEM: 4}
|
| 27 |
self.index2word = {0: self.PAD, 1: self.SOS, 2: self.EOS, 3: self.UNK, 4: self.SYSTEM}
|
| 28 |
self.n_words = 5
|
|
|
|
| 29 |
@staticmethod
|
| 30 |
def load_from_checkpoint(checkpoint):
|
| 31 |
voc = Voc()
|
|
@@ -41,16 +44,13 @@ class Voc:
|
|
| 41 |
voc.SYSTEM = tokens.get("SYSTEM", "<SYSTEM>")
|
| 42 |
return voc
|
| 43 |
|
|
|
|
| 44 |
# English-only sanitation:
|
| 45 |
-
# Define characters that should stick to words (letters, digits, apostrophe, hyphen)
|
| 46 |
_WORD_TOKEN_CHARS = r"a-z0-9\'\-"
|
| 47 |
-
# Define punctuation that should be split as separate tokens (e.g., comma, period, question mark)
|
| 48 |
_SPLIT_PUNCT = r"\.\,\!\?\:\;\(\)\[\]\{\}\"\/\\@#\$%\^&\*\+\<>=~`"
|
| 49 |
-
|
| 50 |
_token_re = re.compile(rf"[{_WORD_TOKEN_CHARS}]+|[{_SPLIT_PUNCT}]", flags=re.IGNORECASE)
|
| 51 |
|
| 52 |
def to_ascii(text: str) -> str:
|
| 53 |
-
# Normalize and remove non-ASCII
|
| 54 |
text = unicodedata.normalize("NFKC", text)
|
| 55 |
return text.encode("ascii", errors="ignore").decode("ascii")
|
| 56 |
|
|
@@ -59,11 +59,6 @@ def tokenize(text: str):
|
|
| 59 |
return _token_re.findall(ascii_text)
|
| 60 |
|
| 61 |
def is_english_like(text: str, min_alpha_ratio: float = 0.6, max_non_ascii: int = 0):
|
| 62 |
-
"""
|
| 63 |
-
Heuristic:
|
| 64 |
-
- Must have <= max_non_ascii non-ASCII after normalization (we remove them, but check original).
|
| 65 |
-
- After ASCII filtering, the ratio of letters to total characters should be high enough.
|
| 66 |
-
"""
|
| 67 |
norm = unicodedata.normalize("NFKC", text)
|
| 68 |
non_ascii_count = sum(1 for ch in norm if ord(ch) > 127)
|
| 69 |
if non_ascii_count > max_non_ascii:
|
|
@@ -77,12 +72,9 @@ def is_english_like(text: str, min_alpha_ratio: float = 0.6, max_non_ascii: int
|
|
| 77 |
return ratio >= min_alpha_ratio
|
| 78 |
|
| 79 |
def check_repetition(text: str, max_repeat: int = 2):
|
| 80 |
-
"""Checks if any single token is repeated more than max_repeat times consecutively."""
|
| 81 |
tokens = tokenize(text)
|
| 82 |
if not tokens:
|
| 83 |
return False
|
| 84 |
-
|
| 85 |
-
# Check for consecutive triples (or more) of the same token
|
| 86 |
for i in range(len(tokens) - max_repeat):
|
| 87 |
if all(tokens[i] == tokens[j] for j in range(i, i + max_repeat + 1)):
|
| 88 |
return True
|
|
@@ -98,9 +90,11 @@ class PositionalEncoding(nn.Module):
|
|
| 98 |
pe[:, 0::2] = torch.sin(position * div_term)
|
| 99 |
pe[:, 1::2] = torch.cos(position * div_term)
|
| 100 |
self.register_buffer("pe", pe.unsqueeze(0))
|
|
|
|
| 101 |
def forward(self, x):
|
| 102 |
return x + self.pe[:, : x.size(1), :]
|
| 103 |
|
|
|
|
| 104 |
class GPT(nn.Module):
|
| 105 |
def __init__(self, n_words, d_model, n_layers, n_head, d_ff, dropout=0.1):
|
| 106 |
super().__init__()
|
|
@@ -111,6 +105,7 @@ class GPT(nn.Module):
|
|
| 111 |
self.transformer = nn.TransformerEncoder(enc_layer, n_layers)
|
| 112 |
self.fc = nn.Linear(d_model, n_words, bias=False)
|
| 113 |
self.fc.weight = self.embedding.weight
|
|
|
|
| 114 |
def forward(self, x, mask=None, key_padding_mask=None):
|
| 115 |
x = self.embedding(x)
|
| 116 |
x = self.pos(x)
|
|
@@ -118,8 +113,8 @@ class GPT(nn.Module):
|
|
| 118 |
out = self.transformer(x, mask=mask, src_key_padding_mask=key_padding_mask)
|
| 119 |
return self.fc(out)
|
| 120 |
|
|
|
|
| 121 |
def indexes_from_sentence(voc, sentence):
|
| 122 |
-
# Sanitize to English-only before mapping to vocab
|
| 123 |
sanitized = " ".join(tokenize(sentence))
|
| 124 |
prompt_tokens = [voc.SYSTEM] + tokenize(sanitized)
|
| 125 |
return [voc.word2index.get(tok, voc.word2index[voc.UNK]) for tok in prompt_tokens] + [voc.word2index[voc.EOS]]
|
|
@@ -127,19 +122,18 @@ def indexes_from_sentence(voc, sentence):
|
|
| 127 |
def make_bool_causal_mask(sz, device):
|
| 128 |
return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)
|
| 129 |
|
|
|
|
| 130 |
device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")
|
| 131 |
|
| 132 |
CHECKPOINT_PATH = "checkpoint.pth"
|
| 133 |
if not os.path.exists(CHECKPOINT_PATH):
|
| 134 |
-
# NOTE: This is a placeholder for a real application setup.
|
| 135 |
print("WARNING: Using dummy checkpoint as real file not found. Online learning will not affect model state permanently.")
|
| 136 |
checkpoint = {
|
| 137 |
"voc_word2index": Voc().word2index,
|
| 138 |
"voc_index2word": Voc().index2word,
|
| 139 |
"gpt_model_state_dict": None
|
| 140 |
}
|
| 141 |
-
|
| 142 |
-
# Placeholder for model initialization if checkpoint fails (for testing/safety)
|
| 143 |
d_model = 768
|
| 144 |
n_head = 48
|
| 145 |
d_ff = 768
|
|
@@ -168,7 +162,7 @@ else:
|
|
| 168 |
gpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)
|
| 169 |
if "gpt_model_state_dict" in checkpoint and checkpoint["gpt_model_state_dict"] is not None:
|
| 170 |
gpt_model.load_state_dict(checkpoint["gpt_model_state_dict"], strict=True)
|
| 171 |
-
|
| 172 |
optimizer = optim.Adam(gpt_model.parameters(), lr=LEARNING_RATE)
|
| 173 |
criterion = nn.CrossEntropyLoss(ignore_index=voc.word2index[voc.PAD])
|
| 174 |
|
|
@@ -183,13 +177,11 @@ def perform_web_search(query):
|
|
| 183 |
else:
|
| 184 |
return ""
|
| 185 |
|
|
|
|
| 186 |
def online_update(model, input_sentence, target_response, max_seq_len, search_context="", conversation_context=""):
|
| 187 |
-
"""
|
| 188 |
-
Performs a fixed number of training steps (epochs), incorporating sanitized English-only search context.
|
| 189 |
-
"""
|
| 190 |
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"])
|
| 191 |
is_not_repetitive = not check_repetition(target_response, max_repeat=2)
|
| 192 |
-
|
| 193 |
if not is_response_clean or not is_not_repetitive:
|
| 194 |
print("Skipping online update: Target response is non-English, corrupted, or highly repetitive.")
|
| 195 |
return
|
|
@@ -216,24 +208,22 @@ def online_update(model, input_sentence, target_response, max_seq_len, search_co
|
|
| 216 |
target_tensor = torch.tensor(target_ids, dtype=torch.long, device=device)
|
| 217 |
|
| 218 |
L = input_tensor.size(1)
|
| 219 |
-
|
| 220 |
model.train()
|
| 221 |
causal = make_bool_causal_mask(L, device)
|
| 222 |
-
|
| 223 |
last_loss = 0.0
|
| 224 |
for epoch in range(ONLINE_LEARNING_EPOCHS):
|
| 225 |
optimizer.zero_grad()
|
| 226 |
-
|
| 227 |
logits = model(input_tensor, mask=causal, key_padding_mask=None)
|
| 228 |
loss = criterion(logits.squeeze(0), target_tensor)
|
| 229 |
-
|
| 230 |
loss.backward()
|
| 231 |
optimizer.step()
|
| 232 |
last_loss = loss.item()
|
| 233 |
-
|
| 234 |
model.eval()
|
| 235 |
print(f"Online update performed over {ONLINE_LEARNING_EPOCHS} epochs. Final Loss: {last_loss:.4f}")
|
| 236 |
|
|
|
|
| 237 |
def generate_response(prompt, search_context="", conversation_context=""):
|
| 238 |
if not is_english_like(prompt):
|
| 239 |
return "Please use English. Non-English input was detected."
|
|
@@ -271,7 +261,7 @@ def generate_response(prompt, search_context="", conversation_context=""):
|
|
| 271 |
candidate_word = voc.index2word.get(candidate_id, voc.UNK)
|
| 272 |
|
| 273 |
token_ok = is_english_like(candidate_word, min_alpha_ratio=0.1, max_non_ascii=0)
|
| 274 |
-
|
| 275 |
if candidate_id == voc.word2index[voc.EOS]:
|
| 276 |
next_id = candidate_id
|
| 277 |
break
|
|
@@ -286,7 +276,7 @@ def generate_response(prompt, search_context="", conversation_context=""):
|
|
| 286 |
|
| 287 |
if next_id == voc.word2index[voc.EOS]:
|
| 288 |
break
|
| 289 |
-
|
| 290 |
generated.append(next_id)
|
| 291 |
input_tensor = torch.cat(
|
| 292 |
[input_tensor, torch.tensor([[next_id]], device=device, dtype=torch.long)],
|
|
@@ -312,7 +302,7 @@ def process_feedback(history, rating):
|
|
| 312 |
return history, "Cannot process feedback: No recent AI response found."
|
| 313 |
|
| 314 |
last_user_message, last_ai_response = history[-1][0], history[-1][1]
|
| 315 |
-
|
| 316 |
print(f"\n--- FEEDBACK RECEIVED ---")
|
| 317 |
print(f"Rating: {rating}")
|
| 318 |
print(f"User Prompt: '{last_user_message}'")
|
|
@@ -326,21 +316,21 @@ def process_feedback(history, rating):
|
|
| 326 |
conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
|
| 327 |
|
| 328 |
online_update(
|
| 329 |
-
gpt_model,
|
| 330 |
-
last_user_message,
|
| 331 |
-
last_ai_response,
|
| 332 |
-
max_length,
|
| 333 |
-
search_context="",
|
| 334 |
conversation_context=conversation_context
|
| 335 |
)
|
| 336 |
feedback_message = f"Thanks for the **Good Response** rating! I just learned from that. Keep the good prompts coming! ✨"
|
| 337 |
-
|
| 338 |
elif rating == "Bad Response":
|
| 339 |
-
feedback_message = f"Acknowledged **Bad Response** feedback. I will try to be better! 🛠
|
| 340 |
|
| 341 |
else:
|
| 342 |
feedback_message = "Unknown rating received."
|
| 343 |
-
|
| 344 |
return history, feedback_message
|
| 345 |
|
| 346 |
|
|
@@ -348,20 +338,26 @@ def on_submit(user_message, history, uploaded_file, web_search_enabled):
|
|
| 348 |
"""
|
| 349 |
The central handler called by the front-end when the user submits a message.
|
| 350 |
"""
|
| 351 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
# 1. Handle file upload (Placeholder)
|
| 353 |
file_context = ""
|
| 354 |
if uploaded_file:
|
| 355 |
-
file_name = uploaded_file.name.split("/")[-1]
|
| 356 |
file_context = f"The user has provided a file named '{file_name}'. Analyze or respond to the user's prompt *about this file*."
|
| 357 |
print(f"File attached: {file_name}")
|
| 358 |
|
| 359 |
# 2. Determine if this is a regeneration/enhancement instruction
|
| 360 |
is_instruction = any(user_message.lower().startswith(p) for p in ["please generate", "provide a much more detailed", "provide a different"])
|
| 361 |
-
|
| 362 |
# 3. Extract the clean message for the model input
|
| 363 |
match = re.search(r':\s*"(.+?)"$', user_message)
|
| 364 |
-
|
| 365 |
if is_instruction and match:
|
| 366 |
clean_user_message = match.group(1).strip()
|
| 367 |
model_prompt = user_message
|
|
@@ -378,10 +374,8 @@ def on_submit(user_message, history, uploaded_file, web_search_enabled):
|
|
| 378 |
conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
|
| 379 |
print(f"Context included: {conversation_context}")
|
| 380 |
|
| 381 |
-
# 5. Enforce English-only input for the *clean* message
|
| 382 |
if not is_english_like(clean_user_message):
|
| 383 |
-
# We assume the user message has already been added by the helper function,
|
| 384 |
-
# so we just update the response field.
|
| 385 |
history[-1][1] = "Please use English. Non-English input was detected."
|
| 386 |
return history, ""
|
| 387 |
|
|
@@ -396,15 +390,15 @@ def on_submit(user_message, history, uploaded_file, web_search_enabled):
|
|
| 396 |
|
| 397 |
# 7. Prepend file context (if any) to the model's prompt
|
| 398 |
final_model_prompt = f"{file_context} {model_prompt}" if file_context else model_prompt
|
| 399 |
-
|
| 400 |
-
# 8. Generate response
|
| 401 |
reply = generate_response(
|
| 402 |
-
final_model_prompt,
|
| 403 |
-
search_context=search_context_text,
|
| 404 |
conversation_context=conversation_context
|
| 405 |
)
|
| 406 |
|
| 407 |
-
# 9. Update the history
|
| 408 |
history[-1][1] = reply
|
| 409 |
return history, ""
|
| 410 |
|
|
@@ -413,84 +407,80 @@ def on_submit(user_message, history, uploaded_file, web_search_enabled):
|
|
| 413 |
|
| 414 |
with gr.Blocks(title="OkemoLLM") as demo:
|
| 415 |
gr.Markdown("# OkemoLLM (English-only, Online Learning & Web Search Enabled with 1-Turn Context)")
|
| 416 |
-
chat = gr.Chatbot(height=500)
|
| 417 |
-
|
| 418 |
with gr.Row():
|
| 419 |
with gr.Column(scale=4):
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
# Hidden state components for the JS front-end to communicate state
|
| 424 |
-
# The elem_id is critical for the external JS to find these elements.
|
| 425 |
uploaded_file_state = gr.File(label="Uploaded File", visible=False, elem_id="uploaded_file_state")
|
| 426 |
-
web_search_enabled_state = gr.Checkbox(label="Web Search Toggle", visible=False, elem_id="web_search_enabled_state")
|
| 427 |
-
|
| 428 |
clear = gr.Button("Clear")
|
| 429 |
-
|
| 430 |
-
# NEW: Hidden button that the JavaScript will "click" to trigger the full submission chain
|
| 431 |
send_trigger = gr.Button(visible=False, elem_id="okemo-send-button-trigger")
|
| 432 |
|
| 433 |
def add_user_message_to_history(message, history, file_ref, web_enabled):
|
| 434 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 435 |
if file_ref:
|
| 436 |
-
# Append filename for history visibility
|
| 437 |
message = f"{message} (Attached: {file_ref.name.split('/')[-1]})"
|
| 438 |
-
|
| 439 |
-
return
|
| 440 |
|
| 441 |
-
# Chain of events for SUBMISSION (triggered by Textbox Enter or the hidden Button):
|
| 442 |
-
|
| 443 |
# 1. Textbox Enter event
|
| 444 |
msg.submit(
|
| 445 |
-
add_user_message_to_history,
|
| 446 |
-
[msg, chat, uploaded_file_state, web_search_enabled_state],
|
| 447 |
-
[chat, msg],
|
| 448 |
queue=False
|
| 449 |
).then(
|
| 450 |
-
on_submit,
|
| 451 |
-
[msg, chat, uploaded_file_state, web_search_enabled_state],
|
| 452 |
[chat],
|
| 453 |
)
|
| 454 |
-
|
| 455 |
-
# 2. Hidden Button Click event
|
| 456 |
send_trigger.click(
|
| 457 |
-
add_user_message_to_history,
|
| 458 |
-
[msg, chat, uploaded_file_state, web_search_enabled_state],
|
| 459 |
-
[chat, msg],
|
| 460 |
queue=False
|
| 461 |
).then(
|
| 462 |
-
on_submit,
|
| 463 |
-
[msg, chat, uploaded_file_state, web_search_enabled_state],
|
| 464 |
[chat],
|
| 465 |
)
|
| 466 |
-
|
| 467 |
# Clear history event
|
| 468 |
clear.click(lambda: [], None, chat, queue=False)
|
| 469 |
|
| 470 |
-
|
| 471 |
# --- 3. FEEDBACK API ENDPOINTS ---
|
| 472 |
def feedback_good_wrapper(history_state):
|
| 473 |
return process_feedback(history_state, "Good Response")
|
| 474 |
-
|
| 475 |
def feedback_bad_wrapper(history_state):
|
| 476 |
return process_feedback(history_state, "Bad Response")
|
| 477 |
-
|
| 478 |
gr.Interface(
|
| 479 |
fn=feedback_good_wrapper,
|
| 480 |
inputs=[gr.State(value=[])],
|
| 481 |
outputs=[gr.State(value=[]), gr.Textbox(visible=False)],
|
| 482 |
-
api_name="feedback_good",
|
| 483 |
live=False,
|
| 484 |
allow_flagging="never",
|
| 485 |
)
|
| 486 |
-
|
| 487 |
gr.Interface(
|
| 488 |
fn=feedback_bad_wrapper,
|
| 489 |
inputs=[gr.State(value=[])],
|
| 490 |
outputs=[gr.State(value=[]), gr.Textbox(visible=False)],
|
| 491 |
-
api_name="feedback_bad",
|
| 492 |
live=False,
|
| 493 |
allow_flagging="never"
|
| 494 |
)
|
| 495 |
|
| 496 |
-
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
|
| 3 |
import os
|
| 4 |
import math
|
| 5 |
import re
|
|
|
|
| 28 |
self.word2index = {self.PAD: 0, self.SOS: 1, self.EOS: 2, self.UNK: 3, self.SYSTEM: 4}
|
| 29 |
self.index2word = {0: self.PAD, 1: self.SOS, 2: self.EOS, 3: self.UNK, 4: self.SYSTEM}
|
| 30 |
self.n_words = 5
|
| 31 |
+
|
| 32 |
@staticmethod
|
| 33 |
def load_from_checkpoint(checkpoint):
|
| 34 |
voc = Voc()
|
|
|
|
| 44 |
voc.SYSTEM = tokens.get("SYSTEM", "<SYSTEM>")
|
| 45 |
return voc
|
| 46 |
|
| 47 |
+
|
| 48 |
# English-only sanitation:
|
|
|
|
| 49 |
_WORD_TOKEN_CHARS = r"a-z0-9\'\-"
|
|
|
|
| 50 |
_SPLIT_PUNCT = r"\.\,\!\?\:\;\(\)\[\]\{\}\"\/\\@#\$%\^&\*\+\<>=~`"
|
|
|
|
| 51 |
_token_re = re.compile(rf"[{_WORD_TOKEN_CHARS}]+|[{_SPLIT_PUNCT}]", flags=re.IGNORECASE)
|
| 52 |
|
| 53 |
def to_ascii(text: str) -> str:
|
|
|
|
| 54 |
text = unicodedata.normalize("NFKC", text)
|
| 55 |
return text.encode("ascii", errors="ignore").decode("ascii")
|
| 56 |
|
|
|
|
| 59 |
return _token_re.findall(ascii_text)
|
| 60 |
|
| 61 |
def is_english_like(text: str, min_alpha_ratio: float = 0.6, max_non_ascii: int = 0):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
norm = unicodedata.normalize("NFKC", text)
|
| 63 |
non_ascii_count = sum(1 for ch in norm if ord(ch) > 127)
|
| 64 |
if non_ascii_count > max_non_ascii:
|
|
|
|
| 72 |
return ratio >= min_alpha_ratio
|
| 73 |
|
| 74 |
def check_repetition(text: str, max_repeat: int = 2):
|
|
|
|
| 75 |
tokens = tokenize(text)
|
| 76 |
if not tokens:
|
| 77 |
return False
|
|
|
|
|
|
|
| 78 |
for i in range(len(tokens) - max_repeat):
|
| 79 |
if all(tokens[i] == tokens[j] for j in range(i, i + max_repeat + 1)):
|
| 80 |
return True
|
|
|
|
| 90 |
pe[:, 0::2] = torch.sin(position * div_term)
|
| 91 |
pe[:, 1::2] = torch.cos(position * div_term)
|
| 92 |
self.register_buffer("pe", pe.unsqueeze(0))
|
| 93 |
+
|
| 94 |
def forward(self, x):
|
| 95 |
return x + self.pe[:, : x.size(1), :]
|
| 96 |
|
| 97 |
+
|
| 98 |
class GPT(nn.Module):
|
| 99 |
def __init__(self, n_words, d_model, n_layers, n_head, d_ff, dropout=0.1):
|
| 100 |
super().__init__()
|
|
|
|
| 105 |
self.transformer = nn.TransformerEncoder(enc_layer, n_layers)
|
| 106 |
self.fc = nn.Linear(d_model, n_words, bias=False)
|
| 107 |
self.fc.weight = self.embedding.weight
|
| 108 |
+
|
| 109 |
def forward(self, x, mask=None, key_padding_mask=None):
|
| 110 |
x = self.embedding(x)
|
| 111 |
x = self.pos(x)
|
|
|
|
| 113 |
out = self.transformer(x, mask=mask, src_key_padding_mask=key_padding_mask)
|
| 114 |
return self.fc(out)
|
| 115 |
|
| 116 |
+
|
| 117 |
def indexes_from_sentence(voc, sentence):
|
|
|
|
| 118 |
sanitized = " ".join(tokenize(sentence))
|
| 119 |
prompt_tokens = [voc.SYSTEM] + tokenize(sanitized)
|
| 120 |
return [voc.word2index.get(tok, voc.word2index[voc.UNK]) for tok in prompt_tokens] + [voc.word2index[voc.EOS]]
|
|
|
|
| 122 |
def make_bool_causal_mask(sz, device):
|
| 123 |
return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)
|
| 124 |
|
| 125 |
+
|
| 126 |
device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")
|
| 127 |
|
| 128 |
CHECKPOINT_PATH = "checkpoint.pth"
|
| 129 |
if not os.path.exists(CHECKPOINT_PATH):
|
|
|
|
| 130 |
print("WARNING: Using dummy checkpoint as real file not found. Online learning will not affect model state permanently.")
|
| 131 |
checkpoint = {
|
| 132 |
"voc_word2index": Voc().word2index,
|
| 133 |
"voc_index2word": Voc().index2word,
|
| 134 |
"gpt_model_state_dict": None
|
| 135 |
}
|
| 136 |
+
|
|
|
|
| 137 |
d_model = 768
|
| 138 |
n_head = 48
|
| 139 |
d_ff = 768
|
|
|
|
| 162 |
gpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)
|
| 163 |
if "gpt_model_state_dict" in checkpoint and checkpoint["gpt_model_state_dict"] is not None:
|
| 164 |
gpt_model.load_state_dict(checkpoint["gpt_model_state_dict"], strict=True)
|
| 165 |
+
|
| 166 |
optimizer = optim.Adam(gpt_model.parameters(), lr=LEARNING_RATE)
|
| 167 |
criterion = nn.CrossEntropyLoss(ignore_index=voc.word2index[voc.PAD])
|
| 168 |
|
|
|
|
| 177 |
else:
|
| 178 |
return ""
|
| 179 |
|
| 180 |
+
|
| 181 |
def online_update(model, input_sentence, target_response, max_seq_len, search_context="", conversation_context=""):
|
|
|
|
|
|
|
|
|
|
| 182 |
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"])
|
| 183 |
is_not_repetitive = not check_repetition(target_response, max_repeat=2)
|
| 184 |
+
|
| 185 |
if not is_response_clean or not is_not_repetitive:
|
| 186 |
print("Skipping online update: Target response is non-English, corrupted, or highly repetitive.")
|
| 187 |
return
|
|
|
|
| 208 |
target_tensor = torch.tensor(target_ids, dtype=torch.long, device=device)
|
| 209 |
|
| 210 |
L = input_tensor.size(1)
|
|
|
|
| 211 |
model.train()
|
| 212 |
causal = make_bool_causal_mask(L, device)
|
| 213 |
+
|
| 214 |
last_loss = 0.0
|
| 215 |
for epoch in range(ONLINE_LEARNING_EPOCHS):
|
| 216 |
optimizer.zero_grad()
|
|
|
|
| 217 |
logits = model(input_tensor, mask=causal, key_padding_mask=None)
|
| 218 |
loss = criterion(logits.squeeze(0), target_tensor)
|
|
|
|
| 219 |
loss.backward()
|
| 220 |
optimizer.step()
|
| 221 |
last_loss = loss.item()
|
| 222 |
+
|
| 223 |
model.eval()
|
| 224 |
print(f"Online update performed over {ONLINE_LEARNING_EPOCHS} epochs. Final Loss: {last_loss:.4f}")
|
| 225 |
|
| 226 |
+
|
| 227 |
def generate_response(prompt, search_context="", conversation_context=""):
|
| 228 |
if not is_english_like(prompt):
|
| 229 |
return "Please use English. Non-English input was detected."
|
|
|
|
| 261 |
candidate_word = voc.index2word.get(candidate_id, voc.UNK)
|
| 262 |
|
| 263 |
token_ok = is_english_like(candidate_word, min_alpha_ratio=0.1, max_non_ascii=0)
|
| 264 |
+
|
| 265 |
if candidate_id == voc.word2index[voc.EOS]:
|
| 266 |
next_id = candidate_id
|
| 267 |
break
|
|
|
|
| 276 |
|
| 277 |
if next_id == voc.word2index[voc.EOS]:
|
| 278 |
break
|
| 279 |
+
|
| 280 |
generated.append(next_id)
|
| 281 |
input_tensor = torch.cat(
|
| 282 |
[input_tensor, torch.tensor([[next_id]], device=device, dtype=torch.long)],
|
|
|
|
| 302 |
return history, "Cannot process feedback: No recent AI response found."
|
| 303 |
|
| 304 |
last_user_message, last_ai_response = history[-1][0], history[-1][1]
|
| 305 |
+
|
| 306 |
print(f"\n--- FEEDBACK RECEIVED ---")
|
| 307 |
print(f"Rating: {rating}")
|
| 308 |
print(f"User Prompt: '{last_user_message}'")
|
|
|
|
| 316 |
conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
|
| 317 |
|
| 318 |
online_update(
|
| 319 |
+
gpt_model,
|
| 320 |
+
last_user_message,
|
| 321 |
+
last_ai_response,
|
| 322 |
+
max_length,
|
| 323 |
+
search_context="",
|
| 324 |
conversation_context=conversation_context
|
| 325 |
)
|
| 326 |
feedback_message = f"Thanks for the **Good Response** rating! I just learned from that. Keep the good prompts coming! ✨"
|
| 327 |
+
|
| 328 |
elif rating == "Bad Response":
|
| 329 |
+
feedback_message = f"Acknowledged **Bad Response** feedback. I will try to be better! 🛠"
|
| 330 |
|
| 331 |
else:
|
| 332 |
feedback_message = "Unknown rating received."
|
| 333 |
+
|
| 334 |
return history, feedback_message
|
| 335 |
|
| 336 |
|
|
|
|
| 338 |
"""
|
| 339 |
The central handler called by the front-end when the user submits a message.
|
| 340 |
"""
|
| 341 |
+
|
| 342 |
+
# Defensive: ensure history has a pending assistant slot
|
| 343 |
+
if history is None:
|
| 344 |
+
history = []
|
| 345 |
+
if len(history) == 0 or history[-1][1] is not None:
|
| 346 |
+
history.append([user_message, None])
|
| 347 |
+
|
| 348 |
# 1. Handle file upload (Placeholder)
|
| 349 |
file_context = ""
|
| 350 |
if uploaded_file:
|
| 351 |
+
file_name = uploaded_file.name.split("/")[-1]
|
| 352 |
file_context = f"The user has provided a file named '{file_name}'. Analyze or respond to the user's prompt *about this file*."
|
| 353 |
print(f"File attached: {file_name}")
|
| 354 |
|
| 355 |
# 2. Determine if this is a regeneration/enhancement instruction
|
| 356 |
is_instruction = any(user_message.lower().startswith(p) for p in ["please generate", "provide a much more detailed", "provide a different"])
|
| 357 |
+
|
| 358 |
# 3. Extract the clean message for the model input
|
| 359 |
match = re.search(r':\s*"(.+?)"$', user_message)
|
| 360 |
+
|
| 361 |
if is_instruction and match:
|
| 362 |
clean_user_message = match.group(1).strip()
|
| 363 |
model_prompt = user_message
|
|
|
|
| 374 |
conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
|
| 375 |
print(f"Context included: {conversation_context}")
|
| 376 |
|
| 377 |
+
# 5. Enforce English-only input for the *clean* message
|
| 378 |
if not is_english_like(clean_user_message):
|
|
|
|
|
|
|
| 379 |
history[-1][1] = "Please use English. Non-English input was detected."
|
| 380 |
return history, ""
|
| 381 |
|
|
|
|
| 390 |
|
| 391 |
# 7. Prepend file context (if any) to the model's prompt
|
| 392 |
final_model_prompt = f"{file_context} {model_prompt}" if file_context else model_prompt
|
| 393 |
+
|
| 394 |
+
# 8. Generate response
|
| 395 |
reply = generate_response(
|
| 396 |
+
final_model_prompt,
|
| 397 |
+
search_context=search_context_text,
|
| 398 |
conversation_context=conversation_context
|
| 399 |
)
|
| 400 |
|
| 401 |
+
# 9. Update the history
|
| 402 |
history[-1][1] = reply
|
| 403 |
return history, ""
|
| 404 |
|
|
|
|
| 407 |
|
| 408 |
with gr.Blocks(title="OkemoLLM") as demo:
|
| 409 |
gr.Markdown("# OkemoLLM (English-only, Online Learning & Web Search Enabled with 1-Turn Context)")
|
| 410 |
+
chat = gr.Chatbot(height=500)
|
| 411 |
+
|
| 412 |
with gr.Row():
|
| 413 |
with gr.Column(scale=4):
|
| 414 |
+
msg = gr.Textbox(placeholder="Type your message…", label="Message", elem_id="okemo-input-textbox")
|
| 415 |
+
|
|
|
|
|
|
|
|
|
|
| 416 |
uploaded_file_state = gr.File(label="Uploaded File", visible=False, elem_id="uploaded_file_state")
|
| 417 |
+
web_search_enabled_state = gr.Checkbox(label="Web Search Toggle", visible=False, elem_id="web_search_enabled_state")
|
| 418 |
+
|
| 419 |
clear = gr.Button("Clear")
|
|
|
|
|
|
|
| 420 |
send_trigger = gr.Button(visible=False, elem_id="okemo-send-button-trigger")
|
| 421 |
|
| 422 |
def add_user_message_to_history(message, history, file_ref, web_enabled):
|
| 423 |
+
"""
|
| 424 |
+
Returns:
|
| 425 |
+
- updated chat history (for the Chatbot)
|
| 426 |
+
- empty string to clear the Textbox
|
| 427 |
+
"""
|
| 428 |
if file_ref:
|
|
|
|
| 429 |
message = f"{message} (Attached: {file_ref.name.split('/')[-1]})"
|
| 430 |
+
updated_history = (history or []) + [[message, None]]
|
| 431 |
+
return updated_history, "" # Chatbot history, cleared textbox
|
| 432 |
|
|
|
|
|
|
|
| 433 |
# 1. Textbox Enter event
|
| 434 |
msg.submit(
|
| 435 |
+
add_user_message_to_history,
|
| 436 |
+
[msg, chat, uploaded_file_state, web_search_enabled_state],
|
| 437 |
+
[chat, msg], # two outputs expected
|
| 438 |
queue=False
|
| 439 |
).then(
|
| 440 |
+
on_submit,
|
| 441 |
+
[msg, chat, uploaded_file_state, web_search_enabled_state],
|
| 442 |
[chat],
|
| 443 |
)
|
| 444 |
+
|
| 445 |
+
# 2. Hidden Button Click event
|
| 446 |
send_trigger.click(
|
| 447 |
+
add_user_message_to_history,
|
| 448 |
+
[msg, chat, uploaded_file_state, web_search_enabled_state],
|
| 449 |
+
[chat, msg], # two outputs expected
|
| 450 |
queue=False
|
| 451 |
).then(
|
| 452 |
+
on_submit,
|
| 453 |
+
[msg, chat, uploaded_file_state, web_search_enabled_state],
|
| 454 |
[chat],
|
| 455 |
)
|
| 456 |
+
|
| 457 |
# Clear history event
|
| 458 |
clear.click(lambda: [], None, chat, queue=False)
|
| 459 |
|
|
|
|
| 460 |
# --- 3. FEEDBACK API ENDPOINTS ---
|
| 461 |
def feedback_good_wrapper(history_state):
|
| 462 |
return process_feedback(history_state, "Good Response")
|
| 463 |
+
|
| 464 |
def feedback_bad_wrapper(history_state):
|
| 465 |
return process_feedback(history_state, "Bad Response")
|
| 466 |
+
|
| 467 |
gr.Interface(
|
| 468 |
fn=feedback_good_wrapper,
|
| 469 |
inputs=[gr.State(value=[])],
|
| 470 |
outputs=[gr.State(value=[]), gr.Textbox(visible=False)],
|
| 471 |
+
api_name="feedback_good",
|
| 472 |
live=False,
|
| 473 |
allow_flagging="never",
|
| 474 |
)
|
| 475 |
+
|
| 476 |
gr.Interface(
|
| 477 |
fn=feedback_bad_wrapper,
|
| 478 |
inputs=[gr.State(value=[])],
|
| 479 |
outputs=[gr.State(value=[]), gr.Textbox(visible=False)],
|
| 480 |
+
api_name="feedback_bad",
|
| 481 |
live=False,
|
| 482 |
allow_flagging="never"
|
| 483 |
)
|
| 484 |
|
| 485 |
+
# Enable SSR info message and make public link configurable
|
| 486 |
+
demo.queue(api_open=True).launch()
|