Update app.py
Browse files39 unmodified lines404142434445219 unmodified lines265266267268269270111 unmodified lines38238338438538638738828 unmodified lines4174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904911 unmodified line49349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652739 unmodified linesimport spacesimport gradio as grimport numpy as npfrom huggingface_hub import hf_hub_download, snapshot_downloadfrom ltx_core.components.diffusion_steps import EulerDiffusionStep219 unmodified linesprint("Downloading LTX-2.3 distilled model + Gemma...")print("=" * 80)checkpoint_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-22b-distilled.safetensors")spatial_upsampler_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.0.safetensors")gemma_root = snapshot_download(repo_id=GEMMA_REPO)111 unmodified linesprogress=gr.Progress(track_tqdm=True),):try:global pipeline # <<< ADD THIS LINE HERE (VERY TOP of try block)torch.cuda.reset_peak_memory_stats()log_memory("start")28 unmodified linestiling_config = TilingConfig.default()video_chunks_number = get_video_chunks_number(num_frames, tiling_config)# >>> RUNTIME LoRA application (robust, multi-fallback)# We cannot rely on mutating the original descriptor (some implementations are immutable),# so create a fresh runtime descriptor and try multiple ways to install it.runtime_strength = float(lora_strength)replaced = False# 1) Try simple approach: build a new LoraPathStrengthAndSDOpsruntime_lora = LoraPathStrengthAndSDOps(lora_path, runtime_strength, LTXV_LORA_COMFY_RENAMING_MAP)print(f"[LoRA] attempting to apply runtime LoRA (strength={runtime_strength})")# Try a few likely places to replace the descriptor used by the pipeline/ledger.try:# common attribute on pipelineif hasattr(pipeline, "loras"):try:pipeline.loras = [runtime_lora]replaced = Trueprint("[LoRA] replaced pipeline.loras")except Exception as e:print(f"[LoRA] pipeline.loras assignment failed: {e}")except Exception:passtry:# common attribute on the model ledgerif hasattr(pipeline, "model_ledger") and hasattr(pipeline.model_ledger, "loras"):try:pipeline.model_ledger.loras = [runtime_lora]replaced = Trueprint("[LoRA] replaced pipeline.model_ledger.loras")except Exception as e:print(f"[LoRA] pipeline.model_ledger.loras assignment failed: {e}")except Exception:passtry:# some internals use a private _loras listif hasattr(pipeline, "model_ledger") and hasattr(pipeline.model_ledger, "_loras"):try:pipeline.model_ledger._loras = [runtime_lora]replaced = Trueprint("[LoRA] replaced pipeline.model_ledger._loras")except Exception as e:print(f"[LoRA] pipeline.model_ledger._loras assignment failed: {e}")except Exception:pass# 2) If we succeeded replacing the descriptor in-place, clear transformer cache so it will rebuildif replaced:try:if hasattr(pipeline.model_ledger, "_transformer"):pipeline.model_ledger._transformer = None# also clear potential caches named similar to 'transformer_cache' if presentif hasattr(pipeline.model_ledger, "transformer_cache"):try:pipeline.model_ledger.transformer_cache = {}except Exception:passprint("[LoRA] in-place descriptor replacement done; transformer cache cleared")except Exception as e:print(f"[LoRA] replacement succeeded but cache clearing failed: {e}")# 3) FINAL FALLBACK - if none of the in-place replacements worked, rebuild the pipelineif not replaced:print("[LoRA] in-place replacement FAILED; rebuilding pipeline with runtime LoRA (this is slow)")try:# Rebuild pipeline object with the new LoRA descriptor# NOTE: this replaces the global `pipeline`. We must declare global to reassign it.pipeline = LTX23DistilledA2VPipeline(distilled_checkpoint_path=checkpoint_path,spatial_upsampler_path=spatial_upsampler_path,gemma_root=gemma_root,1 unmodified linequantization=QuantizationPolicy.fp8_cast(),)# After rebuilding, we *do not* re-run the original module-level preloads here,# because re-pinning may be complex; the rebuilt pipeline will construct its# own ledger as part of the first call. This is slower but reliable.# Clear any transformer caches if they exist on the new ledger as well.try:if hasattr(pipeline.model_ledger, "_transformer"):pipeline.model_ledger._transformer = Noneexcept Exception:passprint("[LoRA] pipeline rebuilt with runtime LoRA")except Exception as e:print(f"[LoRA] pipeline rebuild FAILED: {e}")# Reset transformer so next call rebuilds it with new LoRA strength (NO preloading!)try:if hasattr(pipeline, "model_ledger"):if hasattr(pipeline.model_ledger, "_transformer"):del pipeline.model_ledger._transformerpipeline.model_ledger._transformer = None# CRITICAL: force cleanup BEFORE rebuild happenscleanup_memory()torch.cuda.empty_cache()print("[LoRA] transformer reset; will rebuild during inference")except Exception as e:print(f"[LoRA] transformer reset failed: {e}")log_memory("before pipeline call")video, audio = pipeline(39 unmodified lines40414243444546219 unmodified lines266267268269270271272273274275276277278279280281282111 unmodified lines39439539639739839940028 unmodified lines4294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794801 unmodified line48248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053139 unmodified linesimport spacesimport gradio as grimport numpy as npfrom collections import OrderedDictfrom huggingface_hub import hf_hub_download, snapshot_downloadfrom ltx_core.components.diffusion_steps import EulerDiffusionStep219 unmodified linesprint("Downloading LTX-2.3 distilled model + Gemma...")print("=" * 80)# ----------------------------# Pipeline cache for LoRA strengths (keeps at most 2 pipelines to limit VRAM)# ----------------------------# Use rounded strengths as keys (2 decimal places)pipeline_cache: OrderedDict[float, LTX23DistilledA2VPipeline] = OrderedDict()# Record the current pipeline's LoRA strength (we built the module above with lora_descriptor default 1.0)current_lora_strength: float = round(1.0, 2)pipeline_cache[current_lora_strength] = pipelineCACHE_MAX_SIZE = 2 # keep at most two pipeline instances in memoryprint(f"[CACHE] initialized pipeline cache with strength={current_lora_strength}")checkpoint_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-22b-distilled.safetensors")spatial_upsampler_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.0.safetensors")gemma_root = snapshot_download(repo_id=GEMMA_REPO)111 unmodified linesprogress=gr.Progress(track_tqdm=True),):try:global pipeline, pipeline_cache, current_lora_strengthtorch.cuda.reset_peak_memory_stats()log_memory("start")28 unmodified linestiling_config = TilingConfig.default()video_chunks_number = get_video_chunks_number(num_frames, tiling_config)# ----------------------------# Pipeline-per-strength (small LRU cache) — safe, deterministic LoRA switching# ----------------------------# Globals used: pipeline, pipeline_cache, current_lora_strength, CACHE_MAX_SIZErequested_strength = round(float(lora_strength), 2)# fast-path: same strength currently loadedif requested_strength == current_lora_strength:print(f"[LoRA] requested strength {requested_strength} == current {current_lora_strength} -> using current pipeline")else:print(f"[LoRA] requested strength {requested_strength} != current {current_lora_strength}")# if cached, swap to that pipeline (move to end to mark as recently used)if requested_strength in pipeline_cache:print(f"[LoRA] using cached pipeline for strength={requested_strength}")# set pipeline to cached instance & mark as most-recently-usedcached = pipeline_cache.pop(requested_strength)pipeline_cache[requested_strength] = cachedpipeline = cachedcurrent_lora_strength = requested_strengthelse:# Build new pipeline for requested strength.print(f"[LoRA] building new pipeline for strength={requested_strength} (this will free and reallocate memory)")# Free the previous pipeline & its GPU memory BEFORE building the new onetry:# remove previous pipeline from cache (if present)if current_lora_strength in pipeline_cache:pipeline_cache.pop(current_lora_strength, None)# delete current pipeline object referencetry:del pipelineexcept Exception:pass# aggressively free memorycleanup_memory()torch.cuda.empty_cache()print("[LoRA] freed memory, starting pipeline build")except Exception as e:print(f"[LoRA] error while freeing old pipeline: {e}")# create a runtime LoRA descriptor and build a fresh pipelineruntime_lora = LoraPathStrengthAndSDOps(lora_path, float(requested_strength), LTXV_LORA_COMFY_RENAMING_MAP)new_pipeline = LTX23DistilledA2VPipeline(distilled_checkpoint_path=checkpoint_path,spatial_upsampler_path=spatial_upsampler_path,gemma_root=gemma_root,1 unmodified linequantization=QuantizationPolicy.fp8_cast(),)# Pin safe components (same preloads as original) so heavy parts remain stable.try:ledger = new_pipeline.model_ledger_video_encoder = ledger.video_encoder()_video_decoder = ledger.video_decoder()_audio_encoder = ledger.audio_encoder()_audio_decoder = ledger.audio_decoder()_vocoder = ledger.vocoder()_spatial_upsampler = ledger.spatial_upsampler()_text_encoder = ledger.text_encoder()_embeddings_processor = ledger.gemma_embeddings_processor()ledger.video_encoder = lambda: _video_encoderledger.video_decoder = lambda: _video_decoderledger.audio_encoder = lambda: _audio_encoderledger.audio_decoder = lambda: _audio_decoderledger.vocoder = lambda: _vocoderledger.spatial_upsampler = lambda: _spatial_upsamplerledger.text_encoder = lambda: _text_encoderledger.gemma_embeddings_processor = lambda: _embeddings_processorprint("[LoRA] new pipeline preloaded and pinned safe components")except Exception as e:print(f"[LoRA] warning preloading pinned components failed: {e}")# Set as current pipeline and cache itpipeline = new_pipelinepipeline_cache[requested_strength] = pipelinecurrent_lora_strength = requested_strength# Evict oldest if cache size exceededtry:while len(pipeline_cache) > CACHE_MAX_SIZE:evicted_strength, evicted_pipeline = pipeline_cache.popitem(last=False)try:del evicted_pipelineexcept Exception:passcleanup_memory()torch.cuda.empty_cache()print(f"[CACHE] evicted pipeline strength={evicted_strength}")except Exception as e:print(f"[CACHE] eviction error: {e}")# end of pipeline-per-strength swap/buildlog_memory("before pipeline call")video, audio = pipeline(
app.py+96-92