ar12c commited on
Commit
ca72be1
Β·
verified Β·
1 Parent(s): 2a7616d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +472 -479
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
- Β  Β  "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,77 +45,77 @@ TRAIN_INPUT_STATE = {} # Initial value for the Gradio State
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,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
- Β  Β  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,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
- Β  Β  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 HERE: Removed redundant .unsqueeze(0) ---
261
- Β  Β  # Shape: [1, Sequence_Length]. Embedding will make it [1, L, D] (3D)
262
- Β  Β  input_tensor = torch.tensor([combined_ids[:-1]], dtype=torch.long, device=device)
263
- Β  Β  target_tensor = torch.tensor([combined_ids[1:]], dtype=torch.long, device=device)
264
- Β  Β  # -----------------------------------------------------------
265
-
266
- Β  Β  # 3. Forward Pass
267
- Β  Β  model.train()
268
- Β  Β  optimizer.zero_grad()
269
- Β  Β Β 
270
- Β  Β  L = input_tensor.size(1)
271
- Β  Β  mask = make_bool_causal_mask(L, device)
272
- Β  Β  padmask = (input_tensor == voc.word2index[voc.PAD])
273
- Β  Β  logits = model(input_tensor, mask=mask, key_padding_mask=padmask)
274
-
275
- Β  Β  # Loss calculation: We only calculate loss on the target tokens (Desired Response)
276
- Β  Β  # Loss mask needs to be the same size as the flattened logits/targets
277
- Β  Β  loss_mask = torch.zeros(target_tensor.size(1), dtype=torch.float, device=device)
278
- Β  Β  # Start the loss calculation from the first target token (index prompt_len - 1)
279
- Β  Β  loss_mask[prompt_len - 1:] = 1.0Β 
280
- Β  Β  loss_mask_flat = loss_mask.view(-1)
281
- Β  Β Β 
282
- Β  Β  # Calculate Cross Entropy Loss
283
- Β  Β  loss = F.cross_entropy(
284
- Β  Β  Β  Β  logits.view(-1, voc.n_words),
285
- Β  Β  Β  Β  target_tensor.view(-1),
286
- Β  Β  Β  Β  ignore_index=voc.word2index[voc.PAD],
287
- Β  Β  Β  Β  reduction='none'
288
- Β  Β  )
289
- Β  Β Β 
290
- Β  Β  # Apply mask and re-reduce (average loss over target tokens only)
291
- Β  Β  sum_mask = loss_mask_flat.sum()
292
- Β  Β  if sum_mask > 0:
293
- Β  Β  Β  Β  loss = (loss * loss_mask_flat).sum() / sum_mask
294
- Β  Β  else:
295
- Β  Β  Β  Β  # If the sequence was truncated and contains only the prompt, loss is zero
296
- Β  Β  Β  Β  loss = torch.tensor(0.0, device=device)
297
-
298
- Β  Β  # 4. Backward Pass & Optimization
299
- Β  Β  loss.backward()
300
- Β  Β  torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)Β 
301
- Β  Β  optimizer.step()
302
- Β  Β  start_iteration += 1
303
-
304
- Β  Β  # 5. Save Checkpoint
305
- Β  Β  save_checkpoint(CHECKPOINT_PATH, HP, voc, model, optimizer, start_iteration)
306
-
307
- Β  Β  return loss.item(), start_iteration
308
 
309
  # ------------------------
310
  # DuckDuckGo Web Search (Unchanged)
311
  # ------------------------
312
  def perform_web_search(query: str) -> str:
313
- Β  Β  """Fetch text from DuckDuckGo instant answers."""
314
- Β  Β  query = to_ascii(query.strip())
315
- Β  Β  if not query:
316
- Β  Β  Β  Β  return ""
317
- Β  Β  try:
318
- Β  Β  Β  Β  resp = requests.get(
319
- Β  Β  Β  Β  Β  Β  "https://api.duckduckgo.com/",
320
- Β  Β  Β  Β  Β  Β  params={"q": query, "format": "json", "no_html": 1, "skip_disambig": 1},
321
- Β  Β  Β  Β  Β  Β  timeout=6,
322
- Β  Β  Β  Β  )
323
- Β  Β  Β  Β  resp.raise_for_status()
324
- Β  Β  Β  Β  data = resp.json()
325
- Β  Β  Β  Β  if data.get("AbstractText"):
326
- Β  Β  Β  Β  Β  Β  return to_ascii(data["AbstractText"])
327
- Β  Β  Β  Β  elif data.get("RelatedTopics"):
328
- Β  Β  Β  Β  Β  Β  texts = [t["Text"] for t in data["RelatedTopics"] if isinstance(t, dict) and "Text" in t]
329
- Β  Β  Β  Β  Β  Β  return to_ascii(" ".join(texts[:5]))
330
- Β  Β  except Exception as e:
331
- Β  Β  Β  Β  print("Search failed:", e)
332
- Β  Β  return ""
333
 
