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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import logging
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from ltx_core.components.noisers import GaussianNoiser
|
| 8 |
+
from ltx_core.loader import LTXV_LORA_COMFY_RENAMING_MAP, LoraPathStrengthAndSDOps
|
| 9 |
+
from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number
|
| 10 |
+
from ltx_core.quantization import QuantizationPolicy
|
| 11 |
+
from ltx_core.types import SpatioTemporalScaleFactors, VideoPixelShape
|
| 12 |
+
from ltx_pipelines.utils.args import resolve_path
|
| 13 |
+
from ltx_pipelines.utils.blocks import (
|
| 14 |
+
DiffusionStage,
|
| 15 |
+
ImageConditioner,
|
| 16 |
+
PromptEncoder,
|
| 17 |
+
VideoDecoder,
|
| 18 |
+
VideoUpsampler,
|
| 19 |
+
benchmark_stage,
|
| 20 |
+
)
|
| 21 |
+
from ltx_pipelines.utils.constants import STAGE_2_DISTILLED_SIGMAS
|
| 22 |
+
from ltx_pipelines.utils.denoisers import SimpleDenoiser
|
| 23 |
+
from ltx_pipelines.utils.helpers import get_device, video_latent_from_file
|
| 24 |
+
from ltx_pipelines.utils.media_io import encode_video, get_videostream_metadata
|
| 25 |
+
from ltx_pipelines.utils.types import ModalitySpec, OffloadMode
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _snap_frames_to_8k1(frames: int) -> int:
|
| 29 |
+
time_scale = SpatioTemporalScaleFactors.default().time
|
| 30 |
+
return ((frames - 1) // time_scale) * time_scale + 1
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _align_down(value: int, divisor: int = 32) -> int:
|
| 34 |
+
aligned = value // divisor * divisor
|
| 35 |
+
if aligned <= 0:
|
| 36 |
+
raise ValueError(f"Cannot align non-positive dimension {value}")
|
| 37 |
+
return aligned
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class VideoRefinerUpscalePipeline:
|
| 41 |
+
"""Video-to-video x2 spatial upscaling followed by distilled-LoRA refinement."""
|
| 42 |
+
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
checkpoint_path: str,
|
| 46 |
+
distilled_lora: LoraPathStrengthAndSDOps,
|
| 47 |
+
spatial_upsampler_path: str,
|
| 48 |
+
gemma_root: str,
|
| 49 |
+
device: torch.device | None = None,
|
| 50 |
+
quantization: QuantizationPolicy | None = None,
|
| 51 |
+
torch_compile: bool = False,
|
| 52 |
+
offload_mode: OffloadMode = OffloadMode.NONE,
|
| 53 |
+
) -> None:
|
| 54 |
+
self.device = device or get_device()
|
| 55 |
+
self.dtype = torch.bfloat16
|
| 56 |
+
self.prompt_encoder = PromptEncoder(
|
| 57 |
+
checkpoint_path, gemma_root, self.dtype, self.device, offload_mode=offload_mode
|
| 58 |
+
)
|
| 59 |
+
self.image_conditioner = ImageConditioner(checkpoint_path, self.dtype, self.device)
|
| 60 |
+
self.upsampler = VideoUpsampler(checkpoint_path, spatial_upsampler_path, self.dtype, self.device)
|
| 61 |
+
self.stage = DiffusionStage(
|
| 62 |
+
checkpoint_path,
|
| 63 |
+
self.dtype,
|
| 64 |
+
self.device,
|
| 65 |
+
loras=(distilled_lora,),
|
| 66 |
+
quantization=quantization,
|
| 67 |
+
torch_compile=torch_compile,
|
| 68 |
+
offload_mode=offload_mode,
|
| 69 |
+
)
|
| 70 |
+
self.video_decoder = VideoDecoder(checkpoint_path, self.dtype, self.device)
|
| 71 |
+
|
| 72 |
+
@torch.inference_mode()
|
| 73 |
+
def __call__(
|
| 74 |
+
self,
|
| 75 |
+
input_video: str,
|
| 76 |
+
output_path: str,
|
| 77 |
+
prompt: str,
|
| 78 |
+
seed: int,
|
| 79 |
+
start_frame: int = 0,
|
| 80 |
+
max_frames: int | None = None,
|
| 81 |
+
max_batch_size: int = 1,
|
| 82 |
+
transformer: object | None = None,
|
| 83 |
+
) -> tuple[VideoPixelShape, VideoPixelShape]:
|
| 84 |
+
source_shape = get_videostream_metadata(input_video)
|
| 85 |
+
if start_frame < 0:
|
| 86 |
+
raise ValueError(f"start_frame must be non-negative, got {start_frame}")
|
| 87 |
+
frames = max(source_shape.frames - start_frame, 0)
|
| 88 |
+
if max_frames is not None:
|
| 89 |
+
frames = min(frames, max_frames)
|
| 90 |
+
frames = _snap_frames_to_8k1(frames)
|
| 91 |
+
if frames < 1:
|
| 92 |
+
raise ValueError(
|
| 93 |
+
f"No usable frames after start_frame={start_frame} and snapping frame count from "
|
| 94 |
+
f"{source_shape.frames}"
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
input_shape = VideoPixelShape(
|
| 98 |
+
batch=1,
|
| 99 |
+
frames=frames,
|
| 100 |
+
width=_align_down(source_shape.width),
|
| 101 |
+
height=_align_down(source_shape.height),
|
| 102 |
+
fps=source_shape.fps,
|
| 103 |
+
)
|
| 104 |
+
output_shape = VideoPixelShape(
|
| 105 |
+
batch=1,
|
| 106 |
+
frames=frames,
|
| 107 |
+
width=input_shape.width * 2,
|
| 108 |
+
height=input_shape.height * 2,
|
| 109 |
+
fps=input_shape.fps,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
generator = torch.Generator(device=self.device).manual_seed(seed)
|
| 113 |
+
noiser = GaussianNoiser(generator=generator)
|
| 114 |
+
(ctx,) = self.prompt_encoder([prompt])
|
| 115 |
+
video_context = ctx.video_encoding
|
| 116 |
+
|
| 117 |
+
initial_latent = self.image_conditioner(
|
| 118 |
+
lambda enc: video_latent_from_file(
|
| 119 |
+
video_encoder=enc,
|
| 120 |
+
file_path=input_video,
|
| 121 |
+
output_shape=input_shape,
|
| 122 |
+
dtype=self.dtype,
|
| 123 |
+
device=self.device,
|
| 124 |
+
start_time=start_frame / input_shape.fps,
|
| 125 |
+
max_duration=frames / input_shape.fps,
|
| 126 |
+
)
|
| 127 |
+
)
|
| 128 |
+
if initial_latent is None:
|
| 129 |
+
raise RuntimeError(f"Failed to encode input video: {input_video}")
|
| 130 |
+
|
| 131 |
+
upscaled_latent = self.upsampler(initial_latent)
|
| 132 |
+
sigmas = STAGE_2_DISTILLED_SIGMAS.to(dtype=torch.float32, device=self.device)
|
| 133 |
+
|
| 134 |
+
with benchmark_stage("video_refiner_x2"):
|
| 135 |
+
stage_kwargs = {
|
| 136 |
+
"denoiser": SimpleDenoiser(v_context=video_context, a_context=None),
|
| 137 |
+
"sigmas": sigmas,
|
| 138 |
+
"noiser": noiser,
|
| 139 |
+
"width": output_shape.width,
|
| 140 |
+
"height": output_shape.height,
|
| 141 |
+
"frames": output_shape.frames,
|
| 142 |
+
"fps": output_shape.fps,
|
| 143 |
+
"video": ModalitySpec(
|
| 144 |
+
context=video_context,
|
| 145 |
+
noise_scale=sigmas[0].item(),
|
| 146 |
+
initial_latent=upscaled_latent,
|
| 147 |
+
),
|
| 148 |
+
"audio": None,
|
| 149 |
+
"max_batch_size": max_batch_size,
|
| 150 |
+
}
|
| 151 |
+
if transformer is None:
|
| 152 |
+
video_state, _ = self.stage(**stage_kwargs)
|
| 153 |
+
else:
|
| 154 |
+
video_state, _ = self.stage.run(transformer=transformer, **stage_kwargs)
|
| 155 |
+
|
| 156 |
+
if video_state is None:
|
| 157 |
+
raise RuntimeError("Refiner did not produce a video latent")
|
| 158 |
+
|
| 159 |
+
tiling_config = TilingConfig.default()
|
| 160 |
+
video_chunks_number = get_video_chunks_number(output_shape.frames, tiling_config)
|
| 161 |
+
video = self.video_decoder(video_state.latent, tiling_config, generator)
|
| 162 |
+
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
|
| 163 |
+
encode_video(
|
| 164 |
+
video=video,
|
| 165 |
+
fps=round(output_shape.fps),
|
| 166 |
+
audio=None,
|
| 167 |
+
output_path=output_path,
|
| 168 |
+
video_chunks_number=video_chunks_number,
|
| 169 |
+
)
|
| 170 |
+
return input_shape, output_shape
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _parse_quantization(name: str | None, checkpoint_path: str) -> QuantizationPolicy | None:
|
| 174 |
+
if name is None or name == "none":
|
| 175 |
+
return None
|
| 176 |
+
if name == "fp8-cast":
|
| 177 |
+
return QuantizationPolicy.fp8_cast()
|
| 178 |
+
if name == "fp8-scaled-mm":
|
| 179 |
+
return QuantizationPolicy.fp8_scaled_mm(checkpoint_path)
|
| 180 |
+
raise ValueError(f"Unsupported quantization policy: {name}")
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def main() -> None:
|
| 184 |
+
logging.getLogger().setLevel(logging.INFO)
|
| 185 |
+
parser = argparse.ArgumentParser()
|
| 186 |
+
parser.add_argument("--checkpoint-path", type=resolve_path, required=True)
|
| 187 |
+
parser.add_argument("--gemma-root", type=resolve_path, required=True)
|
| 188 |
+
parser.add_argument("--spatial-upsampler-path", type=resolve_path, required=True)
|
| 189 |
+
parser.add_argument("--distilled-lora-path", type=resolve_path, required=True)
|
| 190 |
+
parser.add_argument("--distilled-lora-strength", type=float, default=0.8)
|
| 191 |
+
parser.add_argument("--input-video", type=resolve_path, required=True)
|
| 192 |
+
parser.add_argument("--output-path", type=resolve_path, required=True)
|
| 193 |
+
parser.add_argument("--prompt", default="high quality video, sharp details")
|
| 194 |
+
parser.add_argument("--seed", type=int, default=10)
|
| 195 |
+
parser.add_argument("--start-frame", type=int, default=0)
|
| 196 |
+
parser.add_argument("--max-frames", type=int)
|
| 197 |
+
parser.add_argument("--max-batch-size", type=int, default=1)
|
| 198 |
+
parser.add_argument("--offload", dest="offload_mode", type=OffloadMode, default=OffloadMode.NONE)
|
| 199 |
+
parser.add_argument("--quantization", choices=("none", "fp8-cast", "fp8-scaled-mm"), default="none")
|
| 200 |
+
parser.add_argument("--compile", action="store_true")
|
| 201 |
+
args = parser.parse_args()
|
| 202 |
+
|
| 203 |
+
pipeline = VideoRefinerUpscalePipeline(
|
| 204 |
+
checkpoint_path=args.checkpoint_path,
|
| 205 |
+
distilled_lora=LoraPathStrengthAndSDOps(
|
| 206 |
+
path=args.distilled_lora_path,
|
| 207 |
+
strength=args.distilled_lora_strength,
|
| 208 |
+
sd_ops=LTXV_LORA_COMFY_RENAMING_MAP,
|
| 209 |
+
),
|
| 210 |
+
spatial_upsampler_path=args.spatial_upsampler_path,
|
| 211 |
+
gemma_root=args.gemma_root,
|
| 212 |
+
quantization=_parse_quantization(args.quantization, args.checkpoint_path),
|
| 213 |
+
torch_compile=args.compile,
|
| 214 |
+
offload_mode=args.offload_mode,
|
| 215 |
+
)
|
| 216 |
+
input_shape, output_shape = pipeline(
|
| 217 |
+
input_video=args.input_video,
|
| 218 |
+
output_path=args.output_path,
|
| 219 |
+
prompt=args.prompt,
|
| 220 |
+
seed=args.seed,
|
| 221 |
+
start_frame=args.start_frame,
|
| 222 |
+
max_frames=args.max_frames,
|
| 223 |
+
max_batch_size=args.max_batch_size,
|
| 224 |
+
)
|
| 225 |
+
print(
|
| 226 |
+
f"Refined frame {args.start_frame}: {input_shape.width}x{input_shape.height}/{input_shape.frames}f "
|
| 227 |
+
f"-> {output_shape.width}x{output_shape.height}/{output_shape.frames}f"
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
if __name__ == "__main__":
|
| 232 |
+
main()
|