Spaces:
Runtime error
Runtime error
Update app.py
Browse files6 unmodified lines7891011121314151617181920212239 unmodified lines62636465666744 unmodified lines11211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525640 unmodified lines29729829930030130230330430530630730830931031131231328 unmodified lines34234334434534634734841 unmodified lines39039139239339439539644 unmodified lines44144244344444544644752 unmodified lines5005015025035045055066 unmodified linesimport torch.nn.functional as Fimport torch.optim as optimimport gradio as grimport kagglehubimport pandas as pd # Needed to read the downloaded CSVfrom tqdm import tqdm # Needed for progress baros.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"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"ONLINE_LEARNING_EPOCHS = 3OFFLINE_LEARNING_EPOCHS = 1 # Set to 1 for quick testing/startupBATCH_SIZE = 64 # Batch size for offline training# --- Data Helpers ---39 unmodified linesdef add_sentence(self, sentence):"""Adds tokens from a sentence to the vocabulary."""for word in tokenize(sentence):if word not in self.word2index:self.word2index[word] = self.n_words44 unmodified linesdef make_bool_causal_mask(sz, device):return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)# --- Offline Training Logic ---def build_vocab_and_tensor(voc, data_path, max_seq_len):"""Loads dataset, expands the vocab, and creates tensors for bulk training."""data_file = os.path.join(data_path, "English-Learning-Data.csv")if not os.path.exists(data_file):print(f"Error: Data file not found at {data_file}")return None, Nonedf = pd.read_csv(data_file)sequences = []# Use the first 1000 rows for quick initialization/testingfor _, row in df.head(1000).iterrows():input_text = f"{SYSTEM_INSTRUCTION} {row['User']} "target_text = row['AI_Response']# 1. Expand Vocabularyvoc.add_sentence(input_text)voc.add_sentence(target_text)# 2. Convert to sequenceprompt_tokens = [voc.SYSTEM] + tokenize(to_ascii(input_text))response_tokens = tokenize(to_ascii(target_text)) + [voc.EOS]full_sequence = prompt_tokens + response_tokensif len(full_sequence) > max_seq_len + 1:continuesequence_ids = [voc.word2index.get(tok, voc.word2index[voc.UNK]) for tok in full_sequence]sequences.append(sequence_ids)if not sequences:return None, Nonemax_len_in_batch = max(len(s) for s in sequences)padded_sequences = [s + [voc.word2index[voc.PAD]] * (max_len_in_batch - len(s))for s in sequences]print(f"Loaded {len(sequences)} sequences. New vocabulary size: {voc.n_words}")data_tensor = torch.tensor(padded_sequences, dtype=torch.long, device=device)return data_tensor, max_len_in_batchdef perform_offline_training(model, criterion, voc, max_len):"""Executes a full training loop on the Kaggle data."""print("\n--- Starting Offline Data Download ---")# 1. Download Datatry:path = kagglehub.dataset_download("zara2099/lms-based-english-learning-data")print(f"Path to dataset files: {path}")data_tensor, data_max_len = build_vocab_and_tensor(voc, path, max_len)if data_tensor is None:print("Skipping offline training: Data processing failed.")returnexcept Exception as e:print(f"Error accessing Kaggle dataset (is kagglehub installed/configured?): {e}")return# 2. Handle Model Resizing (if vocab size changed)if model.embedding.num_embeddings != voc.n_words:print(f"Re-initializing model with new vocab size: {voc.n_words}")# Must declare global variables that will be RE-ASSIGNEDglobal gpt_model, optimizer# Create a new model instance with the updated vocab sizenew_model = GPT(voc.n_words, model.embedding.embedding_dim, model.transformer.num_layers,model.transformer.layers[0].self_attn.num_heads, model.transformer.layers[0].linear1.out_features,model.transformer.layers[0].dropout.p).to(device)# Copy over existing weights to the new, larger embedding matrixold_weights = model.embedding.weight.datanew_model.embedding.weight.data[:old_weights.size(0)] = old_weights# Load other state dict keys (transformer blocks, norms, etc.)model_state_dict = model.state_dict()del model_state_dict['embedding.weight']new_model.load_state_dict(model_state_dict, strict=False)# Update global references and reinitialize optimizergpt_model = new_modeloptimizer = optim.Adam(gpt_model.parameters(), lr=LEARNING_RATE)# 3. Perform Traininggpt_model.train()total_samples = data_tensor.size(0)num_batches = (total_samples + BATCH_SIZE - 1) // BATCH_SIZEprint(f"Starting bulk training over {OFFLINE_LEARNING_EPOCHS} epochs ({total_samples} samples)...")for epoch in range(OFFLINE_LEARNING_EPOCHS):total_loss = 0for i in tqdm(range(num_batches), desc=f"Epoch {epoch+1}"):start_idx = i * BATCH_SIZEend_idx = min((i + 1) * BATCH_SIZE, total_samples)batch = data_tensor[start_idx:end_idx]input_tensor = batch[:, :-1].to(device)target_tensor = batch[:, 1:].contiguous().view(-1).to(device)current_max_len = input_tensor.size(1)causal = make_bool_causal_mask(current_max_len, device)optimizer.zero_grad()logits = gpt_model(input_tensor, mask=causal, key_padding_mask=None)# Reshape logits: [Batch, SeqLen, VocabSize] -> [Batch*SeqLen, VocabSize]logits_flat = logits.view(-1, voc.n_words)loss = criterion(logits_flat, target_tensor)loss.backward()optimizer.step()total_loss += loss.item()avg_loss = total_loss / num_batchesprint(f"Epoch {epoch+1}/{OFFLINE_LEARNING_EPOCHS} complete. Avg Loss: {avg_loss:.4f}")gpt_model.eval()print("--- Offline Training Complete ---")save_checkpoint(gpt_model, optimizer, voc, CHECKPOINT_PATH)print("Model checkpoint saved after offline training.")# --- Initialization ---device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")CHECKPOINT_PATH = "checkpoint.pth"if not os.path.exists(CHECKPOINT_PATH):print("WARNING: Using dummy checkpoint as real file not found.")checkpoint = {40 unmodified linescriterion = nn.CrossEntropyLoss(ignore_index=voc.word2index[voc.PAD])# --- EXECUTE OFFLINE TRAINING HERE ---# NOTE: This will run on startup, downloading data and training the model.perform_offline_training(gpt_model, criterion, voc, max_length)# -------------------------------------# --- Checkpoint Save Function ---def save_checkpoint(model, optimizer, voc, path):"""Saves the current state of the model and optimizer."""print(f"Saving model checkpoint to {path}...")# NOTE: This function still uses the global optimizer variablecheckpoint = {"voc_word2index": voc.word2index,"voc_index2word": voc.index2word,28 unmodified linesdef online_update(model, input_sentence, target_response, max_seq_len, search_context="", file_context="", conversation_context=""):# ... [online_update logic remains the same] ...is_response_clean = not any(t in target_response for t in [voc.UNK, "i couldn't generate"])is_not_repetitive = not check_repetition(target_response, max_repeat=2)41 unmodified linesdef generate_response(prompt, search_context="", conversation_context=""):# ... [generate_response logic remains the same] ...prefix_text = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""context_prefix = f"{conversation_context} " if conversation_context else ""44 unmodified linesdef process_feedback(history, rating):# ... [process_feedback logic remains the same] ...if not isinstance(history, list):return [], "Cannot process feedback: history not a list."if not history or not (isinstance(history[-1], list) and len(history[-1]) == 2 and isinstance(history[-1][1], str)):52 unmodified linesdef on_submit(user_message, history, uploaded_file, web_search_enabled):# ... [on_submit logic remains the same, adjusted for browsing feature return] ...history = history or []if not history or history[-1][1] is not None:history.append([user_message, None])6 unmodified lines78910111213141516171839 unmodified lines585960616263646544 unmodified lines11011111211311411511611711811912012112240 unmodified lines16316416516616716816917017117228 unmodified lines20120220320420520620720820921041 unmodified lines25225325425525625744 unmodified lines30230330430530630752 unmodified lines3603613623633643656 unmodified linesimport torch.nn.functional as Fimport torch.optim as optimimport gradio as gr# Removed: import kagglehub, pandas, tqdmos.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"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"ONLINE_LEARNING_EPOCHS = 10 # Increased for more efficient learning from user input# --- Data Helpers ---39 unmodified linesdef add_sentence(self, sentence):"""Adds tokens from a sentence to the vocabulary."""# Note: This is now only used in `build_vocab_and_tensor` which has been removed.# Keeping for compatibility if future features need it.for word in tokenize(sentence):if word not in self.word2index:self.word2index[word] = self.n_words44 unmodified linesdef make_bool_causal_mask(sz, device):return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)# --- Initialization ---device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")CHECKPOINT_PATH = "checkpoint.pth"# Removed: checkpoint_exists flag logic, as offline training is removed.if not os.path.exists(CHECKPOINT_PATH):print("WARNING: Using dummy checkpoint as real file not found.")checkpoint = {40 unmodified linescriterion = nn.CrossEntropyLoss(ignore_index=voc.word2index[voc.PAD])# --- Checkpoint Save Function ---def save_checkpoint(model, optimizer, voc, path):"""Saves the current state of the model and optimizer."""print(f"Saving model checkpoint to {path}...")checkpoint = {"voc_word2index": voc.word2index,"voc_index2word": voc.index2word,28 unmodified linesdef online_update(model, input_sentence, target_response, max_seq_len, search_context="", file_context="", conversation_context=""):"""Performs online training using a single user input/AI response pair.The number of epochs is increased to improve learning efficiency."""is_response_clean = not any(t in target_response for t in [voc.UNK, "i couldn't generate"])is_not_repetitive = not check_repetition(target_response, max_repeat=2)41 unmodified linesdef generate_response(prompt, search_context="", conversation_context=""):prefix_text = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""context_prefix = f"{conversation_context} " if conversation_context else ""44 unmodified linesdef process_feedback(history, rating):if not isinstance(history, list):return [], "Cannot process feedback: history not a list."if not history or not (isinstance(history[-1], list) and len(history[-1]) == 2 and isinstance(history[-1][1], str)):52 unmodified linesdef on_submit(user_message, history, uploaded_file, web_search_enabled):history = history or []if not history or history[-1][1] is not None:history.append([user_message, None])
app.py+10-151