334
  # ------------------------
335
  # Web Content Preparation (Max Retention)
336
  # ------------------------
337
  def prepare_web_content(text: str) -> str:
338
- Β  Β  """
339
- Β  Β  Prepare raw web text by truncating it to a maximal safe lengthΒ 
340
- Β  Β  (500 characters) to ensure maximum retention while avoiding context overflow.
341
- Β  Β  """
342
- Β  Β  MAX_WEB_CONTENT_LENGTH = 500
343
- Β  Β  if not text.strip():
344
- Β  Β  Β  Β  return ""
345
- Β  Β Β 
346
- Β  Β  prepared_text = to_ascii(text.strip())
347
- Β  Β  if len(prepared_text) > MAX_WEB_CONTENT_LENGTH:
348
- Β  Β  Β  Β  prepared_text = prepared_text[:MAX_WEB_CONTENT_LENGTH] + "..."
349
- Β  Β Β 
350
- Β  Β  return prepared_text
351
 
352
  # ------------------------
353
  # Streaming Generator (STABLE SAMPLER) - REVISED FOR READABILITY
354
  # ------------------------
355
  def generate_response(prompt: str) -> Iterator[str]:
356
- Β  Β  """Token-by-token streaming response generator with improved punctuation handling."""
357
- Β  Β  gpt_model.eval()
358
- Β  Β Β 
359
- Β  Β  # NOTE: The full prompt string is passed, and indexing prepends the SYSTEM token
360
- Β  Β  input_ids = indexes_from_sentence(voc, prompt)
361
- Β  Β Β 
362
- Β  Β  # --- FIX APPLIED HERE: Ensure input_tensor is [1, L] (2D tensor of indices) ---
363
- Β  Β  # The previous code was: torch.tensor(input_ids, dtype=torch.long, device=device).unsqueeze(0)
364
- Β  Β  # This is generally correct, but using the list-of-list convention is safer:
365
- Β  Β  input_tensor = torch.tensor([input_ids], dtype=torch.long, device=device)
366
- Β  Β  # ----------------------------------------------------------------------------
367
- Β  Β Β 
368
- Β  Β  # --- Inference Parameters ---
369
- Β  Β  temperature = 0.8
370
- Β  Β  top_k = HP.get("k_sampling", 200)Β 
371
- Β  Β  # ----------------------------
372
- Β  Β Β 
373
- Β  Β  eos_id = voc.word2index[voc.EOS]
374
- Β  Β Β 
375
- Β  Β  # Get the index for "olm" tokens for strong penalty (still helpful)
376
- Β  Β  # Filter for tokens actually in the current vocabulary
377
- Β  Β  olm_tokens = [voc.word2index.get(t, -1) for t in ['o', 'l', 'm', 'olm'] if t in voc.word2index]
378
- Β  Β  olm_tokens = [t_id for t_id in olm_tokens if t_id != -1]
379
- Β  Β Β 
380
- Β  Β  # Buffer to hold the last yielded token (for conditional spacing)
381
- Β  Β  last_yielded_token = ""Β 
382
-
383
- Β  Β  with torch.no_grad():
384
- Β  Β  Β  Β  for _ in range(HP["max_length"]):
385
- Β  Β  Β  Β  Β  Β  L = input_tensor.size(1)
386
- Β  Β  Β  Β  Β  Β  mask = make_bool_causal_mask(L, device)
387
- Β  Β  Β  Β  Β  Β  padmask = (input_tensor == voc.word2index[voc.PAD])
388
- Β  Β  Β  Β  Β  Β Β 
389
- Β  Β  Β  Β  Β  Β  logits = gpt_model(input_tensor, mask=mask, key_padding_mask=padmask)
390
- Β  Β  Β  Β  Β  Β Β 
391
- Β  Β  Β  Β  Β  Β  # Extract last logits and enforce 1D shapeΒ 
392
- Β  Β  Β  Β  Β  Β  logits = logits[:, -1, :].squeeze(0) / temperature # Shape: [N_vocab]
393
- Β  Β  Β  Β  Β  Β Β 
394
- Β  Β  Β  Β  Β  Β  # --- STABILIZED PENALTIES (operates on 1D logits) ---
395
- Β  Β  Β  Β  Β  Β  # Strong penalty against spamming OLM name
396
- Β  Β  Β  Β  Β  Β  for t_id in olm_tokens:
397
- Β  Β  Β  Β  Β  Β  Β  Β  if t_id < logits.size(-1):
398
- Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  logits[t_id] = -float('inf')Β 
399
-
400
- Β  Β  Β  Β  Β  Β  # Top-K Sampling
401
- Β  Β  Β  Β  Β  Β  if top_k > 0:
402
- Β  Β  Β  Β  Β  Β  Β  Β  v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
403
- Β  Β  Β  Β  Β  Β  Β  Β  logits[logits < v[-1]] = -float('inf')
404
- Β  Β  Β  Β  Β  Β  # ----------------------
405
-
406
- Β  Β  Β  Β  Β  Β  # Softmax on the penalized logits
407
- Β  Β  Β  Β  Β  Β  probs = F.softmax(logits, dim=-1).unsqueeze(0) # Unsqueeze to add batch dim for multinomial
408
- Β  Β  Β  Β  Β  Β Β 
409
- Β  Β  Β  Β  Β  Β  # Runtime safety checks
410
- Β  Β  Β  Β  Β  Β  if probs.size(-1) < gpt_model.embedding.num_embeddings:
411
- Β  Β  Β  Β  Β  Β  Β  Β  probs = probs[..., :gpt_model.embedding.num_embeddings]
412
- Β  Β  Β  Β  Β  Β  Β  Β Β 
413
- Β  Β  Β  Β  Β  Β  next_id = torch.multinomial(probs, 1).item()
414
- Β  Β  Β  Β  Β  Β Β 
415
- Β  Β  Β  Β  Β  Β  if next_id == eos_id:
416
- Β  Β  Β  Β  Β  Β  Β  Β  break
417
- Β  Β  Β  Β  Β  Β  Β  Β Β 
418
- Β  Β  Β  Β  Β  Β  if next_id >= gpt_model.embedding.num_embeddings:
419
- Β  Β  Β  Β  Β  Β  Β  Β  print(f"TERMINATING: Generated token ID {next_id} is out of bounds for current embeddings.")
420
- Β  Β  Β  Β  Β  Β  Β  Β  break
421
- Β  Β  Β  Β  Β  Β  Β  Β Β 
422
- Β  Β  Β  Β  Β  Β  next_token_word = voc.index2word.get(next_id, voc.UNK)
423
- Β  Β  Β  Β  Β  Β Β 
424
- Β  Β  Β  Β  Β  Β  if next_token_word not in [voc.PAD, voc.SOS, voc.EOS, voc.UNK, voc.SYSTEM]:
425
- Β  Β  Β  Β  Β  Β  Β  Β Β 
426
- Β  Β  Β  Β  Β  Β  Β  Β  # Logic: Add space if (it's not the first token) ANDΒ 
427
- Β  Β  Β  Β  Β  Β  Β  Β  # (the previous token wasn't punctuation) ANDΒ 
428
- Β  Β  Β  Β  Β  Β  Β  Β  # (the current token isn't punctuation or an opening bracket/quote)
429
- Β  Β  Β  Β  Β  Β  Β  Β Β 
430
- Β  Β  Β  Β  Β  Β  Β  Β  should_add_space = (
431
- Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  last_yielded_token andΒ 
432
- Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  not is_punctuation_token(last_yielded_token) andΒ 
433
- Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  not is_punctuation_token(next_token_word) andΒ 
434
- Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  next_token_word not in ["(", "[", "{", "\""]
435
- Β  Β  Β  Β  Β  Β  Β  Β  )
436
- Β  Β  Β  Β  Β  Β  Β  Β Β 
437
- Β  Β  Β  Β  Β  Β  Β  Β  if should_add_space:
438
- Β  Β  Β  Β  Β  Β  Β  Β  Β  Β  Β yield " "
439
-
440
- Β  Β  Β  Β  Β  Β  Β  Β  # Yield the word/token
441
- Β  Β  Β  Β  Β  Β  Β  Β  yield next_token_word
442
- Β  Β  Β  Β  Β  Β  Β  Β  last_yielded_token = next_token_word # Update the buffer
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
- Β  Β  Token-by-token chat handler. Performs regular inference.
454
- Β  Β  """
455
- Β  Β  history = history or []
456
- Β  Β  # Strip image/attachment tags
457
- Β  Β  user_message = re.sub(r'\(Attached:.*?\)|\[IMAGE_PREVIEW_URL:.*?]', '', user_message or "").strip()
458
- Β  Β Β 
459
- Β  Β  current_state = train_input_state.copy()
460
- Β  Β Β 
461
- Β  Β  search_summary = ""
462
- Β  Β  is_search = WEB_TAG_RE.search(user_message)
463
- Β  Β  if is_search:
464
- Β  Β  Β  Β  query = WEB_TAG_RE.sub("", user_message).strip()
465
- Β  Β  Β  Β  raw = perform_web_search(query)
466
- Β  Β  Β  Β  search_summary = prepare_web_content(raw)
467
-
468
- Β  Β  # Prepare the FULL PROMPT for generation
469
- Β  Β  prefix = f"The provided web context is: {search_summary}. " if search_summary else ""
470
- Β  Β  full_prompt = f"{SYSTEM_INSTRUCTION} {prefix}{user_message}"
471
-
472
- Β  Β  # Store state data for the training interface and next turns
473
- Β  Β  current_state["full_prompt"] = full_prompt
474
- Β  Β  current_state["user_message"] = user_message
475
- Β  Β  current_state["search_summary"] = search_summary
476
- Β  Β  current_state["last_model_response"] = "" # Will be filled by stream
477
-
478
- Β  Β  response_stream = generate_response(full_prompt)
479
- Β  Β  partial_reply = ""
480
- Β  Β Β 
481
- Β  Β  # Status bar shows search status
482
- Β  Β  search_status = "πŸ” Web search active." if search_summary else "No web info used."
483
-
484
- Β  Β  if not history or (history and history[-1][1] is not None):
485
- Β  Β  Β  Β  history.append([user_message, None])
486
-
487
- Β  Β  for token in response_stream:
488
- Β  Β  Β  Β  partial_reply += token
489
- Β  Β  Β  Β  history[-1][1] = partial_reply
490
- Β  Β  Β  Β  yield history, search_status, current_state
491
-
492
- Β  Β  final_reply = partial_reply.strip()
493
- Β  Β  if history:
494
- Β  Β  Β  Β  history[-1][1] = final_reply
495
-
496
- Β  Β  current_state["last_model_response"] = final_reply
497
-
498
- Β  Β  # Final yield
499
- Β  Β  yield history, "Response complete.", current_state
500
 
501
  # ------------------------
502
  # API Endpoint for Feedback Training
503
  # ------------------------
504
  def feedback_train(history: List[List[str]], desired_response: str) -> str:
505
- Β  Β  """
506
- Β  Β  Endpoint for training the model based on explicit bad feedback and a desired response.
507
- Β  Β  This function is used by the Manual Training panel and is called by the JS Bad Feedback button.
508
- Β  Β  """
509
- Β  Β  global start_iteration
510
-
511
- Β  Β  if not desired_response.strip():
512
- Β  Β  Β  Β  # NOTE: This only logs a status if the desired response is empty.
513
- Β  Β  Β  Β  # The JS client should handle simple logging if needed.
514
- Β  Β  Β  Β  return "Warning: Training skipped. Provide a desired response to train."
515
-
516
- Β  Β  if not history or not history[-1][0]:
517
- Β  Β  Β  Β  return "Error: Chat history is empty or missing user prompt. Cannot train."
518
- Β  Β Β 
519
- Β  Β  # Retrieve the full context from the last state, if available, otherwise reconstruct the simplest form
520
- Β  Β  # The gradio state `train_input_state` should ideally be passed, but using history for simplicity
521
- Β  Β  last_user_prompt_raw = history[-1][0]
522
- Β  Β  # Reconstruct the full input prompt in the safest way possible for training
523
- Β  Β  # NOTE: Since the chat history only contains user message and model response,
524
- Β  Β  # the web context (search_summary) is lost here unless retrieved from a state object.
525
- Β  Β  # For this fix, we assume the base prompt is sufficient for training on the response structure.
526
- Β  Β  full_training_input = f"{SYSTEM_INSTRUCTION} {last_user_prompt_raw}"
527
-
528
- Β  Β  try:
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
- Β  Β  gr.Markdown("# 🌐 OkemoLLM β€” Streaming DuckDuckGo + Stable Inference")
539
- Β  Β Β 
540
- Β  Β  # Status bar
541
- Β  Β  status = gr.Markdown(f"Ready. **Current Checkpoint Iteration: {start_iteration}**. (Training is manual.)")
542
- Β  Β  chat = gr.Chatbot(height=400)
543
- Β  Β Β 
544
- Β  Β  train_state = gr.State(TRAIN_INPUT_STATE)
545
-
546
- Β  Β  with gr.Row():
547
- Β  Β  Β  Β  msg = gr.Textbox(placeholder='Type your message (add <web> for search).', label="Message", scale=4)
548
- Β  Β  Β  Β  clear = gr.Button("Clear", scale=1)
549
-
550
- Β  Β  gr.Markdown("---")
551
- Β  Β  gr.Markdown("## βš™οΈ Manual Feedback Training")
552
- Β  Β  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.")
553
- Β  Β Β 
554
- Β  Β  with gr.Column():
555
- Β  Β  Β  Β  # Defining the train_status component here
556
- Β  Β  Β  Β  train_status = gr.Markdown("Status will update after clicking 'Train'.")
557
- Β  Β  Β  Β Β 
558
- Β  Β  Β  Β  # This displays the last user input
559
- Β  Β  Β  Β  prompt_display = gr.Textbox(label="Last User Message (Input for Training)", interactive=False)
560
- Β  Β  Β  Β  last_response_display = gr.Textbox(label="Model's Last Response", interactive=False)
561
- Β  Β  Β  Β Β 
562
- Β  Β  Β  Β  # User provides the ground truth hereΒ 
563
- Β  Β  Β  Β  manual_target_response = gr.Textbox(label="Desired Response (Ground Truth for Training)", placeholder='Enter the correct/better response for the prompt above.')Β 
564
-
565
- Β  Β  train_button = gr.Button("Perform Manual Feedback Training")
566
-
567
- Β  Β  # Connect Chat Handlers (Inference only)
568
- Β  Β  msg.submit(
569
- Β  Β  Β  Β  on_submit,Β 
570
- Β  Β  Β  Β  [msg, chat, train_state],Β 
571
- Β  Β  Β  Β  [chat, status, train_state]
572
- Β  Β  ).then(
573
- Β  Β  Β  Β  # Update context displays after submission
574
- Β  Β  Β  Β  lambda s: (s.get("user_message", "No message."), s.get("last_model_response", "")),
575
- Β  Β  Β  Β  train_state,
576
- Β  Β  Β  Β  [prompt_display, last_response_display]
577
- Β  Β  )
578
- Β  Β Β 
579
- Β  Β  clear.click(lambda: ([], f"Cleared. Current Checkpoint Iteration: {start_iteration}."), None, [chat, status], queue=False)
580
-
581
- Β  Β  # Connect the Manual Training Button (This implicitly registers the /feedback_train endpoint)
582
- Β  Β  train_button.click(
583
- Β  Β  Β  Β  feedback_train,Β 
584
- Β  Β  Β  Β  [chat, manual_target_response], # chat component passes the history
585
- Β  Β  Β  Β  train_statusΒ 
586
- Β  Β  )
587
- Β  Β Β 
588
- Β  Β  # --- Removing the simple logging endpoint and relying on 'feedback_train' ---
589
- Β  Β  # The JS will send an empty string to /feedback_train, which the Python function handles by skipping training.
590
 
591
 
592
  if __name__ == "__main__":
593
- Β  Β  demo.queue(api_open=True).launch(ssr_mode=False)
 
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)