Download videos_zip_two_refiners/scripts/video_refiner_upscale.py from Perflow-Shuai/refiner_longlive2: direct link, hf CLI and curl.
- Browser
- Download file 9.21 kB
-
https://huggingface.co/datasets/Perflow-Shuai/refiner_longlive2/resolve/main/videos_zip_two_refiners/scripts/video_refiner_upscale.py
- Command line
-
hf download hf://datasets/Perflow-Shuai/refiner_longlive2/videos_zip_two_refiners/scripts/video_refiner_upscale.py
-
curl -L -o video_refiner_upscale.py https://huggingface.co/datasets/Perflow-Shuai/refiner_longlive2/resolve/main/videos_zip_two_refiners/scripts/video_refiner_upscale.py
9.21 kB
| import argparse | |
| import logging | |
| from pathlib import Path | |
| import torch | |
| from ltx_core.components.noisers import GaussianNoiser | |
| from ltx_core.loader import LTXV_LORA_COMFY_RENAMING_MAP, LoraPathStrengthAndSDOps | |
| from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number | |
| from ltx_core.quantization import QuantizationPolicy | |
| from ltx_core.types import SpatioTemporalScaleFactors, VideoPixelShape | |
| from ltx_pipelines.utils.args import resolve_path | |
| from ltx_pipelines.utils.blocks import ( | |
| DiffusionStage, | |
| ImageConditioner, | |
| PromptEncoder, | |
| VideoDecoder, | |
| VideoUpsampler, | |
| benchmark_stage, | |
| ) | |
| from ltx_pipelines.utils.constants import STAGE_2_DISTILLED_SIGMAS | |
| from ltx_pipelines.utils.denoisers import SimpleDenoiser | |
| from ltx_pipelines.utils.helpers import get_device, video_latent_from_file | |
| from ltx_pipelines.utils.media_io import encode_video, get_videostream_metadata | |
| from ltx_pipelines.utils.types import ModalitySpec, OffloadMode | |
| def _snap_frames_to_8k1(frames: int) -> int: | |
| time_scale = SpatioTemporalScaleFactors.default().time | |
| return ((frames - 1) // time_scale) * time_scale + 1 | |
| def _align_down(value: int, divisor: int = 32) -> int: | |
| aligned = value // divisor * divisor | |
| if aligned <= 0: | |
| raise ValueError(f"Cannot align non-positive dimension {value}") | |
| return aligned | |
| class VideoRefinerUpscalePipeline: | |
| """Video-to-video x2 spatial upscaling followed by distilled-LoRA refinement.""" | |
| def __init__( | |
| self, | |
| checkpoint_path: str, | |
| distilled_lora: LoraPathStrengthAndSDOps, | |
| spatial_upsampler_path: str, | |
| gemma_root: str, | |
| device: torch.device | None = None, | |
| quantization: QuantizationPolicy | None = None, | |
| torch_compile: bool = False, | |
| offload_mode: OffloadMode = OffloadMode.NONE, | |
| ) -> None: | |
| self.device = device or get_device() | |
| self.dtype = torch.bfloat16 | |
| self.prompt_encoder = PromptEncoder( | |
| checkpoint_path, gemma_root, self.dtype, self.device, offload_mode=offload_mode | |
| ) | |
| self.image_conditioner = ImageConditioner(checkpoint_path, self.dtype, self.device) | |
| self.upsampler = VideoUpsampler(checkpoint_path, spatial_upsampler_path, self.dtype, self.device) | |
| self.stage = DiffusionStage( | |
| checkpoint_path, | |
| self.dtype, | |
| self.device, | |
| loras=(distilled_lora,), | |
| quantization=quantization, | |
| torch_compile=torch_compile, | |
| offload_mode=offload_mode, | |
| ) | |
| self.video_decoder = VideoDecoder(checkpoint_path, self.dtype, self.device) | |
| def __call__( | |
| self, | |
| input_video: str, | |
| output_path: str, | |
| prompt: str, | |
| seed: int, | |
| start_frame: int = 0, | |
| max_frames: int | None = None, | |
| max_batch_size: int = 1, | |
| transformer: object | None = None, | |
| ) -> tuple[VideoPixelShape, VideoPixelShape]: | |
| source_shape = get_videostream_metadata(input_video) | |
| if start_frame < 0: | |
| raise ValueError(f"start_frame must be non-negative, got {start_frame}") | |
| frames = max(source_shape.frames - start_frame, 0) | |
| if max_frames is not None: | |
| frames = min(frames, max_frames) | |
| frames = _snap_frames_to_8k1(frames) | |
| if frames < 1: | |
| raise ValueError( | |
| f"No usable frames after start_frame={start_frame} and snapping frame count from " | |
| f"{source_shape.frames}" | |
| ) | |
| input_shape = VideoPixelShape( | |
| batch=1, | |
| frames=frames, | |
| width=_align_down(source_shape.width), | |
| height=_align_down(source_shape.height), | |
| fps=source_shape.fps, | |
| ) | |
| output_shape = VideoPixelShape( | |
| batch=1, | |
| frames=frames, | |
| width=input_shape.width * 2, | |
| height=input_shape.height * 2, | |
| fps=input_shape.fps, | |
| ) | |
| generator = torch.Generator(device=self.device).manual_seed(seed) | |
| noiser = GaussianNoiser(generator=generator) | |
| (ctx,) = self.prompt_encoder([prompt]) | |
| video_context = ctx.video_encoding | |
| initial_latent = self.image_conditioner( | |
| lambda enc: video_latent_from_file( | |
| video_encoder=enc, | |
| file_path=input_video, | |
| output_shape=input_shape, | |
| dtype=self.dtype, | |
| device=self.device, | |
| start_time=start_frame / input_shape.fps, | |
| max_duration=frames / input_shape.fps, | |
| ) | |
| ) | |
| if initial_latent is None: | |
| raise RuntimeError(f"Failed to encode input video: {input_video}") | |
| upscaled_latent = self.upsampler(initial_latent) | |
| sigmas = STAGE_2_DISTILLED_SIGMAS.to(dtype=torch.float32, device=self.device) | |
| with benchmark_stage("video_refiner_x2"): | |
| stage_kwargs = { | |
| "denoiser": SimpleDenoiser(v_context=video_context, a_context=None), | |
| "sigmas": sigmas, | |
| "noiser": noiser, | |
| "width": output_shape.width, | |
| "height": output_shape.height, | |
| "frames": output_shape.frames, | |
| "fps": output_shape.fps, | |
| "video": ModalitySpec( | |
| context=video_context, | |
| noise_scale=sigmas[0].item(), | |
| initial_latent=upscaled_latent, | |
| ), | |
| "audio": None, | |
| "max_batch_size": max_batch_size, | |
| } | |
| if transformer is None: | |
| video_state, _ = self.stage(**stage_kwargs) | |
| else: | |
| video_state, _ = self.stage.run(transformer=transformer, **stage_kwargs) | |
| if video_state is None: | |
| raise RuntimeError("Refiner did not produce a video latent") | |
| tiling_config = TilingConfig.default() | |
| video_chunks_number = get_video_chunks_number(output_shape.frames, tiling_config) | |
| video = self.video_decoder(video_state.latent, tiling_config, generator) | |
| Path(output_path).parent.mkdir(parents=True, exist_ok=True) | |
| encode_video( | |
| video=video, | |
| fps=round(output_shape.fps), | |
| audio=None, | |
| output_path=output_path, | |
| video_chunks_number=video_chunks_number, | |
| ) | |
| return input_shape, output_shape | |
| def _parse_quantization(name: str | None, checkpoint_path: str) -> QuantizationPolicy | None: | |
| if name is None or name == "none": | |
| return None | |
| if name == "fp8-cast": | |
| return QuantizationPolicy.fp8_cast() | |
| if name == "fp8-scaled-mm": | |
| return QuantizationPolicy.fp8_scaled_mm(checkpoint_path) | |
| raise ValueError(f"Unsupported quantization policy: {name}") | |
| def main() -> None: | |
| logging.getLogger().setLevel(logging.INFO) | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--checkpoint-path", type=resolve_path, required=True) | |
| parser.add_argument("--gemma-root", type=resolve_path, required=True) | |
| parser.add_argument("--spatial-upsampler-path", type=resolve_path, required=True) | |
| parser.add_argument("--distilled-lora-path", type=resolve_path, required=True) | |
| parser.add_argument("--distilled-lora-strength", type=float, default=0.8) | |
| parser.add_argument("--input-video", type=resolve_path, required=True) | |
| parser.add_argument("--output-path", type=resolve_path, required=True) | |
| parser.add_argument("--prompt", default="high quality video, sharp details") | |
| parser.add_argument("--seed", type=int, default=10) | |
| parser.add_argument("--start-frame", type=int, default=0) | |
| parser.add_argument("--max-frames", type=int) | |
| parser.add_argument("--max-batch-size", type=int, default=1) | |
| parser.add_argument("--offload", dest="offload_mode", type=OffloadMode, default=OffloadMode.NONE) | |
| parser.add_argument("--quantization", choices=("none", "fp8-cast", "fp8-scaled-mm"), default="none") | |
| parser.add_argument("--compile", action="store_true") | |
| args = parser.parse_args() | |
| pipeline = VideoRefinerUpscalePipeline( | |
| checkpoint_path=args.checkpoint_path, | |
| distilled_lora=LoraPathStrengthAndSDOps( | |
| path=args.distilled_lora_path, | |
| strength=args.distilled_lora_strength, | |
| sd_ops=LTXV_LORA_COMFY_RENAMING_MAP, | |
| ), | |
| spatial_upsampler_path=args.spatial_upsampler_path, | |
| gemma_root=args.gemma_root, | |
| quantization=_parse_quantization(args.quantization, args.checkpoint_path), | |
| torch_compile=args.compile, | |
| offload_mode=args.offload_mode, | |
| ) | |
| input_shape, output_shape = pipeline( | |
| input_video=args.input_video, | |
| output_path=args.output_path, | |
| prompt=args.prompt, | |
| seed=args.seed, | |
| start_frame=args.start_frame, | |
| max_frames=args.max_frames, | |
| max_batch_size=args.max_batch_size, | |
| ) | |
| print( | |
| f"Refined frame {args.start_frame}: {input_shape.width}x{input_shape.height}/{input_shape.frames}f " | |
| f"-> {output_shape.width}x{output_shape.height}/{output_shape.frames}f" | |
| ) | |
| if __name__ == "__main__": | |
| main() | |