Add main Space application
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024#!/usr/bin/env python3"""OpenLLM Training Space Application - Fixed with Uploaded ModulesThis version imports OpenLLM modules from the uploaded files in the HF Space:- Imports model.py and data_loader.py that were uploaded to the Space- Uses OpenLLM's actual custom model architecture- Compatible with OpenLLM's implementationThis application provides a complete training interface for OpenLLM models on Hugging Face Spaces.It uses OpenLLM's custom GPTModel architecture instead of Hugging Face Transformers,ensuring compatibility with the actual OpenLLM implementation.Key Features:- Real model training using OpenLLM's custom architecture- SentencePiece tokenization for OpenLLM models- Complete training pipeline with progress monitoring- Automatic model saving and uploading to Hugging Face Hub- Gradio 4.44.1 compatible user interfaceTechnical Architecture:- Uses OpenLLM's GPTModel class (not Hugging Face Transformers)- Imports custom modules from uploaded files in the Space- Uses sentencepiece.SentencePieceProcessor() for tokenization- Implements OpenLLM's training loop and optimization strategy- Saves checkpoints in OpenLLM's formatAuthor: Louis Chua Bean ChongLicense: GPL-3.0Version: 2.1.1Last Updated: 2024"""import gradio as grimport torchimport torch.nn as nnimport osimport timeimport mathimport gcfrom typing import Dict, Any, Optionalimport threadingfrom dataclasses import dataclassfrom pathlib import Path# Import OpenLLM's custom model architecture from uploaded files# These files were uploaded to the HF Space and contain OpenLLM's actual implementationtry:# Import from the uploaded files in the HF Space# model.py contains GPTModel, GPTConfig, and create_model factory functionfrom model import GPTModel, GPTConfig, create_model# data_loader.py contains TextDataLoader for OpenLLM's data loading approachfrom data_loader import TextDataLoaderOPENLLM_AVAILABLE = Trueprint("β OpenLLM custom model architecture imported successfully from uploaded files")print(" - GPTModel: Custom PyTorch model architecture")print(" - GPTConfig: Model configuration dataclass")print(" - create_model: Factory function for model creation")print(" - TextDataLoader: Custom data loading implementation")except ImportError as e:print(f"β OpenLLM imports failed: {e}")print(" This indicates the uploaded OpenLLM source files are not available")print(" The training functionality will be disabled")OPENLLM_AVAILABLE = False# Try to import sentencepiece - CRITICAL for OpenLLM tokenization# OpenLLM uses SentencePiece for tokenization, not Hugging Face tokenizerstry:import sentencepiece as spmSENTENCEPIECE_AVAILABLE = Trueprint(f"β SentencePiece available: {spm.__version__}")print(" - Required for OpenLLM tokenization")print(" - Used for loading tokenizer.model files")except ImportError:SENTENCEPIECE_AVAILABLE = Falseprint("β SentencePiece not available")print(" - This will prevent tokenizer loading")print(" - Training functionality will be limited")# Import other dependencies for the complete training pipelinetry:from datasets import load_dataset # For loading training data from HF Hubfrom huggingface_hub import HfApi, hf_hub_download # For model uploads and downloadsDEPENDENCIES_AVAILABLE = Trueprint("β Training dependencies available")print(" - datasets: For loading training data")print(" - huggingface_hub: For model uploads/downloads")except ImportError as e:print(f"β Dependencies not available: {e}")print(" - This will prevent dataset loading and model uploading")DEPENDENCIES_AVAILABLE = False@dataclassclass TrainingConfig:"""Configuration class for training parameters.This dataclass encapsulates all the training hyperparameters and settingsthat control the OpenLLM training process. It provides a clean interfacefor passing configuration between different components of the training pipeline.Attributes:model_size: Size of the model to train ("small", "medium", "large")max_steps: Maximum number of training iterationslearning_rate: Learning rate for the optimizerbatch_size: Number of samples per training batchoutput_dir: Directory to save trained models and checkpointssave_steps: Frequency of checkpoint saving (every N steps)logging_steps: Frequency of progress logging (every N steps)warmup_steps: Number of warmup steps for learning rate schedulinggradient_accumulation_steps: Number of steps to accumulate gradients"""model_size: strmax_steps: intlearning_rate: floatbatch_size: intoutput_dir: str = "./openllm-trained"save_steps: int = 100logging_steps: int = 10warmup_steps: int = 50gradient_accumulation_steps: int = 4class OpenLLMTrainer:"""Complete training implementation using OpenLLM's actual architecture.This class handles the entire training pipeline including:- Model loading using OpenLLM's custom GPTModel- Tokenizer loading using sentencepiece.SentencePieceProcessor()- Dataset preparation using OpenLLM's TextDataLoader- Training execution using OpenLLM's approach- Model saving and uploading to Hugging Face HubThe trainer implements OpenLLM's actual training methodology rather thanusing Hugging Face Transformers, ensuring compatibility with the realOpenLLM implementation.Key Features:- Custom model architecture (GPTModel, not PreTrainedModel)- SentencePiece tokenization (not Hugging Face tokenizers)- OpenLLM's training loop and optimization strategy- Gradient accumulation for memory efficiency- Learning rate scheduling with warmup- Automatic checkpoint saving and model uploading"""def __init__(self):"""Initialize the trainer with default settings.Sets up the trainer with default values and initializes the Hugging FaceAPI for model uploading. All components start as None and are initializedduring the training process."""# Core training components - initialized during trainingself.model = None # OpenLLM's GPTModel instanceself.tokenizer = None # SentencePieceProcessor instanceself.data_loader = None # OpenLLM's TextDataLoader instanceself.optimizer = None # PyTorch optimizer (AdamW)self.scheduler = None # Learning rate scheduler# Training state managementself.is_training = False # Flag to track training statusself.tokenizer_path = None # Path to the tokenizer.model file# Progress tracking for UI updatesself.training_progress = {"status": "Ready", # Current training status"current_step": 0, # Current training step"total_steps": 0, # Total steps to complete"loss": 0.0, # Current training loss"learning_rate": 0.0 # Current learning rate}# Initialize Hugging Face API for model uploading# This allows the trained model to be automatically uploaded to HF Hubtry:self.hf_api = HfApi()print("β Hugging Face API initialized for model uploading")except Exception as e:print(f"Failed to initialize HF API: {e}")print(" - Model uploading will be disabled")self.hf_api = Nonedef load_model_and_tokenizer(self, model_size: str) -> str:"""Load the pre-trained OpenLLM model and tokenizer using OpenLLM's approach.This method implements OpenLLM's actual model loading strategy:1. Creates a new GPTModel using OpenLLM's factory function2. Downloads the tokenizer.model file from Hugging Face Hub3. Loads the tokenizer using SentencePieceProcessor4. Stores both components for use in trainingThis approach differs from Hugging Face Transformers because:- Uses OpenLLM's custom GPTModel (not AutoModelForCausalLM)- Uses SentencePiece directly (not AutoTokenizer)- Downloads specific files rather than using from_pretrained()Args:model_size: Size of the model to load ("small", "medium", "large")Determines which pre-trained model to downloadReturns:Status message indicating success or failureSuccess: "β Successfully loaded OpenLLM {model_size} model with custom architecture"Failure: "β Failed to load OpenLLM model and tokenizer: {error details}""""try:# Verify OpenLLM modules are availableif not OPENLLM_AVAILABLE:return "β OpenLLM custom model architecture not available"print(f"π Loading OpenLLM {model_size} model using custom architecture...")print(f" - Using OpenLLM's create_model factory function")print(f" - Not using Hugging Face Transformers")# Step 1: Create model using OpenLLM's factory function# This creates a fresh GPTModel instance with the specified sizetry:self.model = create_model(model_size)print(f"β OpenLLM {model_size} model created: {type(self.model).__name__}")print(f" - Model type: {type(self.model).__name__}")print(f" - Parameters: {self.model.get_num_params():,}")print(f" - Architecture: Custom GPTModel (not PreTrainedModel)")except Exception as e:print(f"β Failed to create model: {e}")return f"β Failed to create OpenLLM model: {str(e)}"# Step 2: Load tokenizer using sentencepiece# OpenLLM uses SentencePiece directly, not Hugging Face tokenizerstry:print("π Loading tokenizer using sentencepiece.SentencePieceProcessor()...")print(" - Using SentencePiece directly (not AutoTokenizer)")print(" - Downloading tokenizer.model from Hugging Face Hub")# Download tokenizer.model from HF Hub# This is the actual tokenizer file used by OpenLLM modelsmodel_name = f"lemms/openllm-{model_size}-extended-7k"tokenizer_path = hf_hub_download(repo_id=model_name,filename="tokenizer.model" # Specific file name for OpenLLM)print(f"β Tokenizer downloaded to: {tokenizer_path}")print(f" - Source: {model_name}")print(f" - File: tokenizer.model")# Create SentencePieceProcessor and load the tokenizer# This is OpenLLM's actual tokenization approachsp_processor = spm.SentencePieceProcessor()sp_processor.load(tokenizer_path)# Store tokenizer and its path separately# We need the path for the TextDataLoader laterself.tokenizer = sp_processorself.tokenizer_path = tokenizer_path # Store the path separatelyprint(f"β Tokenizer loaded successfully using SentencePieceProcessor")print(f" - Vocabulary size: {sp_processor.vocab_size()}")print(f" - Tokenizer path: {tokenizer_path}")print(f" - Tokenizer type: {type(sp_processor).__name__}")except Exception as e:print(f"β Failed to load tokenizer: {e}")return f"β Failed to load OpenLLM tokenizer: {str(e)}"return f"β Successfully loaded OpenLLM {model_size} model with custom architecture"except Exception as e:return f"β Failed to load OpenLLM model and tokenizer: {str(e)}"def prepare_dataset(self) -> str:"""Load and prepare the training dataset using OpenLLM's approach.This method implements OpenLLM's data preparation strategy:1. Loads training data from Hugging Face Hub dataset2. Creates a temporary text file for OpenLLM's TextDataLoader3. Initializes OpenLLM's TextDataLoader with the tokenizer4. Prepares the data for trainingOpenLLM's approach differs from Hugging Face because:- Uses a simple text file format (not tokenized datasets)- Uses OpenLLM's TextDataLoader (not Hugging Face datasets)- Tokenization happens on-the-fly during trainingReturns:Status message indicating success or failureSuccess: "β Successfully prepared dataset with {count} samples"Failure: "β Failed to prepare dataset: {error details}""""try:# Verify dependencies are availableif not DEPENDENCIES_AVAILABLE:return "β Required dependencies not available"print("π Loading training dataset...")print(" - Loading from Hugging Face Hub dataset")print(" - Using OpenLLM's data preparation approach")# Load dataset from HF Hub# This contains the training text data for continuing model trainingdataset = load_dataset("lemms/openllm-training-data")print(f"β Dataset loaded: {len(dataset['train'])} samples")print(f" - Dataset: lemms/openllm-training-data")print(f" - Samples: {len(dataset['train'])}")# Create temporary data file for OpenLLM's TextDataLoader# OpenLLM expects a simple text file with one text sample per linetemp_data_file = "temp_training_data.txt"with open(temp_data_file, 'w', encoding='utf-8') as f:for item in dataset['train']:f.write(item['text'] + '\n')print(f"β Temporary data file created: {temp_data_file}")print(f" - Format: One text sample per line")print(f" - Encoding: UTF-8")# Create OpenLLM's TextDataLoader# This is OpenLLM's custom data loading implementationtry:# Use the stored tokenizer path instead of trying to access model_file_path# SentencePieceProcessor doesn't have a model_file_path attributetokenizer_path = self.tokenizer_path # Use the stored pathprint(f"π Creating OpenLLM TextDataLoader...")print(f" - Data file: {temp_data_file}")print(f" - Tokenizer path: {tokenizer_path}")print(f" - Sequence length: 512")print(f" - Batch size: 4 (will be overridden by training config)")self.data_loader = TextDataLoader(data_file=temp_data_file,tokenizer_path=tokenizer_path,seq_len=512, # Maximum sequence length for trainingbatch_size=4, # Will be overridden by training configshuffle=True # Shuffle data for better training)print(f"β OpenLLM TextDataLoader created successfully")print(f" - DataLoader type: {type(self.data_loader).__name__}")print(f" - Uses OpenLLM's custom implementation")except Exception as e:print(f"β Failed to create TextDataLoader: {e}")return f"β Failed to create data loader: {str(e)}"return f"β Successfully prepared dataset with {len(dataset['train'])} samples"except Exception as e:return f"β Failed to prepare dataset: {str(e)}"def setup_training(self, config: TrainingConfig) -> str:"""Set up the training configuration using OpenLLM's approach.This method configures the training environment with:1. Output directory creation2. Optimizer setup with weight decay groups3. Learning rate scheduler with warmup4. Training hyperparametersThe setup follows OpenLLM's training methodology:- Uses AdamW optimizer with weight decay- Implements learning rate warmup followed by cosine annealing- Separates parameters for different weight decay rates- Uses gradient clipping for stabilityArgs:config: Training configuration object containing all hyperparametersReturns:Status message indicating success or failureSuccess: "β Training setup completed successfully"Failure: "β Failed to setup training: {error details}""""try:print("π Setting up training configuration...")print(f" - Output directory: {config.output_dir}")print(f" - Learning rate: {config.learning_rate}")print(f" - Max steps: {config.max_steps}")# Create output directory for saving models and checkpointsos.makedirs(config.output_dir, exist_ok=True)print(f"β Output directory created: {config.output_dir}")# Set up optimizer (AdamW with weight decay)# This follows OpenLLM's optimization strategyprint("π Setting up AdamW optimizer with weight decay...")# Separate parameters for different weight decay rates# This is a common practice for transformer trainingdecay_params = [] # Parameters that should have weight decayno_decay_params = [] # Parameters that should not have weight decayfor name, param in self.model.named_parameters():if not param.requires_grad:continue# Apply weight decay to all parameters except biases and layer norm weightsif len(param.shape) == 1 or name.endswith('.bias'):no_decay_params.append(param)else:decay_params.append(param)# Create parameter groups with different weight decay ratesparam_groups = [{'params': decay_params, 'weight_decay': 0.01}, # 1% weight decay{'params': no_decay_params, 'weight_decay': 0.0} # No weight decay]print(f" - Decay parameters: {len(decay_params)}")print(f" - No-decay parameters: {len(no_decay_params)}")# Initialize AdamW optimizer with OpenLLM's recommended settingsself.optimizer = torch.optim.AdamW(param_groups,lr=config.learning_rate,betas=(0.9, 0.95), # Beta values for momentumeps=1e-8 # Epsilon for numerical stability)print(f"β AdamW optimizer configured")print(f" - Learning rate: {config.learning_rate}")print(f" - Betas: (0.9, 0.95)")print(f" - Epsilon: 1e-8")# Set up learning rate scheduler# OpenLLM uses a warmup followed by cosine annealingprint("π Setting up learning rate scheduler...")# Warmup scheduler: linearly increase LR from 1% to 100%warmup_scheduler = torch.optim.lr_scheduler.LinearLR(self.optimizer,start_factor=0.01, # Start at 1% of target LRend_factor=1.0, # End at 100% of target LRtotal_iters=config.warmup_steps)# Main scheduler: cosine annealing after warmupmain_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(self.optimizer,T_max=config.max_steps - config.warmup_steps # Duration of cosine annealing)# Combine warmup and main schedulersself.scheduler = torch.optim.lr_scheduler.SequentialLR(self.optimizer,schedulers=[warmup_scheduler, main_scheduler],milestones=[config.warmup_steps] # Switch to main scheduler after warmup)print(f"β Learning rate scheduler configured")print(f" - Warmup steps: {config.warmup_steps}")print(f" - Total steps: {config.max_steps}")print(f" - Schedule: Linear warmup β Cosine annealing")print("β Training setup completed successfully")return f"β Training setup completed successfully"except Exception as e:return f"β Failed to setup training: {str(e)}"def train_model(self, config: TrainingConfig, progress_callback=None) -> str:"""Execute the actual model training using OpenLLM's approach.This method implements OpenLLM's training loop:1. Sets up training mode and progress tracking2. Iterates through data batches using OpenLLM's TextDataLoader3. Performs forward pass, loss computation, and backward pass4. Implements gradient accumulation for memory efficiency5. Updates model parameters and learning rate6. Saves checkpoints and logs progressThe training loop follows OpenLLM's methodology:- Uses OpenLLM's GPTModel forward pass (returns logits and loss)- Implements gradient accumulation for effective larger batch sizes- Uses gradient clipping for training stability- Saves checkpoints in OpenLLM's format- Updates progress for UI monitoringArgs:config: Training configuration object containing hyperparametersprogress_callback: Optional callback function for progress updates(Not used in current implementation)Returns:Status message indicating success or failureSuccess: "β Training completed successfully! Final step: {step}"Failure: "β Training failed: {error details}""""try:# Set training stateself.is_training = Trueself.training_progress["status"] = "Training"self.training_progress["total_steps"] = config.max_stepsprint(f"π Starting OpenLLM training for {config.max_steps} steps...")print(f" - Model: {type(self.model).__name__}")print(f" - DataLoader: {type(self.data_loader).__name__}")print(f" - Optimizer: {type(self.optimizer).__name__}")print(f" - Gradient accumulation: {config.gradient_accumulation_steps}")# Training loop using OpenLLM's approachself.model.train() # Set model to training modeaccumulated_loss = 0.0 # Track loss across accumulation stepsself.optimizer.zero_grad() # Clear gradientsstep = 0 # Current training stepfor batch_idx, (input_ids, target_ids) in enumerate(self.data_loader):# Check if we've reached the maximum number of stepsif step >= config.max_steps:break# Forward pass (model computes loss internally when targets provided)# OpenLLM's GPTModel returns both logits and losslogits, loss = self.model(input_ids, target_ids)# Scale loss for gradient accumulation# This allows us to simulate larger batch sizesloss = loss / config.gradient_accumulation_stepsaccumulated_loss += loss.item()# Backward pass - compute gradientsloss.backward()# Update weights every gradient_accumulation_stepsif (batch_idx + 1) % config.gradient_accumulation_steps == 0:# Clip gradients for training stability# This prevents exploding gradientstorch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0)# Update parameters using the optimizerself.optimizer.step()# Update learning rate using the schedulerself.scheduler.step()# Clear gradients for the next accumulation cycleself.optimizer.zero_grad()# Update step countstep += 1# Update progress for UI monitoringself.training_progress["current_step"] = stepself.training_progress["loss"] = accumulated_lossself.training_progress["learning_rate"] = self.scheduler.get_last_lr()[0]# Log progress at specified intervalsif step % config.logging_steps == 0:current_lr = self.scheduler.get_last_lr()[0]print(f"Step {step}/{config.max_steps} | Loss: {accumulated_loss:.4f} | LR: {current_lr:.2e}")# Save checkpoint at specified intervalsif step % config.save_steps == 0:self._save_checkpoint(config.output_dir, step)print(f"πΎ Checkpoint saved at step {step}")# Reset accumulated loss for the next accumulation cycleaccumulated_loss = 0.0# Clean up memory periodicallyif step % 100 == 0:gc.collect()print(f"π§Ή Memory cleanup at step {step}")# Save final checkpointself._save_checkpoint(config.output_dir, step, is_best=True)print(f"πΎ Final checkpoint saved at step {step}")# Update final progressself.training_progress["status"] = "Completed"self.training_progress["current_step"] = stepprint(f"β Training completed! Final step: {step}")print(f" - Total steps completed: {step}")print(f" - Final loss: {self.training_progress['loss']:.4f}")print(f" - Final learning rate: {self.training_progress['learning_rate']:.2e}")return f"β Training completed successfully! Final step: {step}"except Exception as e:self.training_progress["status"] = "Failed"print(f"β Training failed: {e}")print(f" - Error occurred during training")print(f" - Training state: {self.training_progress['status']}")return f"β Training failed: {str(e)}"finally:self.is_training = Falsedef _save_checkpoint(self, output_dir: str, step: int, is_best: bool = False) -> None:"""Save model checkpoint using OpenLLM's approach.This method saves the model state in OpenLLM's checkpoint format:- Model state dictionary- Optimizer state dictionary- Scheduler state dictionary- Model configuration- Training step informationThe checkpoint format is compatible with OpenLLM's loading mechanismand can be used to resume training or load the model for inference.Args:output_dir: Directory to save the checkpointstep: Current training step numberis_best: Whether this is the best model so far"""try:# Create checkpoint dictionary with all necessary componentscheckpoint = {'step': step, # Current training step'model_state_dict': self.model.state_dict(), # Model parameters'optimizer_state_dict': self.optimizer.state_dict(), # Optimizer state'scheduler_state_dict': self.scheduler.state_dict(), # Scheduler state'config': self.model.config.__dict__ # Model configuration}# Save latest checkpointcheckpoint_path = os.path.join(output_dir, f"checkpoint_step_{step}.pt")torch.save(checkpoint, checkpoint_path)# Save best checkpoint if this is the best modelif is_best:best_path = os.path.join(output_dir, "best_model.pt")torch.save(checkpoint, best_path)print(f"πΎ Best model saved: {best_path}")print(f"πΎ Checkpoint saved: {checkpoint_path}")except Exception as e:print(f"β Failed to save checkpoint: {e}")def save_and_upload_model(self, config: TrainingConfig) -> str:"""Save the trained model and upload it to Hugging Face Hub.This method completes the training pipeline by:1. Saving the final model checkpoint2. Copying the tokenizer files3. Uploading the complete model to Hugging Face Hub4. Creating a new model repository for the trained modelThe uploaded model will be available at:https://huggingface.co/lemms/openllm-{size}-extended-8kArgs:config: Training configuration objectReturns:Status message indicating success or failureSuccess: "β Model saved and uploaded to https://huggingface.co/{repo_id}"Failure: "β Failed to save/upload model: {error details}""""try:print("π Saving trained model...")print(f" - Output directory: {config.output_dir}")print(f" - Model size: {config.model_size}")# Save the final model checkpointself._save_checkpoint(config.output_dir, config.max_steps, is_best=True)# Save tokenizer files# Create a tokenizer directory within the output directorytokenizer_dir = os.path.join(config.output_dir, "tokenizer")os.makedirs(tokenizer_dir, exist_ok=True)# Copy the tokenizer.model file using the stored path# This ensures the tokenizer is included with the modelimport shutilshutil.copy2(self.tokenizer_path, os.path.join(tokenizer_dir, "tokenizer.model"))print("β Model saved locally")print(f" - Model checkpoint: {config.output_dir}/best_model.pt")print(f" - Tokenizer: {tokenizer_dir}/tokenizer.model")# Generate model name for upload# The naming convention follows: openllm-{size}-extended-8kmodel_name = f"openllm-{config.model_size}-extended-8k"repo_id = f"lemms/{model_name}"# Upload to Hugging Face Hubif self.hf_api:print(f"π Uploading model to {repo_id}...")print(f" - Repository: {repo_id}")print(f" - Type: model")print(f" - Source: {config.output_dir}")# Create the repository first if it doesn't existtry:from huggingface_hub import create_repocreate_repo(repo_id=repo_id,repo_type="model",exist_ok=True,private=False)print(f"β Repository {repo_id} ready for upload")except Exception as create_error:print(f"β οΈ Repository creation warning: {create_error}")print(" Continuing with upload attempt...")# Upload model files to Hugging Face Hub# This creates a new model repository with all the filesself.hf_api.upload_folder(folder_path=config.output_dir,repo_id=repo_id,repo_type="model",commit_message=f"Add trained OpenLLM {config.model_size} model (8k steps)")print(f"β Model uploaded successfully to {repo_id}")print(f" - Available at: https://huggingface.co/{repo_id}")return f"β Model saved and uploaded to https://huggingface.co/{repo_id}"else:print("β οΈ Hugging Face API not available - model saved locally only")return f"β Model saved locally to {config.output_dir}"except Exception as e:print(f"β Failed to save/upload model: {e}")return f"β Failed to save/upload model: {str(e)}"def get_training_progress(self) -> Dict[str, Any]:"""Get current training progress information.This method returns a copy of the current training progressfor display in the Gradio UI. The progress information includes:- Current training status- Current step and total steps- Current loss value- Current learning rateReturns:Dictionary containing current training progress information"""return self.training_progress.copy()def main():"""Main function that creates the complete Gradio application interface.This function sets up the entire Gradio application with:1. Application header and status information2. Training configuration controls3. Training status and progress display4. Training control buttons5. Instructions and resource links6. Training function implementationThe interface provides a complete training experience for OpenLLM modelswith real-time progress monitoring and comprehensive configuration options.Returns:Gradio Blocks interface for the training application"""# Initialize the trainer# This creates the OpenLLMTrainer instance that will handle all training operationstrainer = OpenLLMTrainer()# Create the main Gradio application interface# Using Gradio 4.44.1 with Soft theme for modern appearancewith gr.Blocks(title="OpenLLM Training Space - Fixed with Uploaded Modules",theme=gr.themes.Soft()) as demo:# Application Header# Provides clear identification and description of the applicationgr.Markdown("# π OpenLLM Training Space - Fixed with Uploaded Modules")gr.Markdown("### *Uses OpenLLM's Custom Model Architecture from Uploaded Files*")gr.Markdown("---")# Status Information# Shows the availability of key components and dependenciesgr.Markdown(f"**OpenLLM Available**: {'β Yes' if OPENLLM_AVAILABLE else 'β No'}")gr.Markdown(f"**SentencePiece Available**: {'β Yes' if SENTENCEPIECE_AVAILABLE else 'β No'}")gr.Markdown(f"**Dependencies Available**: {'β Yes' if DEPENDENCIES_AVAILABLE else 'β No'}")gr.Markdown("**Architecture**: β OpenLLM Custom GPTModel (From Uploaded Files)")# Main Content Area# Two-column layout for configuration and statuswith gr.Row():# Left Column: Training Configuration# Contains all the training hyperparameters and settingswith gr.Column(scale=1):gr.Markdown("## π Training Configuration")# Model Size Selection# Allows users to choose which base model to train frommodel_size = gr.Dropdown(choices=["small", "medium", "large"],value="small",label="Model Size",info="Select the base model size to train from")# Training Steps Configuration# Controls the number of training iterationsmax_steps = gr.Slider(minimum=100,maximum=10000,value=1000,step=100,label="Max Training Steps",info="Number of training iterations (100-10,000)")# Learning Rate Configuration# Controls the learning rate for the optimizerlearning_rate = gr.Slider(minimum=1e-5,maximum=1e-3,value=3e-4,step=1e-5,label="Learning Rate",info="Training rate (0.00001-0.001)")# Batch Size Configuration# Controls the number of samples per training batchbatch_size = gr.Slider(minimum=1,maximum=16,value=4,step=1,label="Batch Size",info="Samples per training batch (1-16)")# Right Column: Training Status and Controls# Contains status display and control buttonswith gr.Column(scale=1):gr.Markdown("## π― Training Status")# Training Status Display# Shows current training status and any error messagesstatus_text = gr.Textbox(value="Ready to start training" if OPENLLM_AVAILABLE else "OpenLLM not available",label="Current Status",interactive=False,lines=5,info="Shows current training status and progress updates")# Progress Information# Displays detailed training progress in JSON formatprogress_info = gr.JSON(value=trainer.get_training_progress(),label="Training Progress")# Training Control Buttons# Buttons to start and stop trainingwith gr.Row():start_btn = gr.Button("π Start Training", variant="primary")stop_btn = gr.Button("βΉοΈ Stop Training", variant="stop")# Instructions Section# Provides detailed instructions for using the training interfacegr.Markdown("## π OpenLLM Training Instructions")gr.Markdown("""This interface uses **OpenLLM's actual custom model architecture** from uploaded files:### **Step 1: Configure Parameters**- **Model Size**: Select the base model to train from (small, medium, large)- **Max Steps**: Number of training iterations (100-10,000)- **Learning Rate**: Training rate (0.00001-0.001)- **Batch Size**: Samples per training batch (1-16)### **Step 2: Start Training**- Click "Start Training" to begin the actual training process- Uses OpenLLM's custom GPTModel class from uploaded files- Uses sentencepiece.SentencePieceProcessor() for tokenization- Compatible with OpenLLM's actual implementation### **Step 3: Monitor Progress**- Watch the status updates and progress information- Training may take several minutes depending on steps- The final model will be uploaded to Hugging Face Hub### **Step 4: Access Results**- Trained models are automatically pushed to: `lemms/openllm-{size}-extended-8k`- Check the model repository for your trained model- Use the model for inference or further training""")# Resource Links Section# Provides links to related models and resourcesgr.Markdown("## π Model Resources")gr.Markdown("""- [π 7k Small Model](https://huggingface.co/lemms/openllm-small-extended-7k)- [π― 8k Small Model](https://huggingface.co/lemms/openllm-small-extended-8k)- [π Training Dataset](https://huggingface.co/datasets/lemms/openllm-training-data)- [π Main Project](https://github.com/louischua/openllm)""")# Training Function Definition# This function is called when the Start Training button is clickeddef start_complete_training(model_size, max_steps, learning_rate, batch_size):"""Execute the complete training process using OpenLLM's approach.This function orchestrates the entire training pipeline:1. Validates OpenLLM availability2. Creates training configuration3. Loads model and tokenizer4. Prepares dataset5. Sets up training environment6. Executes training7. Saves and uploads the trained modelThe function provides comprehensive error handling and status updatesthroughout the training process.Args:model_size: Size of the model to train ("small", "medium", "large")max_steps: Maximum number of training stepslearning_rate: Learning rate for the optimizerbatch_size: Batch size for trainingReturns:Status message indicating the result of the training process"""# Validate OpenLLM availabilityif not OPENLLM_AVAILABLE:return "β OpenLLM custom model architecture not available. Please check the installation."try:print(f"π Starting complete training process...")print(f" - Model size: {model_size}")print(f" - Max steps: {max_steps}")print(f" - Learning rate: {learning_rate}")print(f" - Batch size: {batch_size}")# Create training configuration# This encapsulates all training parametersconfig = TrainingConfig(model_size=model_size,max_steps=max_steps,learning_rate=learning_rate,batch_size=batch_size)# Step 1: Load model and tokenizer using OpenLLM's approachprint("π Step 1: Loading model and tokenizer...")status = trainer.load_model_and_tokenizer(model_size)if "β" in status:return status# Step 2: Prepare datasetprint("π Step 2: Preparing dataset...")status = trainer.prepare_dataset()if "β" in status:return status# Step 3: Setup trainingprint("π Step 3: Setting up training...")status = trainer.setup_training(config)if "β" in status:return status# Step 4: Execute trainingprint("π Step 4: Executing training...")status = trainer.train_model(config)if "β" in status:return status# Step 5: Save and upload modelprint("π Step 5: Saving and uploading model...")status = trainer.save_and_upload_model(config)print("π Complete training process finished!")return f"π Complete training process finished!\n{status}"except Exception as e:print(f"β Training process failed: {str(e)}")return f"β Training process failed: {str(e)}"def update_progress():"""Update the progress display.This function is called periodically to update the progressinformation displayed in the Gradio interface. It returns thecurrent training progress from the trainer.Returns:Current training progress dictionary"""return trainer.get_training_progress()# Connect UI Components to Functions# This connects the Start Training button to the training functionstart_btn.click(fn=start_complete_training,inputs=[model_size, max_steps, learning_rate, batch_size],outputs=[status_text])# Auto-refresh progress every 5 seconds during training# This ensures the progress display stays up to datedemo.load(update_progress, outputs=[progress_info])# Application Footer# Provides attribution and technical informationgr.Markdown("---")gr.Markdown("**Author**: Louis Chua Bean Chong | **Project**: OpenLLM | **License**: GPL-3.0")gr.Markdown("**Architecture**: OpenLLM Custom GPTModel (From Uploaded Files)")gr.Markdown("**Tokenizer**: sentencepiece.SentencePieceProcessor()")return demoif __name__ == "__main__":# Launch the Gradio application# This starts the web interface for the training applicationdemo = main()demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223#!/usr/bin/env python3"""OpenLLM Training Space - Main ApplicationThis is the main entry point for the Hugging Face Space.It provides a web interface for running OpenLLM training with authentication.Author: Louis Chua Bean ChongLicense: GPLv3"""import osimport sysimport gradio as grfrom pathlib import Path# Import our authentication and training modulestry:from space_auth_test import test_space_authenticationfrom openllm_training_with_auth import OpenLLMTrainingManagerMODULES_AVAILABLE = Trueexcept ImportError as e:MODULES_AVAILABLE = Falseprint(f"β Required modules not available: {e}")def create_space_interface():"""Create the Gradio interface for the Space."""def run_authentication_test():"""Run the authentication test and return results."""try:if not MODULES_AVAILABLE:return "β Required modules not available. Please check deployment."# Capture output from authentication testimport ioimport contextliboutput = io.StringIO()with contextlib.redirect_stdout(output):success = test_space_authentication()result = output.getvalue()if success:return f"β Authentication Test Results:\n\n{result}"else:return f"β Authentication Test Failed:\n\n{result}"except Exception as e:return f"β Error running authentication test: {e}"def run_training(model_size, training_steps):"""Run the OpenLLM training with authentication."""try:if not MODULES_AVAILABLE:return "β Required modules not available. Please check deployment."# Capture output from trainingimport ioimport contextliboutput = io.StringIO()with contextlib.redirect_stdout(output):training_manager = OpenLLMTrainingManager()repo_id = training_manager.run_training(model_size=model_size,steps=int(training_steps))result = output.getvalue()return f"β Training Results:\n\n{result}\n\nπ Model available at: https://huggingface.co/{repo_id}"except Exception as e:return f"β Error running training: {e}"def check_space_environment():"""Check the Space environment and configuration."""try:# Check if we're in a Spacespace_vars = ["SPACE_ID", "SPACE_HOST", "SPACE_REPO_ID"]is_space = any(os.getenv(var) for var in space_vars)# Check HF_TOKENhf_token = os.getenv("HF_TOKEN")result = "π Space Environment Check:\n\n"if is_space:result += "β Running in Hugging Face Space environment\n"for var in space_vars:value = os.getenv(var)if value:result += f" - {var}: {value}\n"else:result += "βΉοΈ Running in local environment\n"if hf_token:result += f"β HF_TOKEN found: {hf_token[:8]}...{hf_token[-4:]}\n"result += " - Source: GitHub secrets\n"else:result += "β HF_TOKEN not found\n"result += " - Please set HF_TOKEN in GitHub repository secrets\n"result += f"\nπ Available modules: {'β ' if MODULES_AVAILABLE else 'β'}"return resultexcept Exception as e:return f"β Error checking environment: {e}"# Create the Gradio interfacewith gr.Blocks(title="OpenLLM Training Space", theme=gr.themes.Soft()) as interface:gr.Markdown("""# π OpenLLM Training SpaceWelcome to the OpenLLM Training Space! This Space provides a complete environment for training OpenLLM models with automatic Hugging Face authentication and model upload.## π AuthenticationThis Space uses GitHub secrets for secure authentication. The HF_TOKEN is automatically available from your GitHub repository secrets.## π Available Actions1. **Environment Check**: Verify Space configuration and authentication2. **Authentication Test**: Test Hugging Face authentication3. **Run Training**: Start OpenLLM training with automatic upload""")with gr.Tab("π Environment Check"):gr.Markdown("Check the Space environment and configuration.")env_check_btn = gr.Button("Check Environment", variant="primary")env_output = gr.Textbox(label="Environment Status", lines=10, interactive=False)env_check_btn.click(check_space_environment, outputs=env_output)with gr.Tab("π Authentication Test"):gr.Markdown("Test Hugging Face authentication using GitHub secrets.")auth_test_btn = gr.Button("Run Authentication Test", variant="primary")auth_output = gr.Textbox(label="Authentication Results", lines=15, interactive=False)auth_test_btn.click(run_authentication_test, outputs=auth_output)with gr.Tab("π Run Training"):gr.Markdown("""Start OpenLLM training with automatic model upload.**Training Parameters:**- **Model Size**: Choose the model size (small, medium, large)- **Training Steps**: Number of training steps (default: 8000)**Expected Results:**- Training will complete successfully- Model will be uploaded to Hugging Face Hub- Repository will be created with proper model files""")with gr.Row():model_size = gr.Dropdown(choices=["small", "medium", "large"],value="small",label="Model Size",info="Choose the model size for training")training_steps = gr.Number(value=8000,label="Training Steps",info="Number of training steps",minimum=1000,maximum=50000)train_btn = gr.Button("Start Training", variant="primary", size="lg")train_output = gr.Textbox(label="Training Results", lines=20, interactive=False)train_btn.click(run_training,inputs=[model_size, training_steps],outputs=train_output)with gr.Tab("π Documentation"):gr.Markdown("""## π Available Documentation- **HUGGINGFACE_SPACE_SETUP_GUIDE.md**: Complete setup guide- **SPACE_AUTHENTICATION_SUMMARY.md**: Authentication summary- **SPACE_READY_SUMMARY.md**: Deployment summary## π§ Available Scripts- **space_auth_test.py**: Authentication verification- **openllm_training_with_auth.py**: Complete training script- **integrate_auth_into_training.py**: Integration guide- **setup_hf_space_auth.py**: Space authentication setup- **verify_space_auth.py**: Space verification script## π― Quick Start1. Check the environment to verify configuration2. Run authentication test to ensure GitHub secrets are working3. Start training with your desired parameters4. Monitor the training progress and model upload## π Security- HF_TOKEN is securely stored in GitHub repository secrets- No hardcoded tokens in any scripts- Automatic cleanup of test repositories- Proper error handling and logging""")return interfaceif __name__ == "__main__":# Create and launch the interfaceinterface = create_space_interface()interface.launch(server_name="0.0.0.0",server_port=7860,share=False)
app.py+158-959