Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,16 +7,12 @@ import torch.nn as nn
|
|
| 7 |
import torch.nn.functional as F
|
| 8 |
import torch.optim as optim
|
| 9 |
import gradio as gr
|
| 10 |
-
import kagglehub
|
| 11 |
-
import pandas as pd # Needed to read the downloaded CSV
|
| 12 |
-
from tqdm import tqdm # Needed for progress bar
|
| 13 |
|
| 14 |
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
|
| 15 |
|
| 16 |
SYSTEM_INSTRUCTION = "You are a friendly all general-purpose AI assistant named Okemo Language Model or OLM for short. You only respond mostly in English. Keep your answers short unless the user asks you to elaborate or think longer. Be silly"
|
| 17 |
-
ONLINE_LEARNING_EPOCHS =
|
| 18 |
-
OFFLINE_LEARNING_EPOCHS = 1 # Set to 1 for quick testing/startup
|
| 19 |
-
BATCH_SIZE = 64 # Batch size for offline training
|
| 20 |
|
| 21 |
# --- Data Helpers ---
|
| 22 |
|
|
@@ -62,6 +58,8 @@ class Voc:
|
|
| 62 |
|
| 63 |
def add_sentence(self, sentence):
|
| 64 |
"""Adds tokens from a sentence to the vocabulary."""
|
|
|
|
|
|
|
| 65 |
for word in tokenize(sentence):
|
| 66 |
if word not in self.word2index:
|
| 67 |
self.word2index[word] = self.n_words
|
|
@@ -112,145 +110,13 @@ def indexes_from_sentence(voc, sentence):
|
|
| 112 |
def make_bool_causal_mask(sz, device):
|
| 113 |
return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)
|
| 114 |
|
| 115 |
-
# --- Offline Training Logic ---
|
| 116 |
-
|
| 117 |
-
def build_vocab_and_tensor(voc, data_path, max_seq_len):
|
| 118 |
-
"""Loads dataset, expands the vocab, and creates tensors for bulk training."""
|
| 119 |
-
|
| 120 |
-
data_file = os.path.join(data_path, "English-Learning-Data.csv")
|
| 121 |
-
if not os.path.exists(data_file):
|
| 122 |
-
print(f"Error: Data file not found at {data_file}")
|
| 123 |
-
return None, None
|
| 124 |
-
|
| 125 |
-
df = pd.read_csv(data_file)
|
| 126 |
-
|
| 127 |
-
sequences = []
|
| 128 |
-
|
| 129 |
-
# Use the first 1000 rows for quick initialization/testing
|
| 130 |
-
for _, row in df.head(1000).iterrows():
|
| 131 |
-
input_text = f"{SYSTEM_INSTRUCTION} {row['User']} "
|
| 132 |
-
target_text = row['AI_Response']
|
| 133 |
-
|
| 134 |
-
# 1. Expand Vocabulary
|
| 135 |
-
voc.add_sentence(input_text)
|
| 136 |
-
voc.add_sentence(target_text)
|
| 137 |
-
|
| 138 |
-
# 2. Convert to sequence
|
| 139 |
-
prompt_tokens = [voc.SYSTEM] + tokenize(to_ascii(input_text))
|
| 140 |
-
response_tokens = tokenize(to_ascii(target_text)) + [voc.EOS]
|
| 141 |
-
|
| 142 |
-
full_sequence = prompt_tokens + response_tokens
|
| 143 |
-
|
| 144 |
-
if len(full_sequence) > max_seq_len + 1:
|
| 145 |
-
continue
|
| 146 |
-
|
| 147 |
-
sequence_ids = [voc.word2index.get(tok, voc.word2index[voc.UNK]) for tok in full_sequence]
|
| 148 |
-
sequences.append(sequence_ids)
|
| 149 |
-
|
| 150 |
-
if not sequences:
|
| 151 |
-
return None, None
|
| 152 |
-
|
| 153 |
-
max_len_in_batch = max(len(s) for s in sequences)
|
| 154 |
-
padded_sequences = [
|
| 155 |
-
s + [voc.word2index[voc.PAD]] * (max_len_in_batch - len(s))
|
| 156 |
-
for s in sequences
|
| 157 |
-
]
|
| 158 |
-
|
| 159 |
-
print(f"Loaded {len(sequences)} sequences. New vocabulary size: {voc.n_words}")
|
| 160 |
-
|
| 161 |
-
data_tensor = torch.tensor(padded_sequences, dtype=torch.long, device=device)
|
| 162 |
-
return data_tensor, max_len_in_batch
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
def perform_offline_training(model, criterion, voc, max_len):
|
| 166 |
-
"""Executes a full training loop on the Kaggle data."""
|
| 167 |
-
print("\n--- Starting Offline Data Download ---")
|
| 168 |
-
|
| 169 |
-
# 1. Download Data
|
| 170 |
-
try:
|
| 171 |
-
path = kagglehub.dataset_download("zara2099/lms-based-english-learning-data")
|
| 172 |
-
print(f"Path to dataset files: {path}")
|
| 173 |
-
|
| 174 |
-
data_tensor, data_max_len = build_vocab_and_tensor(voc, path, max_len)
|
| 175 |
-
|
| 176 |
-
if data_tensor is None:
|
| 177 |
-
print("Skipping offline training: Data processing failed.")
|
| 178 |
-
return
|
| 179 |
-
|
| 180 |
-
except Exception as e:
|
| 181 |
-
print(f"Error accessing Kaggle dataset (is kagglehub installed/configured?): {e}")
|
| 182 |
-
return
|
| 183 |
-
|
| 184 |
-
# 2. Handle Model Resizing (if vocab size changed)
|
| 185 |
-
if model.embedding.num_embeddings != voc.n_words:
|
| 186 |
-
print(f"Re-initializing model with new vocab size: {voc.n_words}")
|
| 187 |
-
|
| 188 |
-
# Must declare global variables that will be RE-ASSIGNED
|
| 189 |
-
global gpt_model, optimizer
|
| 190 |
-
|
| 191 |
-
# Create a new model instance with the updated vocab size
|
| 192 |
-
new_model = GPT(voc.n_words, model.embedding.embedding_dim, model.transformer.num_layers,
|
| 193 |
-
model.transformer.layers[0].self_attn.num_heads, model.transformer.layers[0].linear1.out_features,
|
| 194 |
-
model.transformer.layers[0].dropout.p).to(device)
|
| 195 |
-
|
| 196 |
-
# Copy over existing weights to the new, larger embedding matrix
|
| 197 |
-
old_weights = model.embedding.weight.data
|
| 198 |
-
new_model.embedding.weight.data[:old_weights.size(0)] = old_weights
|
| 199 |
-
|
| 200 |
-
# Load other state dict keys (transformer blocks, norms, etc.)
|
| 201 |
-
model_state_dict = model.state_dict()
|
| 202 |
-
del model_state_dict['embedding.weight']
|
| 203 |
-
new_model.load_state_dict(model_state_dict, strict=False)
|
| 204 |
-
|
| 205 |
-
# Update global references and reinitialize optimizer
|
| 206 |
-
gpt_model = new_model
|
| 207 |
-
optimizer = optim.Adam(gpt_model.parameters(), lr=LEARNING_RATE)
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
# 3. Perform Training
|
| 211 |
-
gpt_model.train()
|
| 212 |
-
total_samples = data_tensor.size(0)
|
| 213 |
-
num_batches = (total_samples + BATCH_SIZE - 1) // BATCH_SIZE
|
| 214 |
-
|
| 215 |
-
print(f"Starting bulk training over {OFFLINE_LEARNING_EPOCHS} epochs ({total_samples} samples)...")
|
| 216 |
-
|
| 217 |
-
for epoch in range(OFFLINE_LEARNING_EPOCHS):
|
| 218 |
-
total_loss = 0
|
| 219 |
-
for i in tqdm(range(num_batches), desc=f"Epoch {epoch+1}"):
|
| 220 |
-
start_idx = i * BATCH_SIZE
|
| 221 |
-
end_idx = min((i + 1) * BATCH_SIZE, total_samples)
|
| 222 |
-
batch = data_tensor[start_idx:end_idx]
|
| 223 |
-
|
| 224 |
-
input_tensor = batch[:, :-1].to(device)
|
| 225 |
-
target_tensor = batch[:, 1:].contiguous().view(-1).to(device)
|
| 226 |
-
|
| 227 |
-
current_max_len = input_tensor.size(1)
|
| 228 |
-
causal = make_bool_causal_mask(current_max_len, device)
|
| 229 |
-
|
| 230 |
-
optimizer.zero_grad()
|
| 231 |
-
logits = gpt_model(input_tensor, mask=causal, key_padding_mask=None)
|
| 232 |
-
|
| 233 |
-
# Reshape logits: [Batch, SeqLen, VocabSize] -> [Batch*SeqLen, VocabSize]
|
| 234 |
-
logits_flat = logits.view(-1, voc.n_words)
|
| 235 |
-
|
| 236 |
-
loss = criterion(logits_flat, target_tensor)
|
| 237 |
-
loss.backward()
|
| 238 |
-
optimizer.step()
|
| 239 |
-
total_loss += loss.item()
|
| 240 |
-
|
| 241 |
-
avg_loss = total_loss / num_batches
|
| 242 |
-
print(f"Epoch {epoch+1}/{OFFLINE_LEARNING_EPOCHS} complete. Avg Loss: {avg_loss:.4f}")
|
| 243 |
-
|
| 244 |
-
gpt_model.eval()
|
| 245 |
-
print("--- Offline Training Complete ---")
|
| 246 |
-
save_checkpoint(gpt_model, optimizer, voc, CHECKPOINT_PATH)
|
| 247 |
-
print("Model checkpoint saved after offline training.")
|
| 248 |
-
|
| 249 |
# --- Initialization ---
|
| 250 |
|
| 251 |
device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")
|
| 252 |
|
| 253 |
CHECKPOINT_PATH = "checkpoint.pth"
|
|
|
|
|
|
|
| 254 |
if not os.path.exists(CHECKPOINT_PATH):
|
| 255 |
print("WARNING: Using dummy checkpoint as real file not found.")
|
| 256 |
checkpoint = {
|
|
@@ -297,17 +163,10 @@ if "optimizer_state_dict" in checkpoint:
|
|
| 297 |
criterion = nn.CrossEntropyLoss(ignore_index=voc.word2index[voc.PAD])
|
| 298 |
|
| 299 |
|
| 300 |
-
# --- EXECUTE OFFLINE TRAINING HERE ---
|
| 301 |
-
# NOTE: This will run on startup, downloading data and training the model.
|
| 302 |
-
perform_offline_training(gpt_model, criterion, voc, max_length)
|
| 303 |
-
# -------------------------------------
|
| 304 |
-
|
| 305 |
-
|
| 306 |
# --- Checkpoint Save Function ---
|
| 307 |
def save_checkpoint(model, optimizer, voc, path):
|
| 308 |
"""Saves the current state of the model and optimizer."""
|
| 309 |
print(f"Saving model checkpoint to {path}...")
|
| 310 |
-
# NOTE: This function still uses the global optimizer variable
|
| 311 |
checkpoint = {
|
| 312 |
"voc_word2index": voc.word2index,
|
| 313 |
"voc_index2word": voc.index2word,
|
|
@@ -342,7 +201,10 @@ def perform_web_search(query):
|
|
| 342 |
|
| 343 |
|
| 344 |
def online_update(model, input_sentence, target_response, max_seq_len, search_context="", file_context="", conversation_context=""):
|
| 345 |
-
|
|
|
|
|
|
|
|
|
|
| 346 |
is_response_clean = not any(t in target_response for t in [voc.UNK, "i couldn't generate"])
|
| 347 |
is_not_repetitive = not check_repetition(target_response, max_repeat=2)
|
| 348 |
|
|
@@ -390,7 +252,6 @@ def online_update(model, input_sentence, target_response, max_seq_len, search_co
|
|
| 390 |
|
| 391 |
|
| 392 |
def generate_response(prompt, search_context="", conversation_context=""):
|
| 393 |
-
# ... [generate_response logic remains the same] ...
|
| 394 |
prefix_text = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""
|
| 395 |
context_prefix = f"{conversation_context} " if conversation_context else ""
|
| 396 |
|
|
@@ -441,7 +302,6 @@ def generate_response(prompt, search_context="", conversation_context=""):
|
|
| 441 |
|
| 442 |
|
| 443 |
def process_feedback(history, rating):
|
| 444 |
-
# ... [process_feedback logic remains the same] ...
|
| 445 |
if not isinstance(history, list):
|
| 446 |
return [], "Cannot process feedback: history not a list."
|
| 447 |
if not history or not (isinstance(history[-1], list) and len(history[-1]) == 2 and isinstance(history[-1][1], str)):
|
|
@@ -500,7 +360,6 @@ def process_feedback(history, rating):
|
|
| 500 |
|
| 501 |
|
| 502 |
def on_submit(user_message, history, uploaded_file, web_search_enabled):
|
| 503 |
-
# ... [on_submit logic remains the same, adjusted for browsing feature return] ...
|
| 504 |
history = history or []
|
| 505 |
if not history or history[-1][1] is not None:
|
| 506 |
history.append([user_message, None])
|
|
|
|
| 7 |
import torch.nn.functional as F
|
| 8 |
import torch.optim as optim
|
| 9 |
import gradio as gr
|
| 10 |
+
# Removed: import kagglehub, pandas, tqdm
|
|
|
|
|
|
|
| 11 |
|
| 12 |
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
|
| 13 |
|
| 14 |
SYSTEM_INSTRUCTION = "You are a friendly all general-purpose AI assistant named Okemo Language Model or OLM for short. You only respond mostly in English. Keep your answers short unless the user asks you to elaborate or think longer. Be silly"
|
| 15 |
+
ONLINE_LEARNING_EPOCHS = 10 # Increased for more efficient learning from user input
|
|
|
|
|
|
|
| 16 |
|
| 17 |
# --- Data Helpers ---
|
| 18 |
|
|
|
|
| 58 |
|
| 59 |
def add_sentence(self, sentence):
|
| 60 |
"""Adds tokens from a sentence to the vocabulary."""
|
| 61 |
+
# Note: This is now only used in `build_vocab_and_tensor` which has been removed.
|
| 62 |
+
# Keeping for compatibility if future features need it.
|
| 63 |
for word in tokenize(sentence):
|
| 64 |
if word not in self.word2index:
|
| 65 |
self.word2index[word] = self.n_words
|
|
|
|
| 110 |
def make_bool_causal_mask(sz, device):
|
| 111 |
return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)
|
| 112 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
# --- Initialization ---
|
| 114 |
|
| 115 |
device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")
|
| 116 |
|
| 117 |
CHECKPOINT_PATH = "checkpoint.pth"
|
| 118 |
+
# Removed: checkpoint_exists flag logic, as offline training is removed.
|
| 119 |
+
|
| 120 |
if not os.path.exists(CHECKPOINT_PATH):
|
| 121 |
print("WARNING: Using dummy checkpoint as real file not found.")
|
| 122 |
checkpoint = {
|
|
|
|
| 163 |
criterion = nn.CrossEntropyLoss(ignore_index=voc.word2index[voc.PAD])
|
| 164 |
|
| 165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
# --- Checkpoint Save Function ---
|
| 167 |
def save_checkpoint(model, optimizer, voc, path):
|
| 168 |
"""Saves the current state of the model and optimizer."""
|
| 169 |
print(f"Saving model checkpoint to {path}...")
|
|
|
|
| 170 |
checkpoint = {
|
| 171 |
"voc_word2index": voc.word2index,
|
| 172 |
"voc_index2word": voc.index2word,
|
|
|
|
| 201 |
|
| 202 |
|
| 203 |
def online_update(model, input_sentence, target_response, max_seq_len, search_context="", file_context="", conversation_context=""):
|
| 204 |
+
"""
|
| 205 |
+
Performs online training using a single user input/AI response pair.
|
| 206 |
+
The number of epochs is increased to improve learning efficiency.
|
| 207 |
+
"""
|
| 208 |
is_response_clean = not any(t in target_response for t in [voc.UNK, "i couldn't generate"])
|
| 209 |
is_not_repetitive = not check_repetition(target_response, max_repeat=2)
|
| 210 |
|
|
|
|
| 252 |
|
| 253 |
|
| 254 |
def generate_response(prompt, search_context="", conversation_context=""):
|
|
|
|
| 255 |
prefix_text = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""
|
| 256 |
context_prefix = f"{conversation_context} " if conversation_context else ""
|
| 257 |
|
|
|
|
| 302 |
|
| 303 |
|
| 304 |
def process_feedback(history, rating):
|
|
|
|
| 305 |
if not isinstance(history, list):
|
| 306 |
return [], "Cannot process feedback: history not a list."
|
| 307 |
if not history or not (isinstance(history[-1], list) and len(history[-1]) == 2 and isinstance(history[-1][1], str)):
|
|
|
|
| 360 |
|
| 361 |
|
| 362 |
def on_submit(user_message, history, uploaded_file, web_search_enabled):
|
|
|
|
| 363 |
history = history or []
|
| 364 |
if not history or history[-1][1] is not None:
|
| 365 |
history.append([user_message, None])
|