Julian Bilcke commited on
Commit Β·
98352eb
1
Parent(s): 9fd1204
try to crack Finetrainers
Browse filesFiles changed (5)
123456"""Patches module for VideoModelStudio
This module contains monkey patches and modifications for third-party librariesto extend their functionality for our specific use cases."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142"""Monkey patch for Finetrainers to support loading existing LoRA weights as training initialization.
This patch extends the SFTTrainer to accept a --pretrained_lora_path argument that allowsstarting training from existing LoRA weights instead of random initialization."""
import loggingimport jsonfrom typing import Optional, Dict, Anyfrom pathlib import Path
import safetensors.torchfrom peft import set_peft_model_state_dict
logger = logging.getLogger(__name__)
# Global flag to track if patch has been applied_PATCH_APPLIED = False
def _load_pretrained_lora_weights(self, lora_path: str) -> None: """Load existing LoRA weights as training initialization Args: lora_path: Path to directory containing pytorch_lora_weights.safetensors """ lora_path = Path(lora_path) # Find the safetensors file safetensors_file = lora_path / "pytorch_lora_weights.safetensors" if not safetensors_file.exists(): raise FileNotFoundError(f"LoRA weights file not found: {safetensors_file}") logger.info(f"Loading pretrained LoRA weights from: {safetensors_file}") try: # Load the LoRA weights lora_state_dict = safetensors.torch.load_file(str(safetensors_file)) # Extract metadata if available metadata = {} try: with open(safetensors_file, 'rb') as f: # Try to read metadata from safetensors header header_size = int.from_bytes(f.read(8), 'little') header_data = f.read(header_size) header = json.loads(header_data.decode('utf-8')) metadata = header.get('__metadata__', {}) except Exception as e: logger.debug(f"Could not read metadata from safetensors: {e}") # Log metadata info if available if metadata: logger.info(f"LoRA metadata: rank={metadata.get('rank', 'unknown')}, " f"alpha={metadata.get('lora_alpha', 'unknown')}") # Apply the LoRA weights to the model set_peft_model_state_dict(self.transformer, lora_state_dict) logger.info(f"Successfully loaded LoRA weights from {safetensors_file}") # Log the loaded keys for debugging logger.debug(f"Loaded LoRA keys: {list(lora_state_dict.keys())}") except Exception as e: logger.error(f"Failed to load LoRA weights from {safetensors_file}: {e}") raise RuntimeError(f"Failed to load LoRA weights: {e}")
def patched_prepare_trainable_parameters(self) -> None: """Patched version of _prepare_trainable_parameters that supports pretrained LoRA loading""" # Call the original method first original_prepare_trainable_parameters(self) # Check if pretrained LoRA path is provided if hasattr(self.args, 'pretrained_lora_path') and self.args.pretrained_lora_path: logger.info(f"Pretrained LoRA path specified: {self.args.pretrained_lora_path}") # Only load if we're doing LoRA training if hasattr(self.args, 'training_type') and str(self.args.training_type) == 'TrainingType.LORA': self._load_pretrained_lora_weights(self.args.pretrained_lora_path) else: logger.warning("pretrained_lora_path specified but training_type is not LORA")
def apply_lora_loading_patch() -> None: """Apply the monkey patch to enable LoRA weight loading in Finetrainers""" global _PATCH_APPLIED if _PATCH_APPLIED: logger.debug("Finetrainers LoRA loading patch already applied") return try: from finetrainers.trainer.sft_trainer.trainer import SFTTrainer # Store reference to original method global original_prepare_trainable_parameters original_prepare_trainable_parameters = SFTTrainer._prepare_trainable_parameters # Apply patches SFTTrainer._prepare_trainable_parameters = patched_prepare_trainable_parameters SFTTrainer._load_pretrained_lora_weights = _load_pretrained_lora_weights _PATCH_APPLIED = True logger.info("Successfully applied Finetrainers LoRA loading patch") except ImportError as e: logger.error(f"Failed to import Finetrainers classes for patching: {e}") raise except Exception as e: logger.error(f"Failed to apply Finetrainers LoRA loading patch: {e}") raise
def remove_lora_loading_patch() -> None: """Remove the monkey patch (for testing purposes)""" global _PATCH_APPLIED if not _PATCH_APPLIED: return try: from finetrainers.trainer.sft_trainer.trainer import SFTTrainer # Restore original method SFTTrainer._prepare_trainable_parameters = original_prepare_trainable_parameters # Remove added method if hasattr(SFTTrainer, '_load_pretrained_lora_weights'): delattr(SFTTrainer, '_load_pretrained_lora_weights') _PATCH_APPLIED = False logger.info("Removed Finetrainers LoRA loading patch") except Exception as e: logger.error(f"Failed to remove Finetrainers LoRA loading patch: {e}")
# Store reference to original method (will be set when patch is applied)original_prepare_trainable_parameters = None53 unmodified lines54555657585911 unmodified lines717273747576496 unmodified lines573574575576577578243 unmodified lines822823824825826827330 unmodified lines115811591160116111621163329 unmodified lines14931494149514961497149853 unmodified linesprepare_finetrainers_dataset,copy_files_to_training_dir)logger = logging.getLogger(__name__)logger.setLevel(logging.INFO)11 unmodified linesself.file_handler = Noneself.setup_logging()self.ensure_valid_ui_state_file()logger.info("Training service initialized")496 unmodified linesprecomputation_items: int = DEFAULT_PRECOMPUTATION_ITEMS,lr_warmup_steps: int = DEFAULT_NB_LR_WARMUP_STEPS,progress: Optional[gr.Progress] = None,) -> Tuple[str, str]:"""Start training with finetrainers"""243 unmodified lineslogger.error(error_msg)self.append_log(error_msg)return error_msg, "No valid checkpoints available"# Common settings for both modelsconfig.mixed_precision = DEFAULT_MIXED_PRECISION330 unmodified lineslogger.error(f"Failed to remove corrupted checkpoint {checkpoint_dir}: {e}")self.append_log(f"Failed to remove corrupted checkpoint {checkpoint_dir.name}: {e}")def recover_interrupted_training(self) -> Dict[str, Any]:"""Attempt to recover interrupted training329 unmodified linesgr.Info(success_msg)self.save_status(state='completed', message=success_msg)# Upload final model if repository was specifiedsession = self.load_session()if session and session['params'].get('repo_id'):53 unmodified lines5455565758596011 unmodified lines7273747576777879808182838485868788496 unmodified lines585586587588589590591243 unmodified lines835836837838839840841842843844845846847848849850851852853854855856857858859860861862863330 unmodified lines1194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287329 unmodified lines161716181619162016211622162316241625162616271628162953 unmodified linesprepare_finetrainers_dataset,copy_files_to_training_dir)from vms.patches.finetrainers_lora_loading import apply_lora_loading_patchlogger = logging.getLogger(__name__)logger.setLevel(logging.INFO)11 unmodified linesself.file_handler = Noneself.setup_logging()self.ensure_valid_ui_state_file()# Apply Finetrainers patches for LoRA weight loadingtry:apply_lora_loading_patch()except Exception as e:logger.warning(f"Failed to apply Finetrainers LoRA loading patch: {e}")# Start background cleanup taskself._cleanup_stop_event = threading.Event()self._cleanup_thread = threading.Thread(target=self._background_cleanup_task, daemon=True)self._cleanup_thread.start()logger.info("Training service initialized")496 unmodified linesprecomputation_items: int = DEFAULT_PRECOMPUTATION_ITEMS,lr_warmup_steps: int = DEFAULT_NB_LR_WARMUP_STEPS,progress: Optional[gr.Progress] = None,pretrained_lora_path: Optional[str] = None,) -> Tuple[str, str]:"""Start training with finetrainers"""243 unmodified lineslogger.error(error_msg)self.append_log(error_msg)return error_msg, "No valid checkpoints available"# Add pretrained LoRA path if provided (for starting fresh training with existing weights)if pretrained_lora_path:# Validate the LoRA path exists and contains required fileslora_path = Path(pretrained_lora_path)lora_weights_file = lora_path / "pytorch_lora_weights.safetensors"if not lora_path.exists():error_msg = f"Pretrained LoRA path does not exist: {pretrained_lora_path}"logger.error(error_msg)self.append_log(error_msg)return error_msg, "LoRA path not found"if not lora_weights_file.exists():error_msg = f"LoRA weights file not found: {lora_weights_file}"logger.error(error_msg)self.append_log(error_msg)return error_msg, "LoRA weights file missing"# Set the pretrained LoRA path for the patched Finetrainersconfig.pretrained_lora_path = str(lora_path)self.append_log(f"Starting training with pretrained LoRA weights from: {lora_path}")logger.info(f"Using pretrained LoRA weights: {lora_path}")# Common settings for both modelsconfig.mixed_precision = DEFAULT_MIXED_PRECISION330 unmodified lineslogger.error(f"Failed to remove corrupted checkpoint {checkpoint_dir}: {e}")self.append_log(f"Failed to remove corrupted checkpoint {checkpoint_dir.name}: {e}")def cleanup_old_lora_weights(self, max_to_keep: int = 2) -> None:"""Remove old LoRA weight directories, keeping only the most recent onesArgs:max_to_keep: Maximum number of LoRA weight directories to keep (default: 2)"""lora_weights_path = self.app.output_path / "lora_weights"if not lora_weights_path.exists():logger.debug("LoRA weights directory does not exist, nothing to clean up")return# Find all LoRA weight directories (should be named with step numbers)lora_dirs = []for item in lora_weights_path.iterdir():if item.is_dir() and item.name.isdigit():lora_dirs.append(item)if len(lora_dirs) <= max_to_keep:logger.debug(f"Found {len(lora_dirs)} LoRA weight directories, no cleanup needed (keeping {max_to_keep})")return# Sort by step number (directory name) in descending order (newest first)lora_dirs_sorted = sorted(lora_dirs, key=lambda x: int(x.name), reverse=True)# Keep the most recent max_to_keep directories, remove the restdirs_to_keep = lora_dirs_sorted[:max_to_keep]dirs_to_remove = lora_dirs_sorted[max_to_keep:]logger.info(f"Cleaning up old LoRA weights: keeping {len(dirs_to_keep)}, removing {len(dirs_to_remove)}")self.append_log(f"Cleaning up old LoRA weights: keeping latest {max_to_keep} directories")for lora_dir in dirs_to_remove:try:step_num = int(lora_dir.name)logger.info(f"Removing old LoRA weights at step {step_num}: {lora_dir}")shutil.rmtree(lora_dir)self.append_log(f"Removed old LoRA weights: step {step_num}")except Exception as e:logger.error(f"Failed to remove old LoRA weights {lora_dir}: {e}")self.append_log(f"Failed to remove old LoRA weights {lora_dir.name}: {e}")# Log what we keptkept_steps = [int(d.name) for d in dirs_to_keep]kept_steps.sort(reverse=True)logger.info(f"Kept LoRA weights for steps: {kept_steps}")self.append_log(f"Kept LoRA weights for steps: {kept_steps}")def _background_cleanup_task(self) -> None:"""Background task that runs every 10 minutes to clean up old LoRA weights"""cleanup_interval = 600 # 10 minutes in secondslogger.info("Started background LoRA cleanup task (runs every 10 minutes)")while not self._cleanup_stop_event.is_set():try:# Wait for 10 minutes or until stop event is setif self._cleanup_stop_event.wait(timeout=cleanup_interval):break # Stop event was set# Only run cleanup if we have an output pathif hasattr(self.app, 'output_path') and self.app.output_path:lora_weights_path = self.app.output_path / "lora_weights"# Only cleanup if the directory exists and has contentif lora_weights_path.exists():lora_dirs = [d for d in lora_weights_path.iterdir() if d.is_dir() and d.name.isdigit()]if len(lora_dirs) > 2:logger.info(f"Background cleanup: Found {len(lora_dirs)} LoRA weight directories, cleaning up old ones")self.cleanup_old_lora_weights(max_to_keep=2)else:logger.debug(f"Background cleanup: Found {len(lora_dirs)} LoRA weight directories, no cleanup needed")except Exception as e:logger.error(f"Background LoRA cleanup task error: {e}")# Continue running despite errorslogger.info("Background LoRA cleanup task stopped")def stop_background_cleanup(self) -> None:"""Stop the background cleanup task"""if hasattr(self, '_cleanup_stop_event'):self._cleanup_stop_event.set()if hasattr(self, '_cleanup_thread') and self._cleanup_thread.is_alive():self._cleanup_thread.join(timeout=5)logger.info("Background cleanup task stopped")def recover_interrupted_training(self) -> Dict[str, Any]:"""Attempt to recover interrupted training329 unmodified linesgr.Info(success_msg)self.save_status(state='completed', message=success_msg)# Clean up old LoRA weights to save disk spacetry:self.cleanup_old_lora_weights(max_to_keep=2)except Exception as e:logger.warning(f"Failed to cleanup old LoRA weights: {e}")self.append_log(f"Warning: Failed to cleanup old LoRA weights: {e}")# Upload final model if repository was specifiedsession = self.load_session()if session and session['params'].get('repo_id'):
101 unmodified lines102103104105106107117 unmodified lines225226227228229230115 unmodified lines346347348349350351101 unmodified lines"Push my model")with gr.Row():with gr.Column():gr.Markdown("## β»οΈ Delete your data")117 unmodified linesoutputs=[self.components["download_output_btn"]])# Dataset deletion with modalself.components["delete_dataset_btn"].click(fn=lambda: Modal(visible=True),115 unmodified lineselse:return f"Failed to upload model to {repo_id}"def delete_dataset(self):"""Delete dataset files (images, videos, captions)"""status_messages = {}101 unmodified lines102103104105106107108109110111112113114115116117118119117 unmodified lines237238239240241242243244245246247248115 unmodified lines364365366367368369370371372373374375376377378379101 unmodified lines"Push my model")with gr.Row():with gr.Column():gr.Markdown("## π§Ή Maintenance")gr.Markdown("Clean up old files to free disk space.")with gr.Row():self.components["cleanup_lora_btn"] = gr.Button("π Keep last 2 LoRA weights and clean up older ones",variant="secondary",size="lg")with gr.Row():with gr.Column():gr.Markdown("## β»οΈ Delete your data")117 unmodified linesoutputs=[self.components["download_output_btn"]])# LoRA cleanup buttonself.components["cleanup_lora_btn"].click(fn=self.cleanup_old_lora_weights,outputs=[])# Dataset deletion with modalself.components["delete_dataset_btn"].click(fn=lambda: Modal(visible=True),115 unmodified lineselse:return f"Failed to upload model to {repo_id}"def cleanup_old_lora_weights(self):"""Clean up old LoRA weight directories, keeping only the latest 2"""try:self.app.training.cleanup_old_lora_weights(max_to_keep=2)gr.Info("β Successfully cleaned up old LoRA weights")except Exception as e:error_msg = f"β Failed to cleanup LoRA weights: {str(e)}"gr.Error(error_msg)logger.error(f"LoRA cleanup failed: {e}")def delete_dataset(self):"""Delete dataset files (images, videos, captions)"""status_messages = {}
340 unmodified lines3413423433443453463473483493503513528 unmodified lines361362363364365366130 unmodified lines497498499500501502198 unmodified lines70170270370470570673 unmodified lines78078178278378478554 unmodified lines840841842843844845846340 unmodified lines## βοΈ Train your model on your dataset- **π Start new training**: Begins training from scratch (clears previous checkpoints)- **πΈ Start from latest checkpoint**: Continues training from the most recent checkpoint""")with gr.Row():# Check for existing checkpoints to determine button textcheckpoints = list(self.app.output_path.glob("finetrainers_step_*"))has_checkpoints = len(checkpoints) > 0self.components["start_btn"] = gr.Button("π Start new training",8 unmodified linesinteractive=has_checkpoints and not ASK_USER_TO_DUPLICATE_SPACE)with gr.Row():# Just use stop and pause buttons for now to ensure compatibilityself.components["stop_btn"] = gr.Button(130 unmodified linesresume_from_checkpoint="latest")def connect_events(self) -> None:"""Connect event handlers to UI components"""# Model type change event - Update model version dropdown choices and default parameters198 unmodified linesself.components["log_box"]])# Use simplified event handlers for pause/resume and stop73 unmodified linessave_iterations, repo_id,progress=gr.Progress(),resume_from_checkpoint=None,):"""Handle training start with proper log parser reset and checkpoint detection"""54 unmodified linesnum_gpus=num_gpus,precomputation_items=precomputation_items,lr_warmup_steps=lr_warmup_steps,progress=progress)except Exception as e:logger.exception("Error starting training")340 unmodified lines3413423433443453463473483493503513523533543553563573583593608 unmodified lines369370371372373374375376377378379380381130 unmodified lines512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563198 unmodified lines76276376476576676776876977077177277377477577677777877978078178278378478578678773 unmodified lines86186286386486586686754 unmodified lines922923924925926927928929340 unmodified lines## βοΈ Train your model on your dataset- **π Start new training**: Begins training from scratch (clears previous checkpoints)- **πΈ Start from latest checkpoint**: Continues training from the most recent checkpoint- **π Start over using latest LoRA weights**: Start fresh training but use existing LoRA weights as initialization""")with gr.Row():# Check for existing checkpoints to determine button textcheckpoints = list(self.app.output_path.glob("finetrainers_step_*"))has_checkpoints = len(checkpoints) > 0# Check for existing LoRA weightslora_weights_path = self.app.output_path / "lora_weights"has_lora_weights = Falseif lora_weights_path.exists():lora_dirs = [d for d in lora_weights_path.iterdir() if d.is_dir()]has_lora_weights = len(lora_dirs) > 0self.components["start_btn"] = gr.Button("π Start new training",8 unmodified linesinteractive=has_checkpoints and not ASK_USER_TO_DUPLICATE_SPACE)# Add new button for starting from LoRA weightsself.components["start_from_lora_btn"] = gr.Button("π Start over using latest LoRA weights",variant="secondary",interactive=has_lora_weights and not ASK_USER_TO_DUPLICATE_SPACE)with gr.Row():# Just use stop and pause buttons for now to ensure compatibilityself.components["stop_btn"] = gr.Button(130 unmodified linesresume_from_checkpoint="latest")def handle_start_from_lora_training(self, model_type, model_version, training_type,lora_rank, lora_alpha, train_steps, batch_size, learning_rate,save_iterations, repo_id, progress=gr.Progress()):"""Handle starting training from existing LoRA weights"""# Find the latest LoRA weightslora_weights_path = self.app.output_path / "lora_weights"if not lora_weights_path.exists():return "No LoRA weights found", "Please train a model first or start a new training session"# Find the latest LoRA checkpoint directorylora_dirs = sorted([d for d in lora_weights_path.iterdir() if d.is_dir()],key=lambda x: int(x.name), reverse=True)if not lora_dirs:return "No LoRA weight directories found", "Please train a model first or start a new training session"latest_lora_dir = lora_dirs[0]# Verify the LoRA weights file existslora_weights_file = latest_lora_dir / "pytorch_lora_weights.safetensors"if not lora_weights_file.exists():return f"LoRA weights file not found in {latest_lora_dir}", "Please check your LoRA weights directory"# Clear checkpoints to start fresh (but keep LoRA weights)for checkpoint in self.app.output_path.glob("finetrainers_step_*"):if checkpoint.is_dir():shutil.rmtree(checkpoint)# Delete session.json to start freshsession_file = self.app.output_path / "session.json"if session_file.exists():session_file.unlink()self.app.training.append_log(f"Starting training from LoRA weights: {latest_lora_dir}")# Start training with the LoRA weightsreturn self.handle_training_start(model_type, model_version, training_type,lora_rank, lora_alpha, train_steps, batch_size, learning_rate,save_iterations, repo_id, progress,pretrained_lora_path=str(latest_lora_dir))def connect_events(self) -> None:"""Connect event handlers to UI components"""# Model type change event - Update model version dropdown choices and default parameters198 unmodified linesself.components["log_box"]])self.components["start_from_lora_btn"].click(fn=self.handle_start_from_lora_training,inputs=[self.components["model_type"],self.components["model_version"],self.components["training_type"],self.components["lora_rank"],self.components["lora_alpha"],self.components["train_steps"],self.components["batch_size"],self.components["learning_rate"],self.components["save_iterations"],self.app.tabs["manage_tab"].components["repo_id"]],outputs=[self.components["status_box"],self.components["log_box"]])# Use simplified event handlers for pause/resume and stop73 unmodified linessave_iterations, repo_id,progress=gr.Progress(),resume_from_checkpoint=None,pretrained_lora_path=None,):"""Handle training start with proper log parser reset and checkpoint detection"""54 unmodified linesnum_gpus=num_gpus,precomputation_items=precomputation_items,lr_warmup_steps=lr_warmup_steps,progress=progress,pretrained_lora_path=pretrained_lora_path)except Exception as e:logger.exception("Error starting training")
vms/patches/__init__.pyAdded+6
vms/patches/finetrainers_lora_loading.pyAdded+142
vms/ui/project/services/training.py+131
vms/ui/project/tabs/manage_tab.py+28
vms/ui/project/tabs/train_tab.py+84-1