|
| 1 | +# Copyright © 2026 Apple Inc. |
| 2 | + |
| 3 | +"""Generate videos from an image and text prompt using Wan2.1 I2V.""" |
| 4 | + |
| 5 | +import argparse |
| 6 | +import logging |
| 7 | + |
| 8 | +import mlx.core as mx |
| 9 | +import mlx.nn as nn |
| 10 | +from tqdm import tqdm |
| 11 | +from wan import WanPipeline |
| 12 | +from wan.utils import save_video |
| 13 | + |
| 14 | +if __name__ == "__main__": |
| 15 | + parser = argparse.ArgumentParser( |
| 16 | + description="Generate videos from an image and text prompt using Wan2.1 I2V" |
| 17 | + ) |
| 18 | + parser.add_argument("prompt") |
| 19 | + parser.add_argument("--image", required=True, help="Path to input image") |
| 20 | + parser.add_argument("--model", choices=["i2v-14B"], default="i2v-14B") |
| 21 | + parser.add_argument( |
| 22 | + "--size", |
| 23 | + type=lambda x: tuple(map(int, x.split("x"))), |
| 24 | + default=(832, 480), |
| 25 | + help="Video size as WxH (default: 832x480)", |
| 26 | + ) |
| 27 | + parser.add_argument("--frames", type=int, default=81) |
| 28 | + parser.add_argument( |
| 29 | + "--steps", type=int, default=40, help="Number of denoising steps" |
| 30 | + ) |
| 31 | + parser.add_argument("--guidance", type=float, default=5.0) |
| 32 | + parser.add_argument("--shift", type=float, default=3.0) |
| 33 | + parser.add_argument("--seed", type=int) |
| 34 | + parser.add_argument( |
| 35 | + "--quantize", |
| 36 | + "-q", |
| 37 | + type=int, |
| 38 | + nargs="?", |
| 39 | + const=8, |
| 40 | + default=0, |
| 41 | + choices=[0, 4, 8], |
| 42 | + metavar="{4,8}", |
| 43 | + help="Quantize DiT weights (default: 8-bit when flag used without value)", |
| 44 | + ) |
| 45 | + parser.add_argument( |
| 46 | + "--n-prompt", |
| 47 | + default="Text, watermarks, blurry image, JPEG artifacts", |
| 48 | + ) |
| 49 | + parser.add_argument( |
| 50 | + "--teacache", |
| 51 | + type=float, |
| 52 | + default=0.0, |
| 53 | + help="TeaCache threshold for step skipping (0=off, 0.26=recommended for i2v)", |
| 54 | + ) |
| 55 | + parser.add_argument( |
| 56 | + "--checkpoint", |
| 57 | + type=str, |
| 58 | + default=None, |
| 59 | + help="Path to custom DiT weights (.safetensors), e.g. distilled models", |
| 60 | + ) |
| 61 | + parser.add_argument( |
| 62 | + "--sampler", |
| 63 | + choices=["unipc", "euler"], |
| 64 | + default="unipc", |
| 65 | + help="Sampler: unipc (default) or euler (for step-distilled models)", |
| 66 | + ) |
| 67 | + parser.add_argument("--output", default="out.mp4") |
| 68 | + parser.add_argument("--preload-models", action="store_true") |
| 69 | + parser.add_argument( |
| 70 | + "--no-cache", |
| 71 | + action="store_true", |
| 72 | + help="Disable Metal buffer cache (mx.set_cache_limit(0)) to reduce swap pressure", |
| 73 | + ) |
| 74 | + parser.add_argument("--verbose", "-v", action="store_true") |
| 75 | + args = parser.parse_args() |
| 76 | + |
| 77 | + if args.sampler == "euler": |
| 78 | + # Evenly spaced steps: e.g. 4 steps -> [1000, 750, 500, 250] |
| 79 | + n = args.steps |
| 80 | + denoising_step_list = [1000 * i // n for i in range(n, 0, -1)] |
| 81 | + else: |
| 82 | + denoising_step_list = None |
| 83 | + |
| 84 | + mx.set_default_device(mx.gpu) |
| 85 | + if args.no_cache: |
| 86 | + mx.set_cache_limit(0) |
| 87 | + |
| 88 | + if args.verbose: |
| 89 | + handler = logging.StreamHandler() |
| 90 | + handler.setFormatter(logging.Formatter("%(message)s")) |
| 91 | + logging.getLogger("wan").setLevel(logging.INFO) |
| 92 | + logging.getLogger("wan").addHandler(handler) |
| 93 | + |
| 94 | + # Load pipeline |
| 95 | + pipeline = WanPipeline(args.model, checkpoint=args.checkpoint) |
| 96 | + |
| 97 | + # Quantize DiT |
| 98 | + if args.quantize: |
| 99 | + nn.quantize(pipeline.flow, bits=args.quantize) |
| 100 | + print(f"Quantized DiT to {args.quantize}-bit") |
| 101 | + |
| 102 | + if args.preload_models: |
| 103 | + pipeline.ensure_models_are_loaded() |
| 104 | + |
| 105 | + # Generate latents (generator pattern) |
| 106 | + latents = pipeline.generate_latents( |
| 107 | + args.prompt, |
| 108 | + image_path=args.image, |
| 109 | + negative_prompt=args.n_prompt, |
| 110 | + size=args.size, |
| 111 | + frame_num=args.frames, |
| 112 | + num_steps=args.steps, |
| 113 | + guidance=args.guidance, |
| 114 | + shift=args.shift, |
| 115 | + seed=args.seed, |
| 116 | + teacache=args.teacache, |
| 117 | + verbose=args.verbose, |
| 118 | + denoising_step_list=denoising_step_list, |
| 119 | + ) |
| 120 | + |
| 121 | + # 1. Conditioning |
| 122 | + conditioning = next(latents) |
| 123 | + mx.eval(conditioning) |
| 124 | + peak_mem_conditioning = mx.get_peak_memory() / 1024**3 |
| 125 | + mx.reset_peak_memory() |
| 126 | + |
| 127 | + # Free T5 and CLIP memory |
| 128 | + del pipeline.t5 |
| 129 | + if pipeline.clip is not None: |
| 130 | + del pipeline.clip |
| 131 | + mx.clear_cache() |
| 132 | + |
| 133 | + # 2. Denoising loop |
| 134 | + for x_t in tqdm(latents, total=args.steps): |
| 135 | + mx.eval(x_t) |
| 136 | + |
| 137 | + # Free DiT memory |
| 138 | + del pipeline.flow |
| 139 | + mx.clear_cache() |
| 140 | + peak_mem_generation = mx.get_peak_memory() / 1024**3 |
| 141 | + mx.reset_peak_memory() |
| 142 | + |
| 143 | + # 3. VAE decode |
| 144 | + video = pipeline.decode(x_t) |
| 145 | + mx.eval(video) |
| 146 | + peak_mem_decoding = mx.get_peak_memory() / 1024**3 |
| 147 | + |
| 148 | + # Save video |
| 149 | + save_video(video, args.output) |
| 150 | + |
| 151 | + if args.verbose: |
| 152 | + peak_mem_overall = max( |
| 153 | + peak_mem_conditioning, peak_mem_generation, peak_mem_decoding |
| 154 | + ) |
| 155 | + print(f"Peak memory conditioning: {peak_mem_conditioning:.3f}GB") |
| 156 | + print(f"Peak memory generation: {peak_mem_generation:.3f}GB") |
| 157 | + print(f"Peak memory decoding: {peak_mem_decoding:.3f}GB") |
| 158 | + print(f"Peak memory overall: {peak_mem_overall:.3f}GB") |
0 commit comments