Spaces:
Build error
Build error
Julian Bilcke commited on
Commit ·
7f039e5
1
Parent(s): 55a4bb8
the HF space got corrupted, here's an attempt at salvaging it
Browse filesFiles changed (2)
809 unmodified lines810811812813814815816817818269 unmodified lines1088108910901091109210933 unmodified lines10971098109911001101110211031104110539 unmodified lines114511461147114811491150115111521153115411551156115711581159320 unmodified lines148014811482148314841485148614871488148914901491149214931494149514966 unmodified lines1503150415051506150715082 unmodified lines15111512151315141515151615177 unmodified lines1525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715484 unmodified lines1553155415551556155715581 unmodified line15601561156215631564156515661567156815691570809 unmodified lines# Update with resume_from_checkpoint if providedif resume_from_checkpoint:config.resume_from_checkpoint = resume_from_checkpointself.append_log(f"Resuming from checkpoint: {resume_from_checkpoint} (will use 'latest')")config.resume_from_checkpoint = "latest"# Common settings for both modelsconfig.mixed_precision = DEFAULT_MIXED_PRECISION269 unmodified linesexcept:return Falsedef recover_interrupted_training(self) -> Dict[str, Any]:"""Attempt to recover interrupted training3 unmodified linesstatus = self.get_status()ui_updates = {}# Check for any checkpoints, even if status doesn't indicate trainingcheckpoints = list(self.app.output_path.glob("finetrainers_step_*"))has_checkpoints = len(checkpoints) > 0# If status indicates training but process isn't running, or if we have checkpoints# and no active training process, try to recover39 unmodified lines}return {"status": "idle", "message": "No training in progress", "ui_updates": ui_updates}# Find the latest checkpoint if we have checkpointslatest_checkpoint = Nonecheckpoint_step = 0if has_checkpoints:# Find the latest checkpoint by step numberlatest_checkpoint = max(checkpoints, key=lambda x: int(x.name.split("_")[-1]))checkpoint_step = int(latest_checkpoint.name.split("_")[-1])logger.info(f"Found checkpoint at step {checkpoint_step}")# both options are valid, but imho it is easier to just return "latest"# under the hood Finetrainers will convert ("latest") to (-1)320 unmodified linesself.append_log(f"Error uploading to hub: {str(e)}")return Falsedef get_model_output_safetensors(self) -> Optional[str]:"""Return the path to the model safetensorsReturns:Path to safetensors file or None if not found"""# Check if the root level file exists (this should be the primary location)model_output_safetensors_path = self.app.output_path / "pytorch_lora_weights.safetensors"if model_output_safetensors_path.exists():return str(model_output_safetensors_path)# Check in lora_weights directorylora_weights_dir = self.app.output_path / "lora_weights"6 unmodified lineslatest_lora_checkpoint = max(lora_checkpoints, key=lambda x: int(x.name))logger.info(f"Found latest LoRA checkpoint: {latest_lora_checkpoint}")# List contents of the latest checkpoint directorycheckpoint_contents = list(latest_lora_checkpoint.glob("*"))logger.info(f"Contents of LoRA checkpoint {latest_lora_checkpoint.name}: {checkpoint_contents}")2 unmodified lineslora_safetensors = latest_lora_checkpoint / "pytorch_lora_weights.safetensors"if lora_safetensors.exists():logger.info(f"Found weights in latest LoRA checkpoint: {lora_safetensors}")return str(lora_safetensors)# Also check for other common weight file namespossible_weight_files = [7 unmodified linesweight_path = latest_lora_checkpoint / weight_fileif weight_path.exists():logger.info(f"Found weights file {weight_file} in latest LoRA checkpoint: {weight_path}")return str(weight_path)# Check if any .safetensors files existsafetensors_files = list(latest_lora_checkpoint.glob("*.safetensors"))if safetensors_files:logger.info(f"Found .safetensors files in LoRA checkpoint: {safetensors_files}")# Return the first .safetensors file foundreturn str(safetensors_files[0])# Fallback: check for direct safetensors file in lora_weights rootlora_safetensors = lora_weights_dir / "pytorch_lora_weights.safetensors"if lora_safetensors.exists():logger.info(f"Found weights in lora_weights directory: {lora_safetensors}")return str(lora_safetensors)else:logger.info(f"pytorch_lora_weights.safetensors not found in lora_weights directory")# If not found in root or lora_weights, log the issuelogger.warning(f"Model weights not found at expected location: {model_output_safetensors_path}")logger.info(f"Checking output directory contents: {list(self.app.output_path.glob('*'))}")4 unmodified lineslatest_checkpoint = max(checkpoints, key=lambda x: int(x.name.split("_")[-1]))logger.info(f"Latest checkpoint directory: {latest_checkpoint}")# Log contents of latest checkpointcheckpoint_contents = list(latest_checkpoint.glob("*"))logger.info(f"Contents of latest checkpoint {latest_checkpoint.name}: {checkpoint_contents}")1 unmodified linecheckpoint_weights = latest_checkpoint / "pytorch_lora_weights.safetensors"if checkpoint_weights.exists():logger.info(f"Found weights in latest checkpoint: {checkpoint_weights}")return str(checkpoint_weights)else:logger.info(f"pytorch_lora_weights.safetensors not found in checkpoint directory")return Nonedef create_training_dataset_zip(self) -> str:"""Create a ZIP file containing all training data809 unmodified lines810811812813814815816817818819820821822823824825826827269 unmodified lines109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211733 unmodified lines11771178117911801181118211831184118539 unmodified lines1225122612271228122912301231123212331234123512361237320 unmodified lines155815591560156115621563156415651566156715681569157015711572157315741575157615776 unmodified lines1584158515861587158815891590159115922 unmodified lines159515961597159815991600160116027 unmodified lines1610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516364 unmodified lines1641164216431644164516461647164816491 unmodified line16511652165316541655165616571658165916601661166216631664166516661667166816691670809 unmodified lines# Update with resume_from_checkpoint if providedif resume_from_checkpoint:# Validate checkpoints and find a valid one to resume fromvalid_checkpoint = self.validate_and_find_valid_checkpoint()if valid_checkpoint:config.resume_from_checkpoint = "latest"checkpoint_step = int(Path(valid_checkpoint).name.split("_")[-1])self.append_log(f"Resuming from validated checkpoint at step {checkpoint_step}")logger.info(f"Resuming from validated checkpoint: {valid_checkpoint}")else:error_msg = "No valid checkpoints found to resume from"logger.error(error_msg)self.append_log(error_msg)return error_msg, "No valid checkpoints available"# Common settings for both modelsconfig.mixed_precision = DEFAULT_MIXED_PRECISION269 unmodified linesexcept:return Falsedef validate_and_find_valid_checkpoint(self) -> Optional[str]:"""Validate checkpoint directories and find the most recent valid oneReturns:Path to valid checkpoint directory or None if no valid checkpoint found"""# Find all checkpoint directoriescheckpoints = list(self.app.output_path.glob("finetrainers_step_*"))if not checkpoints:logger.info("No checkpoint directories found")return None# Sort by step number in descending order (latest first)sorted_checkpoints = sorted(checkpoints, key=lambda x: int(x.name.split("_")[-1]), reverse=True)corrupted_checkpoints = []for checkpoint_dir in sorted_checkpoints:step_num = int(checkpoint_dir.name.split("_")[-1])logger.info(f"Validating checkpoint at step {step_num}: {checkpoint_dir}")# Check if the .metadata file existsmetadata_file = checkpoint_dir / ".metadata"if not metadata_file.exists():logger.warning(f"Checkpoint {checkpoint_dir.name} is corrupted: missing .metadata file")corrupted_checkpoints.append(checkpoint_dir)continue# Try to read the metadata file to ensure it's not corruptedtry:with open(metadata_file, 'r') as f:metadata = json.load(f)# Basic validation - metadata should have expected structureif not isinstance(metadata, dict):raise ValueError("Invalid metadata format")logger.info(f"Checkpoint {checkpoint_dir.name} is valid")# Clean up any corrupted checkpoints we found before this valid oneif corrupted_checkpoints:self.cleanup_corrupted_checkpoints(corrupted_checkpoints)return str(checkpoint_dir)except (json.JSONDecodeError, IOError, ValueError) as e:logger.warning(f"Checkpoint {checkpoint_dir.name} is corrupted: failed to read .metadata: {e}")corrupted_checkpoints.append(checkpoint_dir)continue# If we reach here, all checkpoints are corruptedif corrupted_checkpoints:logger.error("All checkpoint directories are corrupted")self.cleanup_corrupted_checkpoints(corrupted_checkpoints)return Nonedef cleanup_corrupted_checkpoints(self, corrupted_checkpoints: List[Path]) -> None:"""Remove corrupted checkpoint directoriesArgs:corrupted_checkpoints: List of corrupted checkpoint directory paths"""for checkpoint_dir in corrupted_checkpoints:try:step_num = int(checkpoint_dir.name.split("_")[-1])logger.info(f"Removing corrupted checkpoint at step {step_num}: {checkpoint_dir}")shutil.rmtree(checkpoint_dir)self.append_log(f"Removed corrupted checkpoint: {checkpoint_dir.name}")except Exception as e:logger.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 training3 unmodified linesstatus = self.get_status()ui_updates = {}# Check for any valid checkpoints, even if status doesn't indicate trainingvalid_checkpoint = self.validate_and_find_valid_checkpoint()has_checkpoints = valid_checkpoint is not None# If status indicates training but process isn't running, or if we have checkpoints# and no active training process, try to recover39 unmodified lines}return {"status": "idle", "message": "No training in progress", "ui_updates": ui_updates}# Use the valid checkpoint we foundlatest_checkpoint = Nonecheckpoint_step = 0if has_checkpoints and valid_checkpoint:checkpoint_step = int(Path(valid_checkpoint).name.split("_")[-1])logger.info(f"Found valid checkpoint at step {checkpoint_step}")# both options are valid, but imho it is easier to just return "latest"# under the hood Finetrainers will convert ("latest") to (-1)320 unmodified linesself.append_log(f"Error uploading to hub: {str(e)}")return Falsedef get_model_output_info(self) -> Dict[str, Any]:"""Return info about the model safetensors including path and step countReturns:Dict with 'path' (str or None) and 'steps' (int or None)"""result = {"path": None, "steps": None}# Check if the root level file exists (this should be the primary location)model_output_safetensors_path = self.app.output_path / "pytorch_lora_weights.safetensors"if model_output_safetensors_path.exists():result["path"] = str(model_output_safetensors_path)# For root level, we can't determine steps easily, so return Nonereturn result# Check in lora_weights directorylora_weights_dir = self.app.output_path / "lora_weights"6 unmodified lineslatest_lora_checkpoint = max(lora_checkpoints, key=lambda x: int(x.name))logger.info(f"Found latest LoRA checkpoint: {latest_lora_checkpoint}")# Extract step count from directory nameresult["steps"] = int(latest_lora_checkpoint.name)# List contents of the latest checkpoint directorycheckpoint_contents = list(latest_lora_checkpoint.glob("*"))logger.info(f"Contents of LoRA checkpoint {latest_lora_checkpoint.name}: {checkpoint_contents}")2 unmodified lineslora_safetensors = latest_lora_checkpoint / "pytorch_lora_weights.safetensors"if lora_safetensors.exists():logger.info(f"Found weights in latest LoRA checkpoint: {lora_safetensors}")result["path"] = str(lora_safetensors)return result# Also check for other common weight file namespossible_weight_files = [7 unmodified linesweight_path = latest_lora_checkpoint / weight_fileif weight_path.exists():logger.info(f"Found weights file {weight_file} in latest LoRA checkpoint: {weight_path}")result["path"] = str(weight_path)return result# Check if any .safetensors files existsafetensors_files = list(latest_lora_checkpoint.glob("*.safetensors"))if safetensors_files:logger.info(f"Found .safetensors files in LoRA checkpoint: {safetensors_files}")# Return the first .safetensors file foundresult["path"] = str(safetensors_files[0])return result# Fallback: check for direct safetensors file in lora_weights rootlora_safetensors = lora_weights_dir / "pytorch_lora_weights.safetensors"if lora_safetensors.exists():logger.info(f"Found weights in lora_weights directory: {lora_safetensors}")result["path"] = str(lora_safetensors)return resultelse:logger.info(f"pytorch_lora_weights.safetensors not found in lora_weights directory")# If not found in root or lora_weights, log the issue and check fallbacklogger.warning(f"Model weights not found at expected location: {model_output_safetensors_path}")logger.info(f"Checking output directory contents: {list(self.app.output_path.glob('*'))}")4 unmodified lineslatest_checkpoint = max(checkpoints, key=lambda x: int(x.name.split("_")[-1]))logger.info(f"Latest checkpoint directory: {latest_checkpoint}")# Extract step count from checkpoint directory nameresult["steps"] = int(latest_checkpoint.name.split("_")[-1])# Log contents of latest checkpointcheckpoint_contents = list(latest_checkpoint.glob("*"))logger.info(f"Contents of latest checkpoint {latest_checkpoint.name}: {checkpoint_contents}")1 unmodified linecheckpoint_weights = latest_checkpoint / "pytorch_lora_weights.safetensors"if checkpoint_weights.exists():logger.info(f"Found weights in latest checkpoint: {checkpoint_weights}")result["path"] = str(checkpoint_weights)return resultelse:logger.info(f"pytorch_lora_weights.safetensors not found in checkpoint directory")return resultdef get_model_output_safetensors(self) -> Optional[str]:"""Return the path to the model safetensorsReturns:Path to safetensors file or None if not found"""return self.get_model_output_info()["path"]def create_training_dataset_zip(self) -> str:"""Create a ZIP file containing all training data
24 unmodified lines25262728293014 unmodified lines4546474849505124 unmodified linesself.id = "manage_tab"self.title = "5️⃣ Storage"def create(self, parent=None) -> gr.TabItem:"""Create the Manage tab UI components"""with gr.TabItem(self.title, id=self.id) as tab:14 unmodified linesgr.Markdown("📦 Training dataset download disabled for large datasets")self.components["download_model_btn"] = gr.DownloadButton("🧠 Download weights (.safetensors)",variant="secondary",size="lg")24 unmodified lines252627282930313233343536373839404142434445464748495051525354555614 unmodified lines7172737475767724 unmodified linesself.id = "manage_tab"self.title = "5️⃣ Storage"def get_download_button_text(self) -> str:"""Get the dynamic text for the download button based on current model state"""try:model_info = self.app.training.get_model_output_info()if model_info["path"] and model_info["steps"]:return f"🧠 Download weights ({model_info['steps']} steps)"elif model_info["path"]:return "🧠 Download weights (.safetensors)"else:return "🧠 Download weights (not available)"except Exception as e:logger.warning(f"Error getting model info for button text: {e}")return "🧠 Download weights (.safetensors)"def update_download_button_text(self) -> gr.update:"""Update the download button text"""return gr.update(value=self.get_download_button_text())def download_and_update_button(self):"""Handle download and return updated button with current text"""# Get the safetensors path for downloadpath = self.app.training.get_model_output_safetensors()# For DownloadButton, we need to return the file path directly for download# The button text will be updated on next renderreturn pathdef create(self, parent=None) -> gr.TabItem:"""Create the Manage tab UI components"""with gr.TabItem(self.title, id=self.id) as tab:14 unmodified linesgr.Markdown("📦 Training dataset download disabled for large datasets")self.components["download_model_btn"] = gr.DownloadButton(self.get_download_button_text(),variant="secondary",size="lg")
vms/ui/project/services/training.py+123-23
vms/ui/project/tabs/manage_tab.py+27-1