Spaces:
Build error
Build error
Julian Bilcke commited on
Commit ·
4cc92e0
1
Parent(s): 71f7495
fix
Browse filesFiles changed (10)
- vms/config.py+10-10
- vms/ui/app_ui.py+30-2
- vms/ui/monitoring/services/monitoring.py+1
- vms/ui/monitoring/tabs/general_tab.py+1-1
- vms/ui/project/services/captioning.py+1
- vms/ui/project/services/previewing.py+123-56
- vms/ui/project/services/splitting.py+1
- vms/ui/project/services/training.py+26-7
- vms/ui/project/tabs/preview_tab.py+147-106
- vms/ui/project/tabs/train_tab.py+112-48
60 unmodified lines616263646566672 unmodified lines7071727374757677264 unmodified lines34234334434534634734866 unmodified lines41541641741841942042115 unmodified lines43743843944044144244315 unmodified lines45946046146246346446513 unmodified lines47948048148248348448516 unmodified lines50250350450550650750850960 unmodified linesMODEL_TYPES = {"HunyuanVideo": "hunyuan_video","LTX-Video": "ltx_video","Wan-2.1-T2V": "wan"}# Training types2 unmodified lines"Full Finetune": "full-finetune"}# Model variants for each model typeMODEL_VARIANTS = {"wan": {"Wan-AI/Wan2.1-T2V-1.3B-Diffusers": {"name": "Wan 2.1 T2V 1.3B (text-only, smaller)",264 unmodified lines# Optional arguments followrevision: Optional[str] = Nonevariant: Optional[str] = Nonecache_dir: Optional[str] = None# Dataset arguments66 unmodified linestrain_steps=DEFAULT_NB_TRAINING_STEPS,lr=2e-5,gradient_checkpointing=True,id_token="afkx",gradient_accumulation_steps=1,lora_rank=DEFAULT_LORA_RANK,lora_alpha=DEFAULT_LORA_ALPHA,15 unmodified linestrain_steps=DEFAULT_NB_TRAINING_STEPS,lr=DEFAULT_LEARNING_RATE,gradient_checkpointing=True,id_token="BW_STYLE",gradient_accumulation_steps=4,lora_rank=DEFAULT_LORA_RANK,lora_alpha=DEFAULT_LORA_ALPHA,15 unmodified linestrain_steps=DEFAULT_NB_TRAINING_STEPS,lr=1e-5,gradient_checkpointing=True,id_token="BW_STYLE",gradient_accumulation_steps=1,video_resolution_buckets=buckets or SMALL_TRAINING_BUCKETS,caption_dropout_p=DEFAULT_CAPTION_DROPOUT_P,13 unmodified linestrain_steps=DEFAULT_NB_TRAINING_STEPS,lr=5e-5,gradient_checkpointing=True,id_token=None, # Default is no ID token for Wangradient_accumulation_steps=1,lora_rank=32,lora_alpha=32,16 unmodified linesargs.extend(["--pretrained_model_name_or_path", self.pretrained_model_name_or_path])if self.revision:args.extend(["--revision", self.revision])if self.variant:args.extend(["--variant", self.variant])if self.cache_dir:args.extend(["--cache_dir", self.cache_dir])60 unmodified lines616263646566672 unmodified lines7071727374757677264 unmodified lines34234334434534634734866 unmodified lines41541641741841942042115 unmodified lines43743843944044144244315 unmodified lines45946046146246346446513 unmodified lines47948048148248348448516 unmodified lines50250350450550650750850960 unmodified linesMODEL_TYPES = {"HunyuanVideo": "hunyuan_video","LTX-Video": "ltx_video","Wan": "wan"}# Training types2 unmodified lines"Full Finetune": "full-finetune"}# Model versions for each model typeMODEL_VERSIONS = {"wan": {"Wan-AI/Wan2.1-T2V-1.3B-Diffusers": {"name": "Wan 2.1 T2V 1.3B (text-only, smaller)",264 unmodified lines# Optional arguments followrevision: Optional[str] = Noneversion: Optional[str] = Nonecache_dir: Optional[str] = None# Dataset arguments66 unmodified linestrain_steps=DEFAULT_NB_TRAINING_STEPS,lr=2e-5,gradient_checkpointing=True,id_token=None,gradient_accumulation_steps=1,lora_rank=DEFAULT_LORA_RANK,lora_alpha=DEFAULT_LORA_ALPHA,15 unmodified linestrain_steps=DEFAULT_NB_TRAINING_STEPS,lr=DEFAULT_LEARNING_RATE,gradient_checkpointing=True,id_token=None,gradient_accumulation_steps=4,lora_rank=DEFAULT_LORA_RANK,lora_alpha=DEFAULT_LORA_ALPHA,15 unmodified linestrain_steps=DEFAULT_NB_TRAINING_STEPS,lr=1e-5,gradient_checkpointing=True,id_token=None,gradient_accumulation_steps=1,video_resolution_buckets=buckets or SMALL_TRAINING_BUCKETS,caption_dropout_p=DEFAULT_CAPTION_DROPOUT_P,13 unmodified linestrain_steps=DEFAULT_NB_TRAINING_STEPS,lr=5e-5,gradient_checkpointing=True,id_token=None,gradient_accumulation_steps=1,lora_rank=32,lora_alpha=32,16 unmodified linesargs.extend(["--pretrained_model_name_or_path", self.pretrained_model_name_or_path])if self.revision:args.extend(["--revision", self.revision])if self.version:args.extend(["--variant", self.version])if self.cache_dir:args.extend(["--cache_dir", self.cache_dir])
7 unmodified lines891011121314205 unmodified lines220221222223224225152 unmodified lines37837938038138238352 unmodified lines43643743843944044111 unmodified lines4534544554564574584594604614627 unmodified linesfrom vms.config import (STORAGE_PATH, VIDEOS_TO_SPLIT_PATH, STAGING_PATH, OUTPUT_PATH,TRAINING_PATH, LOG_FILE_PATH, TRAINING_PRESETS, TRAINING_VIDEOS_PATH, MODEL_PATH, OUTPUT_PATH,MODEL_TYPES, SMALL_TRAINING_BUCKETS, TRAINING_TYPES,DEFAULT_NB_TRAINING_STEPS, DEFAULT_SAVE_CHECKPOINT_EVERY_N_STEPS,DEFAULT_BATCH_SIZE, DEFAULT_CAPTION_DROPOUT_P,DEFAULT_LEARNING_RATE,205 unmodified linesself.project_tabs["train_tab"].components["pause_resume_btn"],self.project_tabs["train_tab"].components["training_preset"],self.project_tabs["train_tab"].components["model_type"],self.project_tabs["train_tab"].components["training_type"],self.project_tabs["train_tab"].components["lora_rank"],self.project_tabs["train_tab"].components["lora_alpha"],152 unmodified linesmodel_type_val = list(MODEL_TYPES.keys())[0]logger.warning(f"Invalid model type '{model_type_val}', using default: {model_type_val}")# Ensure training_type is a valid display nametraining_type_val = ui_state.get("training_type", list(TRAINING_TYPES.keys())[0])if training_type_val not in TRAINING_TYPES:52 unmodified linesdelete_checkpoints_btn,training_preset,model_type_val,training_type_val,lora_rank_val,lora_alpha_val,11 unmodified lines"""Initialize UI components from saved state"""ui_state = self.load_ui_values()# Return values in order matching the outputs in app.loadreturn (ui_state.get("training_preset", list(TRAINING_PRESETS.keys())[0]),ui_state.get("model_type", list(MODEL_TYPES.keys())[0]),ui_state.get("training_type", list(TRAINING_TYPES.keys())[0]),ui_state.get("lora_rank", DEFAULT_LORA_RANK_STR),ui_state.get("lora_alpha", DEFAULT_LORA_ALPHA_STR),7 unmodified lines891011121314205 unmodified lines220221222223224225226152 unmodified lines37938038138238338438538638738838939039139239339439539639739852 unmodified lines45145245345445545645711 unmodified lines4694704714724734744754764774784794804814824834844854864874884894907 unmodified linesfrom vms.config import (STORAGE_PATH, VIDEOS_TO_SPLIT_PATH, STAGING_PATH, OUTPUT_PATH,TRAINING_PATH, LOG_FILE_PATH, TRAINING_PRESETS, TRAINING_VIDEOS_PATH, MODEL_PATH, OUTPUT_PATH,MODEL_TYPES, SMALL_TRAINING_BUCKETS, TRAINING_TYPES, MODEL_VERSIONS,DEFAULT_NB_TRAINING_STEPS, DEFAULT_SAVE_CHECKPOINT_EVERY_N_STEPS,DEFAULT_BATCH_SIZE, DEFAULT_CAPTION_DROPOUT_P,DEFAULT_LEARNING_RATE,205 unmodified linesself.project_tabs["train_tab"].components["pause_resume_btn"],self.project_tabs["train_tab"].components["training_preset"],self.project_tabs["train_tab"].components["model_type"],self.project_tabs["train_tab"].components["model_version"],self.project_tabs["train_tab"].components["training_type"],self.project_tabs["train_tab"].components["lora_rank"],self.project_tabs["train_tab"].components["lora_alpha"],152 unmodified linesmodel_type_val = list(MODEL_TYPES.keys())[0]logger.warning(f"Invalid model type '{model_type_val}', using default: {model_type_val}")# Get model_version valuemodel_version_val = ""# First get the internal model type for the currently selected modelmodel_internal_type = MODEL_TYPES.get(model_type_val)if model_internal_type and model_internal_type in MODEL_VERSIONS:# If there's a saved model_version and it's valid for this model typeif "model_version" in ui_state and ui_state["model_version"] in MODEL_VERSIONS.get(model_internal_type, {}):model_version_val = ui_state["model_version"]else:# Otherwise use the first available versionversions = list(MODEL_VERSIONS.get(model_internal_type, {}).keys())if versions:model_version_val = versions[0]# Ensure training_type is a valid display nametraining_type_val = ui_state.get("training_type", list(TRAINING_TYPES.keys())[0])if training_type_val not in TRAINING_TYPES:52 unmodified linesdelete_checkpoints_btn,training_preset,model_type_val,model_version_val,training_type_val,lora_rank_val,lora_alpha_val,11 unmodified lines"""Initialize UI components from saved state"""ui_state = self.load_ui_values()# Get model type and determine the default model version if not specifiedmodel_type = ui_state.get("model_type", list(MODEL_TYPES.keys())[0])model_internal_type = MODEL_TYPES.get(model_type)# Get model_version, defaulting to first available version if not setmodel_version = ui_state.get("model_version", "")if not model_version and model_internal_type and model_internal_type in MODEL_VERSIONS:versions = list(MODEL_VERSIONS.get(model_internal_type, {}).keys())if versions:model_version = versions[0]# Return values in order matching the outputs in app.loadreturn (ui_state.get("training_preset", list(TRAINING_PRESETS.keys())[0]),model_type,model_version,ui_state.get("training_type", list(TRAINING_TYPES.keys())[0]),ui_state.get("lora_rank", DEFAULT_LORA_RANK_STR),ui_state.get("lora_alpha", DEFAULT_LORA_ALPHA_STR),
21 unmodified lines22232425262721 unmodified linesimport numpy as nplogger = logging.getLogger(__name__)class MonitoringService:"""Service for monitoring system resources and performance"""21 unmodified lines2223242526272821 unmodified linesimport numpy as nplogger = logging.getLogger(__name__)logger.setLevel(logging.INFO)class MonitoringService:"""Service for monitoring system resources and performance"""
16 unmodified lines1718192021222316 unmodified linesfrom vms.ui.monitoring.utils import get_folder_size, human_readable_sizelogger = logging.getLogger(__name__)class GeneralTab(BaseTab):"""Monitor tab for general system resource monitoring"""16 unmodified lines1718192021222316 unmodified linesfrom vms.ui.monitoring.utils import get_folder_size, human_readable_sizelogger = logging.getLogger(__name__)logger.setLevel(logging.INFO)class GeneralTab(BaseTab):"""Monitor tab for general system resource monitoring"""
20 unmodified lines21222324252620 unmodified linesfrom vms.utils import extract_scene_info, is_image_file, is_video_file, copy_files_to_training_dir, prepare_finetrainers_datasetlogger = logging.getLogger(__name__)@dataclassclass CaptioningProgress:20 unmodified lines2122232425262720 unmodified linesfrom vms.utils import extract_scene_info, is_image_file, is_video_file, copy_files_to_training_dir, prepare_finetrainers_datasetlogger = logging.getLogger(__name__)logger.setLevel(logging.INFO)@dataclassclass CaptioningProgress:
5 unmodified lines67891011121314151617181920212225 unmodified lines48495051525354555657585960614 unmodified lines6667686970717273747576777823 unmodified lines1021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331342 unmodified lines13713813914014114214314414514614714814915015115215315415515615715814 unmodified lines1731741751761771781791801811821831841851861871883 unmodified lines1921931941951961971981992002012022032042057 unmodified lines2132142152162172182192202212222232 unmodified lines22622722822923023123210 unmodified lines2432442452462472485 unmodified lines25425525625725825914 unmodified lines2742752762772782792802812822832846 unmodified lines29129229329429529629729829930030130230330430530630730830931031131231331431531631724 unmodified lines34234334434534634731 unmodified lines3793803813823833843853863873881 unmodified line39039139239339439539639739839940040140240340440540640740840941041141241332 unmodified lines4464474484494504515 unmodified linesimport loggingimport tempfilefrom pathlib import Pathfrom typing import Dict, Any, List, Optional, Tuple, Callableimport timefrom vms.config import (OUTPUT_PATH, STORAGE_PATH, MODEL_TYPES, TRAINING_PATH,DEFAULT_PROMPT_PREFIX, MODEL_VARIANTS)from vms.utils import format_timelogger = logging.getLogger(__name__)class PreviewingService:"""Handles the video generation logic and model integration"""25 unmodified lineslogger.error(f"Error finding LoRA weights: {e}")return Nonedef get_model_variants(self, model_type: str) -> Dict[str, Dict[str, str]]:"""Get available model variants for the given model type"""return MODEL_VARIANTS.get(model_type, {})def generate_video(self,model_type: str,model_variant: str,prompt: str,negative_prompt: str,prompt_prefix: str,4 unmodified linesflow_shift: float,lora_weight: float,inference_steps: int,enable_cpu_offload: bool,fps: int,conditioning_image: Optional[str] = None) -> Tuple[Optional[str], str, str]:"""Generate a video using the trained model"""try:log_messages = []def log(msg: str):log_messages.append(msg)23 unmodified linesif not internal_model_type:return None, f"Error: Invalid model type {model_type}", log(f"Error: Invalid model type {model_type}")# Check if model variant is valid for this model typevariants = self.get_model_variants(internal_model_type)if model_variant not in variants:# Use default variant if specified one is invalidif len(variants) > 0:model_variant = next(iter(variants.keys()))log(f"Warning: Invalid model variant, using default: {model_variant}")else:# Fall back to default IDs if no variants definedif internal_model_type == "wan":model_variant = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"elif internal_model_type == "ltx_video":model_variant = "Lightricks/LTX-Video"elif internal_model_type == "hunyuan_video":model_variant = "hunyuanvideo-community/HunyuanVideo"log(f"Warning: No variants defined for model type, using default: {model_variant}")# Check if this is an image-to-video model but no image was providedvariant_info = variants.get(model_variant, {})if variant_info.get("type") == "image-to-video" and not conditioning_image:return None, "Error: This model requires a conditioning image", log("Error: This model variant requires a conditioning image but none was provided")log(f"Generating video with model type: {internal_model_type}")log(f"Using model variant: {model_variant}")log(f"Using LoRA weights from: {lora_path}")log(f"Resolution: {width}x{height}, Frames: {num_frames}, FPS: {fps}")log(f"Guidance Scale: {guidance_scale}, Flow Shift: {flow_shift}, LoRA Weight: {lora_weight}")log(f"Prompt: {full_prompt}")log(f"Negative Prompt: {negative_prompt}")2 unmodified linesreturn self.generate_wan_video(full_prompt, negative_prompt, width, height, num_frames,guidance_scale, flow_shift, lora_path, lora_weight,inference_steps, enable_cpu_offload, fps, log,model_variant, conditioning_image)elif internal_model_type == "ltx_video":return self.generate_ltx_video(full_prompt, negative_prompt, width, height, num_frames,guidance_scale, flow_shift, lora_path, lora_weight,inference_steps, enable_cpu_offload, fps, log,model_variant, conditioning_image)elif internal_model_type == "hunyuan_video":return self.generate_hunyuan_video(full_prompt, negative_prompt, width, height, num_frames,guidance_scale, flow_shift, lora_path, lora_weight,inference_steps, enable_cpu_offload, fps, log,model_variant, conditioning_image)else:return None, f"Error: Unsupported model type {internal_model_type}", log(f"Error: Unsupported model type {internal_model_type}")14 unmodified lineslora_path: str,lora_weight: float,inference_steps: int,enable_cpu_offload: bool,fps: int,log_fn: Callable,model_variant: str = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",conditioning_image: Optional[str] = None) -> Tuple[Optional[str], str, str]:"""Generate video using Wan model"""try:import torchfrom diffusers import AutoencoderKLWan, WanPipelinefrom diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepSchedulerfrom diffusers.utils import export_to_video3 unmodified linesstart_time = torch.cuda.Event(enable_timing=True)end_time = torch.cuda.Event(enable_timing=True)log_fn("Importing Wan model components...")log_fn(f"Loading VAE from {model_variant}...")vae = AutoencoderKLWan.from_pretrained(model_variant, subfolder="vae", torch_dtype=torch.float32)log_fn(f"Loading transformer from {model_variant}...")pipe = WanPipeline.from_pretrained(model_variant, vae=vae, torch_dtype=torch.bfloat16)log_fn(f"Configuring scheduler with flow_shift={flow_shift}...")pipe.scheduler = UniPCMultistepScheduler.from_config(7 unmodified linesif enable_cpu_offload:log_fn("Enabling model CPU offload...")pipe.enable_model_cpu_offload()log_fn(f"Loading LoRA weights from {lora_path} with weight {lora_weight}...")pipe.load_lora_weights(lora_path)pipe.fuse_lora(lora_weight)# Create temporary file for the outputwith tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_file:output_path = temp_file.name2 unmodified linesstart_time.record()# Check if this is an image-to-video modelis_i2v = "I2V" in model_variantif is_i2v and conditioning_image:log_fn(f"Loading conditioning image from {conditioning_image}...")10 unmodified linesnum_frames=num_frames,guidance_scale=guidance_scale,num_inference_steps=inference_steps,).frames[0]else:log_fn("Generating video with text-only conditioning...")5 unmodified linesnum_frames=num_frames,guidance_scale=guidance_scale,num_inference_steps=inference_steps,).frames[0]end_time.record()14 unmodified linesreturn output_path, "Video generated successfully!", log_fn(f"Generation completed in {format_time(generation_time)}")except Exception as e:log_fn(f"Error generating video with Wan: {str(e)}")# Clean up CUDA memorytorch.cuda.empty_cache()return None, f"Error: {str(e)}", log_fn(f"Exception occurred: {str(e)}")def generate_ltx_video(self,prompt: str,6 unmodified lineslora_path: str,lora_weight: float,inference_steps: int,enable_cpu_offload: bool,fps: int,log_fn: Callable,model_variant: str = "Lightricks/LTX-Video",conditioning_image: Optional[str] = None) -> Tuple[Optional[str], str, str]:"""Generate video using LTX model"""try:import torchfrom diffusers import LTXPipelinefrom diffusers.utils import export_to_videofrom PIL import Imagestart_time = torch.cuda.Event(enable_timing=True)end_time = torch.cuda.Event(enable_timing=True)log_fn("Importing LTX model components...")log_fn(f"Loading pipeline from {model_variant}...")pipe = LTXPipeline.from_pretrained(model_variant, torch_dtype=torch.bfloat16)log_fn("Moving pipeline to CUDA device...")pipe.to("cuda")24 unmodified linesdecode_timestep=0.03,decode_noise_scale=0.025,num_inference_steps=inference_steps,).frames[0]end_time.record()31 unmodified lineslora_path: str,lora_weight: float,inference_steps: int,enable_cpu_offload: bool,fps: int,log_fn: Callable,model_variant: str = "hunyuanvideo-community/HunyuanVideo",conditioning_image: Optional[str] = None) -> Tuple[Optional[str], str, str]:"""Generate video using HunyuanVideo model"""1 unmodified linetry:import torchfrom diffusers import HunyuanVideoPipeline, HunyuanVideoTransformer3DModel, AutoencoderKLHunyuanVideofrom diffusers.utils import export_to_videostart_time = torch.cuda.Event(enable_timing=True)end_time = torch.cuda.Event(enable_timing=True)log_fn("Importing HunyuanVideo model components...")log_fn(f"Loading transformer from {model_variant}...")transformer = HunyuanVideoTransformer3DModel.from_pretrained(model_variant,subfolder="transformer",torch_dtype=torch.bfloat16)log_fn(f"Loading pipeline from {model_variant}...")pipe = HunyuanVideoPipeline.from_pretrained(model_variant,transformer=transformer,torch_dtype=torch.float16)32 unmodified linesguidance_scale=guidance_scale,true_cfg_scale=1.0,num_inference_steps=inference_steps,).frames[0]end_time.record()5 unmodified lines67891011121314151617181920212223242525 unmodified lines51525354555657585960616263644 unmodified lines69707172737475767778798081828323 unmodified lines1071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511522 unmodified lines15515615715815916016116216316416516616716816917017117217317417517614 unmodified lines1911921931941951961971981992002012022032042052062072083 unmodified lines2122132142152162172182192202212222232242252262272282292302312322332342352362377 unmodified lines2452462472482492502512522532542552562572 unmodified lines26026126226326426526610 unmodified lines2772782792802812822835 unmodified lines28929029129229329429514 unmodified lines3103113123133143153163173183193203216 unmodified lines32832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736824 unmodified lines39339439539639739839931 unmodified lines4314324334344354364374384394404411 unmodified line44344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847932 unmodified lines5125135145155165175185 unmodified linesimport loggingimport tempfileimport tracebackimport randomfrom pathlib import Pathfrom typing import Dict, Any, List, Optional, Tuple, Callableimport timefrom vms.config import (OUTPUT_PATH, STORAGE_PATH, MODEL_TYPES, TRAINING_PATH,DEFAULT_PROMPT_PREFIX, MODEL_VERSIONS)from vms.utils import format_timelogger = logging.getLogger(__name__)logger.setLevel(logging.INFO)class PreviewingService:"""Handles the video generation logic and model integration"""25 unmodified lineslogger.error(f"Error finding LoRA weights: {e}")return Nonedef get_model_versions(self, model_type: str) -> Dict[str, Dict[str, str]]:"""Get available model versions for the given model type"""return MODEL_VERSIONS.get(model_type, {})def generate_video(self,model_type: str,model_version: str,prompt: str,negative_prompt: str,prompt_prefix: str,4 unmodified linesflow_shift: float,lora_weight: float,inference_steps: int,seed: int = -1,enable_cpu_offload: bool = True,fps: int = 16,conditioning_image: Optional[str] = None) -> Tuple[Optional[str], str, str]:"""Generate a video using the trained model"""try:log_messages = []print("generate_video")def log(msg: str):log_messages.append(msg)23 unmodified linesif not internal_model_type:return None, f"Error: Invalid model type {model_type}", log(f"Error: Invalid model type {model_type}")# Check if model version is valid# This section uses model_version directly from parameterif model_version:# Verify that the specified model_version exists in our versionsversions = self.get_model_versions(internal_model_type)if model_version not in versions:log(f"Warning: Specified model version '{model_version}' is not recognized")# Fall back to default version for this modelif len(versions) > 0:model_version = next(iter(versions.keys()))log(f"Using default model version instead: {model_version}")else:log(f"Using specified model version: {model_version}")else:# No model version specified, use defaultversions = self.get_model_versions(internal_model_type)if len(versions) > 0:model_version = next(iter(versions.keys()))log(f"No model version specified, using default: {model_version}")else:# Fall back to hardcoded defaults if no versions definedif internal_model_type == "wan":model_version = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"elif internal_model_type == "ltx_video":model_version = "Lightricks/LTX-Video"elif internal_model_type == "hunyuan_video":model_version = "hunyuanvideo-community/HunyuanVideo"log(f"No versions defined for model type, using default: {model_version}")# Check if this is an image-to-video model but no image was providedmodel_version_info = versions.get(model_version, {})if model_version_info.get("type") == "image-to-video" and not conditioning_image:return None, "Error: This model requires a conditioning image", log("Error: This model version requires a conditioning image but none was provided")log(f"Generating video with model type: {internal_model_type}")log(f"Using model version: {model_version}")log(f"Using LoRA weights from: {lora_path}")log(f"Resolution: {width}x{height}, Frames: {num_frames}, FPS: {fps}")log(f"Guidance Scale: {guidance_scale}, Flow Shift: {flow_shift}, LoRA Weight: {lora_weight}")log(f"Generation Seed: {seed}")log(f"Prompt: {full_prompt}")log(f"Negative Prompt: {negative_prompt}")2 unmodified linesreturn self.generate_wan_video(full_prompt, negative_prompt, width, height, num_frames,guidance_scale, flow_shift, lora_path, lora_weight,inference_steps, seed, enable_cpu_offload, fps, log,model_version, conditioning_image)elif internal_model_type == "ltx_video":return self.generate_ltx_video(full_prompt, negative_prompt, width, height, num_frames,guidance_scale, flow_shift, lora_path, lora_weight,inference_steps, seed, enable_cpu_offload, fps, log,model_version, conditioning_image)elif internal_model_type == "hunyuan_video":return self.generate_hunyuan_video(full_prompt, negative_prompt, width, height, num_frames,guidance_scale, flow_shift, lora_path, lora_weight,inference_steps, seed, enable_cpu_offload, fps, log,model_version, conditioning_image)else:return None, f"Error: Unsupported model type {internal_model_type}", log(f"Error: Unsupported model type {internal_model_type}")14 unmodified lineslora_path: str,lora_weight: float,inference_steps: int,seed: int = -1,enable_cpu_offload: bool = True,fps: int = 16,log_fn: Callable = print,model_version: str = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",conditioning_image: Optional[str] = None) -> Tuple[Optional[str], str, str]:"""Generate video using Wan model"""try:import torchimport numpy as npfrom diffusers import AutoencoderKLWan, WanPipelinefrom diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepSchedulerfrom diffusers.utils import export_to_video3 unmodified linesstart_time = torch.cuda.Event(enable_timing=True)end_time = torch.cuda.Event(enable_timing=True)print("Initializing wan generation..")log_fn("Importing Wan model components...")# Set up random seedif seed == -1:seed = random.randint(0, 2**32 - 1)log_fn(f"Using randomly generated seed: {seed}")# Set random seeds for reproducibilityrandom.seed(seed)np.random.seed(seed)torch.manual_seed(seed)generator = torch.Generator(device="cuda")generator = generator.manual_seed(seed)log_fn(f"Loading VAE from {model_version}...")vae = AutoencoderKLWan.from_pretrained(model_version, subfolder="vae", torch_dtype=torch.float32)log_fn(f"Loading transformer from {model_version}...")pipe = WanPipeline.from_pretrained(model_version, vae=vae, torch_dtype=torch.bfloat16)log_fn(f"Configuring scheduler with flow_shift={flow_shift}...")pipe.scheduler = UniPCMultistepScheduler.from_config(7 unmodified linesif enable_cpu_offload:log_fn("Enabling model CPU offload...")pipe.enable_model_cpu_offload()log_fn(f"Loading LoRA weights from {lora_path} with weight {lora_weight}...")pipe.load_lora_weights(lora_path)# TODO: Set the lora scale directly instead of using fuse_lora#pipe._lora_scale = lora_weight# Create temporary file for the outputwith tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_file:output_path = temp_file.name2 unmodified linesstart_time.record()# Check if this is an image-to-video modelis_i2v = "I2V" in model_versionif is_i2v and conditioning_image:log_fn(f"Loading conditioning image from {conditioning_image}...")10 unmodified linesnum_frames=num_frames,guidance_scale=guidance_scale,num_inference_steps=inference_steps,generator=generator,).frames[0]else:log_fn("Generating video with text-only conditioning...")5 unmodified linesnum_frames=num_frames,guidance_scale=guidance_scale,num_inference_steps=inference_steps,generator=generator,).frames[0]end_time.record()14 unmodified linesreturn output_path, "Video generated successfully!", log_fn(f"Generation completed in {format_time(generation_time)}")except Exception as e:traceback.print_exc()log_fn(f"Error generating video with Wan: {str(e)}")# Clean up CUDA memorytorch.cuda.empty_cache()return None, f"Error: {str(e)}", log_fn(f"Exception occurred: {str(e)}")def generate_ltx_video(self,prompt: str,6 unmodified lineslora_path: str,lora_weight: float,inference_steps: int,seed: int = -1,enable_cpu_offload: bool = True,fps: int = 16,log_fn: Callable = print,model_version: str = "Lightricks/LTX-Video",conditioning_image: Optional[str] = None) -> Tuple[Optional[str], str, str]:"""Generate video using LTX model"""try:import torchimport numpy as npfrom diffusers import LTXPipelinefrom diffusers.utils import export_to_videofrom PIL import Imagestart_time = torch.cuda.Event(enable_timing=True)end_time = torch.cuda.Event(enable_timing=True)# Set up random seedif seed == -1:seed = random.randint(0, 2**32 - 1)log_fn(f"Using randomly generated seed: {seed}")# Set random seeds for reproducibilityrandom.seed(seed)np.random.seed(seed)torch.manual_seed(seed)generator = torch.Generator(device="cuda")generator = generator.manual_seed(seed)log_fn("Importing LTX model components...")log_fn(f"Loading pipeline from {model_version}...")pipe = LTXPipeline.from_pretrained(model_version, torch_dtype=torch.bfloat16)log_fn("Moving pipeline to CUDA device...")pipe.to("cuda")24 unmodified linesdecode_timestep=0.03,decode_noise_scale=0.025,num_inference_steps=inference_steps,generator=generator,).frames[0]end_time.record()31 unmodified lineslora_path: str,lora_weight: float,inference_steps: int,seed: int = -1,enable_cpu_offload: bool = True,fps: int = 16,log_fn: Callable = print,model_version: str = "hunyuanvideo-community/HunyuanVideo",conditioning_image: Optional[str] = None) -> Tuple[Optional[str], str, str]:"""Generate video using HunyuanVideo model"""1 unmodified linetry:import torchimport numpy as npfrom diffusers import HunyuanVideoPipeline, HunyuanVideoTransformer3DModel, AutoencoderKLHunyuanVideofrom diffusers.utils import export_to_videostart_time = torch.cuda.Event(enable_timing=True)end_time = torch.cuda.Event(enable_timing=True)# Set up random seedif seed == -1:seed = random.randint(0, 2**32 - 1)log_fn(f"Using randomly generated seed: {seed}")# Set random seeds for reproducibilityrandom.seed(seed)np.random.seed(seed)torch.manual_seed(seed)generator = torch.Generator(device="cuda")generator = generator.manual_seed(seed)log_fn("Importing HunyuanVideo model components...")log_fn(f"Loading transformer from {model_version}...")transformer = HunyuanVideoTransformer3DModel.from_pretrained(model_version,subfolder="transformer",torch_dtype=torch.bfloat16)log_fn(f"Loading pipeline from {model_version}...")pipe = HunyuanVideoPipeline.from_pretrained(model_version,transformer=transformer,torch_dtype=torch.float16)32 unmodified linesguidance_scale=guidance_scale,true_cfg_scale=1.0,num_inference_steps=inference_steps,generator=generator,).frames[0]end_time.record()
15 unmodified lines16171819202115 unmodified linesfrom vms.utils import remove_black_bars, extract_scene_info, is_video_file, is_image_file, add_prefix_to_captionlogger = logging.getLogger(__name__)class SplittingService:def __init__(self):15 unmodified lines1617181920212215 unmodified linesfrom vms.utils import remove_black_bars, extract_scene_info, is_video_file, is_image_file, add_prefix_to_captionlogger = logging.getLogger(__name__)logger.setLevel(logging.INFO)class SplittingService:def __init__(self):
22 unmodified lines2324252627282920 unmodified lines50515253545578 unmodified lines13413513613713813973 unmodified lines21321421521621721836 unmodified lines25525625725825926026140 unmodified lines302303304305306307237 unmodified lines545546547548549550318 unmodified lines869870871872873874164 unmodified lines10391040104110421043104457 unmodified lines1102110311041105110611071108110912 unmodified lines11221123112411251126112711281129113011311132113311341135113611371138113911401 unmodified line114211431144114511461147114822 unmodified linesfrom vms.config import (TrainingConfig, TRAINING_PRESETS, LOG_FILE_PATH, TRAINING_VIDEOS_PATH,STORAGE_PATH, TRAINING_PATH, MODEL_PATH, OUTPUT_PATH, HF_API_TOKEN,MODEL_TYPES, TRAINING_TYPES,DEFAULT_NB_TRAINING_STEPS, DEFAULT_SAVE_CHECKPOINT_EVERY_N_STEPS,DEFAULT_BATCH_SIZE, DEFAULT_CAPTION_DROPOUT_P,DEFAULT_LEARNING_RATE,20 unmodified lines)logger = logging.getLogger(__name__)class TrainingService:def __init__(self, app=None):78 unmodified linesvalidated_values = {}default_state = {"model_type": list(MODEL_TYPES.keys())[0],"training_type": list(TRAINING_TYPES.keys())[0],"lora_rank": DEFAULT_LORA_RANK_STR,"lora_alpha": DEFAULT_LORA_ALPHA_STR,73 unmodified linesui_state_file = OUTPUT_PATH / "ui_state.json"default_state = {"model_type": list(MODEL_TYPES.keys())[0],"training_type": list(TRAINING_TYPES.keys())[0],"lora_rank": DEFAULT_LORA_RANK_STR,"lora_alpha": DEFAULT_LORA_ALPHA_STR,36 unmodified linesif "model_type" in saved_state and " (LoRA)" in saved_state["model_type"]:saved_state["model_type"] = saved_state["model_type"].replace(" (LoRA)", "")logger.info(f"Removed (LoRA) suffix from saved model type: {saved_state['model_type']}")# Convert numeric values to appropriate typesif "train_steps" in saved_state:try:40 unmodified linesif not model_found:merged_state["model_type"] = default_state["model_type"]logger.warning(f"Invalid model type in saved state, using default")# Validate training_type is in available choicesif merged_state["training_type"] not in TRAINING_TYPES:237 unmodified linesrepo_id: str,preset_name: str,training_type: str = DEFAULT_TRAINING_TYPE,resume_from_checkpoint: Optional[str] = None,num_gpus: int = DEFAULT_NUM_GPUS,precomputation_items: int = DEFAULT_PRECOMPUTATION_ITEMS,318 unmodified lines# Save session info including repo_id for later hub uploadself.save_session({"model_type": model_type,"training_type": training_type,"lora_rank": lora_rank,"lora_alpha": lora_alpha,164 unmodified lineslast_session = {"params": {"model_type": MODEL_TYPES.get(ui_state.get("model_type", list(MODEL_TYPES.keys())[0])),"training_type": TRAINING_TYPES.get(ui_state.get("training_type", list(TRAINING_TYPES.keys())[0])),"lora_rank": ui_state.get("lora_rank", DEFAULT_LORA_RANK_STR),"lora_alpha": ui_state.get("lora_alpha", DEFAULT_LORA_ALPHA_STR),57 unmodified lines# Add UI updates to restore the training parameters in the UI# This shows the user what values are being used for the resumed trainingui_updates.update({"model_type": model_type_display, # Use the display name for the UI dropdown"training_type": training_type_display, # Use the display name for training type"lora_rank": params.get('lora_rank', DEFAULT_LORA_RANK_STR),"lora_alpha": params.get('lora_alpha', DEFAULT_LORA_ALPHA_STR),"train_steps": params.get('train_steps', DEFAULT_NB_TRAINING_STEPS),12 unmodified lines# Use the internal model_type for the actual training# But keep model_type_display for the UIresult = self.start_training(model_type=model_type_internal,lora_rank=params.get('lora_rank', DEFAULT_LORA_RANK_STR),lora_alpha=params.get('lora_alpha', DEFAULT_LORA_ALPHA_STR),train_size=params.get('train_steps', DEFAULT_NB_TRAINING_STEPS),batch_size=params.get('batch_size', DEFAULT_BATCH_SIZE),learning_rate=params.get('learning_rate', DEFAULT_LEARNING_RATE),save_iterations=params.get('save_iterations', DEFAULT_SAVE_CHECKPOINT_EVERY_N_STEPS),repo_id=params.get('repo_id', ''),preset_name=params.get('preset_name', list(TRAINING_PRESETS.keys())[0]),training_type=training_type_internal,resume_from_checkpoint=str(latest_checkpoint))# Set buttons for active trainingui_updates.update({"start_btn": {"interactive": False, "variant": "secondary", "value": "Continue Training"},1 unmodified line"delete_checkpoints_btn": {"interactive": False, "variant": "stop", "value": "Delete All Checkpoints"},"pause_resume_btn": {"interactive": False, "variant": "secondary", "visible": False}})return {"status": "recovered","message": f"Training resumed from checkpoint {checkpoint_step}",22 unmodified lines2324252627282920 unmodified lines5051525354555678 unmodified lines13513613713813914014173 unmodified lines21521621721821922022136 unmodified lines25825926026126226326440 unmodified lines305306307308309310311312313314315316317318319320321322237 unmodified lines560561562563564565566318 unmodified lines885886887888889890891164 unmodified lines105610571058105910601061106257 unmodified lines11201121112211231124112511261127112812 unmodified lines11411142114311441145114611471148114911501151115211531154115511561157115811591 unmodified line116111621163116411651166116722 unmodified linesfrom vms.config import (TrainingConfig, TRAINING_PRESETS, LOG_FILE_PATH, TRAINING_VIDEOS_PATH,STORAGE_PATH, TRAINING_PATH, MODEL_PATH, OUTPUT_PATH, HF_API_TOKEN,MODEL_TYPES, TRAINING_TYPES, MODEL_VERSIONS,DEFAULT_NB_TRAINING_STEPS, DEFAULT_SAVE_CHECKPOINT_EVERY_N_STEPS,DEFAULT_BATCH_SIZE, DEFAULT_CAPTION_DROPOUT_P,DEFAULT_LEARNING_RATE,20 unmodified lines)logger = logging.getLogger(__name__)logger.setLevel(logging.INFO)class TrainingService:def __init__(self, app=None):78 unmodified linesvalidated_values = {}default_state = {"model_type": list(MODEL_TYPES.keys())[0],"model_version": "","training_type": list(TRAINING_TYPES.keys())[0],"lora_rank": DEFAULT_LORA_RANK_STR,"lora_alpha": DEFAULT_LORA_ALPHA_STR,73 unmodified linesui_state_file = OUTPUT_PATH / "ui_state.json"default_state = {"model_type": list(MODEL_TYPES.keys())[0],"model_version": "","training_type": list(TRAINING_TYPES.keys())[0],"lora_rank": DEFAULT_LORA_RANK_STR,"lora_alpha": DEFAULT_LORA_ALPHA_STR,36 unmodified linesif "model_type" in saved_state and " (LoRA)" in saved_state["model_type"]:saved_state["model_type"] = saved_state["model_type"].replace(" (LoRA)", "")logger.info(f"Removed (LoRA) suffix from saved model type: {saved_state['model_type']}")# Convert numeric values to appropriate typesif "train_steps" in saved_state:try:40 unmodified linesif not model_found:merged_state["model_type"] = default_state["model_type"]logger.warning(f"Invalid model type in saved state, using default")# Validate model_version is appropriate for model_typeif "model_type" in merged_state and "model_version" in merged_state:model_internal_type = MODEL_TYPES.get(merged_state["model_type"])if model_internal_type:valid_versions = MODEL_VERSIONS.get(model_internal_type, {}).keys()if merged_state["model_version"] not in valid_versions:# Set to default for this model typefrom vms.ui.project.tabs.train_tab import TrainTabtrain_tab = TrainTab(None) # Temporary instance just for the helper methodmerged_state["model_version"] = train_tab.get_default_model_version(saved_state["model_type"])logger.warning(f"Invalid model version for {merged_state['model_type']}, using default")# Validate training_type is in available choicesif merged_state["training_type"] not in TRAINING_TYPES:237 unmodified linesrepo_id: str,preset_name: str,training_type: str = DEFAULT_TRAINING_TYPE,model_version: str = "",resume_from_checkpoint: Optional[str] = None,num_gpus: int = DEFAULT_NUM_GPUS,precomputation_items: int = DEFAULT_PRECOMPUTATION_ITEMS,318 unmodified lines# Save session info including repo_id for later hub uploadself.save_session({"model_type": model_type,"model_version": model_version,"training_type": training_type,"lora_rank": lora_rank,"lora_alpha": lora_alpha,164 unmodified lineslast_session = {"params": {"model_type": MODEL_TYPES.get(ui_state.get("model_type", list(MODEL_TYPES.keys())[0])),"model_version": ui_state.get("model_version", ""),"training_type": TRAINING_TYPES.get(ui_state.get("training_type", list(TRAINING_TYPES.keys())[0])),"lora_rank": ui_state.get("lora_rank", DEFAULT_LORA_RANK_STR),"lora_alpha": ui_state.get("lora_alpha", DEFAULT_LORA_ALPHA_STR),57 unmodified lines# Add UI updates to restore the training parameters in the UI# This shows the user what values are being used for the resumed trainingui_updates.update({"model_type": model_type_display,"model_version": params.get('model_version', ''),"training_type": training_type_display,"lora_rank": params.get('lora_rank', DEFAULT_LORA_RANK_STR),"lora_alpha": params.get('lora_alpha', DEFAULT_LORA_ALPHA_STR),"train_steps": params.get('train_steps', DEFAULT_NB_TRAINING_STEPS),12 unmodified lines# Use the internal model_type for the actual training# But keep model_type_display for the UIresult = self.start_training(model_type=model_internal_type,lora_rank=params.get('lora_rank', DEFAULT_LORA_RANK_STR),lora_alpha=params.get('lora_alpha', DEFAULT_LORA_ALPHA_STR),train_size=params.get('train_steps', DEFAULT_NB_TRAINING_STEPS),batch_size=params.get('batch_size', DEFAULT_BATCH_SIZE),learning_rate=params.get('learning_rate', DEFAULT_LEARNING_RATE),save_iterations=params.get('save_iterations', DEFAULT_SAVE_CHECKPOINT_EVERY_N_STEPS),model_version=params.get('model_version', ''),repo_id=params.get('repo_id', ''),preset_name=params.get('preset_name', list(TRAINING_PRESETS.keys())[0]),training_type=training_type_internal,resume_from_checkpoint=str(latest_checkpoint))# Set buttons for active trainingui_updates.update({"start_btn": {"interactive": False, "variant": "secondary", "value": "Continue Training"},1 unmodified line"delete_checkpoints_btn": {"interactive": False, "variant": "stop", "value": "Delete All Checkpoints"},"pause_resume_btn": {"interactive": False, "variant": "secondary", "visible": False}})return {"status": "recovered","message": f"Training resumed from checkpoint {checkpoint_step}",
3 unmodified lines4567891011121314151617181929 unmodified lines49505152535455565758596061626364656667686970717273103 unmodified lines1771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112121 unmodified line2142152162172182192204 unmodified lines2252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542558 unmodified lines26426526626726826927027127227327427527627727827928028128228328428528618 unmodified lines3053063073083093103113123133143153163179 unmodified lines32732832933033133233315 unmodified lines34935035135235335435535635735835936036136236336436536636736836937014 unmodified lines3853863873883893903913923933943958 unmodified lines4044054064074084094103 unmodified lines41441541641741841942035 unmodified lines45645745845946046146210 unmodified lines4734744754764774784794804814824834844851 unmodified line48748848949049149249310 unmodified lines5045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425433 unmodified linesimport gradio as grimport loggingfrom pathlib import Pathfrom typing import Dict, Any, List, Optional, Tupleimport timefrom vms.utils import BaseTabfrom vms.config import (MODEL_TYPES, DEFAULT_PROMPT_PREFIX)logger = logging.getLogger(__name__)class PreviewTab(BaseTab):"""Preview tab for testing trained models"""29 unmodified linesplaceholder="Prefix to add to all prompts",value=DEFAULT_PROMPT_PREFIX)with gr.Row():# Get the currently selected model type from training tab if possibledefault_model = self.get_default_model_type()# Make model_type read-only (disabled), as it must match what was trainedself.components["model_type"] = gr.Dropdown(choices=list(MODEL_TYPES.keys()),label="Model Type (from training)",value=default_model,interactive=False)# Add model variant selection based on model typeself.components["model_variant"] = gr.Dropdown(label="Model Variant",choices=self.get_variant_choices(default_model),value=self.get_default_variant(default_model))# Add image input for image-to-video modelsself.components["conditioning_image"] = gr.Image(103 unmodified linesreturn tabdef get_variant_choices(self, model_type: str) -> List[str]:"""Get model variant choices based on model type"""# Convert UI display name to internal nameinternal_type = MODEL_TYPES.get(model_type)if not internal_type:return []# Get variants from preview servicevariants = self.app.previewing.get_model_variants(internal_type)if not variants:return []# Format choices with display name and descriptionchoices = []for model_id, info in variants.items():choices.append(f"{model_id} - {info.get('name', '')}")return choicesdef get_default_variant(self, model_type: str) -> str:"""Get default model variant for the model type"""choices = self.get_variant_choices(model_type)if choices:return choices[0]return ""def get_default_model_type(self) -> str:"""Get the currently selected model type from training tab"""try:# Try to get the model type from UI stateui_state = self.app.training.load_ui_state()model_type = ui_state.get("model_type")1 unmodified lineif model_type in MODEL_TYPES:return model_type# If we couldn't get a valid model type, try to get it from the training tab directlyif hasattr(self.app, 'tabs') and 'train_tab' in self.app.tabs:train_tab = self.app.tabs['train_tab']if hasattr(train_tab, 'components') and 'model_type' in train_tab.components:4 unmodified lines# Fallback to first model typereturn list(MODEL_TYPES.keys())[0]except Exception as e:logger.warning(f"Failed to get default model type: {e}")return list(MODEL_TYPES.keys())[0]def extract_model_id(self, variant_choice: str) -> str:"""Extract model ID from variant choice string"""if " - " in variant_choice:return variant_choice.split(" - ")[0].strip()return variant_choicedef get_variant_type(self, model_type: str, model_variant: str) -> str:"""Get the variant type (text-to-video or image-to-video)"""# Convert UI display name to internal nameinternal_type = MODEL_TYPES.get(model_type)if not internal_type:return "text-to-video"# Extract model_id from variant choicemodel_id = self.extract_model_id(model_variant)# Get variants from preview servicevariants = self.app.previewing.get_model_variants(internal_type)variant_info = variants.get(model_id, {})# Return the variant type or default to text-to-videoreturn variant_info.get("type", "text-to-video")def connect_events(self) -> None:"""Connect event handlers to UI components"""8 unmodified lines])# Update model_variant choices when model_type changes or tab is selectedif hasattr(self.app, 'tabs_component') and self.app.tabs_component is not None:self.app.tabs_component.select(fn=self.sync_model_type_and_variants,inputs=[],outputs=[self.components["model_type"],self.components["model_variant"]])# Update variant-specific UI elements when variant changesself.components["model_variant"].change(fn=self.update_variant_ui,inputs=[self.components["model_type"],self.components["model_variant"]],outputs=[self.components["conditioning_image"]18 unmodified linesself.components["lora_weight"],self.components["inference_steps"],self.components["enable_cpu_offload"],self.components["model_variant"]])# Save preview UI state when values changefor component_name in ["prompt", "negative_prompt", "prompt_prefix", "model_variant", "resolution_preset","width", "height", "num_frames", "fps", "guidance_scale", "flow_shift","lora_weight", "inference_steps", "enable_cpu_offload"]:9 unmodified linesfn=self.generate_video,inputs=[self.components["model_type"],self.components["model_variant"],self.components["prompt"],self.components["negative_prompt"],self.components["prompt_prefix"],15 unmodified lines])def update_variant_ui(self, model_type: str, model_variant: str) -> Dict[str, Any]:"""Update UI based on the selected model variant"""variant_type = self.get_variant_type(model_type, model_variant)# Show conditioning image input only for image-to-video modelsshow_conditioning_image = variant_type == "image-to-video"return {self.components["conditioning_image"]: gr.Image(visible=show_conditioning_image)}def sync_model_type_and_variants(self) -> Tuple[str, str]:"""Sync model type with training tab when preview tab is selected and update variant choices"""model_type = self.get_default_model_type()model_variant = self.get_default_variant(model_type)return model_type, model_variantdef update_resolution(self, preset: str) -> Tuple[int, int, float]:"""Update resolution and flow shift based on preset"""14 unmodified lines# Get model type (can't be changed in UI)model_type = self.get_default_model_type()# If model_variant not in choices for current model_type, use defaultmodel_variant = preview_state.get("model_variant", "")variant_choices = self.get_variant_choices(model_type)if model_variant not in variant_choices and variant_choices:model_variant = variant_choices[0]return (preview_state.get("prompt", ""),8 unmodified linespreview_state.get("lora_weight", 0.7),preview_state.get("inference_steps", 30),preview_state.get("enable_cpu_offload", True),model_variant)except Exception as e:logger.error(f"Error loading preview state: {e}")3 unmodified lines"worst quality, low quality, blurry, jittery, distorted, ugly, deformed, disfigured, messy background",DEFAULT_PROMPT_PREFIX,832, 480, 49, 16, 5.0, 3.0, 0.7, 30, True,self.get_default_variant(self.get_default_model_type()))def save_preview_state_value(self, value: Any) -> None:35 unmodified linesdef generate_video(self,model_type: str,model_variant: str,prompt: str,negative_prompt: str,prompt_prefix: str,10 unmodified lines) -> Tuple[Optional[str], str, str]:"""Handler for generate button click, delegates to preview service"""# Save all the parameters to preview state before generatingtry:state = self.app.training.load_ui_state()if "preview" not in state:state["preview"] = {}# Extract model ID from variant choicemodel_variant_id = self.extract_model_id(model_variant)# Update all valuespreview_state = {1 unmodified line"negative_prompt": negative_prompt,"prompt_prefix": prompt_prefix,"model_type": model_type,"model_variant": model_variant,"width": width,"height": height,"num_frames": num_frames,10 unmodified linesexcept Exception as e:logger.error(f"Error saving preview state before generation: {e}")# Clear the log display at the start to make room for new logs# Yield and sleep briefly to allow UI updateyield None, "Starting generation...", ""time.sleep(0.1)# Extract model ID from variant choice stringmodel_variant_id = self.extract_model_id(model_variant)# Use streaming updates to provide real-time feedback during generationdef generate_with_updates():# Initial UI updateyield None, "Initializing generation...", "Starting video generation process..."# Start actual generationresult = self.app.previewing.generate_video(model_type=model_type,model_variant=model_variant_id,prompt=prompt,negative_prompt=negative_prompt,prompt_prefix=prompt_prefix,width=width,height=height,num_frames=num_frames,guidance_scale=guidance_scale,flow_shift=flow_shift,lora_weight=lora_weight,inference_steps=inference_steps,enable_cpu_offload=enable_cpu_offload,fps=fps,conditioning_image=conditioning_image)# Return final resultreturn result# Return the generator for streaming updatesreturn generate_with_updates()3 unmodified lines45678910111213141516171819202129 unmodified lines5152535455565758596061626364656667686970717273747576777879808182838485103 unmodified lines1891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422431 unmodified line2452462472482492502514 unmodified lines2562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852868 unmodified lines29529629729829930030130230330430530630730830931031131231331431531631718 unmodified lines3363373383393403413423433443453463473489 unmodified lines35835936036136236336415 unmodified lines38038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942014 unmodified lines4354364374384394404414424434444458 unmodified lines4544554564574584594603 unmodified lines46446546646746846947035 unmodified lines50650750850951051151210 unmodified lines5235245255265275285295305315325335345355361 unmodified line53853954054154254354410 unmodified lines5555565575585595605615625635645655665675685695705715725735745755765775785795805815825835843 unmodified linesimport gradio as grimport loggingimport jsonfrom pathlib import Pathfrom typing import Dict, Any, List, Optional, Tupleimport timefrom vms.utils import BaseTabfrom vms.config import (OUTPUT_PATH, MODEL_TYPES, DEFAULT_PROMPT_PREFIX, MODEL_VERSIONS)logger = logging.getLogger(__name__)logger.setLevel(logging.INFO)class PreviewTab(BaseTab):"""Preview tab for testing trained models"""29 unmodified linesplaceholder="Prefix to add to all prompts",value=DEFAULT_PROMPT_PREFIX)self.components["seed"] = gr.Slider(label="Generation Seed (-1 for random)",minimum=-1,maximum=2147483647, # 2^31 - 1step=1,value=-1,info="Set to -1 for random seed or specific value for reproducible results")with gr.Row():# Get the currently selected model type from training tab if possibledefault_model = self.get_default_model_type()with gr.Column():# Make model_type read-only (disabled), as it must match what was trainedself.components["model_type"] = gr.Dropdown(choices=list(MODEL_TYPES.keys()),label="Model Type (from training)",value=default_model,interactive=False)# Add model version selection based on model typeself.components["model_version"] = gr.Dropdown(label="Model Version",choices=self.get_model_version_choices(default_model),value=self.get_default_model_version(default_model))# Add image input for image-to-video modelsself.components["conditioning_image"] = gr.Image(103 unmodified linesreturn tabdef get_model_version_choices(self, model_type: str) -> List[str]:"""Get model version choices based on model type"""# Convert UI display name to internal nameinternal_type = MODEL_TYPES.get(model_type)if not internal_type:return []# Get versions from preview serviceversions = self.app.previewing.get_model_versions(internal_type)if not versions:return []# Format choices with display name and descriptionchoices = []for model_id, info in versions.items():choices.append(f"{model_id} - {info.get('name', '')}")return choicesdef get_default_model_version(self, model_type: str) -> str:"""Get default model version for the model type"""choices = self.get_model_version_choices(model_type)if choices:return choices[0]return ""def get_default_model_type(self) -> str:"""Get the model type from the latest training session"""try:# First check the session.json which contains the actual training datasession_file = OUTPUT_PATH / "session.json"if session_file.exists():with open(session_file, 'r') as f:session_data = json.load(f)# Get the internal model type from the session parametersif "params" in session_data and "model_type" in session_data["params"]:internal_model_type = session_data["params"]["model_type"]# Convert internal model type to display namefor display_name, internal_name in MODEL_TYPES.items():if internal_name == internal_model_type:logger.info(f"Using model type '{display_name}' from session file")return display_name# If we couldn't map it, log a warninglogger.warning(f"Could not map internal model type '{internal_model_type}' to a display name")# If we couldn't get it from session.json, try to get it from UI stateui_state = self.app.training.load_ui_state()model_type = ui_state.get("model_type")1 unmodified lineif model_type in MODEL_TYPES:return model_type# If we still couldn't get a valid model type, try to get it from the training tabif hasattr(self.app, 'tabs') and 'train_tab' in self.app.tabs:train_tab = self.app.tabs['train_tab']if hasattr(train_tab, 'components') and 'model_type' in train_tab.components:4 unmodified lines# Fallback to first model typereturn list(MODEL_TYPES.keys())[0]except Exception as e:logger.warning(f"Failed to get default model type from session: {e}")return list(MODEL_TYPES.keys())[0]def extract_model_id(self, model_version_choice: str) -> str:"""Extract model ID from model version choice string"""if " - " in model_version_choice:return model_version_choice.split(" - ")[0].strip()return model_version_choicedef get_model_version_type(self, model_type: str, model_version: str) -> str:"""Get the model version type (text-to-video or image-to-video)"""# Convert UI display name to internal nameinternal_type = MODEL_TYPES.get(model_type)if not internal_type:return "text-to-video"# Extract model_id from model version choicemodel_id = self.extract_model_id(model_version)# Get versions from preview serviceversions = self.app.previewing.get_model_versions(internal_type)model_version_info = versions.get(model_id, {})# Return the model version type or default to text-to-videoreturn model_version_info.get("type", "text-to-video")def connect_events(self) -> None:"""Connect event handlers to UI components"""8 unmodified lines])# Update model_version choices when model_type changes or tab is selectedif hasattr(self.app, 'tabs_component') and self.app.tabs_component is not None:self.app.tabs_component.select(fn=self.sync_model_type_and_verions,inputs=[],outputs=[self.components["model_type"],self.components["model_version"]])# Update model version-specific UI elements when version changesself.components["model_version"].change(fn=self.update_model_version_ui,inputs=[self.components["model_type"],self.components["model_version"]],outputs=[self.components["conditioning_image"]18 unmodified linesself.components["lora_weight"],self.components["inference_steps"],self.components["enable_cpu_offload"],self.components["model_version"]])# Save preview UI state when values changefor component_name in ["prompt", "negative_prompt", "prompt_prefix", "model_version", "resolution_preset","width", "height", "num_frames", "fps", "guidance_scale", "flow_shift","lora_weight", "inference_steps", "enable_cpu_offload"]:9 unmodified linesfn=self.generate_video,inputs=[self.components["model_type"],self.components["model_version"],self.components["prompt"],self.components["negative_prompt"],self.components["prompt_prefix"],15 unmodified lines])def update_model_version_ui(self, model_type: str, model_version: str) -> Dict[str, Any]:"""Update UI based on the selected model version"""model_version_type = self.get_model_version_type(model_type, model_version)# Show conditioning image input only for image-to-video modelsshow_conditioning_image = model_version_type == "image-to-video"return {self.components["conditioning_image"]: gr.Image(visible=show_conditioning_image)}def sync_model_type_and_verions(self) -> Tuple[str, str]:"""Sync model type with training tab when preview tab is selected and update model version choices"""model_type = self.get_default_model_type()model_version = ""# Try to get model_version from session or UI stateui_state = self.app.training.load_ui_state()preview_state = ui_state.get("preview", {})model_version = preview_state.get("model_version", "")if not model_version:# Format it as a display choiceinternal_type = MODEL_TYPES.get(model_type)if internal_type and internal_type in MODEL_VERSIONS:first_version = next(iter(MODEL_VERSIONS[internal_type].keys()), "")if first_version:model_version_info = MODEL_VERSIONS[internal_type][first_version]model_version = f"{first_version} - {model_version_info.get('name', '')}"# If we couldn't get it, use defaultif not model_version:model_version = self.get_default_model_version(model_type)return model_type, model_versiondef update_resolution(self, preset: str) -> Tuple[int, int, float]:"""Update resolution and flow shift based on preset"""14 unmodified lines# Get model type (can't be changed in UI)model_type = self.get_default_model_type()# If model_version not in choices for current model_type, use defaultmodel_version = preview_state.get("model_version", "")model_version_choices = self.get_model_version_choices(model_type)if model_version not in model_version_choices and model_version_choices:model_version = model_version_choices[0]return (preview_state.get("prompt", ""),8 unmodified linespreview_state.get("lora_weight", 0.7),preview_state.get("inference_steps", 30),preview_state.get("enable_cpu_offload", True),model_version)except Exception as e:logger.error(f"Error loading preview state: {e}")3 unmodified lines"worst quality, low quality, blurry, jittery, distorted, ugly, deformed, disfigured, messy background",DEFAULT_PROMPT_PREFIX,832, 480, 49, 16, 5.0, 3.0, 0.7, 30, True,self.get_default_model_version(self.get_default_model_type()))def save_preview_state_value(self, value: Any) -> None:35 unmodified linesdef generate_video(self,model_type: str,model_version: str,prompt: str,negative_prompt: str,prompt_prefix: str,10 unmodified lines) -> Tuple[Optional[str], str, str]:"""Handler for generate button click, delegates to preview service"""# Save all the parameters to preview state before generatingprint("preview_tab: generate_video() has been called")try:state = self.app.training.load_ui_state()if "preview" not in state:state["preview"] = {}# Extract model ID from model version choicemodel_version_id = self.extract_model_id(model_version)# Update all valuespreview_state = {1 unmodified line"negative_prompt": negative_prompt,"prompt_prefix": prompt_prefix,"model_type": model_type,"model_version": model_version,"width": width,"height": height,"num_frames": num_frames,10 unmodified linesexcept Exception as e:logger.error(f"Error saving preview state before generation: {e}")# Extract model ID from model version choice stringmodel_version_id = self.extract_model_id(model_version)# Initial UI updatevideo_path, status, log = None, "Initializing generation...", "Starting video generation process..."# Start actual generationresult = self.app.previewing.generate_video(model_type=model_type,model_version=model_version_id,prompt=prompt,negative_prompt=negative_prompt,prompt_prefix=prompt_prefix,width=width,height=height,num_frames=num_frames,guidance_scale=guidance_scale,flow_shift=flow_shift,lora_weight=lora_weight,inference_steps=inference_steps,enable_cpu_offload=enable_cpu_offload,fps=fps,conditioning_image=conditioning_image)# Return final resultreturn result
4 unmodified lines567891011121314151636 unmodified lines535455565758596061626364133 unmodified lines1981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412425 unmodified lines24824925025125225325471 unmodified lines3263273283293303313323 unmodified lines33633733833934034141 unmodified lines3833843853863873883893903914 unmodified lines3963973983994004014024034043 unmodified lines40840941041141241341441541641714 unmodified lines4324334344354364374384394407 unmodified lines4484494504514524534 unmodified lines45845946046146246319 unmodified lines483484485486487488489490491492493494495496104 unmodified lines6016026036046056068 unmodified lines6156166176186196206216226234 unmodified linesimport gradio as grimport loggingimport osfrom typing import Dict, Any, List, Optional, Tuplefrom pathlib import Pathfrom vms.utils import BaseTabfrom vms.config import (TRAINING_PRESETS, OUTPUT_PATH, MODEL_TYPES, ASK_USER_TO_DUPLICATE_SPACE, SMALL_TRAINING_BUCKETS, TRAINING_TYPES,DEFAULT_NB_TRAINING_STEPS, DEFAULT_SAVE_CHECKPOINT_EVERY_N_STEPS,DEFAULT_BATCH_SIZE, DEFAULT_CAPTION_DROPOUT_P,DEFAULT_LEARNING_RATE,36 unmodified lineswith gr.Row():with gr.Column():self.components["model_type"] = gr.Dropdown(choices=list(MODEL_TYPES.keys()),label="Model Type",value=list(MODEL_TYPES.keys())[0])with gr.Column():self.components["training_type"] = gr.Dropdown(choices=list(TRAINING_TYPES.keys()),label="Training Type",133 unmodified linesdef connect_events(self) -> None:"""Connect event handlers to UI components"""# Model type change eventdef update_model_info(model, training_type):params = self.get_default_params(MODEL_TYPES[model], TRAINING_TYPES[training_type])info = self.get_model_info(model, training_type)show_lora_params = training_type == list(TRAINING_TYPES.keys())[0] # Show if LoRA Finetunereturn {self.components["model_info"]: info,self.components["train_steps"]: params["train_steps"],self.components["batch_size"]: params["batch_size"],self.components["learning_rate"]: params["learning_rate"],self.components["save_iterations"]: params["save_iterations"],self.components["lora_params_row"]: gr.Row(visible=show_lora_params)}self.components["model_type"].change(fn=lambda v: self.app.update_ui_state(model_type=v),inputs=[self.components["model_type"]],outputs=[]).then(fn=update_model_info,inputs=[self.components["model_type"], self.components["training_type"]],outputs=[self.components["model_info"],self.components["train_steps"],self.components["batch_size"],self.components["learning_rate"],self.components["save_iterations"],self.components["lora_params_row"]])# Training type change eventself.components["training_type"].change(fn=lambda v: self.app.update_ui_state(training_type=v),inputs=[self.components["training_type"]],outputs=[]).then(fn=update_model_info,inputs=[self.components["model_type"], self.components["training_type"]],outputs=[self.components["model_info"],5 unmodified lines])# Add in the connect_events() method:self.components["num_gpus"].change(fn=lambda v: self.app.update_ui_state(num_gpus=v),71 unmodified linesself.components["lora_params_row"],self.components["num_gpus"],self.components["precomputation_items"],self.components["lr_warmup_steps"]])3 unmodified linesinputs=[self.components["training_preset"],self.components["model_type"],self.components["training_type"],self.components["lora_rank"],self.components["lora_alpha"],41 unmodified linesfn=lambda: self.app.training.delete_all_checkpoints(),outputs=[self.components["status_box"]])def handle_training_start(self, preset, model_type, training_type, lora_rank, lora_alpha, train_steps, batch_size, learning_rate, save_iterations, repo_id, progress=gr.Progress()):"""Handle training start with proper log parser reset and checkpoint detection"""# Safely reset log parser if it exists4 unmodified linesfrom ..utils import TrainingLogParserself.app.log_parser = TrainingLogParser()# Initialize progress#progress(0, desc="Initializing training")# Check for latest checkpointcheckpoints = list(OUTPUT_PATH.glob("checkpoint-*"))resume_from = None3 unmodified lineslatest_checkpoint = max(checkpoints, key=os.path.getmtime)resume_from = str(latest_checkpoint)logger.info(f"Found checkpoint at {resume_from}, will resume training")#progress(0.05, desc=f"Resuming from checkpoint {Path(resume_from).name}")else:#progress(0.05, desc="Starting new training run")pass# Convert model_type display name to internal namemodel_internal_type = MODEL_TYPES.get(model_type)14 unmodified linesprecomputation_items = int(self.components["precomputation_items"].value)lr_warmup_steps = int(self.components["lr_warmup_steps"].value)# Progress update#progress(0.1, desc="Preparing dataset")# Start training (it will automatically use the checkpoint if provided)try:return self.app.training.start_training(7 unmodified linesrepo_id,preset_name=preset,training_type=training_internal_type,resume_from_checkpoint=resume_from,num_gpus=num_gpus,precomputation_items=precomputation_items,4 unmodified lineslogger.exception("Error starting training")return f"Error starting training: {str(e)}", f"Exception: {str(e)}\n\nCheck the logs for more details."def get_model_info(self, model_type: str, training_type: str) -> str:"""Get information about the selected model type and training method"""if model_type == "HunyuanVideo":19 unmodified lineselse:return base_info + "\n- Required VRAM: ~21GB minimum\n- Full model size: ~8GB"elif model_type == "Wan-2.1-T2V":base_info = """### Wan-2.1-T2V- Recommended batch size: ?- Typical training time: ? hours- Default resolution: 49x512x768"""if training_type == "LoRA Finetune":return base_info + "\n- Required VRAM: ?GB minimum\n- Default LoRA rank: 32 (~120 MB)"else:return base_info + "\n- **Full finetune not recommended due to VRAM requirements**"104 unmodified linesprecomputation_items_val = current_state.get("precomputation_items") if current_state.get("precomputation_items") != preset.get("precomputation_items", DEFAULT_PRECOMPUTATION_ITEMS) else preset.get("precomputation_items", DEFAULT_PRECOMPUTATION_ITEMS)lr_warmup_steps_val = current_state.get("lr_warmup_steps") if current_state.get("lr_warmup_steps") != preset.get("lr_warmup_steps", DEFAULT_NB_LR_WARMUP_STEPS) else preset.get("lr_warmup_steps", DEFAULT_NB_LR_WARMUP_STEPS)# Return values in the same order as the output componentsreturn (model_display_name,8 unmodified linesgr.Row(visible=show_lora_params),num_gpus_val,precomputation_items_val,lr_warmup_steps_val)def get_latest_status_message_and_logs(self) -> Tuple[str, str, str]:"""Get latest status message, log content, and status code in a safer way"""state = self.app.training.get_status()4 unmodified lines567891011121314151617181936 unmodified lines565758596061626364656667686970717273747576777879808182133 unmodified lines2162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502515 unmodified lines25725825926026126271 unmodified lines3343353363373383393403413423 unmodified lines34634734834935035135241 unmodified lines3943953963973983994004014024034044054064074084094104114124 unmodified lines4174184194204214223 unmodified lines42642742842943043114 unmodified lines4464474484494504517 unmodified lines4594604614624634644654 unmodified lines47047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052119 unmodified lines541542543544545546547548549550551552553554104 unmodified lines6596606616626636646656666676688 unmodified lines6776786796806816826836846856866874 unmodified linesimport gradio as grimport loggingimport osimport jsonfrom typing import Dict, Any, List, Optional, Tuplefrom pathlib import Pathfrom vms.utils import BaseTabfrom vms.config import (OUTPUT_PATH, ASK_USER_TO_DUPLICATE_SPACE,SMALL_TRAINING_BUCKETS,TRAINING_PRESETS, TRAINING_TYPES, MODEL_TYPES, MODEL_VERSIONS,DEFAULT_NB_TRAINING_STEPS, DEFAULT_SAVE_CHECKPOINT_EVERY_N_STEPS,DEFAULT_BATCH_SIZE, DEFAULT_CAPTION_DROPOUT_P,DEFAULT_LEARNING_RATE,36 unmodified lineswith gr.Row():with gr.Column():# Get the default model type from the first presetdefault_model_type = list(MODEL_TYPES.keys())[0]self.components["model_type"] = gr.Dropdown(choices=list(MODEL_TYPES.keys()),label="Model Type",value=default_model_type,interactive=True)# Get model versions for the default model typedefault_model_versions = self.get_model_version_choices(default_model_type)default_model_version = self.get_default_model_version(default_model_type)self.components["model_version"] = gr.Dropdown(choices=default_model_versions,label="Model Version",value=default_model_version,interactive=True)self.components["training_type"] = gr.Dropdown(choices=list(TRAINING_TYPES.keys()),label="Training Type",133 unmodified linesdef connect_events(self) -> None:"""Connect event handlers to UI components"""# Model type change event - Update model version dropdown choicesself.components["model_type"].change(fn=self.update_model_versions,inputs=[self.components["model_type"]],outputs=[self.components["model_version"]]).then(fn=lambda v: self.app.update_ui_state(model_type=v),inputs=[self.components["model_type"]],outputs=[]).then(# Use get_model_info instead of update_model_infofn=self.get_model_info,inputs=[self.components["model_type"], self.components["training_type"]],outputs=[self.components["model_info"]])# Model version change eventself.components["model_version"].change(fn=lambda v: self.app.update_ui_state(model_version=v),inputs=[self.components["model_version"]],outputs=[])# Training type change eventself.components["training_type"].change(fn=lambda v: self.app.update_ui_state(training_type=v),inputs=[self.components["training_type"]],outputs=[]).then(fn=self.update_model_info,inputs=[self.components["model_type"], self.components["training_type"]],outputs=[self.components["model_info"],5 unmodified lines])# Add in the connect_events() method:self.components["num_gpus"].change(fn=lambda v: self.app.update_ui_state(num_gpus=v),71 unmodified linesself.components["lora_params_row"],self.components["num_gpus"],self.components["precomputation_items"],self.components["lr_warmup_steps"],# Add model_version to the outputsself.components["model_version"]])3 unmodified linesinputs=[self.components["training_preset"],self.components["model_type"],self.components["model_version"], # Add model_version to the inputsself.components["training_type"],self.components["lora_rank"],self.components["lora_alpha"],41 unmodified linesfn=lambda: self.app.training.delete_all_checkpoints(),outputs=[self.components["status_box"]])def update_model_versions(self, model_type: str) -> Dict:"""Update model version choices based on selected model type"""model_versions = self.get_model_version_choices(model_type)default_version = self.get_default_model_version(model_type)# Update the model_version dropdown with new choices and default valuereturn gr.Dropdown(choices=model_versions, value=default_version)def handle_training_start(self, preset, model_type, model_version, training_type,lora_rank, lora_alpha, train_steps, batch_size, learning_rate,save_iterations, repo_id, progress=gr.Progress()):"""Handle training start with proper log parser reset and checkpoint detection"""# Safely reset log parser if it exists4 unmodified linesfrom ..utils import TrainingLogParserself.app.log_parser = TrainingLogParser()# Check for latest checkpointcheckpoints = list(OUTPUT_PATH.glob("checkpoint-*"))resume_from = None3 unmodified lineslatest_checkpoint = max(checkpoints, key=os.path.getmtime)resume_from = str(latest_checkpoint)logger.info(f"Found checkpoint at {resume_from}, will resume training")# Convert model_type display name to internal namemodel_internal_type = MODEL_TYPES.get(model_type)14 unmodified linesprecomputation_items = int(self.components["precomputation_items"].value)lr_warmup_steps = int(self.components["lr_warmup_steps"].value)# Start training (it will automatically use the checkpoint if provided)try:return self.app.training.start_training(7 unmodified linesrepo_id,preset_name=preset,training_type=training_internal_type,model_version=model_version, # Pass the model version from dropdownresume_from_checkpoint=resume_from,num_gpus=num_gpus,precomputation_items=precomputation_items,4 unmodified lineslogger.exception("Error starting training")return f"Error starting training: {str(e)}", f"Exception: {str(e)}\n\nCheck the logs for more details."def get_model_version_choices(self, model_type: str) -> List[str]:"""Get model version choices based on model type"""# Convert UI display name to internal nameinternal_type = MODEL_TYPES.get(model_type)if not internal_type or internal_type not in MODEL_VERSIONS:return []# Get versions and return them as choicesversions = MODEL_VERSIONS.get(internal_type, {})return list(versions.keys())def get_default_model_version(self, model_type: str) -> str:"""Get default model version for the given model type"""# Convert UI display name to internal nameinternal_type = MODEL_TYPES.get(model_type)if not internal_type or internal_type not in MODEL_VERSIONS:return ""# Get the first version available for this model typeversions = MODEL_VERSIONS.get(internal_type, {})if versions:return next(iter(versions.keys()))return ""def update_model_info(self, model_type: str, training_type: str) -> Dict:"""Update model info and related UI components based on model type and training type"""# Get model info textmodel_info = self.get_model_info(model_type, training_type)# Get default parameters for this model type and training typeparams = self.get_default_params(MODEL_TYPES.get(model_type), TRAINING_TYPES.get(training_type))# Check if LoRA params should be visibleshow_lora_params = training_type == "LoRA Finetune"# Return updates for UI componentsreturn {self.components["model_info"]: model_info,self.components["train_steps"]: params["train_steps"],self.components["batch_size"]: params["batch_size"],self.components["learning_rate"]: params["learning_rate"],self.components["save_iterations"]: params["save_iterations"],self.components["lora_params_row"]: gr.Row(visible=show_lora_params)}def get_model_info(self, model_type: str, training_type: str) -> str:"""Get information about the selected model type and training method"""if model_type == "HunyuanVideo":19 unmodified lineselse:return base_info + "\n- Required VRAM: ~21GB minimum\n- Full model size: ~8GB"elif model_type == "Wan":base_info = """### Wan- Recommended batch size: 1-4- Typical training time: 1-3 hours- Default resolution: 49x512x768"""if training_type == "LoRA Finetune":return base_info + "\n- Required VRAM: ~16GB minimum\n- Default LoRA rank: 32 (~120 MB)"else:return base_info + "\n- **Full finetune not recommended due to VRAM requirements**"104 unmodified linesprecomputation_items_val = current_state.get("precomputation_items") if current_state.get("precomputation_items") != preset.get("precomputation_items", DEFAULT_PRECOMPUTATION_ITEMS) else preset.get("precomputation_items", DEFAULT_PRECOMPUTATION_ITEMS)lr_warmup_steps_val = current_state.get("lr_warmup_steps") if current_state.get("lr_warmup_steps") != preset.get("lr_warmup_steps", DEFAULT_NB_LR_WARMUP_STEPS) else preset.get("lr_warmup_steps", DEFAULT_NB_LR_WARMUP_STEPS)# Get the appropriate model version for the selected model typemodel_versions = self.get_model_version_choices(model_display_name)default_model_version = self.get_default_model_version(model_display_name)# Return values in the same order as the output componentsreturn (model_display_name,8 unmodified linesgr.Row(visible=show_lora_params),num_gpus_val,precomputation_items_val,lr_warmup_steps_val,gr.Dropdown(choices=model_versions, value=default_model_version))def get_latest_status_message_and_logs(self) -> Tuple[str, str, str]:"""Get latest status message, log content, and status code in a safer way"""state = self.app.training.get_status()
vms/config.py+10-10
vms/ui/app_ui.py+30-2
vms/ui/monitoring/services/monitoring.py+1
vms/ui/monitoring/tabs/general_tab.py+1-1
vms/ui/project/services/captioning.py+1
vms/ui/project/services/previewing.py+123-56
vms/ui/project/services/splitting.py+1
vms/ui/project/services/training.py+26-7
vms/ui/project/tabs/preview_tab.py+147-106
vms/ui/project/tabs/train_tab.py+112-48