Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -18,24 +18,24 @@ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
|
|
| 18 |
|
| 19 |
# --- SYSTEM INSTRUCTION MODIFIED FOR CHATGPT-LIKE BEHAVIOR ---
|
| 20 |
SYSTEM_INSTRUCTION = (
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
)
|
| 26 |
# -------------------------------------------------------------------------
|
| 27 |
|
| 28 |
CHECKPOINT_PATH = "checkpoint.pth"
|
| 29 |
|
| 30 |
DEFAULTS = {
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
}
|
| 40 |
|
| 41 |
WEB_TAG_RE = re.compile(r"<\s*web\s*>", flags=re.IGNORECASE)
|
|
@@ -45,77 +45,77 @@ TRAIN_INPUT_STATE = {} # Initial value for the Gradio State
|
|
| 45 |
# Helpers
|
| 46 |
# ------------------------
|
| 47 |
def to_ascii(text: Optional[str]) -> str:
|
| 48 |
-
|
| 49 |
|
| 50 |
_TOKEN_RE = re.compile(r"\w+|[^\w\s]", flags=re.UNICODE)
|
| 51 |
|
| 52 |
def tokenize(text: str) -> List[str]:
|
| 53 |
-
|
| 54 |
|
| 55 |
def is_punctuation_token(token: str) -> bool:
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
|
| 61 |
# ------------------------
|
| 62 |
# Vocabulary
|
| 63 |
# ------------------------
|
| 64 |
class Voc:
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
|
| 86 |
# ------------------------
|
| 87 |
# Model
|
| 88 |
# ------------------------
|
| 89 |
class PositionalEncoding(nn.Module):
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
|
| 102 |
class GPT(nn.Module):
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
|
| 120 |
# ------------------------
|
| 121 |
# Device + Checkpoint + Resizing Fix
|
|
@@ -123,84 +123,84 @@ class GPT(nn.Module):
|
|
| 123 |
device = torch.device("cpu")
|
| 124 |
|
| 125 |
def resize_model_if_needed(model: nn.Module, new_n_words: int, d_model: int) -> bool:
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
|
| 154 |
def save_checkpoint(path: str, hp: Dict[str, Any], voc: "Voc", model: nn.Module, optimizer: optim.Optimizer, iteration: int = 0) -> None:
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
|
| 173 |
def load_checkpoint_or_defaults(path: str):
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
|
| 205 |
checkpoint, HP, voc, gpt_model, optimizer = load_checkpoint_or_defaults(CHECKPOINT_PATH)
|
| 206 |
start_iteration = checkpoint.get("iteration", 0)
|
|
@@ -209,385 +209,378 @@ start_iteration = checkpoint.get("iteration", 0)
|
|
| 209 |
# Text utilities
|
| 210 |
# ------------------------
|
| 211 |
def indexes_from_sentence(voc: Voc, sentence: str) -> List[int]:
|
| 212 |
-
|
| 213 |
-
|
| 214 |
|
| 215 |
def make_bool_causal_mask(sz: int, device: torch.device):
|
| 216 |
-
|
| 217 |
-
|
| 218 |
|
| 219 |
# ------------------------
|
| 220 |
# Training Function (Manual Feedback Training)
|
| 221 |
# ------------------------
|
| 222 |
def train_model(
|
| 223 |
-
|
| 224 |
) -> Tuple[float, int]:
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
Β Β return loss.item(), start_iteration
|
| 308 |
|
| 309 |
# ------------------------
|
| 310 |
# DuckDuckGo Web Search (Unchanged)
|
| 311 |
# ------------------------
|
| 312 |
def perform_web_search(query: str) -> str:
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
|
| 334 |
# ------------------------
|
| 335 |
# Web Content Preparation (Max Retention)
|
| 336 |
# ------------------------
|
| 337 |
def prepare_web_content(text: str) -> str:
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
|
| 352 |
# ------------------------
|
| 353 |
# Streaming Generator (STABLE SAMPLER) - REVISED FOR READABILITY
|
| 354 |
# ------------------------
|
| 355 |
def generate_response(prompt: str) -> Iterator[str]:
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
Β Β Β Β Β Β next_token = torch.tensor([[next_id]], device=device)
|
| 445 |
-
Β Β Β Β Β Β input_tensor = torch.cat([input_tensor, next_token], dim=1)
|
| 446 |
|
| 447 |
|
| 448 |
# ------------------------
|
| 449 |
# Core Chat Handler (REGULAR INFERENCE ONLY)
|
| 450 |
# ------------------------
|
| 451 |
def on_submit(user_message: str, history: Optional[List[List[str]]], train_input_state: Dict[str, str], *_):
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
|
| 501 |
# ------------------------
|
| 502 |
# API Endpoint for Feedback Training
|
| 503 |
# ------------------------
|
| 504 |
def feedback_train(history: List[List[str]], desired_response: str) -> str:
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
Β Β Β Β loss_value, new_iteration = train_model(full_training_input, desired_response, voc, gpt_model, optimizer)
|
| 530 |
-
Β Β Β Β return f"β
Training Complete! Iteration: {new_iteration}, Loss: {loss_value:.4f}. Model updated."
|
| 531 |
-
Β Β except Exception as e:
|
| 532 |
-
Β Β Β Β return f"β Training Failed: {e}. Check server logs."
|
| 533 |
|
| 534 |
# ------------------------
|
| 535 |
# Gradio Interface
|
| 536 |
# ------------------------
|
| 537 |
with gr.Blocks(title="OkemoLLM") as demo:
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
|
| 591 |
|
| 592 |
if __name__ == "__main__":
|
| 593 |
-
|
|
|
|
| 18 |
|
| 19 |
# --- SYSTEM INSTRUCTION MODIFIED FOR CHATGPT-LIKE BEHAVIOR ---
|
| 20 |
SYSTEM_INSTRUCTION = (
|
| 21 |
+
"You are Okemo Language Model (OLM), a highly **helpful, verbose, and comprehensive** AI assistant, similar to ChatGPT. "
|
| 22 |
+
"Your goal is to provide detailed and well-structured answers in a conversational tone, ensuring **clarity and fluency**."
|
| 23 |
+
"For complex queries, first generate an internal reasoning chain (DO NOT show it to the user). "
|
| 24 |
+
"If external context is provided, naturally integrate that knowledge into your answer."
|
| 25 |
)
|
| 26 |
# -------------------------------------------------------------------------
|
| 27 |
|
| 28 |
CHECKPOINT_PATH = "checkpoint.pth"
|
| 29 |
|
| 30 |
DEFAULTS = {
|
| 31 |
+
"d_model": 768,
|
| 32 |
+
"n_head": 48,
|
| 33 |
+
"d_ff": 768,
|
| 34 |
+
"n_layers": 12,
|
| 35 |
+
"dropout": 0.1,
|
| 36 |
+
"max_length": 1024,
|
| 37 |
+
"k_sampling": 200, # Using 200 for diversity
|
| 38 |
+
"LEARNING_RATE": 1e-6,
|
| 39 |
}
|
| 40 |
|
| 41 |
WEB_TAG_RE = re.compile(r"<\s*web\s*>", flags=re.IGNORECASE)
|
|
|
|
| 45 |
# Helpers
|
| 46 |
# ------------------------
|
| 47 |
def to_ascii(text: Optional[str]) -> str:
|
| 48 |
+
return unicodedata.normalize("NFKC", text or "")
|
| 49 |
|
| 50 |
_TOKEN_RE = re.compile(r"\w+|[^\w\s]", flags=re.UNICODE)
|
| 51 |
|
| 52 |
def tokenize(text: str) -> List[str]:
|
| 53 |
+
return _TOKEN_RE.findall(to_ascii(text).lower())
|
| 54 |
|
| 55 |
def is_punctuation_token(token: str) -> bool:
|
| 56 |
+
"""Checks if a token is a punctuation mark that typically follows a word without a space."""
|
| 57 |
+
# Added open parenthesis and quotation marks as tokens that may start a new space-separated unit
|
| 58 |
+
# Added common closing punctuation that should NOT have a preceding space
|
| 59 |
+
return token in [".", ",", "!", "?", ":", ";", ")", "]", "}", "'s", "'", "\""]
|
| 60 |
|
| 61 |
# ------------------------
|
| 62 |
# Vocabulary
|
| 63 |
# ------------------------
|
| 64 |
class Voc:
|
| 65 |
+
def __init__(self) -> None:
|
| 66 |
+
self.PAD, self.SOS, self.EOS, self.UNK, self.SYSTEM = "<PAD>", "<SOS>", "<EOS>", "<UNK>", "<SYSTEM>"
|
| 67 |
+
self.word2index = {self.PAD: 0, self.SOS: 1, self.EOS: 2, self.UNK: 3, self.SYSTEM: 4}
|
| 68 |
+
self.index2word = {i: w for w, i in self.word2index.items()}
|
| 69 |
+
self.n_words = len(self.word2index)
|
| 70 |
+
|
| 71 |
+
@staticmethod
|
| 72 |
+
def load_from_checkpoint(ckpt: Dict[str, Any]) -> "Voc":
|
| 73 |
+
voc = Voc()
|
| 74 |
+
if "voc_word2index" in ckpt:
|
| 75 |
+
voc.word2index = ckpt["voc_word2index"]
|
| 76 |
+
voc.index2word = ckpt["voc_index2word"]
|
| 77 |
+
voc.n_words = len(voc.word2index)
|
| 78 |
+
return voc
|
| 79 |
+
|
| 80 |
+
def add_word(self, word: str) -> None:
|
| 81 |
+
if word not in self.word2index:
|
| 82 |
+
self.word2index[word] = self.n_words
|
| 83 |
+
self.index2word[self.n_words] = word
|
| 84 |
+
self.n_words += 1
|
| 85 |
|
| 86 |
# ------------------------
|
| 87 |
# Model
|
| 88 |
# ------------------------
|
| 89 |
class PositionalEncoding(nn.Module):
|
| 90 |
+
def __init__(self, d_model: int, max_len: int = 5000):
|
| 91 |
+
super().__init__()
|
| 92 |
+
pe = torch.zeros(max_len, d_model)
|
| 93 |
+
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
|
| 94 |
+
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
|
| 95 |
+
pe[:, 0::2] = torch.sin(position * div_term)
|
| 96 |
+
pe[:, 1::2] = torch.cos(position * div_term)
|
| 97 |
+
self.register_buffer("pe", pe.unsqueeze(0))
|
| 98 |
+
|
| 99 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 100 |
+
return x + self.pe[:, : x.size(1), :]
|
| 101 |
|
| 102 |
class GPT(nn.Module):
|
| 103 |
+
def __init__(self, n_words, d_model, n_layers, n_head, d_ff, dropout=0.1):
|
| 104 |
+
super().__init__()
|
| 105 |
+
self.embedding = nn.Embedding(n_words, d_model)
|
| 106 |
+
self.pos = PositionalEncoding(d_model)
|
| 107 |
+
self.norm = nn.LayerNorm(d_model)
|
| 108 |
+
layer = nn.TransformerEncoderLayer(d_model, n_head, d_ff, dropout, batch_first=True)
|
| 109 |
+
self.transformer = nn.TransformerEncoder(layer, n_layers)
|
| 110 |
+
self.fc = nn.Linear(d_model, n_words, bias=False)
|
| 111 |
+
self.fc.weight = self.embedding.weight
|
| 112 |
+
|
| 113 |
+
def forward(self, x, mask=None, key_padding_mask=None):
|
| 114 |
+
x = self.embedding(x)
|
| 115 |
+
x = self.pos(x)
|
| 116 |
+
x = self.norm(x)
|
| 117 |
+
out = self.transformer(x, mask=mask, src_key_padding_mask=key_padding_mask)
|
| 118 |
+
return self.fc(out)
|
| 119 |
|
| 120 |
# ------------------------
|
| 121 |
# Device + Checkpoint + Resizing Fix
|
|
|
|
| 123 |
device = torch.device("cpu")
|
| 124 |
|
| 125 |
def resize_model_if_needed(model: nn.Module, new_n_words: int, d_model: int) -> bool:
|
| 126 |
+
"""
|
| 127 |
+
Checks if the model's vocabulary size needs to be updated and resizes the layers.
|
| 128 |
+
Returns True if resize occurred, False otherwise.
|
| 129 |
+
"""
|
| 130 |
+
if new_n_words > model.embedding.num_embeddings:
|
| 131 |
+
print(f"Resizing model from {model.embedding.num_embeddings} to {new_n_words} vocabulary size...")
|
| 132 |
+
|
| 133 |
+
# 1. Save old embedding and fc weights
|
| 134 |
+
old_embedding_weight = model.embedding.weight.data.clone()
|
| 135 |
+
|
| 136 |
+
# 2. Create new embedding layer
|
| 137 |
+
new_embedding = nn.Embedding(new_n_words, d_model)
|
| 138 |
+
new_embedding.to(model.embedding.weight.device) # ensure device consistency
|
| 139 |
+
|
| 140 |
+
# 3. Copy old weights to new layer
|
| 141 |
+
copy_len = min(new_n_words, old_embedding_weight.size(0))
|
| 142 |
+
new_embedding.weight.data[:copy_len] = old_embedding_weight[:copy_len]
|
| 143 |
+
|
| 144 |
+
# 4. Replace old layers
|
| 145 |
+
model.embedding = new_embedding
|
| 146 |
+
model.fc = nn.Linear(d_model, new_n_words, bias=False)
|
| 147 |
+
|
| 148 |
+
# 5. Re-tie weights
|
| 149 |
+
model.fc.weight = model.embedding.weight
|
| 150 |
+
|
| 151 |
+
return True
|
| 152 |
+
return False
|
| 153 |
|
| 154 |
def save_checkpoint(path: str, hp: Dict[str, Any], voc: "Voc", model: nn.Module, optimizer: optim.Optimizer, iteration: int = 0) -> None:
|
| 155 |
+
"""Saves the current model and vocabulary state."""
|
| 156 |
+
print(f"Saving checkpoint to {path} at iteration {iteration}...")
|
| 157 |
+
current_hp = {k: hp[k] for k in hp}
|
| 158 |
+
current_hp["n_words"] = voc.n_words
|
| 159 |
+
|
| 160 |
+
torch.save(
|
| 161 |
+
{
|
| 162 |
+
**current_hp,
|
| 163 |
+
"iteration": iteration,
|
| 164 |
+
"gpt_model_state_dict": model.state_dict(),
|
| 165 |
+
"optimizer_state_dict": optimizer.state_dict(),
|
| 166 |
+
"voc_word2index": voc.word2index,
|
| 167 |
+
"voc_index2word": voc.index2word,
|
| 168 |
+
"voc_n_words": voc.n_words, # Added for robustness
|
| 169 |
+
},
|
| 170 |
+
path,
|
| 171 |
+
)
|
| 172 |
|
| 173 |
def load_checkpoint_or_defaults(path: str):
|
| 174 |
+
global device
|
| 175 |
+
# Attempt to use MPS/CUDA if available
|
| 176 |
+
if torch.backends.mps.is_available():
|
| 177 |
+
device = torch.device("mps")
|
| 178 |
+
elif torch.cuda.is_available():
|
| 179 |
+
device = torch.device("cuda")
|
| 180 |
+
else:
|
| 181 |
+
device = torch.device("cpu")
|
| 182 |
+
print(f"Using device: {device}")
|
| 183 |
+
|
| 184 |
+
if os.path.exists(path):
|
| 185 |
+
ckpt = torch.load(path, map_location=device)
|
| 186 |
+
hp = {k: ckpt.get(k, v) for k, v in DEFAULTS.items()}
|
| 187 |
+
voc = Voc.load_from_checkpoint(ckpt)
|
| 188 |
+
|
| 189 |
+
n_words = ckpt.get("n_words", voc.n_words) # Use n_words from checkpoint if available
|
| 190 |
+
|
| 191 |
+
model = GPT(n_words, hp["d_model"], hp["n_layers"], hp["n_head"], hp["d_ff"], hp["dropout"]).to(device)
|
| 192 |
+
model.load_state_dict(ckpt["gpt_model_state_dict"], strict=False)
|
| 193 |
+
|
| 194 |
+
optimizer = optim.Adam(model.parameters(), lr=hp["LEARNING_RATE"])
|
| 195 |
+
if "optimizer_state_dict" in ckpt:
|
| 196 |
+
optimizer.load_state_dict(ckpt["optimizer_state_dict"])
|
| 197 |
+
|
| 198 |
+
return ckpt, hp, voc, model, optimizer
|
| 199 |
+
else:
|
| 200 |
+
voc = Voc()
|
| 201 |
+
model = GPT(voc.n_words, **{k: v for k, v in DEFAULTS.items() if k in ["d_model", "n_layers", "n_head", "d_ff", "dropout"]}).to(device)
|
| 202 |
+
optimizer = optim.Adam(model.parameters(), lr=DEFAULTS["LEARNING_RATE"])
|
| 203 |
+
return {}, DEFAULTS, voc, model, optimizer
|
| 204 |
|
| 205 |
checkpoint, HP, voc, gpt_model, optimizer = load_checkpoint_or_defaults(CHECKPOINT_PATH)
|
| 206 |
start_iteration = checkpoint.get("iteration", 0)
|
|
|
|
| 209 |
# Text utilities
|
| 210 |
# ------------------------
|
| 211 |
def indexes_from_sentence(voc: Voc, sentence: str) -> List[int]:
|
| 212 |
+
tokens = [voc.SYSTEM] + tokenize(sentence)
|
| 213 |
+
return [voc.word2index.get(tok, voc.word2index[voc.UNK]) for tok in tokens]
|
| 214 |
|
| 215 |
def make_bool_causal_mask(sz: int, device: torch.device):
|
| 216 |
+
# Causal mask (upper triangle is True/ignored)
|
| 217 |
+
return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)
|
| 218 |
|
| 219 |
# ------------------------
|
| 220 |
# Training Function (Manual Feedback Training)
|
| 221 |
# ------------------------
|
| 222 |
def train_model(
|
| 223 |
+
full_prompt_text: str, desired_response_text: str, voc: "Voc", model: nn.Module, optimizer: optim.Optimizer
|
| 224 |
) -> Tuple[float, int]:
|
| 225 |
+
"""Trains the model to produce the desired response given the full context prompt."""
|
| 226 |
+
global start_iteration, checkpoint, HP
|
| 227 |
+
|
| 228 |
+
if not full_prompt_text or not desired_response_text:
|
| 229 |
+
# NOTE: This should only be called when desired_response_text is provided by the GUI
|
| 230 |
+
return 0.0, start_iteration
|
| 231 |
+
|
| 232 |
+
old_n_words = voc.n_words
|
| 233 |
+
|
| 234 |
+
# 1. Update Voc
|
| 235 |
+
for word in tokenize(full_prompt_text):
|
| 236 |
+
voc.add_word(word)
|
| 237 |
+
for word in tokenize(desired_response_text): # Also add words from the target
|
| 238 |
+
voc.add_word(word)
|
| 239 |
+
|
| 240 |
+
# FIX: Resize model if vocabulary grew
|
| 241 |
+
if voc.n_words > old_n_words:
|
| 242 |
+
resize_model_if_needed(model, voc.n_words, HP["d_model"])
|
| 243 |
+
|
| 244 |
+
# 2. Prepare Data: Input is Full Prompt, Target is Desired Response
|
| 245 |
+
input_ids = indexes_from_sentence(voc, full_prompt_text)
|
| 246 |
+
target_ids = indexes_from_sentence(voc, desired_response_text)
|
| 247 |
+
# Target sequence starts after the SYSTEM token
|
| 248 |
+
target_ids = target_ids[1:] + [voc.word2index[voc.EOS]]
|
| 249 |
+
|
| 250 |
+
combined_ids = input_ids + target_ids
|
| 251 |
+
|
| 252 |
+
prompt_len = len(input_ids)
|
| 253 |
+
sequence_len = len(combined_ids)
|
| 254 |
+
|
| 255 |
+
if sequence_len > HP["max_length"]:
|
| 256 |
+
combined_ids = combined_ids[:HP["max_length"]]
|
| 257 |
+
sequence_len = HP["max_length"]
|
| 258 |
+
prompt_len = min(prompt_len, HP["max_length"] - 1)
|
| 259 |
+
|
| 260 |
+
# --- FIX APPLIED PREVIOUSLY: Ensure input_tensor is [1, L] (2D tensor of indices) ---
|
| 261 |
+
input_tensor = torch.tensor([combined_ids[:-1]], dtype=torch.long, device=device)
|
| 262 |
+
target_tensor = torch.tensor([combined_ids[1:]], dtype=torch.long, device=device)
|
| 263 |
+
# -----------------------------------------------------------------------------------
|
| 264 |
+
|
| 265 |
+
# 3. Forward Pass
|
| 266 |
+
model.train()
|
| 267 |
+
optimizer.zero_grad()
|
| 268 |
+
|
| 269 |
+
L = input_tensor.size(1)
|
| 270 |
+
mask = make_bool_causal_mask(L, device)
|
| 271 |
+
padmask = (input_tensor == voc.word2index[voc.PAD])
|
| 272 |
+
logits = model(input_tensor, mask=mask, key_padding_mask=padmask)
|
| 273 |
+
|
| 274 |
+
# Loss calculation: We only calculate loss on the target tokens (Desired Response)
|
| 275 |
+
# Loss mask needs to be the same size as the flattened logits/targets
|
| 276 |
+
loss_mask = torch.zeros(target_tensor.size(1), dtype=torch.float, device=device)
|
| 277 |
+
# Start the loss calculation from the first target token (index prompt_len - 1)
|
| 278 |
+
loss_mask[prompt_len - 1:] = 1.0
|
| 279 |
+
loss_mask_flat = loss_mask.view(-1)
|
| 280 |
+
|
| 281 |
+
# Calculate Cross Entropy Loss
|
| 282 |
+
loss = F.cross_entropy(
|
| 283 |
+
logits.view(-1, voc.n_words),
|
| 284 |
+
target_tensor.view(-1),
|
| 285 |
+
ignore_index=voc.word2index[voc.PAD],
|
| 286 |
+
reduction='none'
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
# Apply mask and re-reduce (average loss over target tokens only)
|
| 290 |
+
sum_mask = loss_mask_flat.sum()
|
| 291 |
+
if sum_mask > 0:
|
| 292 |
+
loss = (loss * loss_mask_flat).sum() / sum_mask
|
| 293 |
+
else:
|
| 294 |
+
# If the sequence was truncated and contains only the prompt, loss is zero
|
| 295 |
+
loss = torch.tensor(0.0, device=device)
|
| 296 |
+
|
| 297 |
+
# 4. Backward Pass & Optimization
|
| 298 |
+
loss.backward()
|
| 299 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 300 |
+
optimizer.step()
|
| 301 |
+
start_iteration += 1
|
| 302 |
+
|
| 303 |
+
# 5. Save Checkpoint
|
| 304 |
+
save_checkpoint(CHECKPOINT_PATH, HP, voc, model, optimizer, start_iteration)
|
| 305 |
+
|
| 306 |
+
return loss.item(), start_iteration
|
|
|
|
| 307 |
|
| 308 |
# ------------------------
|
| 309 |
# DuckDuckGo Web Search (Unchanged)
|
| 310 |
# ------------------------
|
| 311 |
def perform_web_search(query: str) -> str:
|
| 312 |
+
"""Fetch text from DuckDuckGo instant answers."""
|
| 313 |
+
query = to_ascii(query.strip())
|
| 314 |
+
if not query:
|
| 315 |
+
return ""
|
| 316 |
+
try:
|
| 317 |
+
resp = requests.get(
|
| 318 |
+
"https://api.duckduckgo.com/",
|
| 319 |
+
params={"q": query, "format": "json", "no_html": 1, "skip_disambig": 1},
|
| 320 |
+
timeout=6,
|
| 321 |
+
)
|
| 322 |
+
resp.raise_for_status()
|
| 323 |
+
data = resp.json()
|
| 324 |
+
if data.get("AbstractText"):
|
| 325 |
+
return to_ascii(data["AbstractText"])
|
| 326 |
+
elif data.get("RelatedTopics"):
|
| 327 |
+
texts = [t["Text"] for t in data["RelatedTopics"] if isinstance(t, dict) and "Text" in t]
|
| 328 |
+
return to_ascii(" ".join(texts[:5]))
|
| 329 |
+
except Exception as e:
|
| 330 |
+
print("Search failed:", e)
|
| 331 |
+
return ""
|
| 332 |
|
| 333 |
# ------------------------
|
| 334 |
# Web Content Preparation (Max Retention)
|
| 335 |
# ------------------------
|
| 336 |
def prepare_web_content(text: str) -> str:
|
| 337 |
+
"""
|
| 338 |
+
Prepare raw web text by truncating it to a maximal safe length
|
| 339 |
+
(500 characters) to ensure maximum retention while avoiding context overflow.
|
| 340 |
+
"""
|
| 341 |
+
MAX_WEB_CONTENT_LENGTH = 500
|
| 342 |
+
if not text.strip():
|
| 343 |
+
return ""
|
| 344 |
+
|
| 345 |
+
prepared_text = to_ascii(text.strip())
|
| 346 |
+
if len(prepared_text) > MAX_WEB_CONTENT_LENGTH:
|
| 347 |
+
prepared_text = prepared_text[:MAX_WEB_CONTENT_LENGTH] + "..."
|
| 348 |
+
|
| 349 |
+
return prepared_text
|
| 350 |
|
| 351 |
# ------------------------
|
| 352 |
# Streaming Generator (STABLE SAMPLER) - REVISED FOR READABILITY
|
| 353 |
# ------------------------
|
| 354 |
def generate_response(prompt: str) -> Iterator[str]:
|
| 355 |
+
"""Token-by-token streaming response generator with improved punctuation handling."""
|
| 356 |
+
gpt_model.eval()
|
| 357 |
+
|
| 358 |
+
# NOTE: The full prompt string is passed, and indexing prepends the SYSTEM token
|
| 359 |
+
input_ids = indexes_from_sentence(voc, prompt)
|
| 360 |
+
|
| 361 |
+
# --- FIX APPLIED PREVIOUSLY: Ensure input_tensor is [1, L] (2D tensor of indices) ---
|
| 362 |
+
input_tensor = torch.tensor([input_ids], dtype=torch.long, device=device)
|
| 363 |
+
# -----------------------------------------------------------------------------------
|
| 364 |
+
|
| 365 |
+
# --- Inference Parameters ---
|
| 366 |
+
temperature = 0.8
|
| 367 |
+
top_k = HP.get("k_sampling", 200)
|
| 368 |
+
# ----------------------------
|
| 369 |
+
|
| 370 |
+
eos_id = voc.word2index[voc.EOS]
|
| 371 |
+
|
| 372 |
+
# Get the index for "olm" tokens for strong penalty (still helpful)
|
| 373 |
+
# Filter for tokens actually in the current vocabulary
|
| 374 |
+
olm_tokens = [voc.word2index.get(t, -1) for t in ['o', 'l', 'm', 'olm'] if t in voc.word2index]
|
| 375 |
+
olm_tokens = [t_id for t_id in olm_tokens if t_id != -1]
|
| 376 |
+
|
| 377 |
+
# Buffer to hold the last yielded token (for conditional spacing)
|
| 378 |
+
last_yielded_token = ""
|
| 379 |
+
|
| 380 |
+
with torch.no_grad():
|
| 381 |
+
for _ in range(HP["max_length"]):
|
| 382 |
+
L = input_tensor.size(1)
|
| 383 |
+
mask = make_bool_causal_mask(L, device)
|
| 384 |
+
padmask = (input_tensor == voc.word2index[voc.PAD])
|
| 385 |
+
|
| 386 |
+
logits = gpt_model(input_tensor, mask=mask, key_padding_mask=padmask)
|
| 387 |
+
|
| 388 |
+
# Extract last logits and enforce 1D shape
|
| 389 |
+
logits = logits[:, -1, :].squeeze(0) / temperature # Shape: [N_vocab]
|
| 390 |
+
|
| 391 |
+
# --- STABILIZED PENALTIES (operates on 1D logits) ---
|
| 392 |
+
# Strong penalty against spamming OLM name
|
| 393 |
+
for t_id in olm_tokens:
|
| 394 |
+
if t_id < logits.size(-1):
|
| 395 |
+
logits[t_id] = -float('inf')
|
| 396 |
+
|
| 397 |
+
# Top-K Sampling
|
| 398 |
+
if top_k > 0:
|
| 399 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
| 400 |
+
logits[logits < v[-1]] = -float('inf')
|
| 401 |
+
# ----------------------
|
| 402 |
+
|
| 403 |
+
# Softmax on the penalized logits
|
| 404 |
+
probs = F.softmax(logits, dim=-1).unsqueeze(0) # Unsqueeze to add batch dim for multinomial
|
| 405 |
+
|
| 406 |
+
# Runtime safety checks
|
| 407 |
+
if probs.size(-1) < gpt_model.embedding.num_embeddings:
|
| 408 |
+
probs = probs[..., :gpt_model.embedding.num_embeddings]
|
| 409 |
+
|
| 410 |
+
next_id = torch.multinomial(probs, 1).item()
|
| 411 |
+
|
| 412 |
+
if next_id == eos_id:
|
| 413 |
+
break
|
| 414 |
+
|
| 415 |
+
if next_id >= gpt_model.embedding.num_embeddings:
|
| 416 |
+
print(f"TERMINATING: Generated token ID {next_id} is out of bounds for current embeddings.")
|
| 417 |
+
break
|
| 418 |
+
|
| 419 |
+
next_token_word = voc.index2word.get(next_id, voc.UNK)
|
| 420 |
+
|
| 421 |
+
if next_token_word not in [voc.PAD, voc.SOS, voc.EOS, voc.UNK, voc.SYSTEM]:
|
| 422 |
+
|
| 423 |
+
# Logic: Add space if (it's not the first token) AND
|
| 424 |
+
# (the previous token wasn't punctuation) AND
|
| 425 |
+
# (the current token isn't punctuation or an opening bracket/quote)
|
| 426 |
+
|
| 427 |
+
should_add_space = (
|
| 428 |
+
last_yielded_token and
|
| 429 |
+
not is_punctuation_token(last_yielded_token) and
|
| 430 |
+
not is_punctuation_token(next_token_word) and
|
| 431 |
+
next_token_word not in ["(", "[", "{", "\""]
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
if should_add_space:
|
| 435 |
+
yield " "
|
| 436 |
+
|
| 437 |
+
# Yield the word/token
|
| 438 |
+
yield next_token_word
|
| 439 |
+
last_yielded_token = next_token_word # Update the buffer
|
| 440 |
+
|
| 441 |
+
next_token = torch.tensor([[next_id]], device=device)
|
| 442 |
+
input_tensor = torch.cat([input_tensor, next_token], dim=1)
|
|
|
|
|
|
|
| 443 |
|
| 444 |
|
| 445 |
# ------------------------
|
| 446 |
# Core Chat Handler (REGULAR INFERENCE ONLY)
|
| 447 |
# ------------------------
|
| 448 |
def on_submit(user_message: str, history: Optional[List[List[str]]], train_input_state: Dict[str, str], *_):
|
| 449 |
+
"""
|
| 450 |
+
Token-by-token chat handler. Performs regular inference.
|
| 451 |
+
"""
|
| 452 |
+
history = history or []
|
| 453 |
+
# Strip image/attachment tags
|
| 454 |
+
user_message = re.sub(r'\(Attached:.*?\)|\[IMAGE_PREVIEW_URL:.*?]', '', user_message or "").strip()
|
| 455 |
+
|
| 456 |
+
current_state = train_input_state.copy()
|
| 457 |
+
|
| 458 |
+
search_summary = ""
|
| 459 |
+
is_search = WEB_TAG_RE.search(user_message)
|
| 460 |
+
if is_search:
|
| 461 |
+
query = WEB_TAG_RE.sub("", user_message).strip()
|
| 462 |
+
raw = perform_web_search(query)
|
| 463 |
+
search_summary = prepare_web_content(raw)
|
| 464 |
+
|
| 465 |
+
# Prepare the FULL PROMPT for generation
|
| 466 |
+
prefix = f"The provided web context is: {search_summary}. " if search_summary else ""
|
| 467 |
+
full_prompt = f"{SYSTEM_INSTRUCTION} {prefix}{user_message}"
|
| 468 |
+
|
| 469 |
+
# Store state data for the training interface and next turns
|
| 470 |
+
current_state["full_prompt"] = full_prompt
|
| 471 |
+
current_state["user_message"] = user_message
|
| 472 |
+
current_state["search_summary"] = search_summary
|
| 473 |
+
current_state["last_model_response"] = "" # Will be filled by stream
|
| 474 |
+
|
| 475 |
+
response_stream = generate_response(full_prompt)
|
| 476 |
+
partial_reply = ""
|
| 477 |
+
|
| 478 |
+
# Status bar shows search status
|
| 479 |
+
search_status = "π Web search active." if search_summary else "No web info used."
|
| 480 |
+
|
| 481 |
+
if not history or (history and history[-1][1] is not None):
|
| 482 |
+
history.append([user_message, None])
|
| 483 |
+
|
| 484 |
+
for token in response_stream:
|
| 485 |
+
partial_reply += token
|
| 486 |
+
history[-1][1] = partial_reply
|
| 487 |
+
yield history, search_status, current_state
|
| 488 |
+
|
| 489 |
+
final_reply = partial_reply.strip()
|
| 490 |
+
if history:
|
| 491 |
+
history[-1][1] = final_reply
|
| 492 |
+
|
| 493 |
+
current_state["last_model_response"] = final_reply
|
| 494 |
+
|
| 495 |
+
# Final yield
|
| 496 |
+
yield history, "Response complete.", current_state
|
| 497 |
|
| 498 |
# ------------------------
|
| 499 |
# API Endpoint for Feedback Training
|
| 500 |
# ------------------------
|
| 501 |
def feedback_train(history: List[List[str]], desired_response: str) -> str:
|
| 502 |
+
"""
|
| 503 |
+
Endpoint for training the model based on explicit bad feedback and a desired response.
|
| 504 |
+
This function is used by the Manual Training panel and is called by the JS Bad Feedback button.
|
| 505 |
+
"""
|
| 506 |
+
global start_iteration
|
| 507 |
+
|
| 508 |
+
if not desired_response.strip():
|
| 509 |
+
# NOTE: This only logs a status if the desired response is empty.
|
| 510 |
+
# The JS client should handle simple logging if needed.
|
| 511 |
+
return "Warning: Training skipped. Provide a desired response to train."
|
| 512 |
+
|
| 513 |
+
if not history or not history[-1][0]:
|
| 514 |
+
return "Error: Chat history is empty or missing user prompt. Cannot train."
|
| 515 |
+
|
| 516 |
+
# Retrieve the full context from the last state, if available, otherwise reconstruct the simplest form
|
| 517 |
+
last_user_prompt_raw = history[-1][0]
|
| 518 |
+
# Reconstruct the full input prompt in the safest way possible for training
|
| 519 |
+
full_training_input = f"{SYSTEM_INSTRUCTION} {last_user_prompt_raw}"
|
| 520 |
+
|
| 521 |
+
try:
|
| 522 |
+
loss_value, new_iteration = train_model(full_training_input, desired_response, voc, gpt_model, optimizer)
|
| 523 |
+
return f"β
Training Complete! Iteration: {new_iteration}, Loss: {loss_value:.4f}. Model updated."
|
| 524 |
+
except Exception as e:
|
| 525 |
+
return f"β Training Failed: {e}. Check server logs."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 526 |
|
| 527 |
# ------------------------
|
| 528 |
# Gradio Interface
|
| 529 |
# ------------------------
|
| 530 |
with gr.Blocks(title="OkemoLLM") as demo:
|
| 531 |
+
gr.Markdown("# π OkemoLLM β Streaming DuckDuckGo + Stable Inference")
|
| 532 |
+
|
| 533 |
+
# Status bar
|
| 534 |
+
status = gr.Markdown(f"Ready. **Current Checkpoint Iteration: {start_iteration}**. (Training is manual.)")
|
| 535 |
+
chat = gr.Chatbot(height=400)
|
| 536 |
+
|
| 537 |
+
train_state = gr.State(TRAIN_INPUT_STATE)
|
| 538 |
+
|
| 539 |
+
with gr.Row():
|
| 540 |
+
msg = gr.Textbox(placeholder='Type your message (add <web> for search).', label="Message", scale=4)
|
| 541 |
+
clear = gr.Button("Clear", scale=1)
|
| 542 |
+
|
| 543 |
+
gr.Markdown("---")
|
| 544 |
+
gr.Markdown("## βοΈ Manual Feedback Training")
|
| 545 |
+
gr.Markdown("Use this section to train the model with a **correct answer** after a poor response. The Bad Feedback button in the chat also triggers this function.")
|
| 546 |
+
|
| 547 |
+
with gr.Column():
|
| 548 |
+
# Defining the train_status component here
|
| 549 |
+
train_status = gr.Markdown("Status will update after clicking 'Train'.")
|
| 550 |
+
|
| 551 |
+
# This displays the last user input
|
| 552 |
+
prompt_display = gr.Textbox(label="Last User Message (Input for Training)", interactive=False)
|
| 553 |
+
last_response_display = gr.Textbox(label="Model's Last Response", interactive=False)
|
| 554 |
+
|
| 555 |
+
# User provides the ground truth here
|
| 556 |
+
manual_target_response = gr.Textbox(label="Desired Response (Ground Truth for Training)", placeholder='Enter the correct/better response for the prompt above.')
|
| 557 |
+
|
| 558 |
+
train_button = gr.Button("Perform Manual Feedback Training")
|
| 559 |
+
|
| 560 |
+
# Connect Chat Handlers (Inference only)
|
| 561 |
+
msg.submit(
|
| 562 |
+
on_submit,
|
| 563 |
+
[msg, chat, train_state],
|
| 564 |
+
[chat, status, train_state]
|
| 565 |
+
).then(
|
| 566 |
+
# Update context displays after submission
|
| 567 |
+
lambda s: (s.get("user_message", "No message."), s.get("last_model_response", "")),
|
| 568 |
+
train_state,
|
| 569 |
+
[prompt_display, last_response_display]
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
clear.click(lambda: ([], f"Cleared. Current Checkpoint Iteration: {start_iteration}."), None, [chat, status], queue=False)
|
| 573 |
+
|
| 574 |
+
# Connect the Manual Training Button (This implicitly registers the /feedback_train endpoint)
|
| 575 |
+
train_button.click(
|
| 576 |
+
feedback_train,
|
| 577 |
+
[chat, manual_target_response], # chat component passes the history
|
| 578 |
+
train_status
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
# --- Removing the simple logging endpoint and relying on 'feedback_train' ---
|
| 582 |
+
# The JS will send an empty string to /feedback_train, which the Python function handles by skipping training.
|
| 583 |
|
| 584 |
|
| 585 |
if __name__ == "__main__":
|
| 586 |
+
demo.queue(api_open=True).launch(ssr_mode=False)
|