Spaces:
Runtime error
Runtime error
File size: 13,087 Bytes
5dd070e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 |
import streamlit as st
import threading
import random
import time
from datetime import datetime
from utils import add_log, timestamp
# Handle missing dependencies
try:
import torch
import pandas as pd
from transformers import TrainingArguments as HFTrainingArguments
from transformers import Trainer, AutoModelForCausalLM, AutoTokenizer
from datasets import Dataset, DatasetDict
TRANSFORMERS_AVAILABLE = True
except ImportError:
TRANSFORMERS_AVAILABLE = False
HFTrainingArguments = None
# For demo purposes
class DummyTrainer:
def __init__(self, **kwargs):
self.callback = type('obj', (object,), {'__init__': lambda self: None})
def train(self):
pass
def initialize_training_progress(model_id):
"""
Initialize training progress tracking for a model.
Args:
model_id: Identifier for the model
"""
if 'training_progress' not in st.session_state:
st.session_state.training_progress = {}
st.session_state.training_progress[model_id] = {
'status': 'initialized',
'current_epoch': 0,
'total_epochs': 0,
'loss_history': [],
'started_at': timestamp(),
'completed_at': None,
'progress': 0.0
}
def update_training_progress(model_id, epoch=None, loss=None, status=None, progress=None, total_epochs=None):
"""
Update training progress for a model.
Args:
model_id: Identifier for the model
epoch: Current epoch
loss: Current loss value
status: Training status
progress: Progress percentage (0-100)
total_epochs: Total number of epochs
"""
if 'training_progress' not in st.session_state or model_id not in st.session_state.training_progress:
initialize_training_progress(model_id)
progress_data = st.session_state.training_progress[model_id]
if epoch is not None:
progress_data['current_epoch'] = epoch
if loss is not None:
progress_data['loss_history'].append(loss)
if status is not None:
progress_data['status'] = status
if status == 'completed':
progress_data['completed_at'] = timestamp()
progress_data['progress'] = 100.0
if progress is not None:
progress_data['progress'] = progress
if total_epochs is not None:
progress_data['total_epochs'] = total_epochs
def tokenize_dataset(dataset, tokenizer, max_length=512):
"""
Tokenize a dataset for model training.
Args:
dataset: The dataset to tokenize
tokenizer: The tokenizer to use
max_length: Maximum sequence length
Returns:
Dataset: Tokenized dataset
"""
def tokenize_function(examples):
return tokenizer(examples['code'], padding='max_length', truncation=True, max_length=max_length)
tokenized_dataset = dataset.map(tokenize_function, batched=True)
return tokenized_dataset
def train_model_thread(model_id, dataset_name, base_model_name, training_args, device, stop_event):
"""
Thread function for training a model.
Args:
model_id: Identifier for the model
dataset_name: Name of the dataset to use
base_model_name: Base model from Hugging Face
training_args: Training arguments
device: Device to use for training (cpu/cuda)
stop_event: Threading event to signal stopping
"""
try:
# Get dataset
dataset = st.session_state.datasets[dataset_name]['data']
# Initialize model and tokenizer
add_log(f"Initializing model {base_model_name} for training")
tokenizer = AutoTokenizer.from_pretrained(base_model_name)
model = AutoModelForCausalLM.from_pretrained(base_model_name)
# Check if tokenizer has padding token
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
model.config.pad_token_id = model.config.eos_token_id
# Tokenize dataset
add_log(f"Tokenizing dataset {dataset_name}")
train_dataset = tokenize_dataset(dataset['train'], tokenizer)
val_dataset = tokenize_dataset(dataset['validation'], tokenizer)
# Update training progress
update_training_progress(
model_id,
status='running',
total_epochs=training_args.num_train_epochs
)
# Define custom callback to track progress
class CustomCallback(Trainer.callback):
def on_epoch_end(self, args, state, control, **kwargs):
current_epoch = state.epoch
epoch_loss = state.log_history[-1].get('loss', 0)
update_training_progress(
model_id,
epoch=current_epoch,
loss=epoch_loss,
progress=(current_epoch / training_args.num_train_epochs) * 100
)
add_log(f"Epoch {current_epoch}/{training_args.num_train_epochs} completed. Loss: {epoch_loss:.4f}")
# Check if training should be stopped
if stop_event.is_set():
add_log(f"Training for model {model_id} was manually stopped")
control.should_training_stop = True
# Configure training arguments
args = HFTrainingArguments(
output_dir=f"./results/{model_id}",
evaluation_strategy="epoch",
learning_rate=training_args.learning_rate,
per_device_train_batch_size=training_args.batch_size,
per_device_eval_batch_size=training_args.batch_size,
num_train_epochs=training_args.num_train_epochs,
weight_decay=0.01,
save_total_limit=1,
)
# Initialize trainer
trainer = Trainer(
model=model,
args=args,
train_dataset=train_dataset,
eval_dataset=val_dataset,
tokenizer=tokenizer,
callbacks=[CustomCallback]
)
# Train the model
add_log(f"Starting training for model {model_id}")
trainer.train()
# Save the model
if not stop_event.is_set():
add_log(f"Training completed for model {model_id}")
update_training_progress(model_id, status='completed')
# Save to session state
st.session_state.trained_models[model_id] = {
'model': model,
'tokenizer': tokenizer,
'info': {
'id': model_id,
'base_model': base_model_name,
'dataset': dataset_name,
'created_at': timestamp(),
'epochs': training_args.num_train_epochs,
'learning_rate': training_args.learning_rate,
'batch_size': training_args.batch_size
}
}
except Exception as e:
add_log(f"Error during training model {model_id}: {str(e)}", "ERROR")
update_training_progress(model_id, status='failed')
class TrainingArguments:
def __init__(self, learning_rate, batch_size, num_train_epochs):
self.learning_rate = learning_rate
self.batch_size = batch_size
self.num_train_epochs = num_train_epochs
def start_model_training(model_id, dataset_name, base_model_name, learning_rate, batch_size, epochs):
"""
Start model training in a separate thread.
Args:
model_id: Identifier for the model
dataset_name: Name of the dataset to use
base_model_name: Base model from Hugging Face
learning_rate: Learning rate for training
batch_size: Batch size for training
epochs: Number of training epochs
Returns:
threading.Event: Event to signal stopping the training
"""
# Use simulate_training instead if transformers isn't available
if not TRANSFORMERS_AVAILABLE:
add_log("No transformers library available, using simulation mode")
return simulate_training(model_id, dataset_name, base_model_name, epochs)
# Create training arguments
training_args = TrainingArguments(
learning_rate=learning_rate,
batch_size=batch_size,
num_train_epochs=epochs
)
# Determine device
device = "cuda" if torch.cuda.is_available() else "cpu"
add_log(f"Using device: {device}")
# Initialize training progress
initialize_training_progress(model_id)
# Create stop event
stop_event = threading.Event()
# Start training thread
training_thread = threading.Thread(
target=train_model_thread,
args=(model_id, dataset_name, base_model_name, training_args, device, stop_event)
)
training_thread.start()
return stop_event
def stop_model_training(model_id, stop_event):
"""
Stop model training.
Args:
model_id: Identifier for the model
stop_event: Threading event to signal stopping
"""
if stop_event.is_set():
return
add_log(f"Stopping training for model {model_id}")
stop_event.set()
# Update training progress
if 'training_progress' in st.session_state and model_id in st.session_state.training_progress:
progress_data = st.session_state.training_progress[model_id]
if progress_data['status'] == 'running':
progress_data['status'] = 'stopped'
progress_data['completed_at'] = timestamp()
def get_running_training_jobs():
"""
Get list of currently running training jobs.
Returns:
list: List of model IDs with running training jobs
"""
running_jobs = []
if 'training_progress' in st.session_state:
for model_id, progress in st.session_state.training_progress.items():
if progress['status'] == 'running':
running_jobs.append(model_id)
return running_jobs
# For demo purposes - Simulate training progress without actual model training
def simulate_training_thread(model_id, dataset_name, base_model_name, epochs, stop_event):
"""
Simulate training progress for demonstration purposes.
Args:
model_id: Identifier for the model
dataset_name: Name of the dataset to use
base_model_name: Base model from Hugging Face
epochs: Number of training epochs
stop_event: Threading event to signal stopping
"""
add_log(f"Starting simulated training for model {model_id}")
update_training_progress(model_id, status='running', total_epochs=epochs)
for epoch in range(1, epochs + 1):
if stop_event.is_set():
add_log(f"Simulated training for model {model_id} was manually stopped")
update_training_progress(model_id, status='stopped')
return
# Simulate epoch time
time.sleep(2)
# Generate random loss that decreases over time
loss = max(0.1, 2.0 - (epoch / epochs) * 1.5 + random.uniform(-0.1, 0.1))
# Update progress
update_training_progress(
model_id,
epoch=epoch,
loss=loss,
progress=(epoch / epochs) * 100
)
add_log(f"Epoch {epoch}/{epochs} completed. Loss: {loss:.4f}")
# Training completed
add_log(f"Simulated training completed for model {model_id}")
update_training_progress(model_id, status='completed')
# Create dummy model and tokenizer
tokenizer = AutoTokenizer.from_pretrained(base_model_name)
model = AutoModelForCausalLM.from_pretrained(base_model_name)
# Save to session state
st.session_state.trained_models[model_id] = {
'model': model,
'tokenizer': tokenizer,
'info': {
'id': model_id,
'base_model': base_model_name,
'dataset': dataset_name,
'created_at': timestamp(),
'epochs': epochs,
'simulated': True
}
}
def simulate_training(model_id, dataset_name, base_model_name, epochs):
"""
Start simulated training in a separate thread.
Args:
model_id: Identifier for the model
dataset_name: Name of the dataset to use
base_model_name: Base model from Hugging Face
epochs: Number of training epochs
Returns:
threading.Event: Event to signal stopping the training
"""
# Initialize training progress
initialize_training_progress(model_id)
# Create stop event
stop_event = threading.Event()
# Start training thread
training_thread = threading.Thread(
target=simulate_training_thread,
args=(model_id, dataset_name, base_model_name, epochs, stop_event)
)
training_thread.start()
return stop_event
|